/* ========================================
 FILE: /language/js/austrian-german.js
 ==================== */

var cms_js_lang_2code = 'at';

var cms_js_lang_yes = 'Ja';
var cms_js_lang_no = 'Nein';
var cms_js_lang_dashboard_no_orders = '0 new orders';
var cms_js_lang_dashboard_no_customers = '0 new customers.';

var cms_js_lang_orders_mass_inv_text_1 = '1 or more selected records of orders haven\'t invoice. \n\nDo you want to generate mass PDF invoice only for existing invoices?';
var cms_js_lang_orders_mass_inv_text_2 = 'Maximum number of invoices for mass PDF generation is limited to 50 (actual number: {count}).\nPlease select less invoices, or reduce the number of items displayed per page.';

var cms_js_lang_orders_change_status_default_comment = 'Customer comment';
var cms_js_lang_orders_change_status_change_confirm = 'Confirm order status change';
var cms_js_lang_orders_customer_search = 'enter customer\'s name or e-mail';
var cms_js_lang_orders_delete_confirm = 'Delete selected orders?';
var cms_js_lang_orders_message = 'Optional message for customer about actual change of status of his order';
var cms_js_lang_orders_confirm_1 = 'Confirm change, no e-mail notification';
var cms_js_lang_orders_confirm_2 = 'Confirm change with e-mail notification';
var cms_js_lang_orders_confirm_3 = 'or';
var cms_js_lang_orders_confirm_4 = 'Send email to the customer';
var cms_js_lang_orders_confirm_5 = 'Insert from template';
var cms_js_lang_orders_confirm_6 = '- select the template -';
var cms_js_lang_orders_confirm_7 = 'Templates manager';
var cms_js_lang_orders_confirm_8 = 'save the message to customer account';
var cms_js_lang_orders_confirm_9 = '- add new template -';
var cms_js_lang_orders_confirm_10 = 'Delete template';
var cms_js_lang_orders_confirm_11 = 'Template name:';
var cms_js_lang_orders_confirm_12 = 'Text:';
var cms_js_lang_orders_confirm_13 = 'Upload attachment';
var cms_js_lang_orders_confirm_14 = 'Manage your text templates for e-mail about changes in order';
var cms_js_lang_orders_confirm_15 = 'Are you sure to delete the selected template?';
var cms_js_lang_orders_confirm_16 = 'Fill the template data.';
var cms_js_lang_orders_confirm_17_add = 'The template has been successfully added.';
var cms_js_lang_orders_confirm_17_save = 'The template has been successfully saved.';
var cms_js_lang_orders_confirm_18 = 'Wait for the completion of recording files.';

var cms_js_lang_orders_misc_1 = 'original addressee: ';

var js_lang_product_not_in_offer = 'Auch nicht verfügbare Produkte anzeigen ';

var js_lang_adminlang_swe_content_comments_add_main_title = 'Bewertung hinzufügen';

var cms_js_lang_invoice_email = 'Customer\'s e-mail address missing.';
var cms_js_lang_invoice_next_no_err = 'Invoice with the specified number already exists. Enter the other one.';
var cms_js_lang_invoice_info_1 = 'Invoice has already been sent.';
var cms_js_lang_invoice_info_2 = 'Do you want to send it anyway to ';
var cms_js_lang_invoice_info_3 = 'Do you really want to send invoice to ';
var cms_js_lang_products_group_name = 'Products group name';
var cms_js_lang_products_group_1 = 'Show list of products for this group of products';
var cms_js_lang_products_group_2 = 'Save';
var cms_js_lang_products_group_3 = 'Cancel';
var cms_js_lang_products_group_4 = 'Change';
var cms_js_lang_products_group_5 = 'Delete';
var cms_js_lang_products_group_6 = 'Add new group';
var cms_js_lang_products_group_7 = 'Add';
var cms_js_lang_products_group_8 = 'Send';
var cms_js_lang_products_group_9 = 'Close';
var cms_js_lang_products_group_10 = 'Order';
var cms_js_lang_products_group_11 = 'Clear';
var cms_js_lang_products_group_12 = 'Add';
var cms_js_lang_products_group_13 = 'Translate';
var cms_js_lang_products_group_14 = 'Create a copy of the template';
var cms_js_lang_products_group_delete_confirm_1 = 'Product group ';
var cms_js_lang_products_group_delete_confirm_2 = ', which you want to delete has ';
var cms_js_lang_products_group_delete_confirm_3 = ' products. Only empty group of products can be deleted.';
var cms_js_lang_products_group_delete_confirm_4 = 'Delete group of products ';
var cms_js_lang_products_group_lang_empty_input = 'All inputs of translations have to be filled.';

var cms_js_loader_working = 'Bearbeitung läuft...';

var cms_js_lang_products_shipping_message_error_1 = ' Error ';
var cms_js_lang_products_shipping_message_error_2 = 'Unknown error';

var cms_js_lang_products_stock_1 = 'Stock movement was successfully created.';
var cms_js_lang_products_stock_2 = 'In process of creating stock movement, an error occurred.';
var cms_js_lang_products_stock_3 = 'Add';

var cms_js_lang_products_availability_delete_message_1 = 'After deletion ';
var cms_js_lang_products_availability_delete_message_2 = ' product will stop';
var cms_js_lang_products_availability_delete_message_3 = ' products will stop';
var cms_js_lang_products_availability_delete_message_4 = ' products will stop';
var cms_js_lang_products_availability_delete_message_5 = ' having shown availability. Do you want to delete selected availability?';
var cms_js_lang_products_availability_delete_message_6 = 'Delete selected availability?';

var cms_js_lang_products_manufacturer_delete_message_1 = 'After deletion ';
var cms_js_lang_products_manufacturer_delete_message_2 = ' product will stop';
var cms_js_lang_products_manufacturer_delete_message_3 = ' products will stop';
var cms_js_lang_products_manufacturer_delete_message_4 = ' products will stop';
var cms_js_lang_products_manufacturer_delete_message_5 = ' having shown manufacturer. Do you want to delete selected manufacturer?';
var cms_js_lang_products_manufacturer_delete_message_6 = 'Delete selected manufacturer?';

var cms_js_lang_products_tax_rate = 'VAT rate';
var cms_js_lang_products_tax_delete = 'Delete VAT rate?';

var cms_js_lang_products_duplicate_add_finish_first = 'Before creating a copy of the product adding a new product needs to be completed first.';
var cms_js_lang_products_duplicate_product_name_changed = 'Change the product name so it is different than the previous one';

var cms_js_lang_customer_customer_search = 'enter customer\'s name or e-mail';
var cms_js_lang_customer_password_notmatched = 'Hinweis: Die Passwörter stimmen nicht überein.';
var cms_js_lang_customer_delete_confirm = 'Delete selected customers?';
var cms_js_lang_customer_administrator_delete_confirm = 'EN: Naozaj chcete zmazať zvolených administrátorov?';

var cms_js_lang_content_product_added_add_another = 'Product was successfuly added&hellip; you can add another product';
var cms_js_lang_content_product_added_add_another_copied = 'Product was successfuly added&hellip; you can add another product with similar data';
var cms_js_lang_content_product_add = 'Add product';
var cms_js_lang_content_product_edited = 'Product was successfuly edited';
var cms_js_lang_content_products_delete_confirm = 'Delete selected products? Number of products to be deleted: %s.'; // %s = pocet

var cms_js_lang_content_products_tax_select = '- select VAT -';
var cms_js_lang_content_products_tax_add = '- add new VAT -';

var cms_js_lang_content_panel_layout = 'Layout';
var cms_js_lang_content_panel_layout_title_1 = 'Layout - 3 columns';
var cms_js_lang_content_panel_layout_title_2 = 'Layout - 2 columns';
var cms_js_lang_content_panel_layout_title_3 = 'Layout - 3 columns';
var cms_js_lang_content_panel_layout_title_4 = 'Layout - 2 columns';
var cms_js_lang_content_panel_bin_used = 'Used modules';
var cms_js_lang_content_panel_bin_new = 'New modules';
var cms_js_lang_content_panel_restart = 'Return to default modules position?';
var cms_js_lang_content_panel_restart_title = 'Default modules position.';

var cms_js_lang_content_modules_info = 'Hiding right column of your web page, modules are moved to the used modules bin';
var cms_js_lang_content_modules_move = 'Move to new modules bin';
var cms_js_lang_content_modules_moving = 'Hiding module to used modules bin';
var cms_js_lang_content_modules_delete = 'Delete module';
var cms_js_lang_content_modules_delete_confirm = 'Delete module?';
var js_lang_phpshop_product_oos2pu = 'Produkt ist ausverkauft';
var js_lang_variant_code2 = 'Variantencode';

var cms_js_lang_content_modules_change_name = 'Change module name';
var cms_js_lang_content_modules_hide_name = 'Hide module name';
var cms_js_lang_content_modules_show_name = 'Show module name';
var cms_js_lang_content_modules_show_where = 'Where to show module ';
var cms_js_lang_content_modules_show_params = 'Parameters';
var cms_js_lang_content_modules_show_image_params = 'Links';
var cms_js_lang_content_modules_hide = 'Hide module';
var cms_js_lang_content_modules_save = 'Save';
var cms_js_lang_content_modules_cancel = 'Cancel';
var cms_js_lang_content_modules_image_upload = 'Upload image';
var cms_js_lang_content_modules_redirect = 'Umleiten';
var cms_js_lang_cms_lightbox_txtimage = 'Bild';
var cms_js_lang_cms_lightbox_txtof = 'von';

var cms_js_lang_content_modules_group_products_group = 'Group of products';
var cms_js_lang_content_modules_group_products_count = 'Number of products in group:';
var cms_js_lang_content_modules_group_products_ordering = 'Products ordering:';
var cms_js_lang_content_modules_group_products_ordering_1 = 'manual';
var cms_js_lang_content_modules_group_products_ordering_2 = 'random for 1 day';
var cms_js_lang_content_modules_group_products_ordering_3 = 'always random';

var cms_js_lang_content_text_change = 'Edit module';
var cms_js_lang_content_text_change_edit = 'Edit module ';
var cms_js_lang_content_text_change_tooltip = 'Click to edit module';
var cms_js_lang_content_footer_change_edit = 'Edit footer';
var cms_js_lang_content_footer_change_tooltip = 'Click to edit footer';
var cms_js_lang_content_footer_1 = 'footer';


var js_lang_luigibox_hint = 'Um eine normale Suche nach {query} durchzuführen, drücken Sie Enter';
var js_lang_luigibox_min_chars = 'Bitte geben Sie mindestens {char} Zeichen eins';
var js_lang_luigibox_addtocart = 'Zum Korb';
var js_lang_luigibox_ac_query = 'Popular search';
var js_lang_luigibox_ac_categories = 'Kategorien';
var js_lang_luigibox_ac_products = 'Produkte';
var js_lang_luigibox_ac_manufacturers = 'Hersteller';
var js_lang_luigibox_ac_articles = 'Paragraf';

var cms_js_lang_content_menu_item_drag_title = 'Change order';

var cms_js_lang_you_have_free_shipping = 'Der Versand ist für Sie gratis.';

var cms_js_lang_cms_lightbox_txtimage = 'Bild';
var cms_js_lang_cms_lightbox_txtof = 'von';

var cms_js_lang_content_article_change_position = 'Change article position';
var cms_js_lang_content_article_change_position_finish = 'Finish changing article position';
var cms_js_lang_content_article_edit = 'Edit article';
var cms_js_lang_content_article_delete = 'Delete article';
var cms_js_lang_content_article_delete_confirm = 'Delete article?';
var cms_js_lang_content_article_move_1 = 'Show new category "';
var cms_js_lang_content_article_move_2 = '" after moving article?';
var cms_js_lang_content_article_move_title = 'Change order';

var cms_js_lang_content_topmenu_delete_confirm = 'Delete menu?';
var cms_js_lang_content_topmenu_alert_1 = 'Reserved size of topmenu is full, no additional menu could be add.';

var cms_js_lang_content_category_add = 'Add';
var cms_js_lang_content_category_add_name = 'Enter category name';
var cms_js_lang_content_category_add_confirm = 'Add';
var cms_js_lang_content_category_save = 'Save';
var cms_js_lang_content_category_cancel = 'Cancel';
var cms_js_lang_content_category_edit = 'Edit';
var cms_js_lang_content_category_delete = 'Delete';
var cms_js_lang_content_category_delete_confirm = 'Delete this category?';
var cms_js_lang_content_category_show_all_products = 'List of products in category %s';  // %s - nazov kategorie
var cms_js_lang_content_category_translate = 'Translate';
var cms_js_lang_content_category_translate_all = 'Translate all';

var cms_js_lang_orders_x = 'Orders:';
var cms_js_lang_customers_x = 'Customers:';
var cms_js_lang_income_x = 'Income:';

var cms_js_lang_content_alert_1 = 'Unknown error.';
var cms_js_lang_content_alert_2 = 'Please enter category name.';
var cms_js_lang_content_alert_3 = 'Please enter category safe url.';
var cms_js_lang_content_alert_4 = 'Please enter menu item name.';
var cms_js_lang_content_alert_5 = 'Please enter menu item safe url.';
var cms_js_lang_content_alert_6 = 'This menu item cannot be moved to topmenu, because topmenu is full.';
var cms_js_lang_content_alert_7 = 'Please finish first editing ';
var cms_js_lang_content_alert_8 = 'Please enter VAT rate.';
var cms_js_lang_content_alert_9 = 'Incorrectly entered VAT rate';
var cms_js_lang_content_alert_10 = 'Please choose or fill all mandatory items or fields marked by star.';
var cms_js_lang_content_alert_11 = '';
var cms_js_lang_content_alert_12 = 'It is not possible to fill in more characters because this menu item would not fit in the menu.';
var cms_js_lang_content_alert_13 = 'It is not possible to fill in more characters because it reached the maximum length.';
var cms_js_lang_content_alert_14 = 'EN - TODO: Túto položku nie je možné vymazať, pretože má podpoložky.';

var cms_js_lang_customer_password_strength = '<strong>Vysvetlenie pojmu "Sila hesla":</strong><br /><br /><strong>"Príliš krátke"</strong> heslo má dĺžku menej ako 6 znakov.<br /><strong>"Silné"</strong> heslo ma dĺžku najmenej 12 znakov, skladá sa z veľkých písmen, malých písmen a číslic.<br /><strong>"Priemerné"</strong> heslo má dĺžku najmenej 8 znakov, skladá sa z veľkých a malých písmen, alebo z veľkých písmen a číslic, alebo z malých písmen a číslic.<br /><strong>"Slabé"</strong> heslo je horšie ako "Priemerné" heslo v niektorom z jeho parametrov.';

var cms_js_lang_product_availability_name = 'Availability';
var cms_js_lang_product_availability_duplicity = 'Entered availability already exists.';
var cms_js_lang_product_availability_inserted = 'New availability was added.';
var cms_js_lang_product_availability_update_fail = 'Failed to update selected availability.';
var cms_js_lang_product_availability_updated = 'Availability was updated.';
var cms_js_lang_product_availability_deleted = 'Availability was deleted.';

var cms_js_lang_product_manufacturer_name = 'Manufacturer';
var cms_js_lang_product_manufacturer_duplicity = 'Entered manufacturer already exists.';
var cms_js_lang_product_manufacturer_edit_fail = 'Failed to update selected manufacturer.';
var cms_js_lang_product_manufacturer_edit_success = 'Manufacturer was updated.';
var cms_js_lang_product_manufacturer_insert_fail = 'Failed to add new manufacturer.';
var cms_js_lang_product_manufacturer_deleted = 'Manufacturer was deleted.';

var cms_js_lang_always = ' - always -';
var cms_js_lang_change_sef_name = 'Change of SEF url can lower your position on Google search. Continue?';
var cms_js_lang_close = 'Close';


var cms_js_lang_order_items_changes_prod_quant_nonzero_warn = 'The specified number must be an integer greater than zero.';
var cms_js_lang_order_items_changes_other_quant_warn = 'The specified number must be different than the original.';
var cms_js_lang_order_items_changes_check_stock_limit_warn = 'Item order is not possible to change the quantity to the specified value, due to inventory control enabled. The highest possible value for the quantity';
var cms_js_lang_order_items_changes_equal_quant_warn = 'Item order not alter the quantity, as you enter the same value.';
var cms_js_lang_order_items_changes_chng_ord_quest_01 = 'To change the order despite the fact that when you change the total amount of';
var cms_js_lang_order_items_changes_chng_ord_quest_02 = 'will be less than the minimum amount of orders worth';

var cms_js_lang_order_items_changes_only_one_ord_item = 'Item orders can not be deleted, because this order includes only one item';
var cms_js_lang_order_items_changes_del_ord_item_quest = 'Delete an item from your order number';

var cms_js_lang_order_items_changes_put_or_sel_prod_sku = 'Please enter or select';
var cms_js_lang_order_print_sku = 'Product Code';
var cms_js_lang_order_print_sku_form = 'Code:';

var cms_js_lang_display = 'Display';
var cms_js_lang_hide = 'Hide';
var cms_js_lang_change = 'Change';
var cms_js_lang_order_items_changes_dupli_ord_item = 'New item orders can not be added because the order contains no other item with the same product code';
var cms_js_lang_order_items_changes_unknown_prod_sku = 'New item orders can not be added because you entered a non-existent data for';

var cms_js_lang_products_filter_entry_search = 'enter name or code of product';
var cms_js_lang_order_number_entry_search = 'set order no.';
var cms_js_lang_system_account_changed = 'Your account was saved successfuly';

var cms_js_lang_content_leadimg_tooltip = 'Click to edit page header';
var cms_js_lang_content_leadimg_web_name = 'E-shop name:';
var cms_js_lang_content_leadimg_web_desc = 'E-shop slogan:';
var cms_js_lang_content_leadimg_def_web_name = 'Title of your e-commerce';
var cms_js_lang_content_leadimg_def_web_desc = 'Slogan of your e-commerce';
var cms_js_lang_content_leadimg_change_header_height = 'Change header height';
var cms_js_lang_content_leadimg_change_header_save = 'Save height';
var cms_js_lang_content_leadimg_banner_upload_notice = 'Width of the recorded image is recommended to have 940px, height range 100-200px.';

var cms_js_lang_system_first_login_invitation = 'EN - TODO: <div>Bezplatné testovanie e-shop riešenia Skvelý Shop v plnej verzii je Vám k dispozícii 15 dní. V tomto období si môžete navrhnúť Váš e-shopu, jeho dizajn a napĺňať ho reálnymi dátami. Pred ukončením tohto obdobia si prosím zvoľte subdoménu alebo doménu, na ktorej si Váš e-shop prajete prevádzkovať. Takisto si môžete zvoliť balík služieb, ktorý Vám bude najviac vyhovovať.</div><br/><div>Návrh Vášho e-shopu je automaticky ukladaný a všetky dáta sú bezpečne zachované.</div><br/><div>Odporúčame Vám pozrieť si inštruktážne videá, ktoré Vám priblížia jednoduchosť práce v systéme Skvelý Shop.Vśetky videá nájdete tiež v sekcii Nástroje v administrácii.</div><br/><div>Prajeme Vám príjemnú skúsenosť s revolučným systémom Skvelý Shop.V prípade akýchkoľvek otázok nás neváhajte kontaktovať. Váš Skvelý Shop tím.</div><br/><br/><div>Vytvorenie obsahu a dizajnu webstránky</div><div>VIDEO 1</div><br/><div>Pridávanie a nastavenia produktov</div><div>VIDEO 2</div><br/><div>Administrácia e-shopu</div><div>VIDEO 3</div>';
var cms_js_lang_system_first_login_invitation_free = 'EN - TODO: <div><div><h3>Ďakujeme za objednanie e-shop riešenia Skvelý Shop.</h3> K dispozícii máte 15 dní na vyskúšanie e-shop riešenia Skvelý Shop v plnej verzii - balík PREMIUM, po skončení 15-dňovej skúšobnej prevádzky sa balík PREMIUM zmení na Vami vybraný balík %s.</div><br /><div>Návrh Vášho e-shopu je automaticky ukladaný a všetky dáta sú bezpečne zachované.</div><br /><div>Odporúčame Vám pozrieť si inštruktážne videá, ktoré Vám priblížia jednoduchosť práce v systéme Skvelý Shop. Všetky videá nájdete tiež v sekcii Pomocník v administrácii.</div><br/><div>V prípade akýchkoľvek otázok nás neváhajte kontaktovať. Váš Skvelý Shop tím.</div><br/><div class="video_container"><div class="video"><a href="/administrator/index2.php?help&amp;video_autostart=1">1. VIDEO - Správa obsahu<br /><img src="/templates/admin/init/images/admin-video-small1.jpg" alt="1. VIDEO - Správa obsahu web stránok e-shopu [Skvelý Shop]" title="1. VIDEO - Správa obsahu web stránok e-shopu [Skvelý Shop]"></a></div><div class="video"><a href="/administrator/index2.php?help&amp;video_autostart=2">2. VIDEO - Administrácia<br /><img src="/templates/admin/init/images/admin-video-small2.jpg" alt="2. VIDEO - Administrácia a správa e-shopu [Skvelý Shop]" title="2. VIDEO - Administrácia a správa e-shopu [Skvelý Shop]" /></a></div><div class="video video3"><a href="/administrator/index2.php?help&amp;video_autostart=3">3. VIDEO - Produkty<br /><img src="/templates/admin/init/images/admin-video-small3.jpg" alt="3. VIDEO - Pridanie a úprava produktov [Skvelý Shop]" title="3. VIDEO - Pridanie a úprava produktov [Skvelý Shop]" /></a></div></div><div class="cleaner">&nbsp;</div></div>';

var cms_js_lang_system_cfg_delete_payment_method = 'Delete selected payment methods?';
var cms_js_lang_system_cfg_delete_shipping_rate = 'Delete selected shipping rates?';

var cms_js_lang_my_account_wrong_username_format = 'User name has to be in the format of an e-mail address.';
var cms_js_lang_new_account_no_product_results = 'No purchased products were found';

var cms_js_lang_leadimg_reset_values = 'Default header setup';
var cms_js_lang_leadimg_reset_values_confirm = 'Are you sure you want to set the initial header text, it\'s color, size and position, as well as the original header image?';
var cms_js_lang_leadimg_jpicker_new = 'new';
var cms_js_lang_leadimg_jpicker_current = 'current';
var cms_js_lang_leadimg_jpicker_drag_and_pick = 'Drag Markers To Pick A Color';
var cms_js_lang_leadimg_jpicker_more_options = 'More options&nbsp;&gt;';

var cms_js_lang_leadimg_qq_upload_button = 'Upload new header image';
var cms_js_lang_leadimg_move_texts_info = 'You can change the positions of texts by dragging them to a new location.';
var cms_js_lang_leadimg_banner_notice = 'Some designs are designed that they normally do not support the insertion of another image in the page header.';
var cms_js_lang_leadimg_banner_wrong_template = 'This also applies to the design that you have currently selected. If you would like to have your own image in this design nevertheless, please contact us, we will try to help you.';

var cms_js_lang_products_edit_product_title = 'Edit product';

var cms_js_lang_cart_product_is_unsaleable_msg = 'Sorry, product is not for sale';
var cms_js_lang_last_product_piece_warn = 'Bald ausverkauft';
var cms_js_lang_last_product_piece_txt1 = 'Letzte Stück. Bald ausverkauft! Kaufe es jetzt!';
var cms_js_lang_last_product_piece_txt2 = 'Letzten 2 Stück. Bald ausverkauft!';
var cms_js_lang_last_product_piece_txt3 = 'Mehr als 2 stück';
var cms_js_lang_cart_product_is_in_stock = 'product is in stock';
var cms_js_lang_cart_product_is_not_in_stock = 'product is out of stock';

var cms_js_lang_content_def_category_sef_1 = 'product-category-1';
var cms_js_lang_content_def_category_sef_2 = 'product-category-2';
var cms_js_lang_content_def_category_sef_3 = 'product-category-3';
var cms_js_lang_content_def_category_sef_4 = 'product-category-4';

var cms_js_lang_users_add_user_group = 'add new group';
var cms_js_lang_users_add_user_group_def_text = 'group name';
var cms_js_lang_users_add_user_group_fill_name = 'Please fill in the group name.';

var cms_js_lang_display_on_save_empty_warning = 'Choose at least one e-shop page where should be the module displayed.';

var cms_js_lang_sitemap_title = 'Title';
var cms_js_lang_sitemap_desc = 'Description';
var cms_js_lang_sitemap_kyewo = 'Keywords';

var cms_js_lang_admin_cfg_migration_no_www_proceed = 'Live Domain enthält nicht "www". - möchtest du fortfahren?';
var cms_js_duplicity = 'Der eingegebene Wert wird dupliziert.';
var cms_js_back_to_basket = 'Zurück zum Warenkorb';
var cms_js_confirm_order = 'Bestellung aufgeben';
var cms_js_confirm_avail_notify_in_cart = 'Bestätigen und fortfahren';
var cms_js_check_stock_with_return_strct_check_text1 = 'Die folgenden Produkte sind derzeit nicht verfügbar und der Kauf kann nicht abgeschlossen werden:';
var cms_js_check_stock_with_return_strct_check_text2 = 'Bitte kehren Sie zum Warenkorb zurück und entfernen Sie Produkte, die nicht verfügbar sind.';
var cms_js_check_stock_with_return_text1 = 'Die folgenden Produkte sind derzeit nicht auf Lager, daher kann der Versand der Bestellung länger dauern:';
var cms_js_check_stock_with_return_text2 = 'Wenn Sie mit einer längeren Versandzeit einverstanden sind, klicken Sie bitte auf den Button <b>"' + cms_js_confirm_order + '"</b>.<br/> </b>.<br />. Andernfalls kehren Sie bitte zum Warenkorb zurück und entfernen Sie diese Produkte aus Ihrer Bestellung.';

var js_lang_ssp_cms_order_eshop_title = 'Order of e-shop solution package Skvelý Shop';
var js_lang_ssp_cms_order_eshop_title_new = 'Order of new e-shop solution package Skvelý Shop';

var js_lang_ssp_cms_order_eshop_info = '<div class="ssp_tooltip_info">After receiving your order we will contact you with further instructions.< br/>Thank you for your trust and we are looking forward to our successful cooperation.< br/> Your Skvelý Shop team.</div>';
var js_lang_ssp_cms_order_eshop_email = 'Enter your e-mail address:';
var js_lang_ssp_cms_order_eshop_email_def_text = 'your@email.com';
var js_lang_ssp_cms_order_eshop_email_error = 'Please fill in your e-mail address.';

var js_lang_ssp_cms_order_eshop_bundle = 'Choose package:';

var js_lang_ssp_cms_order_eshop_phone = 'Enter your phone number:';
var js_lang_ssp_cms_order_eshop_phone_def_text = '+421 Your phone no.';
var js_lang_ssp_cms_order_eshop_phone_error = 'Please fill in your phone number.';

var js_lang_ssp_cms_order_sent = 'Your order of e-shop solution Skvelý Shop has been sent successfully.';
var js_lang_ssp_cms_order_sent_paid1 = 'Your order of e-shop solution Skvelý Shop - package';
var js_lang_ssp_cms_order_sent_paid2 = 'has been sent successfully. Further information regard invoicing will send you mail.';


//var js_lang_ssp_order_eshop_package_date_1 = '12 days already.';
//var js_lang_ssp_order_eshop_package_date_2 = '15 days already.';

var js_lang_ssp_order_eshop_agree_to_toc = 'I agree with <a href="http://www.skvelyshop.sk/SkvelyShop_VOP.pdf">Terms and Conditions of SkvelyShop.sk</a>';
var js_lang_ssp_cms_order_eshop_agree_to_toc_error = 'Before ordering it is necessary to agree with the Terms and Conditions of SkvelyShop.sk.';

var js_lang_ssp_cms_order_test_eshop_valid_info = '%s until the end of your test operation.';
var js_lang_ssp_cms_order_test_eshop_valid_info_days = ['Unknown number of days remain', '1 day remains', '2 days remain', '3 days remain'];
var js_lang_ssp_cms_order_test_eshop_expired_info = 'Your test operation has expired.';

var js_lang_ssp_cms_order_eshop_pricelist_info = '<div class="ssp_tooltip_info">You can find the package overview on the page <a href="http://www.skvelyshop.sk/cennik/" target="_blank">Pricelist</a>. You can change your package anytime.</div>';

var js_lang_ssp_cms_order_eshop_subdomain = 'Enter your subdomain:';
var js_lang_ssp_cms_order_eshop_subdomain_def_text = 'Your subdomain';
var js_lang_ssp_cms_order_eshop_subdomain_error_1 = 'Please fill in your subdomain!';
var js_lang_ssp_cms_order_eshop_subdomain_error_2 = 'Entered subdomain already exists!';
var js_lang_ssp_cms_settings_google_analytics_error = 'EN - TODO: Google Analytics ID bol zadaný v nesprávnom formáte. Správny formát je UA-XXXXXXXX-1.';
var js_lang_ssp_cms_settings_google_tools_error = 'EN - TODO: Google Webmaster Tools meta bol zadaný v nesprávnom formáte. Mal by mať 43 znakov.';

var js_price_from_bundle_id1 = 'The amount to be paid';
var js_price_from_bundle_id2 = 'EUR + VAT x 12 month.';

var js_import_product_data = new Object();
    js_import_product_data[''] = '- do not import -';
    js_import_product_data['name'] = 'product name';
    js_import_product_data['sku'] = 'product code';
    js_import_product_data['price_with_vat'] = 'price with VAT';
    js_import_product_data['price_without_vat'] = 'price without VAT';
    js_import_product_data['old_price_with_vat'] = 'standard price with VAT';
    js_import_product_data['old_price_without_vat'] = 'standard price without VAT';
    js_import_product_data['s_desc'] = 'short description';
    js_import_product_data['desc'] = 'product description';
  //  js_import_product_data['is_unsaleable'] = 'product is unsellable';
    js_import_product_data['in_stock'] = 'in stock';
    js_import_product_data['weight'] = 'weight [kg]';
    js_import_product_data['publish'] = 'publish (Y/N)';
    js_import_product_data['manufacturer'] = 'manufacturer';
  //  js_import_product_data['plength'] = 'length';
  //  js_import_product_data['width'] = 'width';
  //  js_import_product_data['height'] = 'height';
    js_import_product_data['primary_img'] = 'EN: hlavný obrázok';
    js_import_product_data['secondary_img'] = 'EN: ďaľšie obrázky';
    js_import_product_data['category'] = 'EN: kategória';
    js_import_product_data['category_id'] = 'DE: ID kategórie';
var js_import_product_data_no_vat = new Object();
    js_import_product_data_no_vat[''] = '- do not import -';
    js_import_product_data_no_vat['name'] = 'product name';
    js_import_product_data_no_vat['sku'] = 'product code';
    // js_import_product_data_no_vat['price_with_vat'] = 'price with VAT';
    js_import_product_data_no_vat['price_without_vat'] = 'price';
    // js_import_product_data_no_vat['old_price_with_vat'] = 'standard price with VAT';
    js_import_product_data_no_vat['old_price_without_vat'] = 'standard price';
    js_import_product_data_no_vat['s_desc'] = 'short description';
    js_import_product_data_no_vat['desc'] = 'product description';
  //  js_import_product_data_no_vat['is_unsaleable'] = 'product is unsellable';
    js_import_product_data_no_vat['in_stock'] = 'in stock';
    js_import_product_data_no_vat['weight'] = 'weight [kg]';
    js_import_product_data_no_vat['publish'] = 'publish (Y/N)';
    js_import_product_data_no_vat['manufacturer'] = 'manufacturer';
  //  js_import_product_data_no_vat['plength'] = 'length';
  //  js_import_product_data_no_vat['width'] = 'width';
  //  js_import_product_data_no_vat['height'] = 'height';
    js_import_product_data_no_vat['primary_img'] = 'EN: hlavný obrázok';
    js_import_product_data_no_vat['secondary_img'] = 'EN: ďaľšie obrázky';
    js_import_product_data_no_vat['category'] = 'EN: kategória';
    js_import_product_data_no_vat['category_id'] = 'DE: ID kategórie';

var js_import_gui_login = 'Login';
var js_import_gui_pass = 'Password';
var js_import_gui_url_to_login_form = 'Link to registration form';
var js_import_gui_send = 'Go';
var js_import_gui_products = 'Products';
var js_import_gui_categories = 'Categories';
var js_import_gui_users = 'Customers';
var js_import_gui_orders = 'Orders';
var js_import_gui_found_notice = 'Choose which data you wish to import. (Number in parentheses indicates the number of items found.)';
var js_import_gui_welcome_notice = 'Import data';
var js_import_product_main_link_text = 'Import product';


var js_import_product_data_type = new Array();
    js_import_product_data_type[1] = 'If checked, new products from the CSV file will be import, ie that on the list of products not yet exist. If unchecked, new products are not imported.';
    js_import_product_data_type[2] = 'If checked, adjusted to the products, i.e. which are also in e-shop and in CSV. If unchecked these will not be modified';
    js_import_product_data_type[3] = 'If checked, those products which are in the e-shop, but not in the CSV will be "unpublished!. If odčiarknete will be ignored.';

var js_import_product_data_import_type = new Array();
    js_import_product_data_import_type[0] = 'I want to <strong>add products</strong> (the first import, respectively. adding new products to existing)';
    js_import_product_data_import_type[1] = 'I want to <strong>update existing products</strong> (down to select items of existing products, for example. price)';

var js_import_product_choose_tax = 'Select a VAT';
var js_import_product_only_one_tax = 'The product will be added VAT';
var js_import_product_choose_category = 'Select a category';
var js_import_product_choose_start_import = 'Start the import';
var js_import_product_ignore_first_row = 'Ignore first row';
var js_import_product_no_category_notice = 'All impoted products will be imported so that they are not assigned to any category (on the Products page to see them from view the products you choose - without assigning categories -)';

var js_import_product_choose_csv_separator = 'Change CSV delimiter';
var js_import_product_choose_csv_encoding = 'Change encoding';
var js_import_product_reload_csv_from_server = 'Reload csv file';
var js_import_product_show_column_error = 'You can only hide the column with data that you do not wish to import.';
var js_import_product_show_full_file = 'View the full file?';
var js_import_product_cancel = 'Are you sure you want to cancel import this file?';

var js_import_product_import_is_ok = 'Import is alright';
var js_import_product_revert_last_import = 'Cancel import and return data back';

var js_import_product_revert_last_import_intro = new Array();
    js_import_product_revert_last_import_intro[0] = 'Instructions';
    js_import_product_revert_last_import_intro[1] = 'All new imported products are such that they are assigned to any category (in the PRODUCTS tab display them so that you at the top of the filter you view the products "- without assigned category - \', ie you change the filter in" all categories "on" without the associated category). Then you can add the newly added products into categories.';
    js_import_product_revert_last_import_intro[3] = 'Following the final treatment and inclusion of newly added products in the categories they select as published by clicking on the red ring quite right for the one product.)';
    js_import_product_revert_last_import_intro[4] = 'After checking whether the import file %s1 on %s2 ok, please confirm:';
    js_import_product_revert_last_import_intro[5] = 'EN: Všetky aktualizované produkty sú zobrazené v záložke PRODUKTY.';
    js_import_product_revert_last_import_intro[6] = 'EN: tlacidlom sa dostane do zalozky produkty s filtrom nastavenym na zobrazenie vsetkych kategorii';
    js_import_product_revert_last_import_intro[7] = 'EN: Všetky aktualizované produkty, ktoré sú zaradené v kategóriach sú zobrazené v záložke PRODUKTY. Všetky aktualizované produkty, ktoré ešte nie sú zaradené v kategóriach sú zobrazené v záložke PRODUKTY v "- bez priradenej kategórie -".';
    js_import_product_revert_last_import_intro[8] = 'EN: Prejsť do záložky PRODUKTY';
    js_import_product_revert_last_import_intro[9] = 'EN: Prejsť do "- bez priradenej kategórie -" v záložke PRODUKTY';

var js_import_product_revert_last_import_comment_1 = 'Notice: If you confirm the import, the data will not be undone. Imported products but still you can bulk delete and continue again.';
var js_import_product_revert_last_import_comment_2 = 'If the data come back, you have products in the same condition as that before the import.';
var js_import_product_revert_last_import_confirm = 'Are you sure you want to return the data product to its original state before the import of';
var js_import_product_revert_last_import_done = 'State product and the pictures have been restored from backup %s, which was created prior to the import.'

var js_import_product_main_import_status_report = new Array();
    js_import_product_main_import_status_report[0] = 'Import the file %s1 was %s2 successfully processed';
    js_import_product_main_import_status_report[1] = 'Number of records in the imported file';
    js_import_product_main_import_status_report[2] = 'Number of products in e-shop after import';
    js_import_product_main_import_status_report[3] = 'Number of modified products in the e-shop';
    js_import_product_main_import_status_report[4] = 'Unchanged number of products in e-shop';
    js_import_product_main_import_status_report[5] = 'Number of surplus and unpublished products in e-shop';
    js_import_product_main_import_status_report[6] = 'Number of duplicate rows in the import file';
    js_import_product_main_import_status_report[7] = 'Number of new products added to the e-shop';

var js_import_product_help_text_main = new Array();
    js_import_product_help_text_main[0] = 'EN: Poznámky';
    js_import_product_help_text_main[1] = 'EN: Položka "krátky popis" môže obsahovať len 250 znakov, všetky znaky naviac nebudú importované.';
    js_import_product_help_text_main[2] = 'EN: Nevyplnený (prázdny) údaj v položke záznamu sa neimportuje, číselná hodnota "0" sa importuje ako "0".';
    js_import_product_help_text_main[3] = 'EN: V prípade, ak existuje rovnaký kód produktu vo viacerých záznamoch, pri prvom importe sa importuje len prvý záznam s rovnakým kódom produktu, v prípade aktualizácie existujúceho produktu sa importujú údaje vybraných položiek tak ako sú uvedené v poslednom zázname s rovnakým kódom produktu.';
    js_import_product_help_text_main[4] = 'EN: Ak sa súbežne importujú položky "cena/bežná cena bez DPH" a "cena/bežná cena s DPH", pre potreby importu sa vychádza len z položky "cena/bežná cena bez DPH", z ktorej sa vypočíta hodnota aj pre položku "cena/bežná cena s DPH.';
    js_import_product_help_text_main[5] = 'EN: Ak importujete položku kde je stav "ano-nie" (napr. zverejniť produkt), ako "áno" sa chápu  tieto zadané hodnoty: "y, Y, ano, áno, Ano, Áno, 1"';

var js_import_product_help_text_intro = new Array();
    js_import_product_help_text_intro[0] = 'EN: Inštrukcie';
    js_import_product_help_text_intro[1] = 'EN: Pred nahratím CSV súboru si prosím pozrite návod ako importovať dáta, obrázky a kategórie produktov. Návod si môžete stiahnuť tu';
    js_import_product_help_text_intro[2] = 'EN: Tiež si stiahnite a pozrite vzorový CSV súbor tu';
    js_import_product_help_text_intro[3] = 'EN: Pre potreby importu sa zatiaľ bez úprav nedá použiť CSV súbor získaný exportom produktov.';
    js_import_product_help_text_intro[4] = 'EN: V prípade otázok alebo nefunkčnosti importu nám napíšte e-mail alebo zavolajte na tel. č.: +421 908 449 013.';
    js_import_product_help_text_intro[5] = 'CreativeShop_Produkty_Import.pdf';
    js_import_product_help_text_intro[6] = 'SkvelyShop_Produkty_Import.pdf';
    js_import_product_help_text_intro[7] = 'Produkty_Import.csv';

var cms_js_lang_shopper_group_edit_success = 'EN: Skupina bola upravená.';
var cms_js_lang_shopper_group_edit_fail = 'EN: Nepodarilo sa upraviť skupinu!';
var cms_js_lang_shopper_group_duplicity = 'EN: Zadaná skupina už existuje.';
var cms_js_lang_shopper_group_deleted = 'EN: Skupina bola zmazaná.';
var cms_js_lang_shopper_group_name = 'EN: Názov skupiny';
var cms_js_lang_shopper_group_insert_fail = 'EN: Nepodarilo sa pridať novú skupinu.';

var cms_js_lang_shopper_group_delete_message_6 = 'EN: Naozaj chcete zmazať túto skupinu?';
var cms_js_lang_shopper_group_delete_message_0 = 'EN: Skupinu nie je možné zmazať pretože sa používa - v cenách produktov, v zákazníkoch, v spôsoboch platieb, alebo v spôsoboch dodania.';
var cms_js_lang_users_add_user_group_def_text2 = 'EN: Zľava';
var cms_js_lang_users_add_user_group_fill_discount_correctly = 'EN: Celoplošná zľava pre skupinu zákazníkov je nepovinný údaj a môže byť zadaný ako číselná hodnota, vyjadrujúca percentuálnu zľavu.';
var cms_js_lang_shopper_group_delete_message_5 = 'EN: Základnú skupinu "zákazník" nie je možné zmazať.';
var cms_js_lang_shopper_group_discount_tip = 'Celoplošná zľava pre prihlásených zákazníkov patriacich do tejto zákazníckej skupiny. Zľava bude aplikovaná a zobrazovaná pre všetky produkty bez výnimky.';

var cms_js_lang_cfg_product_attrib_products_text = 'products';
var cms_js_lang_cfg_product_attrib_1_product_text = 'product';

var cms_js_lang_cfg_product_new_attrib_def_text = 'Attribute name';
var cms_js_lang_cfg_product_new_attrib_name_error = 'Please enter attribute name.';
var cms_js_lang_cfg_product_new_attrib_name_exists = 'Entered attribute already exists.';

var cms_js_lang_cfg_product_attrib_name_delete_confirm = 'Are you sure you want to delete attribute %s?';
var cms_js_lang_cfg_product_attrib_name_delete_error = 'Before deleting attribute %s you must delete all it\'s values.';
var cms_js_lang_cfg_product_attrib_value_delete_confirm = 'Are you sure you want to delete attribute value %s?';
var cms_js_lang_cfg_product_attrib_value_delete_confirm_2 = 'Are you sure you want to delete attribute value %s1? This value will be deleted from attributes of %s2.';

var cms_js_lang_cfg_product_new_attrib_value_def_text = 'Attribute value';
var cms_js_lang_cfg_product_new_attrib_value_error = 'Please fill in the attribute value.';
var cms_js_lang_cfg_product_new_attrib_value_error_2 = 'Entered value for attribute %s already exists.';

var cms_js_lang_product_attrib_price_help_info = 'Product price editing based on individual attributes:<br/>entered &quot;+&quot; before the amount means: Increase product price by entered amount.<br/>entered &quot;-&quot; before the amount means: Decrease product price by entered amount.<br/>no entered amount means: Price does not change.';

var cms_js_lang_system_cfg_delete_coupons = 'Are you sure you want to delete selected coupons?';

var cms_js_lang_system_cfg_delete_order_state = 'Are you sure to delete selected orders status?';
var cms_js_lang_system_cfg_delete_order_state_delete_notif_default_status = 'This order status can\'t be deleted, because it is necessary to run whole system.';
var cms_js_lang_system_cfg_delete_order_state_delete_notif_has_orders = 'This state is allready in use and therefore cannot be deleted.';
var cms_js_lang_system_cfg_order_state_name_max_length_alert = 'It is not possible to fill in more characters because it reached the maximum length (40 characters).';

var cms_js_lang_system_cfg_delete_countries = 'Are you sure to delete selected states?';

var cms_js_lang_content_header_custom_image_info = 'Some designs are so designed that do not support image input to the header pages.';
var cms_js_lang_content_header_custom_image_upload_stop = 'Design %s which you have currently selected, does not insert a picture in the header pages.';
var cms_js_lang_content_header_custom_image_not_supported_info = 'That also applies to design %s, which you have selected. In case you want to use a custom header image nevertheless please contact us and we will try to help you.';
var cms_js_lang_content_header_custom_image_is_supported_info = 'That however does not apply to design %s1, which you have selected (this design supports header images with heights up to %s2px).';

var cms_js_lang_shopper_list_group = 'EN: Skupina';
var cms_js_lang_product_form_price_net_label = 'EN: bez DPH';
var cms_js_lang_product_form_price_gross_label = 'EN: s DPH';
var cms_js_lang_price_form_mnu = 'EN: Pridať ďalšiu cenu';
var cms_js_lang_other_prices_label = 'EN: Ďalšie ceny';
var cms_js_lang_select_shopper_group = '- EN: vyberte skupinu -';

var cms_js_lang_product_attrib_select = '- select attribute -';
var cms_js_lang_product_attrib_value_select = '- select attribute value -';
//var cms_js_lang_product_attrib_value_error = 'Before adding a value you must select an attribute.';
var cms_js_lang_other_prices_for_shopper_group_label = 'Price for:';
var cms_js_lang_product_add_comb_name_error = 'Please select an attribute.';
var cms_js_lang_product_add_comb_value_error = 'Please select a value of attribute.';

var cms_js_lang_product_attrib_comb_add = 'Add variant';
var cms_js_lang_product_attrib_comb_add2 = 'Add variant combination';
var cms_js_lang_product_attrib_comb_generate = 'Generate combinations';
var cms_js_lang_product_attrib_comb_generate_save = 'Save combinations';
var cms_js_lang_product_attrib_comb_attrib_count_less = 'To create a combination of attributes you have to created 2 attributes at least. Would you like to go into attibutes administration section?';
var cms_js_lang_product_attrib_price_without_vat = 'Price without VAT';
var cms_js_lang_product_attrib_price_with_vat = 'Price with VAT:';
var cms_js_lang_product_attrib_sku = 'Code';
var cms_js_lang_product_attrib_in_stock = 'In stock';
var cms_js_lang_product_attrib_confirm = 'Are you sure you want to delete variant: \n   "%var"\n from product "%prod"?';

var cms_js_lang_overview_test_package_over_2_days_info = '<div><h3>Nejaký nadpis</h3><div class="cleaner">&nbsp;</div></div>';

var cms_adminlang_mod_fullmenu_swe_mediamanag = 'Media Manager';

var cms_js_lang_product_detail_in_stock_label = 'In stock';

var cms_js_lang_product_price_net = 'Product price';

var cms_js_lang_product_list_manual_order_notice = 'Manually ordered products will be ordered according to their shown order in the list.';

var cms_js_lang_cfg_vat_payer_to_non_payer_info = 'Before switching your company from a VAT payer to non VAT payer it is necessary to choose how the price of all products will be calculated.<br/><br/>The price of products of a non VAT payer will be set from:';
var cms_js_lang_cfg_vat_payer_to_non_payer_with_vat = 'existing prices with VAT';
var cms_js_lang_cfg_vat_payer_to_non_payer_without_vat = 'existing prices without VAT';

var cms_js_lang_cfg_non_vat_payer_to_payer_info = 'Before switching your company from a non VAT payer to a VAT payer it is necessary to choose how the price of all products will be calculated.<br/><br/>The price of products of a VAT payer will be set from:';
var cms_js_lang_cfg_non_vat_payer_to_payer_with_vat = 'price with VAT';
var cms_js_lang_cfg_non_vat_payer_to_payer_without_vat = 'price without VAT';

var js_lang_admin_manage_users_switch = new Array();
    js_lang_admin_manage_users_switch['main'] = new Array();
    js_lang_admin_manage_users_switch['main'][0] = 'Manage Administrators';
    js_lang_admin_manage_users_switch['main'][1] = 'Manage Customers';

    js_lang_admin_manage_users_switch['add_new'] = new Array();
    js_lang_admin_manage_users_switch['add_new'][0] = 'Add New customer';
    js_lang_admin_manage_users_switch['add_new'][1] = 'Add New Administrator';

var cms_js_lang_content_editing_content_sef_update_info = 'Updating&hellip;';
var cms_js_lang_content_editing_content_sef_error = 'Please fill out the SEF address.';
var cms_js_lang_content_editing_content_sef_error_2 = 'Filled SEF address is already used. Please type in a different one.';
var cms_js_lang_content_editing_content_sef_error_3 = 'You\'ve filled duplicate SEF addresses.';

var cms_js_lang_content_menu_item_type_url_error = 'Please type in existing URL on your web page.';

var cms_js_lang_content_menu_item_type_content_tooltip = 'A web page (menu item) will be created where you can add content and/or other modules.';
var cms_js_lang_content_menu_item_type_url_tooltip = 'There will be created a link to a content or web page (menu item)';

var cms_js_lang_add_comment_your_name_error = 'Please fill in your name.';
var cms_js_lang_add_comment_your_email_error = 'Bitte geben Sie Ihre E-Mail-Adresse ein.';
var cms_js_lang_add_comment_body_error = 'Please fill in comment\'s body.';
var cms_js_lang_edit_comment_date_error = 'Incorrect date format. The correct format is dd.mm.yyyy hh:mm';

var cms_js_lang_order_status = 'Bestellstatus';
var cms_js_lang_delivery_date = 'Lieferdatum';
var cms_js_lang_error_found = 'Fehler wurde gefunden!';

var cms_js_lang_delete_comment_confirm = 'Wollen Sie diesen Kommentar wirklich löschen?';
var cms_js_lang_delete_comment_error = 'You do not have the permission to delete this comment.';
var cms_js_lang_edit_comment_error = 'You do not have the permission to edit this comment.';
var cms_js_lang_edit_comment_time_left = 'Für die Bearbeitung des Kommentars bleiben <span class="time_left">%s</span>';
var cms_js_lang_edit_commnet_minute = 'Minuten';
var cms_js_lang_edit_commnet_minutes = 'Minuten';
var cms_js_lang_edit_commnet_minutes2 = 'Minuten';
var cms_js_lang_reply_to_comment_opened_error = 'Before creating a reply to this comment it is necessary to close the opened reply to another comment.';

var cms_js_lang_poll_title_error = 'Fill the poll title.';
var cms_js_lang_poll_options_error = 'You have to fill minimum 2 options.';

var cms_js_lang_lm_delete_subsc_group = ' subscriber/s has set this group. Are you sure to remove it?';
var cms_js_lang_lm_fill_all_fields = 'Please fill all fields.';
var cms_js_lang_lm_wrong_email = 'Malformed e-mail address.';
var cms_js_lang_lm_subscribers_required = 'It is necessary to specify the recipient / s newsletter.';
var cms_js_lang_lm_subscribers_group_delete = 'Do you really want to delete a group ';

var cms_js_lang_delete_main_product_img_confirm = 'EN: Naozaj chcete zmazať hlavný obrázok produktu?';
var cms_js_lang_delete_category_img_confirm = 'EN: Naozaj chcete zmazať obrázok kategórie?';
var cms_js_lang_delete_logo_img_confirm = 'EN: Naozaj chcete zmazať logo?';

var cms_js_lang_print_order_file_prefix = 'EN: objednavka_';

var js_lang_read_more = 'Weiterlesen';
var js_lang_read_less = 'Lese weniger';

var cms_js_lang_product_price = 'EN: Cena produktu';
var cms_js_lang_product_old_price = 'EN: Bežná cena';

var cms_js_lang_shipping_start_rate_vs_end_rate_notice = 'EN: Dolná hranica ceny musí byť nižšia ako horná.';
var cms_js_lang_shipping_no_payment_selected = 'EN: Zadajte prosím spôsob pre platby.';

var cms_js_lang_tools_reporting_bugs_url_def_text = '- vložte sem prosím úplnú URL adresu stránky, na ktorej ste chybu zistili -';
var cms_js_lang_tools_reporting_bugs_descr_def_text = '- pokúste sa čo najpresnejšie popísať Vami zistenú chybu -';
var cms_js_lang_tools_reporting_bugs_alert1 = 'Zadajte prosím URL adresu, kde sa chyba vyskytla.';
var cms_js_lang_tools_reporting_bugs_alert2 = 'Zadajte prosím popis Vami zistenej chyby.';
var cms_js_lang_tools_reporting_bugs_alert3 = 'Prajete si odoslať chybové hlásenie?';
var cms_js_lang_tools_reporting_bugs_alert4 = '<p>Ďakujeme Vám za nahlásenie chyby, túto sa pokúsime čo najskôr analyzovať a opraviť.<br /><br />Po jej odstránení Vás budeme informovať e-mailom.</p>';

var cms_js_lang_tools_request_descr_def_text = '- pokúste sa čo najpresnejšie popísať Vašu požiadavku -';
var cms_js_lang_tools_request_alert1 = 'Zadajte prosím popis Vašej požiadavky.';
var cms_js_lang_tools_request_alert2 = 'Prajete si odoslať požiadavku?';
var cms_js_lang_tools_request_alert3 = '<p>Ďakujeme Vám za nahlásenie požiadavky, túto sa pokúsime čo najskôr analyzovať.<br /><br />O možnosti jej realizovania Vás budeme informovať e-mailom.</p>';

var cms_js_lang_product_other_price_valid_msg_01 = 'EN: Chyba v údajoch pre Ďalšie ceny!';
var cms_js_lang_product_other_price_valid_msg_02 = 'EN: <i>Každá ďalšia cena musí mať vybranú <strong>nejakú</strong> Skupinu zákazníkov.</i>';
var cms_js_lang_product_other_price_valid_msg_03 = 'EN: <i>Každá ďalšia cena musí mať vybranú <strong>inú</strong> Skupinu zákazníkov.</i>';
var cms_js_lang_product_form_stock_in_attribs = 'EN: Stav na sklade je nastavený pre atribút';

var cms_js_lang_product_form_availability_price_portal_days_warn = 'The specified number must be an integer.';

var cms_js_lang_nivo_slider_no_dir = 'Enter the directory in the module parameters, please.';

var cms_js_lang_product_form_unit_fill_err = 'Please enter the name of the unit.';

var cms_js_lang_product_form_active_images_select_confirm_1 = 'Would you like to assign this 1 uploaded image to selected active images of product {product_name}?';
var cms_js_lang_product_form_active_images_select_confirm_2_4 = 'Would you like to assign these {img_count} uploaded images to selected active images of product {product_name}?';
var cms_js_lang_product_form_active_images_select_confirm_5 = cms_js_lang_product_form_active_images_select_confirm_2_4;

var cms_js_lang_user_user_search = 'enter user\'s name or e-mail';

js_import_product_data['ean'] = 'ean';
js_import_product_data_no_vat['ean'] = 'ean';
js_import_product_data['product_purchase_price'] = 'purchase price without VAT';
js_import_product_data_no_vat['product_purchase_price'] = 'purchase price without VAT';
js_import_product_data['product_availability'] = 'availability';
js_import_product_data_no_vat['product_availability'] = 'availability';

var cms_js_lang_order_details_check_order_item_quantity_validity_warn = 'Please enter a valid quantity for this item.';

var cms_js_lang_unchanged_order_coupon_discount_alert_msg = 'You have not changed any value for the voucher discount!';
var cms_js_lang_empty_order_coupon_discount_alert_msg = 'You did not enter any value for the voucher discount!';
var cms_js_lang_week = 'Week';
var cms_js_lang_cfg_curr_code_err = 'The field must contain exactly three uppercase symbols.';
var cms_js_lang_cfg_curr_delete_alert = 'Are you sure you want to delete this menu?';

var cms_js_lang_cfg_order_payment_method_q = 'Are you sure you want to send a request for interest on the payment method:\n%s ?\n\n(We contact you and specify arrangements in a short time.)';
var cms_js_lang_cfg_order_payment_method_txt = 'I am interested in the method of payment';
var cms_js_lang_cfg_order_payment_method_sent = 'The request was sent successfully.';

var cms_js_lang_ga_act_confirm = 'EN: Naozaj si prajete zaslať požiadavku pre záujem o modul Google Analytics štatistík?';
var cms_js_lang_ga_problem_confirm = 'EN: Naozaj si prajete zaslať požiadavku o probléme pri aktivovaní modulu Google Analytics štatistík?';
var cms_js_lang_cke_jq_adapter_cms_content = 'Article';
var cms_js_lang_cke_jq_adapter_cms_page = 'Page';
var cms_js_lang_cke_jq_adapter_shop_category = 'Product\'s category';
var cms_js_lang_cke_jq_adapter_shop_product = 'Product';
var cms_js_lang_cke_jq_adapter_enter_product_part = 'Enter the product\'s name';
var cms_js_lang_cke_jq_adapter_enter_product_categ_part = 'Enter the product\'s category name';
var cms_js_lang_cke_jq_adapter_select = 'select';

var cms_js_lang_header_edit_template_save_alert = 'In Design section -> ADMIN PANEL - DESIGN you have selected:\n"{template_name}"\n\nClick the "Use selected design" before adjusting the head.';
var cms_js_lang_header_edit_close_finallize_poshy = 'Changes in the design of the headers have been saved, please check them in the Design section.';
var js_import_product_data_for_shopper_group = ' - ';

var cms_js_lang_GA_manual_header = 'Google Analytics reports problem solving instructions.';
var cms_js_lang_GA_manual_content = ['prihláste sa do svojho Google účtu (účet, na ktorom máte aktivované Google Analytics štatistiky pre Vašu doménu)', 'navštívte stránku <a href="https://www.google.com/accounts/ManageDomains" target="_blank">https://www.google.com/accounts/ManageDomains</a>', 'do sekcie "Add a New Domain" vložte názov domeny (napr. "{js_live_site}"), následne kliknite na "Add domain"', 'v zozname (Manage registration) sa objaví novopridaná doména, kliknutím vojdite do jej úpravy', 'následne choďte na záložku alternatívne spôsoby -> Použite svoj účet služby Google Analytics -> tlačidlo overiť', 'pokračovať -> kliknite na súhlasiť s podmienkami (ToS)', 'v nasledujúcom formulári zadajte pre "Target URL path prefix" URL v tvare:<br/> "http://{js_live_site}/administrator/index2.php?authsub=y"', 'SAVE - následne by vedľa nadpisu v tejto sekcii malo zobraziť (Aktívne)', 'v ďalšej záložke sa prihláste do administrácie e-shopu a "Kliknite pre povolenie", pričom v predchádzajúcej záložke ste stále prihásení do Google Analytics účtu'];
var cms_js_lang_GA_manual_content_finish = 'EN: Následne je možné postupovať podľa video návodu na aktiváciu Google analytics prehľadov.';

var cms_js_lang_module_multilang_dir_tip = 'For viewing in <strong>{langs}</strong> language upload your images to following {dirs_count_title}:<ul><li>{dir_lang_list}</li></ul>';
var cms_js_lang_module_multilang_dir_tip_1_dir = 'folder';
var cms_js_lang_module_multilang_dir_tip_more_dirs = 'folders';
var cms_js_lang_module_multilang_dir_tip_li_temp = '<strong>{dir_name}__{lang_lower}</strong> - for {lang_upper} site version';

var cms_js_lang_cfg_product_new_attrib_value_error_3 = 'Der Wert für das Attribut darf keine Anführungszeichen oder einen Apostroph!';

var cms_js_lang_products_primary_category_out_of_range_text1 = 'URL-Adresse lesbar Produkt wird von Kategorie erstellt \'';
var cms_js_lang_products_primary_category_out_of_range_text2 = '\', jedoch in dem das Produkt ist nicht inbegriffen.\nSo wählen Sie die Registerkarte SEO eine andere Kategorie, bitte.'

var cms_js_lang_order_checkout_payment_need_admin_authorize = 'Um einen Zahlungsauftrag zu genehmigen?';

var cms_js_lang_checkout_unknown_error = '<p>Wahrscheinlich aufgrund einer instabilen Internetverbindung Fehler aufgetreten ist.</p><p>Aktualisieren Sie die Seite und wiederholen Sie die Aktion.</p>';

var cms_js_lang_yes_C = 'Ja';
var cms_js_lang_no_C = 'Nein';

var cms_js_lang_fb_logged_in = 'Die Anmeldung über Facebook war erfolgreich.';
var cms_js_lang_fb_login_link = 'Login über Facebook';

var cms_js_lang_wrong_format_http_301 = 'DE: URL adresy webových stránok musia začínať s "http"';
var cms_js_lang_no_delimiter_301 = 'DE: URL adresy webových stránok musia byť rozdelené bodkočiarkou ";"';
var cms_js_lang_same_uel_on_one_line = 'DE: Počiatočná a cieľová adresa sa zhodujú';
var cms_js_lang_start_to_target_same = 'DE: Cieľová adresa presmerováva na počiatočnú';
var cms_js_lang_open_sef_error = 'OPEN_SEF_ERROR';
var cms_js_lang_system_sef_error = 'SYSTEM_SEF_ERROR';
var cms_js_lang_product_sef_error = 'PRODUCT_SEF_ERROR';
var cms_js_lang_category_sef_error = 'CATEGORY_SEF_ERROR';

var cms_js_lang_error_on_line_num = 'DE: chyba na riadku č. ';

var cms_fill_message = 'Bitte füllen Sie den Nachrichtentext.';

js_import_product_data['product_tax_rate'] = 'VAT rate';

var js_import_product_variants_help_text_intro = new Array();
    js_import_product_variants_help_text_intro[0] = 'EN: Inštrukcie';
    js_import_product_variants_help_text_intro[1] = '';	//	'Pred nahratím CSV súboru si prosím pozrite návod ako importovať dáta variantov produktov. Návod v PDF formáte';
    js_import_product_variants_help_text_intro[2] = 'EN: Formát CSV súboru je: '; 	//	'Tiež si stiahnite a pozrite vzorový CSV súbor';
    js_import_product_variants_help_text_intro[5] = 'EN: &nbsp;&nbsp;&nbsp;(<a href="#" style="font-size:10px" onclick="return js_dipv_toggle_display(\'#help_text_intro_21_show_more\');">zobraziť viac</a>)<br /><span id="help_text_intro_21_show_more" style="display:none;font-size:12px;color:#AAAAAA;margin-top:3px;margin-left:15px">- všetky položky v riadkoch by mali byť uzavreté v úvodzovkách, najmä "Variant",<br />- každý variant má názov a za dvojbodkou uvedenú hodnotu,<br />napr.: "Veľkosť:45",<br />- zložený variant sa skladá z viacerých variantov oddelených bodkočiarkou,<br />napr.: "Veľkosť:45;Farba:červeno-zelená",<br />- žiadny variant nesmie obsahovať znaky hranatých zátvoriek, ani zložených zátvoriek, ani čiarky ( t.j. znaky [ ] { } , ),<br />- žiadna položka v riadku nesmie obsahovať riadiaci znak ukončenia riadku (t.j. "enter"),<br />- nevyplnený (prázdny) údaj v položke riadku sa neimportuje, číselná hodnota "0" sa importuje ako "0",<br />- desatinnú časť číselných hodnôt je najlepšie oddeľovať bodkou.</span>';
    js_import_product_variants_help_text_intro[3] = 'EN: Pre potreby importu sa dá použiť CSV súbor získaný exportom variantov produktov.';
    js_import_product_variants_help_text_intro[4] = 'EN: V prípade otázok alebo nefunkčnosti importu nám napíšte e-mail, radi Vám pomôžeme.';

var js_import_product_variants_data_import_type = new Array();
    js_import_product_variants_data_import_type[0] = 'EN: chcem pridať varianty produktov (prvý import, resp. pridanie nových neexistujúcich variantov)';
    js_import_product_variants_data_import_type[1] = 'EN: chcem aktualizovať existujúce varianty produktov (upravia sa vybrané vlastnosti už existujúcich variantov, napr. cena, zásoba, ...)';

var cms_js_lang_phpshop_product_img_tag_file_name_alert_01 = 'Hochgeladenes Bild hat eine andere Format und Art (zB die original "jpg" oder "bmp"-Datei hat die Endung "jpg", etc.).';

var cms_js_lang_phpshop_gift_added_info = 'Freies Geschenk %gift_name% wurde zu Ihrem Warenkorb hinzugefügt.';

var js_lang_checkout_vhl_map = 'Wählen Sie den Sammelpunkt aus';
var js_lang_checkout_balikovna_map = 'Wählen Sie den Sammelpunkt aus';

var cms_js_lang_phpshop_newsletter_edit_html_code 	= 'DE: Edit HTML code';
var cms_js_lang_phpshop_newsletter_show_preview 	= 'DE: Show newsletter preview';
var cms_js_lang_phpshop_newsletter_save_html_file 	= 'DE: Save HTML file';
var cms_js_lang_phpshop_newsletter_lang_of_export 	= 'DE: Language of export';
var cms_js_lang_phpshop_newsletter_chosen_lang 		= 'DE: Chosen language';
var cms_js_lang_phpshop_newsletter_showed_prods 	= 'DE: showing %num_of_displayed_prods% of %num_of_selected_prods% products.';
var cms_js_lang_phpshop_newsletter_sk_lang 			= 'DE: Slovak';
var cms_js_lang_phpshop_newsletter_cz_lang 			= 'DE: Czech';
var cms_js_lang_phpshop_newsletter_pl_lang 			= 'DE: Polish';
var cms_js_lang_phpshop_newsletter_hu_lang 			= 'DE: Hungarian';
var cms_js_lang_phpshop_newsletter_ro_lang 			= 'DE: Romanian';
var cms_js_lang_phpshop_newsletter_auto_code_save	= 'DE: Changes in code are saved automatically.';

var cms_js_lang_only_gift_product = 'Dieses Produkt ist nicht zum Verkauf getrennt, und ist so konzipiert, um Geschenke zu funktionieren.';
var cms_js_lang_free_gift = 'Freies_Geschenk';
var cms_js_lang_free_gift_text = 'Freies_Geschenk';
var cms_js_lang_supplier_order_number_entry_search = 'DE: zadajte číslo dod. obj.';

var js_lang_phpshop_product_unavailable = 'Verkauf ende';

var js_lang_osch_confirm_order_text = 'Sind Sie sicher, dass Sie Ihre Bestellung bestätigen möchten?';
var cms_js_duplicity = 'Der eingegebene Wert ist ein Duplikat.';

var cms_js_image = "Bild";
var cms_js_txtOf = 'von';
var cms_js_prev = 'Vorig';
var cms_js_next = 'Nächster';

var cms_js_lang_phpshop_zasilkovna_alert_sel = 'Please select pickup point for your delivery';

var js_lang_product_attribute_unavailable = 'Das Produkt  in der Variante "{variant}: {value}" ist leider nicht verfügbar. Suchen Sie bitte eine verfügbare Variante aus. Es tut uns leid.';

var js_lang_dynamic_attributes_modify_item = 'Editing an item that is already in your cart.';
var js_lang_dynamic_attributes_duplicate_item = 'Now you can change attributes and click buy.';
var js_lang_dynamic_attributes_new_item = 'New item';
var js_lang_dynamic_attributes_copy = 'Modify';
var js_lang_dynamic_attributes_duplicate = 'Duplicate';
var js_lang_dynamic_attributes_delete = 'Delete';
var js_lang_dynamic_attributes_min_alert = 'The minimum value for this field is';
var js_lang_dynamic_attributes_max_alert = 'The maximum value for this field is';
var js_lang_dynamic_attributes_field_required = 'The value for this field is required';

var cms_js_lang_phpshop_order_item_edit = 'Edit order item';
var cms_js_lang_phpshop_order_item_edit_err1 = 'New item can not be added because the order already has another item with the same code (or attributes) of item!';
var cms_js_lang_phpshop_order_item_edit_err2 = 'New item can not be added, because the stock control is turned on. The highest possible order count is';
var cms_js_lang_phpshop_order_item_edit_err3 = 'New item can not be added because you specified an empty (zero) number!';

var js_lang_checkout_speedup_process_speed_up = 'Sie haben bereits bei uns gekauft';
var js_lang_checkout_speedup_process_logg_in = 'und können sich anmelden';
var js_lang_checkout_speedup_process_speed_up_two = 'und beschleunigen Sie ihre daten füllen, oder sie können';
var js_lang_checkout_speedup_process_1 = 'und beschleunigen Sie ihre daten füllen';
var js_lang_checkout_speedup_process_fastcheckout = 'kauf ohne registrierung';
var js_lang_checkout_speedup_process_2 = 'oder sie können';
var js_lang_checkout_speedup_process_forgot_password = 'erhole dein vergessenes passwort';
var js_lang_checkout_speedup_email_was_send = "Die Bestätigungs-E-Mail wurde an Ihre angegebene E-Mail-Adresse gesendet.";

var js_lang_sphf_remove_all_filters = 'Alle Filter entfernen';
var js_lang_sphf_filter_active = 'Aktivfilter:';
var js_lang_sphf_more_results = 'Mehr';
var js_lang_sphf_less_results = 'Weniger';
var js_lang_sphf_no_results = 'Keine Resultate';
var js_lang_sphf_show = 'Anzeige';
var js_lang_sphf_found1 = 'Gefunden';
var js_lang_sphf_found2 = 'Gefunden';
var js_lang_sphf_found3 = 'Gefunden';
var js_lang_sphf_result_1 = 'ergebnis';
var js_lang_sphf_result_2 = 'ergebnisse';
var js_lang_sphf_result_3 = 'ergebnisse';
var js_lang_sphf_pag_next = 'Anzeigen weiter {+}';
var js_lang_sphf_pag_next1 = 'Anzeigen weiter {+}';
var js_lang_sphf_pag_next2 = 'Anzeigen weiter {+}';
var js_lang_sphf_pag_next3 = 'Anzeigen weiter {+}';
var js_lang_sphf_pag_last = 'Zeige die letzten {+}';
var js_lang_sphf_pag_last1 = 'Zeige die letzten {+}';
var js_lang_sphf_pag_last2 = 'Zeige die letzten {+}';
var js_lang_sphf_pag_last3 = 'Zeige die letzten {+}';

var js_lang_one_step_checkout_company_warning_title = 'Warnung';
var js_lang_one_step_checkout_company_warning_input = 'Sie haben Unternehmensdaten abgeschlossen, aber ich werde als Privatperson zu kaufen. Wollen Sie weitermachen?';
var js_lang_one_step_checkout_company_warning_button_yes = 'Kaufen Sie als Privatperson ';
var js_lang_one_step_checkout_company_warning_button_no = 'Stornieren';

var js_lang_one_step_checkout_tos_price_offer_lbl = 'Request a quote';

var js_lang_order_flag_set_wait = 'Bitte warten';

var js_lang_manage_account = 'Kontoverwaltung';
var js_lang_account_logout = 'Ausloggen';
var js_registration_url = '/register/';
var js_lang_email_did_you_mean = 'Meintein Sie: :suggestion?';

var js_lang_prof_select_offer = 'Please check at least one offer';
var js_lang_prof_select_variant = 'Please select the variant of ticked offer';
var js_lang_prof_select_main_variant = 'Please select product variant';
var js_lang_prof_show_more = 'Show more gifts';
var js_lang_prof_show_less = 'Show less';
var js_lang_prof_free = 'Kostenlos';
var js_lang_set_not_avail = 'Einige der Produkte in einem Satz ist nicht verfügbar auf Lager.';

var js_lang_prod_slick_show_more = 'Alle anzeigen';
var js_lang_prod_slick_show_less = 'Zeigen Sie auf Linie';

var js_lang_back_btn_lbl = 'Zurück zur ';

var cms_js_lang_add_comment_success = 'Your question has been successfully submitted';
var cms_js_lang_add_review_success = 'Your review has been successfully added';

var js_lang_shopping_cart_empty_confirm = 'Möchten Sie Ihren Einkaufswagen wirklich leeren?';
var js_lang_product_has_been_to_cart = 'Das Produkt wurde in den Warenkorb gelegt';


// GDPR
var js_gdpr_tooltip = "Your consent to the processing of your personal data is necessary.";
var js_newsletter_tooltip = "Durch Markierung des Kästchens erteile ich mit dem Betreiber die Einwilligung, die von mir angegebenen persönlichen Daten <br>zum Versenden des Newsletters zu verarbeiten, und bestätige gleichzeitig, dass ich mit den Regeln für die Verarbeitung <br>personenbezogener Daten, die im Abschnitt „Verarbeitung personenbezogener Daten“ dieser Seite aufgeführt sind, vertraut bin.";
var js_gdpr_agree_to_gdpr = "Your consent to the processing of your personal data is necessary.";

var js_gdrp_agree_info_0 = "I acknowledge the";
var js_gdrp_agree_info_1 = " terms and conditions";
var js_gdrp_agree_info_2 = " and take note of the";
var js_gdrp_agree_info_3 = " processing of my personal data.";

var js_lang_availability = 'Availability';

var js_shop_cart_quantity = 'Anzahl';
var js_shop_flypage_lbl = 'Produkt Detail';

var js_all_categories = 'Alle Kategorien';
var js_close_categories = 'Kategorien schließen';

var js_lang_shopping_cart_delete_item_confirm = 'Möchten Sie das Produkt wirklich aus dem Warenkorb entfernen?';

var js_lang_wishlist_item_delete = 'Produkt von der Wunschliste löschen';
var js_lang_wishlist_in_wishlist = 'Das Produkt ist bereits in der Wunschliste';

var cms_js_lang_credit_note_next_no_err = 'Credit note with the specified number already exists. Enter the other one.';
var js_lang_my_account = 'Mein Konto';

var js_lang_finstat_info_message = 'Geben Sie hier Ihren Firmennamen oder Ihre Firmen-ID ein, und wir werden automatisch Ihre Rechnungsinformationen für Ihr Unternehmen vervollständigen.';
var js_lang_finstat_info_fill_message = 'Geschäftsdaten wurden erfolgreich abgeschlossen.';
var js_lang_google_places_info_message = 'Start typing, address autocompletion is active.';
var GDPR_EMAIL_ADDED = "Ihre E-Mail-Adresse wurde zu unserem Newsletter-Abonnement hinzugefügt";
var GDPR_EMAIL_REMOVED = 'Ihre E-Mail wurde aus dem Abonnement-Newsletter entfernt.';
var GDPR_NO_EMAIL = 'Ihre E-Mail Adresse ist nicht angegeben';
var ACC_VOUCHER_EMAIL_NOT_VALID = 'Ungültige E-Mail-Adresse.';
var GDPR_EMAIL_SEND2 = "Ihre Bestätigungs-E-Mail wurde bereits an Ihre E-Mail-Adresse gesendet.";
var GDPR_NO_ACCEPTED = "Ihre Zustimmung zur Verarbeitung personenbezogener Daten ist erforderlich.";
var GDPR_EMAIL_QUESTION = "Möchten Sie den Newsletter wirklich abbestellen?";
var GDPR_EMAIL_SEND = "Eine Bestätigungs-E-Mail wurde an Ihre E-Mail-Adresse gesendet.";
var LM_SAME_EMAIL_TWICE = "Die von Ihnen eingegebene E-Mail-Adresse ist bereits im Newsletter verzeichnet.";
var LM_FORM_NOEMAIL = "Bitte geben Sie eine gültige E-Mail-Adresse ein.";

var js_lang_time_day_1 = 'day';
var js_lang_time_day_more = 'days';
var js_lang_time_day_more_2 = 'days';

var js_lang_time_hours_1 = 'Stunde';
var js_lang_time_hours_2_4 = 'Stunden';
var js_lang_time_hours_more = 'Stunden';

var js_lang_time_minutes_1 = 'Minute';
var js_lang_time_minutes_2_4 = 'Minuten';
var js_lang_time_minutes_more = 'Minuten';

var js_lang_time_seconds_1 = 'Sekunde';
var js_lang_time_seconds_2_4 = 'Sekunden';
var js_lang_time_seconds_more = 'Sekunden';

var js_lang_max_product_stock_per_order = '(max. {stock}er Bestellung)';

var cms_js_lang_mod_category_title_img = 'Modulbild';
var cms_js_lang_mod_category_title_desc = 'Kategoriebeschreibung';

var js_lang_checkout_vat_valid = 'gültige Umsatzsteuer-Identifikationsnummer';
var js_lang_checkout_vat_valid_with_zero_vat = 'gültige Mehrwertsteuer - kaufen Sie beim Kauf aus dem Ausland ohne Mehrwertsteuer';
var js_lang_checkout_vat_invalid = 'ungültige Umsatzsteuer-Identifikationsnummer';
var js_lang_checkout_vat_unavail = 'Ihre Umsatzsteuer-Identifikationsnummer kann nicht überprüft werden';
var js_lang_new_form_item = 'Eintrag';
var js_lang_new_form_nesessery = 'ist obligatorisch';
var js_lang_new_form_nesessery_item = 'Dieser Artikel ist erforderlich.';
var cms_js_lang_checkout_street_validation_error = 'Fügen Sie eine beschreibende Nummer hinzu';

// sprava uctu 2.0
var js_lang_account_index_datatable_orders_sSearch = 'Goods name, order number, invoice . . .';
var js_lang_account_index_datatable_orders_sLengthMenu = 'Displayed on page: _MENU_';
var js_lang_account_index_datatable_orders_sInfo = 'Displayed _START_-_END_ of _TOTAL_ orders';
var js_lang_account_index_datatable_products_sInfo = 'Displayed _START_-_END_ of _TOTAL_ products';
var js_lang_account_index_allowed_products_export_tooltip = 'At least one child must be selected for export';
var js_lang_account_index_allowed_products_clear_tooltip = 'At least one child must be selected for deletion';
var js_lang_account_index_repeat_order = 'Repeat order';
var js_lang_account_index_product_no_exists = 'Product is no longer available';

var js_admin_lang_complete_before_leave_warning = 'Please complete and save previous edits first.';

// NSU
var js_lang_nsu_phone_valid_error = 'Zulässig sind nur die Zeichen "0-9", "+", "-" und "/"';
var js_lang_nsu_ico_valid_error = 'Zulässig sind nur die Zeichen "0-9"';
var js_lang_nsu_default_address_add_rly = 'Wollen Sie wirklich die Anschrift %adress_name% voreinstellen?';
var js_lang_nsu_default_address_checkbox_hover = 'Die erste Lieferadresse muss voreingestellt sein';
var js_lang_nsu_default_address_successfully_changed = 'Die Lieferadresse %adress_name% wurde voreingestellt';
var js_lang_nsu_default_address_remove_error = 'Die voreingestellte Anschrift kann nicht gelöscht werden.';
var js_lang_nsu_delete_shipping_address_rly = 'Wollen Sie diese Lieferadresse wirklich löschen?';
var js_lang_nsu_delete_shipping_address_rly_alone_default = 'Die Lieferadresse ist voreingestellt.<br>Wollen Sie sie wirklich löschen?';
var js_lang_nsu_next_page = 'Nächste Seite';
var js_lang_nsu_orders_multi_purchased_products = 'Bestellungen mit ';
var js_lang_nsu_delete_watchdog_rly = 'Verfolgung dieses Produkts wirklich beenden?';
var js_lang_nsu_credits_not_allowed_amount_error = 'Das niedrigste Guthaben, das übertragen werden kann, ist +1 Punkt.';
var js_lang_nsu_credits_low_amount_error = 'Das höchste Guthaben, das übertragen werden kann, sind %s Punkte.';
var js_lang_nsu_credits_update_rly = 'Wollen Sie wirklich ein Guthaben in Höhe von %credit% Punkten auf den Benutzer %user% übertragen?';
var js_lang_nsu_donate_credit_valid_error = 'Zulässig ist ein Wert von 1 bis %credit%';
var js_lang_nsu_no_product_results = 'Es wurden keine eingekauften Produkte gefunden.';
var js_lang_nsu_no_saved_cart_results = 'No saved baskets were found.';
var js_lang_nsu_saved_cart_load = 'Activate saved basket';
var js_lang_nsu_saved_cart_delete = 'Delete saved basket';
var js_lang_nsu_saved_cart_load_modal_title = 'Saved cart - %_SAVED_CART_NAME_%';
var js_lang_nsu_saved_cart_load_modal_msg = 'Do you wish to add products to your cart and keep the saved basket for any reuse?';
var js_lang_nsu_saved_cart_load_modal_btn_1 = 'Fill and leave';
var js_lang_nsu_saved_cart_load_modal_btn_2 = 'Fill and remove';
var js_lang_nsu_saved_cart_delete_modal_title = 'Saved cart - %_SAVED_CART_NAME_%';
var js_lang_nsu_saved_cart_delete_modal_msg = 'Do you really want to delete the saved basket called "%_SAVED_CART_NAME_%"?';
var js_lang_nsu_saved_cart_delete_success = 'The saved basket has been erased';
var js_lang_nsu_saved_cart_delete_error = 'The saved basket failed to delete';
var js_lang_nsu_datatable_orders_sSearch = 'Warenbezeichnung, Bestellnummer, Rechnung...';
var js_lang_nsu_datatable_orders_sLengthMenu = 'Anzeigen auf der Seite: _MENU_';
var js_lang_nsu_datatable_orders_sInfo = '_START_-_END_ von _TOTAL_ Bestellungen angezeigt';
var js_lang_nsu_datatable_products_sInfo = '_START_-_END_ von _TOTAL_ Produkten angezeigt';
var js_lang_nsu_pw_too_short = 'Zu kurz (min. 6 Zeichen)';
var js_lang_nsu_pw_too_short_hint = 'Ein zu kurzes Passwort umfasst weniger als 6 Zeichen.';
var js_lang_nsu_pw_weak = 'Schwach';
var js_lang_nsu_pw_weak_hint = 'Ein schwaches Passwort besteht aus weniger als 8 Zeichen und nicht aus Groß- und Kleinbuchstaben sowie Zahlen';
var js_lang_nsu_pw_medium = 'Durchschnittlich';
var js_lang_nsu_pw_medium_hint = 'Ein durchschnittliches Passwort besteht aus weniger als 12 Zeichen und nicht aus Groß- und Kleinbuchstaben sowie Zahlen.';
var js_lang_nsu_pw_strong = 'Stark';
var js_lang_nsu_customer_password_strength = '<strong>Erklärung des Begriffs "Starkes Passwort":</strong><br /><br /><strong>"Ein zu kurzes"</strong> Passwort umfasst weniger als 6 Zeichen.<br /><strong>"Ein starkes"</strong> Passwort besteht aus mindestens 12 Zeichen sowie aus Groß- und Kleinbuchstaben und aus Zahlen.<br /><strong>"Ein durchschnittliches"</strong> Passwort besteht aus mindestens 8 Zeichen, aus Groß- und Kleinbuchstaben oder aus Großbuchstaben und Zahlen oder aus Kleinbuchstaben und Zahlen.<br /><strong>"Ein schwaches"</strong> Passwort ist in einem Parameter schwächer als ein „durchschnittliches“ Passwort.';
var js_lang_nsu_new_form_nesessery_item = 'Pflichtfeld.';
var js_lang_nsu_lm_wrong_email = 'Falsches Format der E-Mail-Adresse.';
var js_lang_nsu_customer_password_notmatched = 'Die Passwörter sind nicht identisch.';
var js_lang_nsu_product_no_exists = 'Das Produkt ist nicht mehr verfügbar';
var js_lang_nsu_datatable_wishlist_sEmptyTable = 'Ihre Wunschliste ist derzeit leer';
var js_lang_nsu_no_wishlist_product_results = 'Es wurden keine Produkte aus der Wunschliste gefunden:';
// NSU

var js_lang_product_attachment_info = 'Upload the design file you want to print to the product in .pdf or .zip format';

var js_lang_show_more = 'Zeig mehr';
var js_lang_show_less = 'Zeige weniger';

var js_lang_show_filter = 'Filter anzeigen';
var js_lang_show_full_filter = 'Vollständigen Filter anzeigen';
var js_lang_hide_filter = 'Filter ausblenden';

var csm_js_lang_pw_strength = 'Password strength';
var cms_js_lang_pw_too_short = 'Too short (6 characters minimum)';
var cms_js_lang_pw_weak = 'Weak';
var cms_js_lang_pw_medium = 'Average';
var cms_js_lang_pw_strong = 'Strong';

var js_lang_phpshop_product_details_watchers = '<span>1</span> Kunden besichtigen';
var js_lang_phpshop_product_details_watchers_2 = '<span>1</span> Kunden besichtigen';
var js_lang_phpshop_product_details_watchers_5 = '<span>1</span> Kunden besichtigen';

var js_lang_action_estimated  = 'Action remaining time';
var js_lang_action_expired = 'The action is over';

var cms_js_lang_instagram_img_num_display = 'Number of images displayed';
var js_lang_new_pickupdate_rule = 'Der frühestmögliche Termin ist ca. 2 Werktage';

var js_lang_instagram_users = 'Users';
var js_lang_instagram_no_users = 'No user';
var js_lang_show_only_default_vv = 'Show only default virt. variants';

var js_watch_stock_attr_error_msg = 'Sie müssen eine der Größenoptionen auswählen.';

var cms_js_lang_more = 'mehr';
var cms_js_lang_less = 'weniger';
var cms_js_lang_updated = 'Aktualisiert';
var cms_js_iterate_notfound = 'Your search returned no results.';
var cms_js_lang_claim_choose_product = 'Choose product';

var js_add_to_cart_as_inquiry = 'Add to cart as inquiry';

var js_lang_registration_reset_password_email_already_sent = 'A password change verification email has already been sent for the email you entered. Check your inbox.';
var js_lang_registration_reset_password_email_sent = 'A verification email has been sent to the email address you entered. Follow the instructions in the email.';
var js_lang_registration_reset_password_password_changed = 'Password has been changed successfully. From now on, you can log in with your new password.';
var js_lang_registration_reset_password_password_changed_continue = 'Continue by auto-login';
var js_lang_registration_reset_password_field_required = 'Field is required';
var js_lang_registration_reset_password_passwords_dont_match = 'Passwords don\'t match';
var js_lang_registration_reset_password_password_too_short = 'Password too short';

var js_lang_one_step_checkout_company_tin_expected_format = 'Expected format';

var js_lang_product_variant_out_of_stock_info = 'Out of Stock';

var js_lang_admin_media_dropzone_hint = 'Drop files here to upload';
var js_lang_admin_media_dropzone_fallback_message = 'Your browser does not support drag\'n\'drop file uploads';
var js_lang_admin_media_dropzone_invalid_filetype = 'you can\'t upload files of this type';
var js_lang_admin_media_dropzone_file_too_big = 'file is too big';
var js_lang_admin_media_dropzone_response_error = 'server upload error';
var js_lang_admin_media_dropzone_too_many_files = 'Unauthorized number of files';
var js_lang_admin_media_dropzone_upload_cancel = 'File upload canceled';
var cms_dropzone_drop_images_here = 'Drop image here to upload';
var cms_dropzone_remove_file = 'Remove';

var js_lang_town = "Stadt";
var js_lang_company = "Unternehmen";
var js_lang_country = "Land";
var js_lang_zip = "PLZ";
var js_lang_name = "Vorname";
var js_lang_surname = "Nachname";
var js_lang_middle_name = "Zweiter Vorname";
var js_lang_state = "Zustand";
var js_lang_title = "Titel";
var js_lang_phone = "Telefonnummer";
var js_lang_phone_2 = "Telefonnummer 2";
var js_lang_address_type = "Adresstyp";
var js_lang_address_type_bt = "Rechnungsadresse";
var js_lang_address_type_st = "Lieferanschrift";
var js_lang_address = "Adresse";
var js_lang_address_2 = "Adresse 2";

var js_gdpr_personal_data_title = 'Auflistung personenbezogener Daten';
var js_gdpr_personal_gdpr_approval_title = 'Einwilligung in die Verarbeitung personenbezogener Daten';
var js_gdpr_empty_data = 'Wir registrieren keine Genehmigung';

// GDPR Zakaznik
var js_gdpr_copy = 'Kopieren Sie die GDPR-Version des Artikels';
var js_gdpr_version = 'Version des GDPR-Artikels';
var js_gdpr_version_title = 'Version des GDPR-Artikels';
var js_gdpr_cdate = 'Datum der Zustimmung';
var js_gdpr_form_id = 'Ort der Genehmigung';
var js_gdpr_version_title_head = 'Version des GDPR-Artikels';
var js_gdpr_cdate_title_head = 'Datum der Zustimmung';
var js_gdpr_form_id_title_head = 'Ort der Genehmigung';

var js_gdpr_register_form = 'Anmeldeformular';

var js_universal_contact_form_suc_alert = "Email was send.";

var js_gdpr_watch_dog = 'Watch dog';
var js_gdpr_send_to_friend = 'Email a friend';
var js_gdpr_product_question = 'Product question';
var js_gdpr_contact_form = 'Kontakt Formular';
var js_gdpr_module_newsleatter = 'Modul Newsletter';
var js_gdpr_module_short_contact_form = 'Module with contact form';
var js_gdpr_module_contest_form = 'Module competition';
var js_gdpr_checkout = 'Auschecken';
var js_gdpr_dt_form = 'A tailor-made form';
var js_gdpr_unknown = "Unknown";
var js_gdpr_comment = 'Comment';
var js_gdpr_product_best_price = 'Did you find a better price?';
var js_gdpr_first_login = 'Prvé prihlásenie';

var js_gdpr_article_copy = "Der Artikel wurde in die Zwischenablage kopiert (mit Strg + V, in der Sie es an einem anderen Ort setzen)";

var js_lang_checkout_loader_initial = 'Wird bearbeitet...';
var js_lang_checkout_loader_intermediate = 'Bitte haben Sie Geduld...';
var js_lang_checkout_loader_final = 'Moment mal...';

var js_lang_payment_loader_delay_text = 'Bitte warten Sie, das Zahlungsgateway öffnet sich für die Zahlung...';

var js_lang_product_available_again = 'Voraussichtlich wieder lieferbar ab: ';
var cms_js_lang_add_comment_captcha_error = 'Defekter bestätigungscode.';

var js_lang_tin_number = 'StNr.';

var js_lang_saving_price_label = 'Du sparst';

var js_lang_multiple_packages_1 = 'package';
var js_lang_multiple_packages_2 = 'packages';
var js_lang_multiple_packages_3 = 'packages';

var js_lang_product_detail_delivery_date_tomorrow = 'morgen';
var js_lang_product_detail_delivery_date_deliver_by_1 = 'Wir liefern nach';
var js_lang_product_detail_delivery_date_deliver_by_2 = 'Wir liefern ein';

var js_lang_measure_unit_pcs = 'Stck';

var js_lang_edit_label = 'Anpassen';

var js_lang_contact_form = {
    gdpr: "Sie müssen den Bedingungen für die Verarbeitung personenbezogener Daten zustimmen"
};

const js_langs = {
    plugins: {
        chosen: {
            placeholder_text_multiple: 'Select values',
            placeholder_text_single: 'Select value',
            placeholder_text: 'Select value',
            no_results_text: 'No results found for',
            create_option_text: 'Create option'
        }
    },
    frontend: {
        checkout: {
            errors: {
                subscriptionRequiredBeforeCheckout: 'Before proceeding with the purchase, you need to have an active subscription.',
                maximumPurchasedProductsForUserReached: 'You have exceeded the purchase limit, you can still buy in a total quantity of #_VALID_PURCHASE_QUANTITY_#',
                maximumOrdersForUserReached: 'You have exceeded the limit of orders, please try again later.',
            }
        },
    }
};

var js_lang_api_dpd = {
    dpdWidget: {
        defaultOption: 'Standort auswählen',
        selectParcelShop: 'Bitte wählen Sie den Pickup Standort aus'
    }
};

var js_lang_modal_after_add_to_cart_vex_title = 'Der Artikel wurde in den Warenkorb gelegt';
var js_lang_checkout_payment_avail_btn_yes = 'I agree';
var js_lang_checkout_payment_avail_btn_no  = 'Back';
var js_lang_checkout_payment_avail_msg = 'In a short time we will inform you about the availability of goods.';

var js_lang_gift_free_title = 'Gratis-Geschenk - Es fehlen noch Einkäufe im Wert von';
var js_lang_gift_free_enabled = 'Sie haben ein Gratis-Geschenk.';

var js_lang_batch_code = 'Batch code';
var js_lang_batch_code_expiration = 'Expiration';


/* ========================================
 FILE: /sub/robel.sk/language/js/austrian-german.js
 ==================== */

var js_cart_select_item = 'Bitte Größe wählen.';
var js_lang_sphf_pag_next = 'Anzeigen weitere {+}';
var js_lang_sphf_pag_next1 = 'Anzeigen weitere {+}';
var js_lang_sphf_pag_next2 = 'Anzeigen weitere {+}';
var js_lang_sphf_pag_next3 = 'Anzeigen weitere {+}';

/* ========================================
 FILE: /includes/js/state-management-lib/state.min.js
 ==================== */

var initState=function(){function a(b){var c=Object.getOwnPropertyNames(b);return c.map(function(c){if(b.hasOwnProperty(c)){var d=b[c];d&&"object"==typeof d&&a(d)}}),Object.freeze(b)}function b(a){return"object"==typeof a?Object.assign({},a):{}}function c(b){return function(c){var d=Object.assign({},b);return"string"==typeof c?"undefined"==typeof d[c]?null:a(d[c]):a(d)}}function d(a,b){return function(c,d){"string"!=typeof c||(b("stateWillChange",{key:c,value:d}),a[c]=d,b("stateDidChange",{key:c,value:d}))}}function e(a,b){return function(c,d,e){return Array.isArray(e)||(e=[]),a[c]=a[c]||[],a[c].push({listener:d,dependencies:e,once:b}),this}}function f(a){return function(b,c){return a[b]||a[b].length?c?(a[b]=a[b].filter(function(a){return a.listener!==c}),this):(delete a[b],this):this}}function g(a){return function(b,c){return a[b]&&a[b].length?(a[b]=a[b].filter(function(a){return a.dependencies.length&&(c=c||{},-1===a.dependencies.indexOf(c.key))?this:(a.listener(c),!a.once)}),this):this}}return"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(a){if(null==a)throw new TypeError("Cannot convert undefined or null to object");for(var b,c=Object(a),d=1;d<arguments.length;d++)if(b=arguments[d],null!=b)for(var e in b)Object.prototype.hasOwnProperty.call(b,e)&&(c[e]=b[e]);return c},writable:!0,configurable:!0}),function(a){var h=b(a),i={};return{getState:c(h),setState:d(h,g(i)),once:e(i,!0),on:e(i,!1),off:f(i),trigger:g(i)}}}();

/* ========================================
 FILE: /includes/js/state-management-lib/globalState.min.js
 ==================== */

var globalState=initState();

/* ========================================
 FILE: /includes/js/jquery/core/jquery-3.7.1.min.js
 ==================== */

/*! jQuery v3.7.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(ie,e){"use strict";var oe=[],r=Object.getPrototypeOf,ae=oe.slice,g=oe.flat?function(e){return oe.flat.call(e)}:function(e){return oe.concat.apply([],e)},s=oe.push,se=oe.indexOf,n={},i=n.toString,ue=n.hasOwnProperty,o=ue.toString,a=o.call(Object),le={},v=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},y=function(e){return null!=e&&e===e.window},C=ie.document,u={type:!0,src:!0,nonce:!0,noModule:!0};function m(e,t,n){var r,i,o=(n=n||C).createElement("script");if(o.text=e,t)for(r in u)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[i.call(e)]||"object":typeof e}var t="3.7.1",l=/HTML$/i,ce=function(e,t){return new ce.fn.init(e,t)};function c(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!v(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}function fe(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}ce.fn=ce.prototype={jquery:t,constructor:ce,length:0,toArray:function(){return ae.call(this)},get:function(e){return null==e?ae.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=ce.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return ce.each(this,e)},map:function(n){return this.pushStack(ce.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(ae.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(ce.grep(this,function(e,t){return(t+1)%2}))},odd:function(){return this.pushStack(ce.grep(this,function(e,t){return t%2}))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:s,sort:oe.sort,splice:oe.splice},ce.extend=ce.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||v(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(ce.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||ce.isPlainObject(n)?n:{},i=!1,a[t]=ce.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},ce.extend({expando:"jQuery"+(t+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==i.call(e))&&(!(t=r(e))||"function"==typeof(n=ue.call(t,"constructor")&&t.constructor)&&o.call(n)===a)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t,n){m(e,{nonce:t&&t.nonce},n)},each:function(e,t){var n,r=0;if(c(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},text:function(e){var t,n="",r=0,i=e.nodeType;if(!i)while(t=e[r++])n+=ce.text(t);return 1===i||11===i?e.textContent:9===i?e.documentElement.textContent:3===i||4===i?e.nodeValue:n},makeArray:function(e,t){var n=t||[];return null!=e&&(c(Object(e))?ce.merge(n,"string"==typeof e?[e]:e):s.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:se.call(t,e,n)},isXMLDoc:function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!l.test(t||n&&n.nodeName||"HTML")},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(c(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g(a)},guid:1,support:le}),"function"==typeof Symbol&&(ce.fn[Symbol.iterator]=oe[Symbol.iterator]),ce.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var pe=oe.pop,de=oe.sort,he=oe.splice,ge="[\\x20\\t\\r\\n\\f]",ve=new RegExp("^"+ge+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ge+"+$","g");ce.contains=function(e,t){var n=t&&t.parentNode;return e===n||!(!n||1!==n.nodeType||!(e.contains?e.contains(n):e.compareDocumentPosition&&16&e.compareDocumentPosition(n)))};var f=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;function p(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e}ce.escapeSelector=function(e){return(e+"").replace(f,p)};var ye=C,me=s;!function(){var e,b,w,o,a,T,r,C,d,i,k=me,S=ce.expando,E=0,n=0,s=W(),c=W(),u=W(),h=W(),l=function(e,t){return e===t&&(a=!0),0},f="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",t="(?:\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",p="\\["+ge+"*("+t+")(?:"+ge+"*([*^$|!~]?=)"+ge+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+t+"))|)"+ge+"*\\]",g=":("+t+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+p+")*)|.*)\\)|)",v=new RegExp(ge+"+","g"),y=new RegExp("^"+ge+"*,"+ge+"*"),m=new RegExp("^"+ge+"*([>+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\([^\\r\\n\\f])","g"),P=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},M=function(){V()},R=J(function(e){return!0===e.disabled&&fe(e,"fieldset")},{dir:"parentNode",next:"legend"});try{k.apply(oe=ae.call(ye.childNodes),ye.childNodes),oe[ye.childNodes.length].nodeType}catch(e){k={apply:function(e,t){me.apply(e,ae.call(t))},call:function(e){me.apply(e,ae.call(arguments,1))}}}function I(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(V(e),e=e||T,C)){if(11!==p&&(u=L.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return k.call(n,a),n}else if(f&&(a=f.getElementById(i))&&I.contains(e,a)&&a.id===i)return k.call(n,a),n}else{if(u[2])return k.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&e.getElementsByClassName)return k.apply(n,e.getElementsByClassName(i)),n}if(!(h[t+" "]||d&&d.test(t))){if(c=t,f=e,1===p&&(x.test(t)||m.test(t))){(f=H.test(t)&&U(e.parentNode)||e)==e&&le.scope||((s=e.getAttribute("id"))?s=ce.escapeSelector(s):e.setAttribute("id",s=S)),o=(l=Y(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+Q(l[o]);c=l.join(",")}try{return k.apply(n,f.querySelectorAll(c)),n}catch(e){h(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return re(t.replace(ve,"$1"),e,n,r)}function W(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function F(e){return e[S]=!0,e}function $(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function B(t){return function(e){return fe(e,"input")&&e.type===t}}function _(t){return function(e){return(fe(e,"input")||fe(e,"button"))&&e.type===t}}function z(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&R(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function X(a){return F(function(o){return o=+o,F(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function U(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function V(e){var t,n=e?e.ownerDocument||e:ye;return n!=T&&9===n.nodeType&&n.documentElement&&(r=(T=n).documentElement,C=!ce.isXMLDoc(T),i=r.matches||r.webkitMatchesSelector||r.msMatchesSelector,r.msMatchesSelector&&ye!=T&&(t=T.defaultView)&&t.top!==t&&t.addEventListener("unload",M),le.getById=$(function(e){return r.appendChild(e).id=ce.expando,!T.getElementsByName||!T.getElementsByName(ce.expando).length}),le.disconnectedMatch=$(function(e){return i.call(e,"*")}),le.scope=$(function(){return T.querySelectorAll(":scope")}),le.cssHas=$(function(){try{return T.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}}),le.getById?(b.filter.ID=function(e){var t=e.replace(O,P);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(O,P);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):t.querySelectorAll(e)},b.find.CLASS=function(e,t){if("undefined"!=typeof t.getElementsByClassName&&C)return t.getElementsByClassName(e)},d=[],$(function(e){var t;r.appendChild(e).innerHTML="<a id='"+S+"' href='' disabled='disabled'></a><select id='"+S+"-\r\\' disabled='disabled'><option selected=''></option></select>",e.querySelectorAll("[selected]").length||d.push("\\["+ge+"*(?:value|"+f+")"),e.querySelectorAll("[id~="+S+"-]").length||d.push("~="),e.querySelectorAll("a#"+S+"+*").length||d.push(".#.+[+~]"),e.querySelectorAll(":checked").length||d.push(":checked"),(t=T.createElement("input")).setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&d.push(":enabled",":disabled"),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||d.push("\\["+ge+"*name"+ge+"*="+ge+"*(?:''|\"\")")}),le.cssHas||d.push(":has"),d=d.length&&new RegExp(d.join("|")),l=function(e,t){if(e===t)return a=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!le.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument==ye&&I.contains(ye,e)?-1:t===T||t.ownerDocument==ye&&I.contains(ye,t)?1:o?se.call(o,e)-se.call(o,t):0:4&n?-1:1)}),T}for(e in I.matches=function(e,t){return I(e,null,null,t)},I.matchesSelector=function(e,t){if(V(e),C&&!h[t+" "]&&(!d||!d.test(t)))try{var n=i.call(e,t);if(n||le.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){h(t,!0)}return 0<I(t,T,null,[e]).length},I.contains=function(e,t){return(e.ownerDocument||e)!=T&&V(e),ce.contains(e,t)},I.attr=function(e,t){(e.ownerDocument||e)!=T&&V(e);var n=b.attrHandle[t.toLowerCase()],r=n&&ue.call(b.attrHandle,t.toLowerCase())?n(e,t,!C):void 0;return void 0!==r?r:e.getAttribute(t)},I.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},ce.uniqueSort=function(e){var t,n=[],r=0,i=0;if(a=!le.sortStable,o=!le.sortStable&&ae.call(e,0),de.call(e,l),a){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)he.call(e,n[r],1)}return o=null,e},ce.fn.uniqueSort=function(){return this.pushStack(ce.uniqueSort(ae.apply(this)))},(b=ce.expr={cacheLength:50,createPseudo:F,match:D,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(O,P),e[3]=(e[3]||e[4]||e[5]||"").replace(O,P),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||I.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&I.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return D.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&j.test(n)&&(t=Y(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(O,P).toLowerCase();return"*"===e?function(){return!0}:function(e){return fe(e,t)}},CLASS:function(e){var t=s[e+" "];return t||(t=new RegExp("(^|"+ge+")"+e+"("+ge+"|$)"))&&s(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=I.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace(v," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(d,e,t,h,g){var v="nth"!==d.slice(0,3),y="last"!==d.slice(-4),m="of-type"===e;return 1===h&&0===g?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u=v!==y?"nextSibling":"previousSibling",l=e.parentNode,c=m&&e.nodeName.toLowerCase(),f=!n&&!m,p=!1;if(l){if(v){while(u){o=e;while(o=o[u])if(m?fe(o,c):1===o.nodeType)return!1;s=u="only"===d&&!s&&"nextSibling"}return!0}if(s=[y?l.firstChild:l.lastChild],y&&f){p=(a=(r=(i=l[S]||(l[S]={}))[d]||[])[0]===E&&r[1])&&r[2],o=a&&l.childNodes[a];while(o=++a&&o&&o[u]||(p=a=0)||s.pop())if(1===o.nodeType&&++p&&o===e){i[d]=[E,a,p];break}}else if(f&&(p=a=(r=(i=e[S]||(e[S]={}))[d]||[])[0]===E&&r[1]),!1===p)while(o=++a&&o&&o[u]||(p=a=0)||s.pop())if((m?fe(o,c):1===o.nodeType)&&++p&&(f&&((i=o[S]||(o[S]={}))[d]=[E,p]),o===e))break;return(p-=g)===h||p%h==0&&0<=p/h}}},PSEUDO:function(e,o){var t,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||I.error("unsupported pseudo: "+e);return a[S]?a(o):1<a.length?(t=[e,e,"",o],b.setFilters.hasOwnProperty(e.toLowerCase())?F(function(e,t){var n,r=a(e,o),i=r.length;while(i--)e[n=se.call(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:F(function(e){var r=[],i=[],s=ne(e.replace(ve,"$1"));return s[S]?F(function(e,t,n,r){var i,o=s(e,null,r,[]),a=e.length;while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:F(function(t){return function(e){return 0<I(t,e).length}}),contains:F(function(t){return t=t.replace(O,P),function(e){return-1<(e.textContent||ce.text(e)).indexOf(t)}}),lang:F(function(n){return A.test(n||"")||I.error("unsupported lang: "+n),n=n.replace(O,P).toLowerCase(),function(e){var t;do{if(t=C?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=ie.location&&ie.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===r},focus:function(e){return e===function(){try{return T.activeElement}catch(e){}}()&&T.hasFocus()&&!!(e.type||e.href||~e.tabIndex)},enabled:z(!1),disabled:z(!0),checked:function(e){return fe(e,"input")&&!!e.checked||fe(e,"option")&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!b.pseudos.empty(e)},header:function(e){return q.test(e.nodeName)},input:function(e){return N.test(e.nodeName)},button:function(e){return fe(e,"input")&&"button"===e.type||fe(e,"button")},text:function(e){var t;return fe(e,"input")&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:X(function(){return[0]}),last:X(function(e,t){return[t-1]}),eq:X(function(e,t,n){return[n<0?n+t:n]}),even:X(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:X(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:X(function(e,t,n){var r;for(r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:X(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=b.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[e]=B(e);for(e in{submit:!0,reset:!0})b.pseudos[e]=_(e);function G(){}function Y(e,t){var n,r,i,o,a,s,u,l=c[e+" "];if(l)return t?0:l.slice(0);a=e,s=[],u=b.preFilter;while(a){for(o in n&&!(r=y.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=m.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace(ve," ")}),a=a.slice(n.length)),b.filter)!(r=D[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?I.error(e):c(e,s).slice(0)}function Q(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function J(a,e,t){var s=e.dir,u=e.next,l=u||s,c=t&&"parentNode"===l,f=n++;return e.first?function(e,t,n){while(e=e[s])if(1===e.nodeType||c)return a(e,t,n);return!1}:function(e,t,n){var r,i,o=[E,f];if(n){while(e=e[s])if((1===e.nodeType||c)&&a(e,t,n))return!0}else while(e=e[s])if(1===e.nodeType||c)if(i=e[S]||(e[S]={}),u&&fe(e,u))e=e[s]||e;else{if((r=i[l])&&r[0]===E&&r[1]===f)return o[2]=r[2];if((i[l]=o)[2]=a(e,t,n))return!0}return!1}}function K(i){return 1<i.length?function(e,t,n){var r=i.length;while(r--)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Z(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function ee(d,h,g,v,y,e){return v&&!v[S]&&(v=ee(v)),y&&!y[S]&&(y=ee(y,e)),F(function(e,t,n,r){var i,o,a,s,u=[],l=[],c=t.length,f=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)I(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),p=!d||!e&&h?f:Z(f,u,d,n,r);if(g?g(p,s=y||(e?d:c||v)?[]:t,n,r):s=p,v){i=Z(s,l),v(i,[],n,r),o=i.length;while(o--)(a=i[o])&&(s[l[o]]=!(p[l[o]]=a))}if(e){if(y||d){if(y){i=[],o=s.length;while(o--)(a=s[o])&&i.push(p[o]=a);y(null,s=[],i,r)}o=s.length;while(o--)(a=s[o])&&-1<(i=y?se.call(e,a):u[o])&&(e[i]=!(t[i]=a))}}else s=Z(s===t?s.splice(c,s.length):s),y?y(null,t,s,r):k.apply(t,s)})}function te(e){for(var i,t,n,r=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,u=J(function(e){return e===i},a,!0),l=J(function(e){return-1<se.call(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!=w)||((i=t).nodeType?u(e,t,n):l(e,t,n));return i=null,r}];s<r;s++)if(t=b.relative[e[s].type])c=[J(K(c),t)];else{if((t=b.filter[e[s].type].apply(null,e[s].matches))[S]){for(n=++s;n<r;n++)if(b.relative[e[n].type])break;return ee(1<s&&K(c),1<s&&Q(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(ve,"$1"),t,s<n&&te(e.slice(s,n)),n<r&&te(e=e.slice(n)),n<r&&Q(e))}c.push(t)}return K(c)}function ne(e,t){var n,v,y,m,x,r,i=[],o=[],a=u[e+" "];if(!a){t||(t=Y(e)),n=t.length;while(n--)(a=te(t[n]))[S]?i.push(a):o.push(a);(a=u(e,(v=o,m=0<(y=i).length,x=0<v.length,r=function(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],p=w,d=e||x&&b.find.TAG("*",i),h=E+=null==p?1:Math.random()||.1,g=d.length;for(i&&(w=t==T||t||i);l!==g&&null!=(o=d[l]);l++){if(x&&o){a=0,t||o.ownerDocument==T||(V(o),n=!C);while(s=v[a++])if(s(o,t||T,n)){k.call(r,o);break}i&&(E=h)}m&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,m&&l!==u){a=0;while(s=y[a++])s(c,f,t,n);if(e){if(0<u)while(l--)c[l]||f[l]||(f[l]=pe.call(r));f=Z(f)}k.apply(r,f),i&&!e&&0<f.length&&1<u+y.length&&ce.uniqueSort(r)}return i&&(E=h,w=p),c},m?F(r):r))).selector=e}return a}function re(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&Y(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&C&&b.relative[o[1].type]){if(!(t=(b.find.ID(a.matches[0].replace(O,P),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}i=D.needsContext.test(e)?0:o.length;while(i--){if(a=o[i],b.relative[s=a.type])break;if((u=b.find[s])&&(r=u(a.matches[0].replace(O,P),H.test(o[0].type)&&U(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&Q(o)))return k.apply(n,r),n;break}}}return(l||ne(e,c))(r,t,!C,n,!t||H.test(e)&&U(t.parentNode)||t),n}G.prototype=b.filters=b.pseudos,b.setFilters=new G,le.sortStable=S.split("").sort(l).join("")===S,V(),le.sortDetached=$(function(e){return 1&e.compareDocumentPosition(T.createElement("fieldset"))}),ce.find=I,ce.expr[":"]=ce.expr.pseudos,ce.unique=ce.uniqueSort,I.compile=ne,I.select=re,I.setDocument=V,I.tokenize=Y,I.escape=ce.escapeSelector,I.getText=ce.text,I.isXML=ce.isXMLDoc,I.selectors=ce.expr,I.support=ce.support,I.uniqueSort=ce.uniqueSort}();var d=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&ce(e).is(n))break;r.push(e)}return r},h=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},b=ce.expr.match.needsContext,w=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function T(e,n,r){return v(n)?ce.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?ce.grep(e,function(e){return e===n!==r}):"string"!=typeof n?ce.grep(e,function(e){return-1<se.call(n,e)!==r}):ce.filter(n,e,r)}ce.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?ce.find.matchesSelector(r,e)?[r]:[]:ce.find.matches(e,ce.grep(t,function(e){return 1===e.nodeType}))},ce.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(ce(e).filter(function(){for(t=0;t<r;t++)if(ce.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)ce.find(e,i[t],n);return 1<r?ce.uniqueSort(n):n},filter:function(e){return this.pushStack(T(this,e||[],!1))},not:function(e){return this.pushStack(T(this,e||[],!0))},is:function(e){return!!T(this,"string"==typeof e&&b.test(e)?ce(e):e||[],!1).length}});var k,S=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(ce.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||k,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:S.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:C,!0)),w.test(r[1])&&ce.isPlainObject(t))for(r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=C.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(ce):ce.makeArray(e,this)}).prototype=ce.fn,k=ce(C);var E=/^(?:parents|prev(?:Until|All))/,j={children:!0,contents:!0,next:!0,prev:!0};function A(e,t){while((e=e[t])&&1!==e.nodeType);return e}ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(ce.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&ce(e);if(!b.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&ce.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?ce.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?se.call(ce(e),this[0]):se.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ce.uniqueSort(ce.merge(this.get(),ce(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ce.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return d(e,"parentNode")},parentsUntil:function(e,t,n){return d(e,"parentNode",n)},next:function(e){return A(e,"nextSibling")},prev:function(e){return A(e,"previousSibling")},nextAll:function(e){return d(e,"nextSibling")},prevAll:function(e){return d(e,"previousSibling")},nextUntil:function(e,t,n){return d(e,"nextSibling",n)},prevUntil:function(e,t,n){return d(e,"previousSibling",n)},siblings:function(e){return h((e.parentNode||{}).firstChild,e)},children:function(e){return h(e.firstChild)},contents:function(e){return null!=e.contentDocument&&r(e.contentDocument)?e.contentDocument:(fe(e,"template")&&(e=e.content||e),ce.merge([],e.childNodes))}},function(r,i){ce.fn[r]=function(e,t){var n=ce.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=ce.filter(t,n)),1<this.length&&(j[r]||ce.uniqueSort(n),E.test(r)&&n.reverse()),this.pushStack(n)}});var D=/[^\x20\t\r\n\f]+/g;function N(e){return e}function q(e){throw e}function L(e,t,n,r){var i;try{e&&v(i=e.promise)?i.call(e).done(t).fail(n):e&&v(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}ce.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},ce.each(e.match(D)||[],function(e,t){n[t]=!0}),n):ce.extend({},r);var i,t,o,a,s=[],u=[],l=-1,c=function(){for(a=a||r.once,o=i=!0;u.length;l=-1){t=u.shift();while(++l<s.length)!1===s[l].apply(t[0],t[1])&&r.stopOnFalse&&(l=s.length,t=!1)}r.memory||(t=!1),i=!1,a&&(s=t?[]:"")},f={add:function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){ce.each(e,function(e,t){v(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==x(t)&&n(t)})}(arguments),t&&!i&&c()),this},remove:function(){return ce.each(arguments,function(e,t){var n;while(-1<(n=ce.inArray(t,s,n)))s.splice(n,1),n<=l&&l--}),this},has:function(e){return e?-1<ce.inArray(e,s):0<s.length},empty:function(){return s&&(s=[]),this},disable:function(){return a=u=[],s=t="",this},disabled:function(){return!s},lock:function(){return a=u=[],t||i||(s=t=""),this},locked:function(){return!!a},fireWith:function(e,t){return a||(t=[e,(t=t||[]).slice?t.slice():t],u.push(t),i||c()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},ce.extend({Deferred:function(e){var o=[["notify","progress",ce.Callbacks("memory"),ce.Callbacks("memory"),2],["resolve","done",ce.Callbacks("once memory"),ce.Callbacks("once memory"),0,"resolved"],["reject","fail",ce.Callbacks("once memory"),ce.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},"catch":function(e){return a.then(null,e)},pipe:function(){var i=arguments;return ce.Deferred(function(r){ce.each(o,function(e,t){var n=v(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&v(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,v(t)?s?t.call(e,l(u,o,N,s),l(u,o,q,s)):(u++,t.call(e,l(u,o,N,s),l(u,o,q,s),l(u,o,N,o.notifyWith))):(a!==N&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){ce.Deferred.exceptionHook&&ce.Deferred.exceptionHook(e,t.error),u<=i+1&&(a!==q&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(ce.Deferred.getErrorHook?t.error=ce.Deferred.getErrorHook():ce.Deferred.getStackHook&&(t.error=ce.Deferred.getStackHook()),ie.setTimeout(t))}}return ce.Deferred(function(e){o[0][3].add(l(0,e,v(r)?r:N,e.notifyWith)),o[1][3].add(l(0,e,v(t)?t:N)),o[2][3].add(l(0,e,v(n)?n:q))}).promise()},promise:function(e){return null!=e?ce.extend(e,a):a}},s={};return ce.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){var n=arguments.length,t=n,r=Array(t),i=ae.call(arguments),o=ce.Deferred(),a=function(t){return function(e){r[t]=this,i[t]=1<arguments.length?ae.call(arguments):e,--n||o.resolveWith(r,i)}};if(n<=1&&(L(e,o.done(a(t)).resolve,o.reject,!n),"pending"===o.state()||v(i[t]&&i[t].then)))return o.then();while(t--)L(i[t],a(t),o.reject);return o.promise()}});var H=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;ce.Deferred.exceptionHook=function(e,t){ie.console&&ie.console.warn&&e&&H.test(e.name)&&ie.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},ce.readyException=function(e){ie.setTimeout(function(){throw e})};var O=ce.Deferred();function P(){C.removeEventListener("DOMContentLoaded",P),ie.removeEventListener("load",P),ce.ready()}ce.fn.ready=function(e){return O.then(e)["catch"](function(e){ce.readyException(e)}),this},ce.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--ce.readyWait:ce.isReady)||(ce.isReady=!0)!==e&&0<--ce.readyWait||O.resolveWith(C,[ce])}}),ce.ready.then=O.then,"complete"===C.readyState||"loading"!==C.readyState&&!C.documentElement.doScroll?ie.setTimeout(ce.ready):(C.addEventListener("DOMContentLoaded",P),ie.addEventListener("load",P));var M=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n))for(s in i=!0,n)M(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,v(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(ce(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},R=/^-ms-/,I=/-([a-z])/g;function W(e,t){return t.toUpperCase()}function F(e){return e.replace(R,"ms-").replace(I,W)}var $=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function B(){this.expando=ce.expando+B.uid++}B.uid=1,B.prototype={cache:function(e){var t=e[this.expando];return t||(t={},$(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[F(t)]=n;else for(r in t)i[F(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][F(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(F):(t=F(t))in r?[t]:t.match(D)||[]).length;while(n--)delete r[t[n]]}(void 0===t||ce.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!ce.isEmptyObject(t)}};var _=new B,z=new B,X=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,U=/[A-Z]/g;function V(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(U,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+""?+i:X.test(i)?JSON.parse(i):i)}catch(e){}z.set(e,t,n)}else n=void 0;return n}ce.extend({hasData:function(e){return z.hasData(e)||_.hasData(e)},data:function(e,t,n){return z.access(e,t,n)},removeData:function(e,t){z.remove(e,t)},_data:function(e,t,n){return _.access(e,t,n)},_removeData:function(e,t){_.remove(e,t)}}),ce.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0===n){if(this.length&&(i=z.get(o),1===o.nodeType&&!_.get(o,"hasDataAttrs"))){t=a.length;while(t--)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=F(r.slice(5)),V(o,r,i[r]));_.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof n?this.each(function(){z.set(this,n)}):M(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=z.get(o,n))?t:void 0!==(t=V(o,n))?t:void 0;this.each(function(){z.set(this,n,e)})},null,e,1<arguments.length,null,!0)},removeData:function(e){return this.each(function(){z.remove(this,e)})}}),ce.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=_.get(e,t),n&&(!r||Array.isArray(n)?r=_.access(e,t,ce.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=ce.queue(e,t),r=n.length,i=n.shift(),o=ce._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){ce.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return _.get(e,n)||_.access(e,n,{empty:ce.Callbacks("once memory").add(function(){_.remove(e,[t+"queue",n])})})}}),ce.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?ce.queue(this[0],t):void 0===n?this:this.each(function(){var e=ce.queue(this,t,n);ce._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&ce.dequeue(this,t)})},dequeue:function(e){return this.each(function(){ce.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=ce.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=_.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var G=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Y=new RegExp("^(?:([+-])=|)("+G+")([a-z%]*)$","i"),Q=["Top","Right","Bottom","Left"],J=C.documentElement,K=function(e){return ce.contains(e.ownerDocument,e)},Z={composed:!0};J.getRootNode&&(K=function(e){return ce.contains(e.ownerDocument,e)||e.getRootNode(Z)===e.ownerDocument});var ee=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&K(e)&&"none"===ce.css(e,"display")};function te(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return ce.css(e,t,"")},u=s(),l=n&&n[3]||(ce.cssNumber[t]?"":"px"),c=e.nodeType&&(ce.cssNumber[t]||"px"!==l&&+u)&&Y.exec(ce.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)ce.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,ce.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var ne={};function re(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=_.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&ee(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ne[s])||(o=a.body.appendChild(a.createElement(s)),u=ce.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ne[s]=u)))):"none"!==n&&(l[c]="none",_.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}ce.fn.extend({show:function(){return re(this,!0)},hide:function(){return re(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ee(this)?ce(this).show():ce(this).hide()})}});var xe,be,we=/^(?:checkbox|radio)$/i,Te=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i;xe=C.createDocumentFragment().appendChild(C.createElement("div")),(be=C.createElement("input")).setAttribute("type","radio"),be.setAttribute("checked","checked"),be.setAttribute("name","t"),xe.appendChild(be),le.checkClone=xe.cloneNode(!0).cloneNode(!0).lastChild.checked,xe.innerHTML="<textarea>x</textarea>",le.noCloneChecked=!!xe.cloneNode(!0).lastChild.defaultValue,xe.innerHTML="<option></option>",le.option=!!xe.lastChild;var ke={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};function Se(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&fe(e,t)?ce.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n<r;n++)_.set(e[n],"globalEval",!t||_.get(t[n],"globalEval"))}ke.tbody=ke.tfoot=ke.colgroup=ke.caption=ke.thead,ke.th=ke.td,le.option||(ke.optgroup=ke.option=[1,"<select multiple='multiple'>","</select>"]);var je=/<|&#?\w+;/;function Ae(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===x(o))ce.merge(p,o.nodeType?[o]:o);else if(je.test(o)){a=a||f.appendChild(t.createElement("div")),s=(Te.exec(o)||["",""])[1].toLowerCase(),u=ke[s]||ke._default,a.innerHTML=u[1]+ce.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;ce.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&-1<ce.inArray(o,r))i&&i.push(o);else if(l=K(o),a=Se(f.appendChild(o),"script"),l&&Ee(a),n){c=0;while(o=a[c++])Ce.test(o.type||"")&&n.push(o)}return f}var De=/^([^.]*)(?:\.(.+)|)/;function Ne(){return!0}function qe(){return!1}function Le(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Le(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=qe;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return ce().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=ce.guid++)),e.each(function(){ce.event.add(this,t,i,r,n)})}function He(e,r,t){t?(_.set(e,r,!1),ce.event.add(e,r,{namespace:!1,handler:function(e){var t,n=_.get(this,r);if(1&e.isTrigger&&this[r]){if(n)(ce.event.special[r]||{}).delegateType&&e.stopPropagation();else if(n=ae.call(arguments),_.set(this,r,n),this[r](),t=_.get(this,r),_.set(this,r,!1),n!==t)return e.stopImmediatePropagation(),e.preventDefault(),t}else n&&(_.set(this,r,ce.event.trigger(n[0],n.slice(1),this)),e.stopPropagation(),e.isImmediatePropagationStopped=Ne)}})):void 0===_.get(e,r)&&ce.event.add(e,r,Ne)}ce.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=_.get(t);if($(t)){n.handler&&(n=(o=n).handler,i=o.selector),i&&ce.find.matchesSelector(J,i),n.guid||(n.guid=ce.guid++),(u=v.events)||(u=v.events=Object.create(null)),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof ce&&ce.event.triggered!==e.type?ce.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(D)||[""]).length;while(l--)d=g=(s=De.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=ce.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=ce.event.special[d]||{},c=ce.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&ce.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),ce.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=_.hasData(e)&&_.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(D)||[""]).length;while(l--)if(d=g=(s=De.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=ce.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||ce.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)ce.event.remove(e,d+t[l],n,r,!0);ce.isEmptyObject(u)&&_.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=new Array(arguments.length),u=ce.event.fix(e),l=(_.get(this,"events")||Object.create(null))[u.type]||[],c=ce.event.special[u.type]||{};for(s[0]=u,t=1;t<arguments.length;t++)s[t]=arguments[t];if(u.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,u)){a=ce.event.handlers.call(this,u,l),t=0;while((i=a[t++])&&!u.isPropagationStopped()){u.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!u.isImmediatePropagationStopped())u.rnamespace&&!1!==o.namespace&&!u.rnamespace.test(o.namespace)||(u.handleObj=o,u.data=o.data,void 0!==(r=((ce.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s))&&!1===(u.result=r)&&(u.preventDefault(),u.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,u),u.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&1<=e.button))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?-1<ce(i,this).index(l):ce.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(t,e){Object.defineProperty(ce.Event.prototype,t,{enumerable:!0,configurable:!0,get:v(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[ce.expando]?e:new ce.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return we.test(t.type)&&t.click&&fe(t,"input")&&He(t,"click",!0),!1},trigger:function(e){var t=this||e;return we.test(t.type)&&t.click&&fe(t,"input")&&He(t,"click"),!0},_default:function(e){var t=e.target;return we.test(t.type)&&t.click&&fe(t,"input")&&_.get(t,"click")||fe(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},ce.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},ce.Event=function(e,t){if(!(this instanceof ce.Event))return new ce.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?Ne:qe,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&ce.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[ce.expando]=!0},ce.Event.prototype={constructor:ce.Event,isDefaultPrevented:qe,isPropagationStopped:qe,isImmediatePropagationStopped:qe,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=Ne,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=Ne,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=Ne,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},ce.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:!0},ce.event.addProp),ce.each({focus:"focusin",blur:"focusout"},function(r,i){function o(e){if(C.documentMode){var t=_.get(this,"handle"),n=ce.event.fix(e);n.type="focusin"===e.type?"focus":"blur",n.isSimulated=!0,t(e),n.target===n.currentTarget&&t(n)}else ce.event.simulate(i,e.target,ce.event.fix(e))}ce.event.special[r]={setup:function(){var e;if(He(this,r,!0),!C.documentMode)return!1;(e=_.get(this,i))||this.addEventListener(i,o),_.set(this,i,(e||0)+1)},trigger:function(){return He(this,r),!0},teardown:function(){var e;if(!C.documentMode)return!1;(e=_.get(this,i)-1)?_.set(this,i,e):(this.removeEventListener(i,o),_.remove(this,i))},_default:function(e){return _.get(e.target,r)},delegateType:i},ce.event.special[i]={setup:function(){var e=this.ownerDocument||this.document||this,t=C.documentMode?this:e,n=_.get(t,i);n||(C.documentMode?this.addEventListener(i,o):e.addEventListener(r,o,!0)),_.set(t,i,(n||0)+1)},teardown:function(){var e=this.ownerDocument||this.document||this,t=C.documentMode?this:e,n=_.get(t,i)-1;n?_.set(t,i,n):(C.documentMode?this.removeEventListener(i,o):e.removeEventListener(r,o,!0),_.remove(t,i))}}}),ce.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){ce.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||ce.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),ce.fn.extend({on:function(e,t,n,r){return Le(this,e,t,n,r)},one:function(e,t,n,r){return Le(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,ce(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=qe),this.each(function(){ce.event.remove(this,e,n,t)})}});var Oe=/<script|<style|<link/i,Pe=/checked\s*(?:[^=]|=\s*.checked.)/i,Me=/^\s*<!\[CDATA\[|\]\]>\s*$/g;function Re(e,t){return fe(e,"table")&&fe(11!==t.nodeType?t:t.firstChild,"tr")&&ce(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function We(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Fe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(_.hasData(e)&&(s=_.get(e).events))for(i in _.remove(t,"handle events"),s)for(n=0,r=s[i].length;n<r;n++)ce.event.add(t,i,s[i][n]);z.hasData(e)&&(o=z.access(e),a=ce.extend({},o),z.set(t,a))}}function $e(n,r,i,o){r=g(r);var e,t,a,s,u,l,c=0,f=n.length,p=f-1,d=r[0],h=v(d);if(h||1<f&&"string"==typeof d&&!le.checkClone&&Pe.test(d))return n.each(function(e){var t=n.eq(e);h&&(r[0]=d.call(this,e,t.html())),$e(t,r,i,o)});if(f&&(t=(e=Ae(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=ce.map(Se(e,"script"),Ie)).length;c<f;c++)u=e,c!==p&&(u=ce.clone(u,!0,!0),s&&ce.merge(a,Se(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,ce.map(a,We),c=0;c<s;c++)u=a[c],Ce.test(u.type||"")&&!_.access(u,"globalEval")&&ce.contains(l,u)&&(u.src&&"module"!==(u.type||"").toLowerCase()?ce._evalUrl&&!u.noModule&&ce._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")},l):m(u.textContent.replace(Me,""),u,l))}return n}function Be(e,t,n){for(var r,i=t?ce.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||ce.cleanData(Se(r)),r.parentNode&&(n&&K(r)&&Ee(Se(r,"script")),r.parentNode.removeChild(r));return e}ce.extend({htmlPrefilter:function(e){return e},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=K(e);if(!(le.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ce.isXMLDoc(e)))for(a=Se(c),r=0,i=(o=Se(e)).length;r<i;r++)s=o[r],u=a[r],void 0,"input"===(l=u.nodeName.toLowerCase())&&we.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||Se(e),a=a||Se(c),r=0,i=o.length;r<i;r++)Fe(o[r],a[r]);else Fe(e,c);return 0<(a=Se(c,"script")).length&&Ee(a,!f&&Se(e,"script")),c},cleanData:function(e){for(var t,n,r,i=ce.event.special,o=0;void 0!==(n=e[o]);o++)if($(n)){if(t=n[_.expando]){if(t.events)for(r in t.events)i[r]?ce.event.remove(n,r):ce.removeEvent(n,r,t.handle);n[_.expando]=void 0}n[z.expando]&&(n[z.expando]=void 0)}}}),ce.fn.extend({detach:function(e){return Be(this,e,!0)},remove:function(e){return Be(this,e)},text:function(e){return M(this,function(e){return void 0===e?ce.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return $e(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Re(this,e).appendChild(e)})},prepend:function(){return $e(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Re(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return $e(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return $e(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(ce.cleanData(Se(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return ce.clone(this,e,t)})},html:function(e){return M(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Oe.test(e)&&!ke[(Te.exec(e)||["",""])[1].toLowerCase()]){e=ce.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(ce.cleanData(Se(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return $e(this,arguments,function(e){var t=this.parentNode;ce.inArray(this,n)<0&&(ce.cleanData(Se(this)),t&&t.replaceChild(e,this))},n)}}),ce.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){ce.fn[e]=function(e){for(var t,n=[],r=ce(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),ce(r[o])[a](t),s.apply(n,t.get());return this.pushStack(n)}});var _e=new RegExp("^("+G+")(?!px)[a-z%]+$","i"),ze=/^--/,Xe=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=ie),t.getComputedStyle(e)},Ue=function(e,t,n){var r,i,o={};for(i in t)o[i]=e.style[i],e.style[i]=t[i];for(i in r=n.call(e),t)e.style[i]=o[i];return r},Ve=new RegExp(Q.join("|"),"i");function Ge(e,t,n){var r,i,o,a,s=ze.test(t),u=e.style;return(n=n||Xe(e))&&(a=n.getPropertyValue(t)||n[t],s&&a&&(a=a.replace(ve,"$1")||void 0),""!==a||K(e)||(a=ce.style(e,t)),!le.pixelBoxStyles()&&_e.test(a)&&Ve.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=n.width,u.width=r,u.minWidth=i,u.maxWidth=o)),void 0!==a?a+"":a}function Ye(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}!function(){function e(){if(l){u.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",l.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",J.appendChild(u).appendChild(l);var e=ie.getComputedStyle(l);n="1%"!==e.top,s=12===t(e.marginLeft),l.style.right="60%",o=36===t(e.right),r=36===t(e.width),l.style.position="absolute",i=12===t(l.offsetWidth/3),J.removeChild(u),l=null}}function t(e){return Math.round(parseFloat(e))}var n,r,i,o,a,s,u=C.createElement("div"),l=C.createElement("div");l.style&&(l.style.backgroundClip="content-box",l.cloneNode(!0).style.backgroundClip="",le.clearCloneStyle="content-box"===l.style.backgroundClip,ce.extend(le,{boxSizingReliable:function(){return e(),r},pixelBoxStyles:function(){return e(),o},pixelPosition:function(){return e(),n},reliableMarginLeft:function(){return e(),s},scrollboxSize:function(){return e(),i},reliableTrDimensions:function(){var e,t,n,r;return null==a&&(e=C.createElement("table"),t=C.createElement("tr"),n=C.createElement("div"),e.style.cssText="position:absolute;left:-11111px;border-collapse:separate",t.style.cssText="box-sizing:content-box;border:1px solid",t.style.height="1px",n.style.height="9px",n.style.display="block",J.appendChild(e).appendChild(t).appendChild(n),r=ie.getComputedStyle(t),a=parseInt(r.height,10)+parseInt(r.borderTopWidth,10)+parseInt(r.borderBottomWidth,10)===t.offsetHeight,J.removeChild(e)),a}}))}();var Qe=["Webkit","Moz","ms"],Je=C.createElement("div").style,Ke={};function Ze(e){var t=ce.cssProps[e]||Ke[e];return t||(e in Je?e:Ke[e]=function(e){var t=e[0].toUpperCase()+e.slice(1),n=Qe.length;while(n--)if((e=Qe[n]+t)in Je)return e}(e)||e)}var et=/^(none|table(?!-c[ea]).+)/,tt={position:"absolute",visibility:"hidden",display:"block"},nt={letterSpacing:"0",fontWeight:"400"};function rt(e,t,n){var r=Y.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function it(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0,l=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(l+=ce.css(e,n+Q[a],!0,i)),r?("content"===n&&(u-=ce.css(e,"padding"+Q[a],!0,i)),"margin"!==n&&(u-=ce.css(e,"border"+Q[a]+"Width",!0,i))):(u+=ce.css(e,"padding"+Q[a],!0,i),"padding"!==n?u+=ce.css(e,"border"+Q[a]+"Width",!0,i):s+=ce.css(e,"border"+Q[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u+l}function ot(e,t,n){var r=Xe(e),i=(!le.boxSizingReliable()||n)&&"border-box"===ce.css(e,"boxSizing",!1,r),o=i,a=Ge(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if(_e.test(a)){if(!n)return a;a="auto"}return(!le.boxSizingReliable()&&i||!le.reliableTrDimensions()&&fe(e,"tr")||"auto"===a||!parseFloat(a)&&"inline"===ce.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===ce.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+it(e,t,n||(i?"border":"content"),o,r,a)+"px"}function at(e,t,n,r,i){return new at.prototype.init(e,t,n,r,i)}ce.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Ge(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,aspectRatio:!0,borderImageSlice:!0,columnCount:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,scale:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeMiterlimit:!0,strokeOpacity:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=F(t),u=ze.test(t),l=e.style;if(u||(t=Ze(s)),a=ce.cssHooks[t]||ce.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"===(o=typeof n)&&(i=Y.exec(n))&&i[1]&&(n=te(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(ce.cssNumber[s]?"":"px")),le.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=F(t);return ze.test(t)||(t=Ze(s)),(a=ce.cssHooks[t]||ce.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Ge(e,t,r)),"normal"===i&&t in nt&&(i=nt[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),ce.each(["height","width"],function(e,u){ce.cssHooks[u]={get:function(e,t,n){if(t)return!et.test(ce.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?ot(e,u,n):Ue(e,tt,function(){return ot(e,u,n)})},set:function(e,t,n){var r,i=Xe(e),o=!le.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===ce.css(e,"boxSizing",!1,i),s=n?it(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-it(e,u,"border",!1,i)-.5)),s&&(r=Y.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=ce.css(e,u)),rt(0,t,s)}}}),ce.cssHooks.marginLeft=Ye(le.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Ge(e,"marginLeft"))||e.getBoundingClientRect().left-Ue(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),ce.each({margin:"",padding:"",border:"Width"},function(i,o){ce.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+Q[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(ce.cssHooks[i+o].set=rt)}),ce.fn.extend({css:function(e,t){return M(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Xe(e),i=t.length;a<i;a++)o[t[a]]=ce.css(e,t[a],!1,r);return o}return void 0!==n?ce.style(e,t,n):ce.css(e,t)},e,t,1<arguments.length)}}),((ce.Tween=at).prototype={constructor:at,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||ce.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(ce.cssNumber[n]?"":"px")},cur:function(){var e=at.propHooks[this.prop];return e&&e.get?e.get(this):at.propHooks._default.get(this)},run:function(e){var t,n=at.propHooks[this.prop];return this.options.duration?this.pos=t=ce.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):at.propHooks._default.set(this),this}}).init.prototype=at.prototype,(at.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=ce.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){ce.fx.step[e.prop]?ce.fx.step[e.prop](e):1!==e.elem.nodeType||!ce.cssHooks[e.prop]&&null==e.elem.style[Ze(e.prop)]?e.elem[e.prop]=e.now:ce.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=at.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ce.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},ce.fx=at.prototype.init,ce.fx.step={};var st,ut,lt,ct,ft=/^(?:toggle|show|hide)$/,pt=/queueHooks$/;function dt(){ut&&(!1===C.hidden&&ie.requestAnimationFrame?ie.requestAnimationFrame(dt):ie.setTimeout(dt,ce.fx.interval),ce.fx.tick())}function ht(){return ie.setTimeout(function(){st=void 0}),st=Date.now()}function gt(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=Q[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function vt(e,t,n){for(var r,i=(yt.tweeners[t]||[]).concat(yt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function yt(o,e,t){var n,a,r=0,i=yt.prefilters.length,s=ce.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=st||ht(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:ce.extend({},e),opts:ce.extend(!0,{specialEasing:{},easing:ce.easing._default},t),originalProperties:e,originalOptions:t,startTime:st||ht(),duration:t.duration,tweens:[],createTween:function(e,t){var n=ce.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=F(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=ce.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=yt.prefilters[r].call(l,o,c,l.opts))return v(n.stop)&&(ce._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return ce.map(c,vt,l),v(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),ce.fx.timer(ce.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}ce.Animation=ce.extend(yt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return te(n.elem,e,Y.exec(t),n),n}]},tweener:function(e,t){v(e)?(t=e,e=["*"]):e=e.match(D);for(var n,r=0,i=e.length;r<i;r++)n=e[r],yt.tweeners[n]=yt.tweeners[n]||[],yt.tweeners[n].unshift(t)},prefilters:[function(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ee(e),v=_.get(e,"fxshow");for(r in n.queue||(null==(a=ce._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,ce.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],ft.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!v||void 0===v[r])continue;g=!0}d[r]=v&&v[r]||ce.style(e,r)}if((u=!ce.isEmptyObject(t))||!ce.isEmptyObject(d))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=v&&v.display)&&(l=_.get(e,"display")),"none"===(c=ce.css(e,"display"))&&(l?c=l:(re([e],!0),l=e.style.display||l,c=ce.css(e,"display"),re([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===ce.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1,d)u||(v?"hidden"in v&&(g=v.hidden):v=_.access(e,"fxshow",{display:l}),o&&(v.hidden=!g),g&&re([e],!0),p.done(function(){for(r in g||re([e]),_.remove(e,"fxshow"),d)ce.style(e,r,d[r])})),u=vt(g?v[r]:0,r,p),r in v||(v[r]=u.start,g&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?yt.prefilters.unshift(e):yt.prefilters.push(e)}}),ce.speed=function(e,t,n){var r=e&&"object"==typeof e?ce.extend({},e):{complete:n||!n&&t||v(e)&&e,duration:e,easing:n&&t||t&&!v(t)&&t};return ce.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in ce.fx.speeds?r.duration=ce.fx.speeds[r.duration]:r.duration=ce.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){v(r.old)&&r.old.call(this),r.queue&&ce.dequeue(this,r.queue)},r},ce.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ee).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){var i=ce.isEmptyObject(t),o=ce.speed(e,n,r),a=function(){var e=yt(this,ce.extend({},t),o);(i||_.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(i,e,o){var a=function(e){var t=e.stop;delete e.stop,t(o)};return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=ce.timers,r=_.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&pt.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||ce.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=_.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=ce.timers,o=n?n.length:0;for(t.finish=!0,ce.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),ce.each(["toggle","show","hide"],function(e,r){var i=ce.fn[r];ce.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(gt(r,!0),e,t,n)}}),ce.each({slideDown:gt("show"),slideUp:gt("hide"),slideToggle:gt("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){ce.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),ce.timers=[],ce.fx.tick=function(){var e,t=0,n=ce.timers;for(st=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||ce.fx.stop(),st=void 0},ce.fx.timer=function(e){ce.timers.push(e),ce.fx.start()},ce.fx.interval=13,ce.fx.start=function(){ut||(ut=!0,dt())},ce.fx.stop=function(){ut=null},ce.fx.speeds={slow:600,fast:200,_default:400},ce.fn.delay=function(r,e){return r=ce.fx&&ce.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=ie.setTimeout(e,r);t.stop=function(){ie.clearTimeout(n)}})},lt=C.createElement("input"),ct=C.createElement("select").appendChild(C.createElement("option")),lt.type="checkbox",le.checkOn=""!==lt.value,le.optSelected=ct.selected,(lt=C.createElement("input")).value="t",lt.type="radio",le.radioValue="t"===lt.value;var mt,xt=ce.expr.attrHandle;ce.fn.extend({attr:function(e,t){return M(this,ce.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){ce.removeAttr(this,e)})}}),ce.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?ce.prop(e,t,n):(1===o&&ce.isXMLDoc(e)||(i=ce.attrHooks[t.toLowerCase()]||(ce.expr.match.bool.test(t)?mt:void 0)),void 0!==n?null===n?void ce.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=ce.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!le.radioValue&&"radio"===t&&fe(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(D);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),mt={set:function(e,t,n){return!1===t?ce.removeAttr(e,n):e.setAttribute(n,n),n}},ce.each(ce.expr.match.bool.source.match(/\w+/g),function(e,t){var a=xt[t]||ce.find.attr;xt[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=xt[o],xt[o]=r,r=null!=a(e,t,n)?o:null,xt[o]=i),r}});var bt=/^(?:input|select|textarea|button)$/i,wt=/^(?:a|area)$/i;function Tt(e){return(e.match(D)||[]).join(" ")}function Ct(e){return e.getAttribute&&e.getAttribute("class")||""}function kt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(D)||[]}ce.fn.extend({prop:function(e,t){return M(this,ce.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[ce.propFix[e]||e]})}}),ce.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&ce.isXMLDoc(e)||(t=ce.propFix[t]||t,i=ce.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=ce.find.attr(e,"tabindex");return t?parseInt(t,10):bt.test(e.nodeName)||wt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),le.optSelected||(ce.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),ce.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ce.propFix[this.toLowerCase()]=this}),ce.fn.extend({addClass:function(t){var e,n,r,i,o,a;return v(t)?this.each(function(e){ce(this).addClass(t.call(this,e,Ct(this)))}):(e=kt(t)).length?this.each(function(){if(r=Ct(this),n=1===this.nodeType&&" "+Tt(r)+" "){for(o=0;o<e.length;o++)i=e[o],n.indexOf(" "+i+" ")<0&&(n+=i+" ");a=Tt(n),r!==a&&this.setAttribute("class",a)}}):this},removeClass:function(t){var e,n,r,i,o,a;return v(t)?this.each(function(e){ce(this).removeClass(t.call(this,e,Ct(this)))}):arguments.length?(e=kt(t)).length?this.each(function(){if(r=Ct(this),n=1===this.nodeType&&" "+Tt(r)+" "){for(o=0;o<e.length;o++){i=e[o];while(-1<n.indexOf(" "+i+" "))n=n.replace(" "+i+" "," ")}a=Tt(n),r!==a&&this.setAttribute("class",a)}}):this:this.attr("class","")},toggleClass:function(t,n){var e,r,i,o,a=typeof t,s="string"===a||Array.isArray(t);return v(t)?this.each(function(e){ce(this).toggleClass(t.call(this,e,Ct(this),n),n)}):"boolean"==typeof n&&s?n?this.addClass(t):this.removeClass(t):(e=kt(t),this.each(function(){if(s)for(o=ce(this),i=0;i<e.length;i++)r=e[i],o.hasClass(r)?o.removeClass(r):o.addClass(r);else void 0!==t&&"boolean"!==a||((r=Ct(this))&&_.set(this,"__className__",r),this.setAttribute&&this.setAttribute("class",r||!1===t?"":_.get(this,"__className__")||""))}))},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&-1<(" "+Tt(Ct(n))+" ").indexOf(t))return!0;return!1}});var St=/\r/g;ce.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=v(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,ce(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=ce.map(t,function(e){return null==e?"":e+""})),(r=ce.valHooks[this.type]||ce.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=ce.valHooks[t.type]||ce.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(St,""):null==e?"":e:void 0}}),ce.extend({valHooks:{option:{get:function(e){var t=ce.find.attr(e,"value");return null!=t?t:Tt(ce.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!fe(n.parentNode,"optgroup"))){if(t=ce(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=ce.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=-1<ce.inArray(ce.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),ce.each(["radio","checkbox"],function(){ce.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<ce.inArray(ce(e).val(),t)}},le.checkOn||(ce.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Et=ie.location,jt={guid:Date.now()},At=/\?/;ce.parseXML=function(e){var t,n;if(!e||"string"!=typeof e)return null;try{t=(new ie.DOMParser).parseFromString(e,"text/xml")}catch(e){}return n=t&&t.getElementsByTagName("parsererror")[0],t&&!n||ce.error("Invalid XML: "+(n?ce.map(n.childNodes,function(e){return e.textContent}).join("\n"):e)),t};var Dt=/^(?:focusinfocus|focusoutblur)$/,Nt=function(e){e.stopPropagation()};ce.extend(ce.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,p=[n||C],d=ue.call(e,"type")?e.type:e,h=ue.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||C,3!==n.nodeType&&8!==n.nodeType&&!Dt.test(d+ce.event.triggered)&&(-1<d.indexOf(".")&&(d=(h=d.split(".")).shift(),h.sort()),u=d.indexOf(":")<0&&"on"+d,(e=e[ce.expando]?e:new ce.Event(d,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:ce.makeArray(t,[e]),c=ce.event.special[d]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!y(n)){for(s=c.delegateType||d,Dt.test(s+d)||(o=o.parentNode);o;o=o.parentNode)p.push(o),a=o;a===(n.ownerDocument||C)&&p.push(a.defaultView||a.parentWindow||ie)}i=0;while((o=p[i++])&&!e.isPropagationStopped())f=o,e.type=1<i?s:c.bindType||d,(l=(_.get(o,"events")||Object.create(null))[e.type]&&_.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&$(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=d,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(p.pop(),t)||!$(n)||u&&v(n[d])&&!y(n)&&((a=n[u])&&(n[u]=null),ce.event.triggered=d,e.isPropagationStopped()&&f.addEventListener(d,Nt),n[d](),e.isPropagationStopped()&&f.removeEventListener(d,Nt),ce.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=ce.extend(new ce.Event,n,{type:e,isSimulated:!0});ce.event.trigger(r,null,t)}}),ce.fn.extend({trigger:function(e,t){return this.each(function(){ce.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return ce.event.trigger(e,t,n,!0)}});var qt=/\[\]$/,Lt=/\r?\n/g,Ht=/^(?:submit|button|image|reset|file)$/i,Ot=/^(?:input|select|textarea|keygen)/i;function Pt(n,e,r,i){var t;if(Array.isArray(e))ce.each(e,function(e,t){r||qt.test(n)?i(n,t):Pt(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i)});else if(r||"object"!==x(e))i(n,e);else for(t in e)Pt(n+"["+t+"]",e[t],r,i)}ce.param=function(e,t){var n,r=[],i=function(e,t){var n=v(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!ce.isPlainObject(e))ce.each(e,function(){i(this.name,this.value)});else for(n in e)Pt(n,e[n],t,i);return r.join("&")},ce.fn.extend({serialize:function(){return ce.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ce.prop(this,"elements");return e?ce.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ce(this).is(":disabled")&&Ot.test(this.nodeName)&&!Ht.test(e)&&(this.checked||!we.test(e))}).map(function(e,t){var n=ce(this).val();return null==n?null:Array.isArray(n)?ce.map(n,function(e){return{name:t.name,value:e.replace(Lt,"\r\n")}}):{name:t.name,value:n.replace(Lt,"\r\n")}}).get()}});var Mt=/%20/g,Rt=/#.*$/,It=/([?&])_=[^&]*/,Wt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Ft=/^(?:GET|HEAD)$/,$t=/^\/\//,Bt={},_t={},zt="*/".concat("*"),Xt=C.createElement("a");function Ut(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(D)||[];if(v(t))while(n=i[r++])"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function Vt(t,i,o,a){var s={},u=t===_t;function l(e){var r;return s[e]=!0,ce.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function Gt(e,t){var n,r,i=ce.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&ce.extend(!0,e,r),e}Xt.href=Et.href,ce.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Et.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Et.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":zt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":ce.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Gt(Gt(e,ce.ajaxSettings),t):Gt(ce.ajaxSettings,e)},ajaxPrefilter:Ut(Bt),ajaxTransport:Ut(_t),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,p,n,d,r,h,g,i,o,v=ce.ajaxSetup({},t),y=v.context||v,m=v.context&&(y.nodeType||y.jquery)?ce(y):ce.event,x=ce.Deferred(),b=ce.Callbacks("once memory"),w=v.statusCode||{},a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n){n={};while(t=Wt.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?p:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(v.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(x.promise(T),v.url=((e||v.url||Et.href)+"").replace($t,Et.protocol+"//"),v.type=t.method||t.type||v.method||v.type,v.dataTypes=(v.dataType||"*").toLowerCase().match(D)||[""],null==v.crossDomain){r=C.createElement("a");try{r.href=v.url,r.href=r.href,v.crossDomain=Xt.protocol+"//"+Xt.host!=r.protocol+"//"+r.host}catch(e){v.crossDomain=!0}}if(v.data&&v.processData&&"string"!=typeof v.data&&(v.data=ce.param(v.data,v.traditional)),Vt(Bt,v,t,T),h)return T;for(i in(g=ce.event&&v.global)&&0==ce.active++&&ce.event.trigger("ajaxStart"),v.type=v.type.toUpperCase(),v.hasContent=!Ft.test(v.type),f=v.url.replace(Rt,""),v.hasContent?v.data&&v.processData&&0===(v.contentType||"").indexOf("application/x-www-form-urlencoded")&&(v.data=v.data.replace(Mt,"+")):(o=v.url.slice(f.length),v.data&&(v.processData||"string"==typeof v.data)&&(f+=(At.test(f)?"&":"?")+v.data,delete v.data),!1===v.cache&&(f=f.replace(It,"$1"),o=(At.test(f)?"&":"?")+"_="+jt.guid+++o),v.url=f+o),v.ifModified&&(ce.lastModified[f]&&T.setRequestHeader("If-Modified-Since",ce.lastModified[f]),ce.etag[f]&&T.setRequestHeader("If-None-Match",ce.etag[f])),(v.data&&v.hasContent&&!1!==v.contentType||t.contentType)&&T.setRequestHeader("Content-Type",v.contentType),T.setRequestHeader("Accept",v.dataTypes[0]&&v.accepts[v.dataTypes[0]]?v.accepts[v.dataTypes[0]]+("*"!==v.dataTypes[0]?", "+zt+"; q=0.01":""):v.accepts["*"]),v.headers)T.setRequestHeader(i,v.headers[i]);if(v.beforeSend&&(!1===v.beforeSend.call(y,T,v)||h))return T.abort();if(u="abort",b.add(v.complete),T.done(v.success),T.fail(v.error),c=Vt(_t,v,t,T)){if(T.readyState=1,g&&m.trigger("ajaxSend",[T,v]),h)return T;v.async&&0<v.timeout&&(d=ie.setTimeout(function(){T.abort("timeout")},v.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,d&&ie.clearTimeout(d),c=void 0,p=r||"",T.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}(v,T,n)),!i&&-1<ce.inArray("script",v.dataTypes)&&ce.inArray("json",v.dataTypes)<0&&(v.converters["text script"]=function(){}),s=function(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}(v,s,T,i),i?(v.ifModified&&((u=T.getResponseHeader("Last-Modified"))&&(ce.lastModified[f]=u),(u=T.getResponseHeader("etag"))&&(ce.etag[f]=u)),204===e||"HEAD"===v.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),T.status=e,T.statusText=(t||l)+"",i?x.resolveWith(y,[o,l,T]):x.rejectWith(y,[T,l,a]),T.statusCode(w),w=void 0,g&&m.trigger(i?"ajaxSuccess":"ajaxError",[T,v,i?o:a]),b.fireWith(y,[T,l]),g&&(m.trigger("ajaxComplete",[T,v]),--ce.active||ce.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return ce.get(e,t,n,"json")},getScript:function(e,t){return ce.get(e,void 0,t,"script")}}),ce.each(["get","post"],function(e,i){ce[i]=function(e,t,n,r){return v(t)&&(r=r||n,n=t,t=void 0),ce.ajax(ce.extend({url:e,type:i,dataType:r,data:t,success:n},ce.isPlainObject(e)&&e))}}),ce.ajaxPrefilter(function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||"")}),ce._evalUrl=function(e,t,n){return ce.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){ce.globalEval(e,t,n)}})},ce.fn.extend({wrapAll:function(e){var t;return this[0]&&(v(e)&&(e=e.call(this[0])),t=ce(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(n){return v(n)?this.each(function(e){ce(this).wrapInner(n.call(this,e))}):this.each(function(){var e=ce(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=v(t);return this.each(function(e){ce(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){ce(this).replaceWith(this.childNodes)}),this}}),ce.expr.pseudos.hidden=function(e){return!ce.expr.pseudos.visible(e)},ce.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},ce.ajaxSettings.xhr=function(){try{return new ie.XMLHttpRequest}catch(e){}};var Yt={0:200,1223:204},Qt=ce.ajaxSettings.xhr();le.cors=!!Qt&&"withCredentials"in Qt,le.ajax=Qt=!!Qt,ce.ajaxTransport(function(i){var o,a;if(le.cors||Qt&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(Yt[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&ie.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),ce.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),ce.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return ce.globalEval(e),e}}}),ce.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),ce.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=ce("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=Tt(e.slice(s)),e=e.slice(0,s)),v(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&ce.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?ce("<div>").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}});var en=/^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;ce.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),v(e))return r=ae.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(ae.call(arguments)))}).guid=e.guid=e.guid||ce.guid++,i},ce.holdReady=function(e){e?ce.readyWait++:ce.ready(!0)},ce.isArray=Array.isArray,ce.parseJSON=JSON.parse,ce.nodeName=fe,ce.isFunction=v,ce.isWindow=y,ce.camelCase=F,ce.type=x,ce.now=Date.now,ce.isNumeric=function(e){var t=ce.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},ce.trim=function(e){return null==e?"":(e+"").replace(en,"$1")},"function"==typeof define&&define.amd&&define("jquery",[],function(){return ce});var tn=ie.jQuery,nn=ie.$;return ce.noConflict=function(e){return ie.$===ce&&(ie.$=nn),e&&ie.jQuery===ce&&(ie.jQuery=tn),ce},"undefined"==typeof e&&(ie.jQuery=ie.$=ce),ce});

/* ========================================
 FILE: /includes/js/jquery/core/jquery-migrate-3.5.2.min.js
 ==================== */

/*! jQuery Migrate v3.5.2 | (c) OpenJS Foundation and other contributors | jquery.com/license */
"undefined"==typeof jQuery.migrateMute&&(jQuery.migrateMute=!0),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e,window)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery"),window):t(jQuery,window)}(function(s,n){"use strict";function e(e){return 0<=function(e,t){for(var r=/^(\d+)\.(\d+)\.(\d+)/,n=r.exec(e)||[],o=r.exec(t)||[],a=1;a<=3;a++){if(+o[a]<+n[a])return 1;if(+n[a]<+o[a])return-1}return 0}(s.fn.jquery,e)}s.migrateVersion="3.5.2";var t=Object.create(null);s.migrateDisablePatches=function(){for(var e=0;e<arguments.length;e++)t[arguments[e]]=!0},s.migrateEnablePatches=function(){for(var e=0;e<arguments.length;e++)delete t[arguments[e]]},s.migrateIsPatchEnabled=function(e){return!t[e]},n.console&&n.console.log&&(s&&e("3.0.0")&&!e("5.0.0")||n.console.log("JQMIGRATE: jQuery 3.x-4.x REQUIRED"),s.migrateWarnings&&n.console.log("JQMIGRATE: Migrate plugin loaded multiple times"),n.console.log("JQMIGRATE: Migrate is installed"+(s.migrateMute?"":" with logging active")+", version "+s.migrateVersion));var o={};function u(e,t){var r=n.console;!s.migrateIsPatchEnabled(e)||s.migrateDeduplicateWarnings&&o[t]||(o[t]=!0,s.migrateWarnings.push(t+" ["+e+"]"),r&&r.warn&&!s.migrateMute&&(r.warn("JQMIGRATE: "+t),s.migrateTrace&&r.trace&&r.trace()))}function r(e,t,r,n,o){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return u(n,o),r},set:function(e){u(n,o),r=e}})}function a(e,t,r,n,o){var a=e[t];e[t]=function(){return o&&u(n,o),(s.migrateIsPatchEnabled(n)?r:a||s.noop).apply(this,arguments)}}function c(e,t,r,n,o){if(!o)throw new Error("No warning message provided");return a(e,t,r,n,o),0}function i(e,t,r,n){return a(e,t,r,n),0}s.migrateDeduplicateWarnings=!0,s.migrateWarnings=[],void 0===s.migrateTrace&&(s.migrateTrace=!0),s.migrateReset=function(){o={},s.migrateWarnings.length=0},"BackCompat"===n.document.compatMode&&u("quirks","jQuery is not compatible with Quirks Mode");var d,l,p,f={},m=s.fn.init,y=s.find,g=/\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/,h=/\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/g,v=/^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;for(d in i(s.fn,"init",function(e){var t=Array.prototype.slice.call(arguments);return s.migrateIsPatchEnabled("selector-empty-id")&&"string"==typeof e&&"#"===e&&(u("selector-empty-id","jQuery( '#' ) is not a valid selector"),t[0]=[]),m.apply(this,t)},"selector-empty-id"),s.fn.init.prototype=s.fn,i(s,"find",function(t){var r=Array.prototype.slice.call(arguments);if("string"==typeof t&&g.test(t))try{n.document.querySelector(t)}catch(e){t=t.replace(h,function(e,t,r,n){return"["+t+r+'"'+n+'"]'});try{n.document.querySelector(t),u("selector-hash","Attribute selector with '#' must be quoted: "+r[0]),r[0]=t}catch(e){u("selector-hash","Attribute selector with '#' was not fixed: "+r[0])}}return y.apply(this,r)},"selector-hash"),y)Object.prototype.hasOwnProperty.call(y,d)&&(s.find[d]=y[d]);c(s.fn,"size",function(){return this.length},"size","jQuery.fn.size() is deprecated and removed; use the .length property"),c(s,"parseJSON",function(){return JSON.parse.apply(null,arguments)},"parseJSON","jQuery.parseJSON is deprecated; use JSON.parse"),c(s,"holdReady",s.holdReady,"holdReady","jQuery.holdReady is deprecated"),c(s,"unique",s.uniqueSort,"unique","jQuery.unique is deprecated; use jQuery.uniqueSort"),r(s.expr,"filters",s.expr.pseudos,"expr-pre-pseudos","jQuery.expr.filters is deprecated; use jQuery.expr.pseudos"),r(s.expr,":",s.expr.pseudos,"expr-pre-pseudos","jQuery.expr[':'] is deprecated; use jQuery.expr.pseudos"),e("3.1.1")&&c(s,"trim",function(e){return null==e?"":(e+"").replace(v,"$1")},"trim","jQuery.trim is deprecated; use String.prototype.trim"),e("3.2.0")&&(c(s,"nodeName",function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},"nodeName","jQuery.nodeName is deprecated"),c(s,"isArray",Array.isArray,"isArray","jQuery.isArray is deprecated; use Array.isArray")),e("3.3.0")&&(c(s,"isNumeric",function(e){var t=typeof e;return("number"==t||"string"==t)&&!isNaN(e-parseFloat(e))},"isNumeric","jQuery.isNumeric() is deprecated"),s.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){f["[object "+t+"]"]=t.toLowerCase()}),c(s,"type",function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?f[Object.prototype.toString.call(e)]||"object":typeof e},"type","jQuery.type is deprecated"),c(s,"isFunction",function(e){return"function"==typeof e},"isFunction","jQuery.isFunction() is deprecated"),c(s,"isWindow",function(e){return null!=e&&e===e.window},"isWindow","jQuery.isWindow() is deprecated")),s.ajax&&(l=s.ajax,p=/(=)\?(?=&|$)|\?\?/,i(s,"ajax",function(){var e=l.apply(this,arguments);return e.promise&&(c(e,"success",e.done,"jqXHR-methods","jQXHR.success is deprecated and removed"),c(e,"error",e.fail,"jqXHR-methods","jQXHR.error is deprecated and removed"),c(e,"complete",e.always,"jqXHR-methods","jQXHR.complete is deprecated and removed")),e},"jqXHR-methods"),e("4.0.0")||s.ajaxPrefilter("+json",function(e){!1!==e.jsonp&&(p.test(e.url)||"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&p.test(e.data))&&u("jsonp-promotion","JSON-to-JSONP auto-promotion is deprecated")}));var j=s.fn.removeAttr,b=s.fn.toggleClass,Q=/^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i,w=/\S+/g;function x(e){return e.replace(/-([a-z])/g,function(e,t){return t.toUpperCase()})}i(s.fn,"removeAttr",function(e){var r=this,n=!1;return s.each(e.match(w),function(e,t){Q.test(t)&&r.each(function(){if(!1!==s(this).prop(t))return!(n=!0)}),n&&(u("removeAttr-bool","jQuery.fn.removeAttr no longer sets boolean properties: "+t),r.prop(t,!1))}),j.apply(this,arguments)},"removeAttr-bool"),i(s.fn,"toggleClass",function(t){return void 0!==t&&"boolean"!=typeof t?b.apply(this,arguments):(u("toggleClass-bool","jQuery.fn.toggleClass( boolean ) is deprecated"),this.each(function(){var e=this.getAttribute&&this.getAttribute("class")||"";e&&s.data(this,"__className__",e),this.setAttribute&&this.setAttribute("class",!e&&!1!==t&&s.data(this,"__className__")||"")}))},"toggleClass-bool");var A,R,S=!1,k=/^[a-z]/,N=/^(?:Border(?:Top|Right|Bottom|Left)?(?:Width|)|(?:Margin|Padding)?(?:Top|Right|Bottom|Left)?|(?:Min|Max)?(?:Width|Height))$/;s.swap&&s.each(["height","width","reliableMarginRight"],function(e,t){var r=s.cssHooks[t]&&s.cssHooks[t].get;r&&(s.cssHooks[t].get=function(){var e;return S=!0,e=r.apply(this,arguments),S=!1,e})}),i(s,"swap",function(e,t,r,n){var o,a,i={};for(a in S||u("swap","jQuery.swap() is undocumented and deprecated"),t)i[a]=e.style[a],e.style[a]=t[a];for(a in o=r.apply(e,n||[]),t)e.style[a]=i[a];return o},"swap"),e("3.4.0")&&"undefined"!=typeof Proxy&&(s.cssProps=new Proxy(s.cssProps||{},{set:function(){return u("cssProps","jQuery.cssProps is deprecated"),Reflect.set.apply(this,arguments)}})),e("4.0.0")?(R={animationIterationCount:!0,aspectRatio:!0,borderImageSlice:!0,columnCount:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,scale:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeMiterlimit:!0,strokeOpacity:!0},"undefined"!=typeof Proxy?s.cssNumber=new Proxy(R,{get:function(){return u("css-number","jQuery.cssNumber is deprecated"),Reflect.get.apply(this,arguments)},set:function(){return u("css-number","jQuery.cssNumber is deprecated"),Reflect.set.apply(this,arguments)}}):s.cssNumber=R):R=s.cssNumber,A=s.fn.css,i(s.fn,"css",function(e,t){var r,n,o=this;return e&&"object"==typeof e&&!Array.isArray(e)?(s.each(e,function(e,t){s.fn.css.call(o,e,t)}),this):("number"==typeof t&&(r=x(e),n=r,k.test(n)&&N.test(n[0].toUpperCase()+n.slice(1))||R[r]||u("css-number",'Number-typed values are deprecated for jQuery.fn.css( "'+e+'", value )')),A.apply(this,arguments))},"css-number");var P,C,H,E,M=s.data;i(s,"data",function(e,t,r){var n,o,a;if(t&&"object"==typeof t&&2===arguments.length){for(a in n=s.hasData(e)&&M.call(this,e),o={},t)a!==x(a)?(u("data-camelCase","jQuery.data() always sets/gets camelCased names: "+a),n[a]=t[a]):o[a]=t[a];return M.call(this,e,o),t}return t&&"string"==typeof t&&t!==x(t)&&(n=s.hasData(e)&&M.call(this,e))&&t in n?(u("data-camelCase","jQuery.data() always sets/gets camelCased names: "+t),2<arguments.length&&(n[t]=r),n[t]):M.apply(this,arguments)},"data-camelCase"),s.fx&&(H=s.Tween.prototype.run,E=function(e){return e},i(s.Tween.prototype,"run",function(){1<s.easing[this.easing].length&&(u("easing-one-arg","'jQuery.easing."+this.easing.toString()+"' should use only one argument"),s.easing[this.easing]=E),H.apply(this,arguments)},"easing-one-arg"),P=s.fx.interval,C="jQuery.fx.interval is deprecated",n.requestAnimationFrame&&Object.defineProperty(s.fx,"interval",{configurable:!0,enumerable:!0,get:function(){return n.document.hidden||u("fx-interval",C),s.migrateIsPatchEnabled("fx-interval")&&void 0===P?13:P},set:function(e){u("fx-interval",C),P=e}}));var q=s.fn.load,O=s.event.add,F=s.event.fix;s.event.props=[],s.event.fixHooks={},r(s.event.props,"concat",s.event.props.concat,"event-old-patch","jQuery.event.props.concat() is deprecated and removed"),i(s.event,"fix",function(e){var t,r=e.type,n=this.fixHooks[r],o=s.event.props;if(o.length){u("event-old-patch","jQuery.event.props are deprecated and removed: "+o.join());while(o.length)s.event.addProp(o.pop())}if(n&&!n._migrated_&&(n._migrated_=!0,u("event-old-patch","jQuery.event.fixHooks are deprecated and removed: "+r),(o=n.props)&&o.length))while(o.length)s.event.addProp(o.pop());return t=F.call(this,e),n&&n.filter?n.filter(t,e):t},"event-old-patch"),i(s.event,"add",function(e,t){return e===n&&"load"===t&&"complete"===n.document.readyState&&u("load-after-event","jQuery(window).on('load'...) called after load event occurred"),O.apply(this,arguments)},"load-after-event"),s.each(["load","unload","error"],function(e,t){i(s.fn,t,function(){var e=Array.prototype.slice.call(arguments,0);return"load"===t&&"string"==typeof e[0]?q.apply(this,e):(u("shorthand-removed-v3","jQuery.fn."+t+"() is deprecated"),e.splice(0,0,t),arguments.length?this.on.apply(this,e):(this.triggerHandler.apply(this,e),this))},"shorthand-removed-v3")}),s.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,r){c(s.fn,r,function(e,t){return 0<arguments.length?this.on(r,null,e,t):this.trigger(r)},"shorthand-deprecated-v3","jQuery.fn."+r+"() event shorthand is deprecated")}),s(function(){s(n.document).triggerHandler("ready")}),s.event.special.ready={setup:function(){this===n.document&&u("ready-event","'ready' event is deprecated")}},c(s.fn,"bind",function(e,t,r){return this.on(e,null,t,r)},"pre-on-methods","jQuery.fn.bind() is deprecated"),c(s.fn,"unbind",function(e,t){return this.off(e,null,t)},"pre-on-methods","jQuery.fn.unbind() is deprecated"),c(s.fn,"delegate",function(e,t,r,n){return this.on(t,e,r,n)},"pre-on-methods","jQuery.fn.delegate() is deprecated"),c(s.fn,"undelegate",function(e,t,r){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",r)},"pre-on-methods","jQuery.fn.undelegate() is deprecated"),c(s.fn,"hover",function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)},"pre-on-methods","jQuery.fn.hover() is deprecated");function T(e){var t=n.document.implementation.createHTMLDocument("");return t.body.innerHTML=e,t.body&&t.body.innerHTML}var D=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi;c(s,"UNSAFE_restoreLegacyHtmlPrefilter",function(){s.migrateEnablePatches("self-closed-tags")},"legacy-self-closed-tags",'jQuery.UNSAFE_restoreLegacyHtmlPrefilter deprecated; use `jQuery.migrateEnablePatches( "self-closed-tags" )`'),i(s,"htmlPrefilter",function(e){var t,r;return(r=(t=e).replace(D,"<$1></$2>"))!==t&&T(t)!==T(r)&&u("self-closed-tags","HTML tags must be properly nested and closed: "+t),e.replace(D,"<$1></$2>")},"self-closed-tags"),s.migrateDisablePatches("self-closed-tags");var _,I,W,J=s.fn.offset;return i(s.fn,"offset",function(){var e=this[0];return!e||e.nodeType&&e.getBoundingClientRect?J.apply(this,arguments):(u("offset-valid-elem","jQuery.fn.offset() requires a valid DOM element"),arguments.length?this:void 0)},"offset-valid-elem"),s.ajax&&(_=s.param,i(s,"param",function(e,t){var r=s.ajaxSettings&&s.ajaxSettings.traditional;return void 0===t&&r&&(u("param-ajax-traditional","jQuery.param() no longer uses jQuery.ajaxSettings.traditional"),t=r),_.call(this,e,t)},"param-ajax-traditional")),c(s.fn,"andSelf",s.fn.addBack,"andSelf","jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()"),s.Deferred&&(I=s.Deferred,W=[["resolve","done",s.Callbacks("once memory"),s.Callbacks("once memory"),"resolved"],["reject","fail",s.Callbacks("once memory"),s.Callbacks("once memory"),"rejected"],["notify","progress",s.Callbacks("memory"),s.Callbacks("memory")]],i(s,"Deferred",function(e){var a=I(),i=a.promise();function t(){var o=arguments;return s.Deferred(function(n){s.each(W,function(e,t){var r="function"==typeof o[e]&&o[e];a[t[1]](function(){var e=r&&r.apply(this,arguments);e&&"function"==typeof e.promise?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[t[0]+"With"](this===i?n.promise():this,r?[e]:arguments)})}),o=null}).promise()}return c(a,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),c(i,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),e&&e.call(a,a),a},"deferred-pipe"),s.Deferred.exceptionHook=I.exceptionHook),s});

/* ========================================
 FILE: /includes/js/jquery/cs_custom_jquery_functions.js
 ==================== */

/*
 * Creativesites s.r.o.
 * Custom Jquery Functions
 *
 * Vsetky custom funkcie, ktore rozsiruju jQuery objekt, pridavajte sem
 */

if ( typeof js_CS_Config_log_xhr_payload !== 'undefined' && js_CS_Config_log_xhr_payload ) {
	(function() {
		window.csSavedErrorJsonResponse = '';

		var origOpen = XMLHttpRequest.prototype.open;
		XMLHttpRequest.prototype.open = function() {
			this.addEventListener('loadstart', function() {
				csSavedErrorJsonResponse = '';
			});
			this.addEventListener('progress', function() {
				if ( this.responseType === '' || this.responseType === 'text' ) {
					csSavedErrorJsonResponse = this.responseText;
				}
			});
			origOpen.apply(this, arguments);
		};
	})();
} else {
	window.csSavedErrorJsonResponse = '';
}

document.addEventListener('lazybeforeunveil', function(event) {
	if (event.target.tagName == 'svg') {
		var elem = event.target;
		var url = elem.getAttribute('data-src');
		elem.removeAttribute('data-src');

		jQuery.get(url, function(res) {
			if (typeof res === 'undefined' || typeof res.getElementsByTagName !== 'function') {
				return;
			}

			var svg = res.getElementsByTagName('svg');
			if (svg.length) {
				// But we only want the first.
				svg = svg[0];

				// Copy over the attributes first.
				var attr = svg.attributes;
				var attrLen = attr.length;
				for (var i = 0; i < attrLen; ++i) {
					if (attr[i].specified) {
						// Merge classes.
						if ('class' === attr[i].name) {
							//var classes = attr[i].value.replace(/\s+/g, ' ').trim().split(' ');
							//var classesLen = classes.length;
							//for (var j = 0; j < classesLen; ++j) {
							//	elem.classList.add(classes[j]);
							//}
						}
						// Add/replace anything else.
						else {
							elem.setAttribute(attr[i].name, attr[i].value);
						}
					}
				}

				// Now transfer over the children. Note: IE does not
				// assign an innerHTML property to SVGs, so we need to
				// go node by node.
				while (svg.childNodes.length) {
					elem.appendChild(svg.childNodes[0]);
				}
			}
		});
	}
});

(function() {
	var matched, browser;

	// Use of jQuery.browser is frowned upon.
	// More details: http://api.jquery.com/jQuery.browser
	// jQuery.uaMatch maintained for back-compat
	jQuery.uaMatch = function( ua ) {
		ua = ua.toLowerCase();

		var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
			/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
			/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
			/(msie) ([\w.]+)/.exec( ua ) ||
			ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
			[];

		return {
			browser: match[ 1 ] || "",
			version: match[ 2 ] || "0"
		};
	};

	matched = jQuery.uaMatch( navigator.userAgent );
	browser = {};

	if ( matched.browser ) {
		browser[ matched.browser ] = true;
		browser.version = matched.version;
	}

	// Chrome is Webkit, but Webkit is also Safari.
	if ( browser.chrome ) {
		browser.webkit = true;
	} else if ( browser.webkit ) {
		browser.safari = true;
	}

	jQuery.browser = browser;
})();

window.addEventListener('DOMContentLoaded', function() {

	// ak uiautocomplete nie je definovany on ready, tak ho definujeme
	if ( typeof jQuery.fn.uiautocomplete === 'undefined' && jQuery.fn.autocomplete !== 'undefined' ) {
		jQuery.fn.uiautocomplete = jQuery.fn.autocomplete;
	}
});


/* ========================================
 FILE: /includes/js/jquery.cookie.js
 ==================== */

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $jQ.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $jQ.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $jQ.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $jQ.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $jQ.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $jQ.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $jQ.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the values of all cookies.
 *
 * @example $jQ.cookie('*');
 * @desc Get the values of all cookie in array.
 *
 * @example $jQ.cookie('my_items_*');
 * @desc Get the values of all cookie with name begins 'my_items_' in array.
 *
 * @name $jQ.cookie
 * @cat Plugins/Cookie
 * @author Calim
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            if (name.substr(-1, 1)=='*') {
            		//cookieValue = cookies;
            		cookieValue = new Array();
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					var cp = cookie.indexOf('=');
					if (cp > -1) {
						cn = cookie.substr(0, cp);
						if (name=='*' || cn.substr(0, name.length-1)+'*' == name) cookieValue[cookieValue.length] = [cn, decodeURIComponent(cookie.substr(cp+1))];
					}
				}
            } else {
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
            }
        }
        return cookieValue;
    }
};

/* ========================================
 FILE: /includes/js/js-cookie/js.cookie.js
 ==================== */

/*!
 * JavaScript Cookie v2.2.1
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
;(function (factory) {
	var registeredInModuleLoader;
	if (typeof define === 'function' && define.amd) {
		define(factory);
		registeredInModuleLoader = true;
	}
	if (typeof exports === 'object') {
		module.exports = factory();
		registeredInModuleLoader = true;
	}
	if (!registeredInModuleLoader) {
		var OldCookies = window.Cookies;
		var api = window.Cookies = factory();
		api.noConflict = function () {
			window.Cookies = OldCookies;
			return api;
		};
	}
}(function () {
	function extend () {
		var i = 0;
		var result = {};
		for (; i < arguments.length; i++) {
			var attributes = arguments[ i ];
			for (var key in attributes) {
				result[key] = attributes[key];
			}
		}
		return result;
	}

	function decode (s) {
		return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
	}

	function init (converter) {
		function api() {}

		function set (key, value, attributes) {
			if (typeof document === 'undefined') {
				return;
			}

			attributes = extend({
				path: '/'
			}, api.defaults, attributes);

			if (typeof attributes.expires === 'number') {
				attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
			}

			// We're using "expires" because "max-age" is not supported by IE
			attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';

			try {
				var result = JSON.stringify(value);
				if (/^[\{\[]/.test(result)) {
					value = result;
				}
			} catch (e) {}

			value = converter.write ?
				converter.write(value, key) :
				encodeURIComponent(String(value))
					.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);

			key = encodeURIComponent(String(key))
				.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
				.replace(/[\(\)]/g, escape);

			var stringifiedAttributes = '';
			for (var attributeName in attributes) {
				if (!attributes[attributeName]) {
					continue;
				}
				stringifiedAttributes += '; ' + attributeName;
				if (attributes[attributeName] === true) {
					continue;
				}

				// Considers RFC 6265 section 5.2:
				// ...
				// 3.  If the remaining unparsed-attributes contains a %x3B (";")
				//     character:
				// Consume the characters of the unparsed-attributes up to,
				// not including, the first %x3B (";") character.
				// ...
				stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
			}

			return (document.cookie = key + '=' + value + stringifiedAttributes);
		}

		function get (key, json) {
			if (typeof document === 'undefined') {
				return;
			}

			var jar = {};
			// To prevent the for loop in the first place assign an empty array
			// in case there are no cookies at all.
			var cookies = document.cookie ? document.cookie.split('; ') : [];
			var i = 0;

			for (; i < cookies.length; i++) {
				var parts = cookies[i].split('=');
				var cookie = parts.slice(1).join('=');

				if (!json && cookie.charAt(0) === '"') {
					cookie = cookie.slice(1, -1);
				}

				try {
					var name = decode(parts[0]);
					cookie = (converter.read || converter)(cookie, name) ||
						decode(cookie);

					if (json) {
						try {
							cookie = JSON.parse(cookie);
						} catch (e) {}
					}

					jar[name] = cookie;

					if (key === name) {
						break;
					}
				} catch (e) {}
			}

			return key ? jar[key] : jar;
		}

		api.set = set;
		api.get = function (key) {
			return get(key, false /* read as raw */);
		};
		api.getJSON = function (key) {
			return get(key, true /* read as json */);
		};
		api.remove = function (key, attributes) {
			set(key, '', extend(attributes, {
				expires: -1
			}));
		};

		api.defaults = {};

		api.withConverter = init;

		return api;
	}

	return init(function () {});
}));


/* ========================================
 FILE: /includes/js/core.js
 ==================== */

var script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};
var script_manage_params_jcsl_jq = typeof script_manage_params.jcsl_jq !== 'undefined' ? script_manage_params.jcsl_jq : '';
var script_manage_params_jcsl_g = typeof script_manage_params.jcsl_g !== 'undefined' ? script_manage_params.jcsl_g : '';
var script_manage_params_ls = typeof script_manage_params.ls !== 'undefined' ? script_manage_params.ls : '';
var script_manage_params_sws = typeof script_manage_params.sws !== 'undefined' ? script_manage_params.sws : '';
var script_manage_params_lss = typeof script_manage_params.lss !== 'undefined' ? script_manage_params.lss : '';
var script_manage_params_cs = typeof script_manage_params.cs !== 'undefined' ? script_manage_params.cs : '';
var script_manage_params_csu = typeof script_manage_params.csu !== 'undefined' ? script_manage_params.csu : '';
var script_manage_params_is_admin = typeof script_manage_params.is_admin !== 'undefined' ? script_manage_params.is_admin : '';
var script_manage_params_csu_ip = typeof script_manage_params.csu_ip !== 'undefined' ? script_manage_params.csu_ip : '';
var script_manage_params_jsc = typeof script_manage_params.jsc !== 'undefined' ? script_manage_params.jsc : '';
var script_manage_params_sra = typeof script_manage_params.sra !== 'undefined' ? script_manage_params.sra : '';
var script_manage_params_du = typeof script_manage_params.devu !== 'undefined' ? script_manage_params.devu : false;
var script_manage_params_svp = typeof script_manage_params.svp !== 'undefined' ? script_manage_params.svp : '';
var script_manage_params_pame = typeof script_manage_params.pame !== 'undefined' ? script_manage_params.pame : false;
var script_manage_params_pamsf = typeof script_manage_params.pamsf !== 'undefined' ? script_manage_params.pamsf : false;
var script_manage_params_npfsv = typeof script_manage_params.npfsv !== 'undefined' ? script_manage_params.npfsv : false;
var script_manage_params_madom = typeof script_manage_params.madom !== 'undefined' && script_manage_params.madom !== null ? script_manage_params.madom : '';
var script_manage_params_ismyid = typeof script_manage_params.ismyid !== 'undefined' ? script_manage_params.ismyid : '';
var script_manage_params_mynm = typeof script_manage_params.mynm !== 'undefined' ? script_manage_params.mynm : '';
var script_manage_params_myem = typeof script_manage_params.myem !== 'undefined' ? script_manage_params.myem : '';
var script_manage_params_mygid = typeof script_manage_params.mygid !== 'undefined' ? script_manage_params.mygid : '';
var script_manage_params_myshgid = typeof script_manage_params.myshgid !== 'undefined' ? script_manage_params.myshgid : '';
var script_manage_params_ucri = typeof script_manage_params.ucri !== 'undefined' ? script_manage_params.ucri : '';
var script_manage_params_sspuefri = typeof script_manage_params.sspuefri !== 'undefined' ? script_manage_params.sspuefri : '';
var script_manage_params_sspuefrit = typeof script_manage_params.sspuefrit !== 'undefined' ? script_manage_params.sspuefrit : '';
var script_manage_params_gl = typeof script_manage_params.gl !== 'undefined' ? script_manage_params.gl : '';
var script_manage_params_cl = typeof script_manage_params.cl !== 'undefined' ? script_manage_params.cl : '';
var script_manage_params_jfe = typeof script_manage_params.jfe !== 'undefined' ? script_manage_params.jfe : '';
var script_manage_params_jfl = typeof script_manage_params.jfl !== 'undefined' ? script_manage_params.jfl : '';
var script_manage_params_jflid = typeof script_manage_params.jflid !== 'undefined' ? script_manage_params.jflid : '';
var script_manage_params_c_f = typeof script_manage_params.c_f !== 'undefined' ? script_manage_params.c_f : '';
var script_manage_params_j_f = typeof script_manage_params.j_f !== 'undefined' ? script_manage_params.j_f : '';
var script_manage_params_rqcid = typeof script_manage_params.rqcid !== 'undefined' ? script_manage_params.rqcid : '';
var script_manage_params_ptab = typeof script_manage_params.ptab !== 'undefined' ? script_manage_params.ptab : '';
var script_manage_params_paimg = typeof script_manage_params.paimg !== 'undefined' ? script_manage_params.paimg == 'true' : '';
var script_manage_params_paaimg = typeof script_manage_params.paaimg !== 'undefined' ? script_manage_params.paaimg == 'true' : '';
var script_manage_params_paean = typeof script_manage_params.paean !== 'undefined' ? script_manage_params.paean == 'true' : '';
var script_manage_params_paw = typeof script_manage_params.paw !== 'undefined' ? script_manage_params.paw == 'true' : '';
var script_manage_params_pasid = typeof script_manage_params.pasid !== 'undefined' ? script_manage_params.pasid == 'true' : '';
var script_manage_params_pasidftr = typeof script_manage_params.pasidftr !== 'undefined' ? script_manage_params.pasidftr == 'true' : '';
var script_manage_params_pamq = typeof script_manage_params.pamq !== 'undefined' ? script_manage_params.pamq == 'true' : '';
var script_manage_params_vdate = typeof script_manage_params.vdate !== 'undefined' ? script_manage_params.vdate : '';
var script_manage_params_attcfill = typeof script_manage_params.attcfill !== 'undefined' ? script_manage_params.attcfill : '';
var script_manage_params_pst = typeof script_manage_params.pst !== 'undefined' ? script_manage_params.pst : '';
var script_manage_params_pact = typeof script_manage_params.pact !== 'undefined' ? script_manage_params.pact : '';
var script_manage_params_product_attribute_custom_text_title = typeof script_manage_params.product_attribute_custom_text_title !== 'undefined' ? script_manage_params.product_attribute_custom_text_title : '';
var script_manage_params_pca = typeof script_manage_params.pca !== 'undefined' ? script_manage_params.pca : '';
var script_manage_params_mca = typeof script_manage_params.mca !== 'undefined' ? script_manage_params.mca : '';
var script_manage_params_pp = typeof script_manage_params.pp !== 'undefined' ? script_manage_params.pp : '';
var script_manage_params_himg = typeof script_manage_params.himg !== 'undefined' ? script_manage_params.himg : '';
var script_manage_params_paop = typeof script_manage_params.paop !== 'undefined' ? script_manage_params.paop == 'true' : '';
var script_manage_params_pprice = typeof script_manage_params.pprice !== 'undefined' ? script_manage_params.pprice == 'true' : '';
var script_manage_params_pasgp = typeof script_manage_params.pasgp !== 'undefined' ? script_manage_params.pasgp == 'true' : '';
var script_manage_params_pass = typeof script_manage_params.pass !== 'undefined' ? script_manage_params.pass == 'true' : '';
var script_manage_params_pcuc = typeof script_manage_params.pcuc !== 'undefined' ? script_manage_params.pcuc : '';
var script_manage_params_aslt = typeof script_manage_params.aslt !== 'undefined' ? script_manage_params.aslt : '';
var script_manage_params_cla = typeof script_manage_params.cla !== 'undefined' ? script_manage_params.cla : '';
var script_manage_params_sfpfel = typeof script_manage_params.sfpfel !== 'undefined' ? script_manage_params.sfpfel : '';
var script_manage_params_pl = typeof script_manage_params.pl !== 'undefined' ? script_manage_params.pl : '';
var script_manage_params_jcsl_fb = typeof script_manage_params.jcsl_fb !== 'undefined' ? script_manage_params.jcsl_fb : '';
var script_manage_params_jcsl_jqac = typeof script_manage_params.jcsl_jqac !== 'undefined' ? script_manage_params.jcsl_jqac : '';
var script_manage_params_pc = typeof script_manage_params.pc !== 'undefined' ? script_manage_params.pc : '';
var script_manage_params_r05 = typeof script_manage_params.r05 !== 'undefined' ? script_manage_params.r05 : '';
var script_manage_params_r1 = typeof script_manage_params.r1 !== 'undefined' ? script_manage_params.r1 : '';
var script_manage_params_r24 = typeof script_manage_params.r24 !== 'undefined' ? script_manage_params.r24 : '';
var script_manage_params_sspascshop_b = typeof script_manage_params.sspascshop_b !== 'undefined' ? script_manage_params.sspascshop_b : '';
var script_manage_params_sspascsites_b = typeof script_manage_params.sspascsites_b !== 'undefined' ? script_manage_params.sspascsites_b : '';
var script_manage_params_sspascsites = typeof script_manage_params.sspascsites !== 'undefined' ? script_manage_params.sspascsites : '';
var script_manage_params_aws_security_level = typeof script_manage_params.aws_security_level !== 'undefined' ? script_manage_params.aws_security_level : 'x';
var script_manage_params_js_server_ip = typeof script_manage_params.js_server_ip !== 'undefined' ? script_manage_params.js_server_ip : '';
var script_manage_params_paaf = typeof script_manage_params.paaf !== 'undefined' ? script_manage_params.paaf : ''; //product atribute available from
var script_manage_params_gdir = typeof script_manage_params.gdir !== 'undefined' ? script_manage_params.gdir : [];

if (script_manage_params_jcsl_jq) {
	$jQ = jQuery.noConflict();
}

if (js_aws_security_level == null || typeof(js_aws_security_level) === 'undefined') var js_aws_security_level = script_manage_params.aws_security_level;
if (js_server_ip == null || typeof(js_server_ip) != 'string' || js_server_ip.trim() == '') var js_server_ip = script_manage_params.js_server_ip;

if (script_manage_params_jcsl_g) {
	if (typeof(js_cf_active) === 'undefined') js_cf_active = script_manage_params.cf_active;
	if (typeof(js_global_live_site) === 'undefined') var js_global_live_site = script_manage_params_ls;
	if (typeof(js_global_skvelyweb_site) === 'undefined') var js_global_skvelyweb_site = script_manage_params_sws;
	if (typeof(js_global_live_site_sef) === 'undefined') js_global_live_site_sef = script_manage_params_lss;
	if (typeof(js_global_cache_site) === 'undefined') js_global_cache_site = script_manage_params_cs;
	if (typeof(js_global_is_csu) === 'undefined') var js_global_is_csu = script_manage_params_csu;
	if (typeof(js_global_is_admin) === 'undefined') var js_global_is_admin = script_manage_params_is_admin;
	if (typeof(js_global_js_categories) === 'undefined') var js_global_js_categories = script_manage_params_jsc;
	if (typeof(js_global_is_csip) === 'undefined') js_global_is_csip = script_manage_params_csu_ip;
	if (typeof(js_global_is_devu) === 'undefined') js_global_is_devu = script_manage_params_du;
	if (typeof(js_global_user_shgid) === 'undefined') js_global_user_shgid = script_manage_params_myshgid;
	if (typeof(js_global_is_store_vat_payer) === 'undefined') js_global_is_store_vat_payer = script_manage_params_svp;
	
	if (typeof(js_global_product_attribute_matrix_enabled) === 'undefined') js_global_product_attribute_matrix_enabled = script_manage_params_pame;
	if (typeof(js_global_product_attribute_matrix_in_stock_forced) === 'undefined') js_global_product_attribute_matrix_in_stock_forced = script_manage_params_pamsf;
	if (typeof(js_global_new_product_forced_stock_value) === 'undefined') js_global_new_product_forced_stock_value = script_manage_params_npfsv;
	if (typeof(js_global_main_domain) === 'undefined') js_global_main_domain = ( script_manage_params_madom !== '' ? script_manage_params_madom : '' );

	if ( script_manage_params_ismyid ) {
		
		if (typeof(js_global_user_info) === 'undefined') js_global_user_info = {};
		
		if ( script_manage_params_mynm != '' ) {
			if (typeof(js_global_user_info.name) === 'undefined') js_global_user_info.name = script_manage_params_mynm;
		}
		
		if ( script_manage_params_myem != '' ) {
			if (typeof(js_global_user_info.email) === 'undefined') js_global_user_info.email = script_manage_params_myem;
		}
		
		if ( script_manage_params_mygid != '' ) {
			if (typeof(js_global_user_info.gid) === 'undefined') js_global_user_info.gid = script_manage_params_mygid;
		}
		
		// JAN user credit info
		if ( script_manage_params_ucri != '' ) {
			if (typeof(js_global_user_info.ucri) === 'undefined') js_global_user_info.ucri = script_manage_params_ucri;
		}
	}
	
	if ( script_manage_params_sspuefri ) {
		
		if (typeof(js_global_ssp_user_info) === 'undefined') js_global_ssp_user_info = {};

		if ( script_manage_params_sspuefrit != '' ) {
			if (typeof(js_global_ssp_user_info.package_type) === 'undefined') js_global_ssp_user_info.package_type = script_manage_params_sspuefrit;
		}
	}
	if (script_manage_params_gl != '')	if (typeof(js_get_lang) === 'undefined') js_get_lang = script_manage_params_gl;
	if (typeof(js_curr_lang) === 'undefined') js_curr_lang  = script_manage_params_cl;
	if (typeof(jf_enabled) === 'undefined') jf_enabled  = script_manage_params_jfe;
	
	if (typeof(jf_langs) === 'undefined') jf_langs  = typeof script_manage_params_jfl === 'string' ? JSON.parse(script_manage_params_jfl) : script_manage_params_jfl;
	if (jf_langs === null) jf_langs = [];
	
	if (typeof(jf_langs_id) === 'undefined') jf_langs_id  = typeof script_manage_params_jflid === 'string' ? JSON.parse(script_manage_params_jflid) : script_manage_params_jflid;
	if (typeof(jf_curr_flag) === 'undefined') jf_curr_flag  = script_manage_params_c_f;
	
	if (typeof(jf_flags) === 'undefined') jf_flags  = typeof script_manage_params_j_f === 'string' ? JSON.parse(script_manage_params_j_f) : script_manage_params_j_f;
	if (jf_flags === null) jf_flags = [];

	if (typeof(js_category_id) === 'undefined') js_category_id = script_manage_params_rqcid;
	if (typeof(js_prod_tabs) === 'undefined') js_prod_tabs = script_manage_params_ptab;
	if (typeof(js_prod_attr_img) === 'undefined') js_prod_attr_img = script_manage_params_paimg;
	if (typeof(js_prod_attr_active_img) === 'undefined') js_prod_attr_active_img = script_manage_params_paaimg;
	//if (typeof(js_prod_attr_ean) === 'undefined') js_prod_attr_ean = true;
	if (typeof(js_prod_attr_ean) === 'undefined') js_prod_attr_ean = script_manage_params_paean;
	if (typeof(js_prod_attr_weight) === 'undefined') js_prod_attr_weight = script_manage_params_paw;
	if (typeof(js_prod_attr_sid) === 'undefined') js_prod_attr_sid = script_manage_params_pasid;
	if (typeof(js_prod_attr_sid_filter) === 'undefined') js_prod_attr_sid_filter = script_manage_params_pasidftr;
	if (typeof(js_prod_attr_vdate) === 'undefined') js_prod_attr_vdate = script_manage_params_vdate;
	if (typeof(js_prod_attr_check_fill) === 'undefined') js_prod_attr_check_fill = script_manage_params_attcfill;
	if (typeof(js_prod_size_table_dir) === 'undefined') js_prod_size_table_dir = script_manage_params_pst;
	if (typeof(js_prod_attr_available_from) === 'undefined') js_prod_attr_available_from = script_manage_params_paaf;
	if (typeof(js_gdir_list) === 'undefined') js_gdir_list = script_manage_params_gdir;

	if (typeof(js_prod_attr_mq) === 'undefined') js_prod_attr_mq = script_manage_params_pamq;

	var js_product_attribute_custom_text_tmp = 0;
	
	if ( typeof script_manage_params_pact === 'number' && script_manage_params_pact > 0 ) {
		js_product_attribute_custom_text_tmp = script_manage_params_pact;
	}

	if (typeof(js_product_attribute_custom_text) === 'undefined') js_product_attribute_custom_text = js_product_attribute_custom_text_tmp;
	delete js_product_attribute_custom_text_tmp;


	var js_product_attribute_custom_text_title_tmp = 0;

	if ( script_manage_params_product_attribute_custom_text_title.length > 1) {
		js_product_attribute_custom_text_title_tmp = script_manage_params_product_attribute_custom_text_title;
	}

	if (typeof(js_product_attribute_custom_text_title) == 'undefined') js_product_attribute_custom_text_title = js_product_attribute_custom_text_title_tmp;
	delete js_product_attribute_custom_text_title_tmp;
	
	if (typeof(js_product_categ_list_parent_categ_autoselect) === 'undefined') js_product_categ_list_parent_categ_autoselect = script_manage_params_pca;
	if (typeof(js_product_manu_to_categ_list_autoselect_id) === 'undefined') js_product_manu_to_categ_list_autoselect_id = script_manage_params_mca;
	if (typeof(js_product_params_enabled) === 'undefined') js_product_params_enabled = script_manage_params_pp;
	if (typeof(js_header_edit_img_forced) === 'undefined') js_header_edit_img_forced = script_manage_params_himg;
	if (typeof(js_prod_attr_old_price) === 'undefined') js_prod_attr_old_price = script_manage_params_paop;
	if (typeof(js_prod_attr_purchase_price) === 'undefined') js_prod_attr_purchase_price = script_manage_params_pprice;
	if (typeof(js_prod_attr_sgp) === 'undefined') js_prod_attr_sgp = script_manage_params_pasgp;
	if (typeof(js_prod_attr_ss) === 'undefined') js_prod_attr_ss = script_manage_params_pass;
	
	if (typeof(js_prod_compare_use_carousel) === 'undefined') js_prod_compare_use_carousel = script_manage_params_pcuc != '';
	
	if ( typeof script_manage_params_aslt !== 'undefined' ) { /* admin session life time */
		if (typeof(js_admin_sess_lt) === 'undefined') js_admin_sess_lt = 43200;
	}

	/* pexf + param filter */
	if ( typeof script_manage_params_cla !== 'undefined'  ) {
		if (typeof(js_custom_page_limit) === 'undefined') js_custom_page_limit = script_manage_params_cla;
	}
	if ( typeof script_manage_params_sfpfel !== 'undefined' ) {
		if (typeof(js_filter_param_from_url) === 'undefined') js_filter_param_from_url = script_manage_params_sfpfel;
	}
	if ( typeof script_manage_params_pl !== 'undefined' ) {
		if (typeof(js_filter_pagination_enabled) === 'undefined') js_filter_pagination_enabled = script_manage_params_pl;
	}
	/* \\ pexf + param filter */
}

if ( typeof script_manage_params_jcsl_fb !== 'undefined' && script_manage_params_jcsl_fb ) {
	_JS_LNG_PROMPT_CLOSE = script_manage_params_pc;
}

if ( typeof script_manage_params_jcsl_jqac !== 'undefined' && script_manage_params_jcsl_jqac ) {
	js_global_adminlang_results_0_5 = script_manage_params_r05;
	js_global_adminlang_results_1 = script_manage_params_r1;
	js_global_adminlang_results_2_4 = script_manage_params_r24;
}

var countryISOMapping = {
	AFG: "AF",
	ALA: "AX",
	ALB: "AL",
	DZA: "DZ",
	ASM: "AS",
	AND: "AD",
	AGO: "AO",
	AIA: "AI",
	ATA: "AQ",
	ATG: "AG",
	ARG: "AR",
	ARM: "AM",
	ABW: "AW",
	AUS: "AU",
	AUT: "AT",
	AZE: "AZ",
	BHS: "BS",
	BHR: "BH",
	BGD: "BD",
	BRB: "BB",
	BLR: "BY",
	BEL: "BE",
	BLZ: "BZ",
	BEN: "BJ",
	BMU: "BM",
	BTN: "BT",
	BOL: "BO",
	BIH: "BA",
	BWA: "BW",
	BVT: "BV",
	BRA: "BR",
	VGB: "VG",
	IOT: "IO",
	BRN: "BN",
	BGR: "BG",
	BFA: "BF",
	BDI: "BI",
	KHM: "KH",
	CMR: "CM",
	CAN: "CA",
	CPV: "CV",
	CYM: "KY",
	CAF: "CF",
	TCD: "TD",
	CHL: "CL",
	CHN: "CN",
	HKG: "HK",
	MAC: "MO",
	CXR: "CX",
	CCK: "CC",
	COL: "CO",
	COM: "KM",
	COG: "CG",
	COD: "CD",
	COK: "CK",
	CRI: "CR",
	CIV: "CI",
	HRV: "HR",
	CUB: "CU",
	CYP: "CY",
	CZE: "CZ",
	DNK: "DK",
	DJI: "DJ",
	DMA: "DM",
	DOM: "DO",
	ECU: "EC",
	EGY: "EG",
	SLV: "SV",
	GNQ: "GQ",
	ERI: "ER",
	EST: "EE",
	ETH: "ET",
	FLK: "FK",
	FRO: "FO",
	FJI: "FJ",
	FIN: "FI",
	FRA: "FR",
	GUF: "GF",
	PYF: "PF",
	ATF: "TF",
	GAB: "GA",
	GMB: "GM",
	GEO: "GE",
	DEU: "DE",
	GHA: "GH",
	GIB: "GI",
	GRC: "GR",
	GRL: "GL",
	GRD: "GD",
	GLP: "GP",
	GUM: "GU",
	GTM: "GT",
	GGY: "GG",
	GIN: "GN",
	GNB: "GW",
	GUY: "GY",
	HTI: "HT",
	HMD: "HM",
	VAT: "VA",
	HND: "HN",
	HUN: "HU",
	ISL: "IS",
	IND: "IN",
	IDN: "ID",
	IRN: "IR",
	IRQ: "IQ",
	IRL: "IE",
	IMN: "IM",
	ISR: "IL",
	ITA: "IT",
	JAM: "JM",
	JPN: "JP",
	JEY: "JE",
	JOR: "JO",
	KAZ: "KZ",
	KEN: "KE",
	KIR: "KI",
	PRK: "KP",
	KOR: "KR",
	KWT: "KW",
	KGZ: "KG",
	LAO: "LA",
	LVA: "LV",
	LBN: "LB",
	LSO: "LS",
	LBR: "LR",
	LBY: "LY",
	LIE: "LI",
	LTU: "LT",
	LUX: "LU",
	MKD: "MK",
	MDG: "MG",
	MWI: "MW",
	MYS: "MY",
	MDV: "MV",
	MLI: "ML",
	MLT: "MT",
	MHL: "MH",
	MTQ: "MQ",
	MRT: "MR",
	MUS: "MU",
	MYT: "YT",
	MEX: "MX",
	FSM: "FM",
	MDA: "MD",
	MCO: "MC",
	MNG: "MN",
	MNE: "ME",
	MSR: "MS",
	MAR: "MA",
	MOZ: "MZ",
	MMR: "MM",
	NAM: "NA",
	NRU: "NR",
	NPL: "NP",
	NLD: "NL",
	ANT: "AN",
	NCL: "NC",
	NZL: "NZ",
	NIC: "NI",
	NER: "NE",
	NGA: "NG",
	NIU: "NU",
	NFK: "NF",
	MNP: "MP",
	NOR: "NO",
	OMN: "OM",
	PAK: "PK",
	PLW: "PW",
	PSE: "PS",
	PAN: "PA",
	PNG: "PG",
	PRY: "PY",
	PER: "PE",
	PHL: "PH",
	PCN: "PN",
	POL: "PL",
	PRT: "PT",
	PRI: "PR",
	QAT: "QA",
	REU: "RE",
	ROU: "RO",
	ROM: "RO",
	RUS: "RU",
	RWA: "RW",
	BLM: "BL",
	SHN: "SH",
	KNA: "KN",
	LCA: "LC",
	MAF: "MF",
	SPM: "PM",
	VCT: "VC",
	WSM: "WS",
	SMR: "SM",
	STP: "ST",
	SAU: "SA",
	SEN: "SN",
	SRB: "RS",
	SYC: "SC",
	SLE: "SL",
	SGP: "SG",
	SVK: "SK",
	SVN: "SI",
	SLB: "SB",
	SOM: "SO",
	ZAF: "ZA",
	SGS: "GS",
	SSD: "SS",
	ESP: "ES",
	LKA: "LK",
	SDN: "SD",
	SUR: "SR",
	SJM: "SJ",
	SWZ: "SZ",
	SWE: "SE",
	CHE: "CH",
	SYR: "SY",
	TWN: "TW",
	TJK: "TJ",
	TZA: "TZ",
	THA: "TH",
	TLS: "TL",
	TGO: "TG",
	TKL: "TK",
	TON: "TO",
	TTO: "TT",
	TUN: "TN",
	TUR: "TR",
	TKM: "TM",
	TCA: "TC",
	TUV: "TV",
	UGA: "UG",
	UKR: "UA",
	ARE: "AE",
	GBR: "GB",
	USA: "US",
	UMI: "UM",
	URY: "UY",
	UZB: "UZ",
	VUT: "VU",
	VEN: "VE",
	VNM: "VN",
	VIR: "VI",
	WLF: "WF",
	ESH: "EH",
	YEM: "YE",
	ZMB: "ZM",
	ZWE: "ZW",
	OTH: "OT",
	HOL: "HO",
	IRS: "IR",
	LIT: "LI",
	POR: "PO",
	PLN: "PL"
};

/* ========================================
 FILE: /includes/js/system/FormValidator.js
 ==================== */

/**
 * Validator na formy pisane cez divField v material designe
 * - required inputy su validovane automaticky
 * - pre custom validaciu a pridanie pravidiel je potrebne pouzit addRule
 *
 * @param formContainer jQuery element, v ktorom sa nachadza cely form
 * @returns {FormValidator}
 * @constructor
 *
 * @author Jakub Sakac <jakub.sakac@creativesites.sk>
 */
var FormValidator = function (formContainer) {
	this.form = jQuery(formContainer);
	this.inputs = this.form.find('input, select, textarea');
	this.rules = [];

	return this;
};

/**
 * Ziskanie hodnot vsetkych inputov, okrem tych disabled
 *
 * @param sanitizeInputs {boolean} ak je true, tak vrati osetrene hodnoty
 */
FormValidator.prototype.getFormValues = function(sanitizeInputs) {
	var formValues = {};

	if ( sanitizeInputs ) {
		this.sanitize();
	}

	this.inputs.not(':disabled').each(function(key, elm) {
		elm = jQuery(elm);

		// ak je input radio button alebo checkbox a nie je zaskrtnuty, tak ho nepridavajme
		if ( (elm.is(':radio') || elm.is(':checkbox')) && !elm.prop('checked') ) {
			return;
		}

		var elmVal = elm.val();
		var elmName = elm.attr('name');

		formValues[elmName] = elmVal;
	});

	return formValues;
};

/**
 * Nabindovanie validacie na vsetky inputy po definovani vsetkych nastaveni a pridani pravidiel
 */
FormValidator.prototype.bindValidation = function() {
	this.inputs.not(':checkbox').on('blur change', jQuery.proxy(function(e) {
		this.validateInput(jQuery(e.target));
	}, this));
};

/**
 * Manualna validacia formulara
 * je potrebne volat pri submite
 *
 * Prechadza vsetky inputy najdene v poli inputov (vytvori sa v constructe)
 *
 * @returns {boolean} vrati ci je formular validny podla definovanych pravidiel
 */
FormValidator.prototype.validate = function() {
	var valid = true;

	this.inputs.not(':disabled').each(jQuery.proxy(function(key, elm) {
		if (!this.validateInput(elm)) valid = false;
	}, this));

	return valid;
};

/**
 * Funkcia na zvalidovanie konkretneho inputu/selectu
 * Interna funkcia, nie je potrebne volat vonku
 *
 * V pripade, ze pravidlo nie je pre input definovane, vrati true a input je validny
 *
 * @param elm konkretny input element
 * @returns {boolean} vrati ci je input validny
 */
FormValidator.prototype.validateInput = function(elm) {
	elm = jQuery(elm);
	var elmVal = elm.val();
	var elmName = elm.attr('name');
	var elmRules = this.rules[elmName];
	var elmIsRequired = elm.hasClass('required');

	elm.toggleClass('filled', this.isDefined(elmVal) && elmVal != '');

	this.removeError(elm);

	// required field
	if (elmIsRequired && ( !this.isDefined(elmVal) || elmVal == '' || (config('js_Config_custom_contact_form_selects') && elm.is('select') && elm.val() === '0')) ) {
		if ( typeof js_Config_forgotten_password_new !== 'undefined' && js_Config_forgotten_password_new ) {

			var labelText = elm.closest('.field').find('label').text();
			labelText = labelText.trim().replace(':', '');

			if (labelText !== '') {
				this.addError(elm, js_lang_new_form_item + ' "' +labelText+ '" ' + js_lang_new_form_nesessery);
			} else {
				this.addError(elm, js_lang_registration_reset_password_field_required );
			}
		} else {
			this.addError(elm, 'Položka je povinná');
		}


		return false;
	}

	// rules nastavene cez addRule
	if (this.isDefined(elmRules)) {
		for (var ruleName in elmRules) {
			if (!elmRules.hasOwnProperty(ruleName)) {
				continue;
			}

			var rule = elmRules[ruleName];

			if (this.isSanitizationRule(rule)) {
				continue;
			}

			if (this.isDefined(rule.conditions) && !this.checkConditions(rule.conditions)) {
				elm.addClass('valid');
				return true;
			}

			if (typeof this[ruleName] === 'function') {
				// zavolanie custom funkcie na overenie
				if ( !this[ruleName](elm, rule) ) {
					return false;
				}
			}
		}
	}

	if (elmIsRequired || this.isDefined(elmRules)) {
		elm.addClass('valid');
	}

	return true;
};

/**
 * Satinizacia/osetrenie hodnot formulara
 * bud sa musi zavolat manualne alebo pri ziskani vsektych hodnot v getFormValues
 *
 * Prechadza vsetky inputy najdene v poli inputov (vytvori sa v constructe)
 */
FormValidator.prototype.sanitize = function() {
	this.inputs.not(':disabled').each(jQuery.proxy(function(key, elm) {
		this.sanitizeInput(elm);
	}, this));
};

/**
 * Funkcia na sanitizaciu/osetrenie konkretneho inputu
 *
 * V pripade, ze custom pravidlo nie je pre input definovane, vrati trimnutu hodnotu
 *
 * @param elm
 * @returns {string}
 */
FormValidator.prototype.sanitizeInput = function(elm) {
	elm = jQuery(elm);
	var elmVal = elm.val();
	var elmName = elm.attr('name');
	var elmRules = this.rules[elmName];

	var trimmedVal = elmVal.trim();

	// rules nastavene cez addRule
	if (this.isDefined(elmRules)) {
		trimmedVal = Object.keys(elmRules).reduce(jQuery.proxy(function(inputVal, ruleName) {
			var rule = elmRules[ruleName];

			if (!this.isSanitizationRule(rule)) {
				return inputVal;
			}

			return this[ruleName](elm, rule, inputVal);
		}, this), trimmedVal);
	}

	elm.val(trimmedVal);
	return trimmedVal;
};

/**
 * Sluzi na overenie podmienok, ktore urcuju, ci sa ma validacia inputu vykonat - vo validateInput
 *
 * V pripade, ak niektory z inputov nema platnu value (podla pola),
 * podmienka nepresla a pravidlo na ktore je naviazana sa nebude overovat (input bude validny)
 *
 * @param {Object.<string, Array>} conditions objekt, v ktorom su ako kluce nazvy inputov (atribut name) a ako value pole hodnot moznych pre tento input
 * @returns {boolean}
 */
FormValidator.prototype.checkConditions = function(conditions) {
	var valid = true;

	for (var elmName in conditions) {
		if (!conditions.hasOwnProperty(elmName)) {
			continue;
		}

		var elm = this.inputs.filter('[name="' + elmName + '"]');

		if (elm.length) {
			var elmVal = elm.val();

			if (typeof conditions[elmName] == 'object' && conditions[elmName].indexOf(elmVal) == -1) {
				valid = false;
			}
		}
	}

	return valid;
};

/**
 * Pridanie pravidla validacie do zoznamu pravidiel
 *
 *
 * @param inputName nazov inputu vo forme
 * @param rule custom metoda overovania - metody su definovane dole v classe
 * @param value kontrolovana hodnota
 * @param message chybova hlaska v pripade, ze input neprejde validaciou
 * @param conditions podmienka, ak jej vysledok je true, input sa zvaliduje, inac nie
 * @param sanitizationRule {boolean} kontrola, ci sa jedna o validacne alebo sanitizacne pravidlo
 * @returns {FormValidator}
 */
FormValidator.prototype.addRule = function(inputName, rule, value, message, conditions, sanitizationRule) {
	if (!this.isDefined(this.rules[inputName])) {
		this.rules[inputName] = [];
	}

	this.rules[inputName][rule] = [];
	this.rules[inputName][rule].value = value;

	if (this.isDefined(sanitizationRule)) {
		this.rules[inputName][rule].sanitizationRule = sanitizationRule;
	}

	if (this.isDefined(message)) {
		this.rules[inputName][rule].message = message;
	}

	if (this.isDefined(conditions)) {
		this.rules[inputName][rule].conditions = conditions;
	}

	return this;
};

/**
 * Vykreslenie chyby v pripade nevalidneho inputu
 *
 * @param elm
 * @param message
 */
FormValidator.prototype.addError = function(elm, message) {
	var $wrapper = elm.closest('.field');

	this.removeError(elm);

	$wrapper.append('<div class="error_box">' + message + "</div>");
	elm.addClass('error');
	elm.removeClass('valid');
};

/**
 * Odstranenie chyby v pripade, ze input je validny
 *
 * @param elm
 */
FormValidator.prototype.removeError = function(elm) {
	var $wrapper = elm.closest('.field');

	$wrapper.find('.error_box').remove();
	elm.removeClass('error');
};

/**
 * @param variable kontrolovana premenna
 * @returns {boolean} premenna existuje
 */
FormValidator.prototype.isDefined = function(variable) {
	return typeof variable !== 'undefined';
};

/**
 *
 * @param rule kontrolovane pravidlo
 * @returns {boolean} nie je validacne pravidlo, ale sanitizacne
 */
FormValidator.prototype.isSanitizationRule = function(rule) {
	return typeof rule.sanitizationRule !== 'undefined' && rule.sanitizationRule ;
};

/*********************************
 ** CUSTOM VALIDACNE PRAVIDLA PRE addRule **
 ********************************/

/**
 * Regex validacia
 *
 * @param elm
 * @param rule
 * @returns {boolean}
 */
FormValidator.prototype.regexMatch = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var valid = elm.val().match(rule.value) != null;
	var message = this.isDefined(rule.message) ? rule.message : 'Hodnota nie je v správnom formáte';

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.allowedChars = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var valid = elm.val().match(rule.value) != null;
	var message = this.isDefined(rule.message) ? rule.message : 'Obsahuje nepovolené znaky';

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.minLength = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var valid = elm.val().length >= rule.value;
	var message = this.isDefined(rule.message) ? rule.message : 'Min. počet znakov: ' + rule.value;

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.maxLength = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var valid = elm.val().length <= rule.value;
	var message = this.isDefined(rule.message) ? rule.message : 'Max. počet znakov: ' + rule.value;

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.min = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	if (isNaN(elm.val()) || isNaN(rule.value)) {
		this.addError(elm, 'Hodnota musí byť číslo');
		return false;
	}

	var valid = elm.val() >= rule.value;
	var message = this.isDefined(rule.message) ? rule.message : 'Min. hodnota: ' + rule.value;

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.max = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	if (isNaN(elm.val()) || isNaN(rule.value)) {
		this.addError(elm, 'Hodnota musí byť číslo');
		return false;
	}

	var valid = elm.val() <= rule.value;
	var message = this.isDefined(rule.message) ? rule.message : 'Max. hodnota: ' + rule.value;

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.enum = function(elm, rule) {
	if (!this.isDefined(rule.value) || !(rule.value instanceof Array)) {
		return false;
	}

	var valid = rule.value.indexOf(elm.val()) !== -1;
	var message = this.isDefined(rule.message) ? rule.message : 'Hodnota nie je v správnom formáte';

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.isEmail = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var emailAddress = elm.val();

	var valid = emailAddress.match(/[\w.\-]+@\w+[\w.\-]*?\.\w{1,4}/) != null;
	var message = this.isDefined(rule.message) ? rule.message : 'Nesprávny tvar e-mailovej adresy: "' + emailAddress + '"';

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.isNumber = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var valid = !isNaN(elm.val());
	var message = this.isDefined(rule.message) ? rule.message : 'Hodnota musí byť číslo';

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.isEqualTo = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var checkAgainstInput = this.form.find('[name="' + rule.value + '"]');

	var valid = elm.val() === checkAgainstInput.val();
	var message = this.isDefined(rule.message) ? rule.message : 'Hodnoty sa nezhodujú';

	if (!valid) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.isChecked = function(elm, rule) {
	if (!elm.prop('checked')) {
		var message = this.isDefined(rule.message) ? rule.message : 'Položka je povinná';
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.isBarcode = function(elm, rule) {
	var barcode = elm.val();
	var message = this.isDefined(rule.message) ? rule.message : 'Kód klubovej karty nie je platný';

	// check length
	if (barcode.length < 8 || barcode.length > 18 ||
		(barcode.length != 8 && barcode.length != 12 &&
			barcode.length != 13 && barcode.length != 14 &&
			barcode.length != 18)) {
		this.addError(elm, message);
		return false;
	}

	var lastDigit = Number(barcode.substring(barcode.length - 1));
	var checkSum = 0;
	if (isNaN(lastDigit)) {
		this.addError(elm, message);
		return false;
	} // not a valid upc/ean

	var arr = barcode.substring(0,barcode.length - 1).split("").reverse();
	var oddTotal = 0, evenTotal = 0;

	for (var i=0; i<arr.length; i++) {
		if (isNaN(arr[i])) {
			this.addError(elm, message);
			return false;
		} // can't be a valid upc/ean we're checking for

		if (i % 2 == 0) { oddTotal += Number(arr[i]) * 3; }
		else { evenTotal += Number(arr[i]); }
	}
	checkSum = (10 - ((evenTotal + oddTotal) % 10)) % 10;

	// true if they are equal
	if (checkSum != lastDigit) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

FormValidator.prototype.isZipCode = function(elm, rule) {
	// TODO
};

/**
 *  DEPRECATED ↓
 */

/**
 * Validacia checkboxu
 *
 * @param elm
 * @param rule
 * @returns {boolean}
 */
FormValidator.prototype.validateCheckbox = function(elm, rule) {
	if (!elm.prop('checked')) {
		var message = this.isDefined(rule.message) ? rule.message : 'Položka je povinná';
		this.addError(elm, message);
		return false;
	}

	return true;
};

/**
 * Validacia dlzky hodnoty
 *
 * @param elm
 * @param rule
 * @returns {boolean}
 */
FormValidator.prototype.validateLength = function(elm, rule) {
	if (!this.isDefined(rule.value)) {
		return false;
	}

	var requiredLength = rule.value;

	if ( elm.val().trim().length < requiredLength ) {
		var message = this.isDefined(rule.message) ? rule.message : 'Minimálne ' + requiredLength + ' znakov';
		this.addError(elm, message);
		return false;
	}

	return true;
};

/**
 * Porovnanie hodnot dvoch inputov
 *
 * rule.value musi byt jQuery Object
 *
 * @param elm
 * @param rule
 * @returns {boolean}
 */
FormValidator.prototype.compareInputValues = function(elm, rule) {
	if (!this.isDefined(rule.value) || !rule.value.length) {
		return false;
	}

	var firstValue = elm.val().trim();
	var secondValue = rule.value.val().trim();

	if ( firstValue !== secondValue ) {
		var message = this.isDefined(rule.message) ? rule.message : 'Hodnoty sa nezhodujú';
		this.addError(elm, message);
		return false;
	}

	return true;
};

/**
 * Validacia klubovej karty
 *
 * @param elm
 * @param rule
 * @returns {boolean}
 */
FormValidator.prototype.validateBarcode = function(elm, rule) {
	var barcode = elm.val();
	var message = this.isDefined(rule.message) ? rule.message : 'Kód klubovej karty nie je platný';

	// check length
	if (barcode.length < 8 || barcode.length > 18 ||
		(barcode.length != 8 && barcode.length != 12 &&
			barcode.length != 13 && barcode.length != 14 &&
			barcode.length != 18)) {
		this.addError(elm, message);
		return false;
	}

	var lastDigit = Number(barcode.substring(barcode.length - 1));
	var checkSum = 0;
	if (isNaN(lastDigit)) {
		this.addError(elm, message);
		return false;
	} // not a valid upc/ean

	var arr = barcode.substring(0,barcode.length - 1).split("").reverse();
	var oddTotal = 0, evenTotal = 0;

	for (var i=0; i<arr.length; i++) {
		if (isNaN(arr[i])) {
			this.addError(elm, message);
			return false;
		} // can't be a valid upc/ean we're checking for

		if (i % 2 == 0) { oddTotal += Number(arr[i]) * 3; }
		else { evenTotal += Number(arr[i]); }
	}
	checkSum = (10 - ((evenTotal + oddTotal) % 10)) % 10;

	// true if they are equal
	if (checkSum != lastDigit) {
		this.addError(elm, message);
		return false;
	}

	return true;
};

/*********************************
 ** CUSTOM SANITIZACNE PRAVIDLA PRE addRule **
 ********************************/

/**
 * Regex sanitizacia
 * rule.value musi byt object vo formate { regex: Regex, replacement: String }
 *
 * @param elm
 * @param rule
 * @param elemVal {string}
 * @returns {string}
 */
FormValidator.prototype.regexReplace = function(elm, rule, elemVal) {
	if (!this.isSanitizationRule(rule)) {
		return elemVal;
	}

	if (
		!this.isDefined(rule.value)
		|| !this.isDefined(rule.value.pattern)
		|| !this.isDefined(rule.value.replacement)
		) {
		return elemVal;
	}

	var pattern = new RegExp(rule.value.pattern, 'gi');
	var replacement = rule.value.replacement;

	return elemVal.replace(pattern, replacement);
};


/* ========================================
 FILE: /includes/js/jquery/jquery.jcarousel.min.js
 ==================== */

/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function(g){var q={vertical:!1,rtl:!1,start:1,offset:1,size:null,scroll:3,visible:null,animation:"normal",easing:"swing",auto:0,wrap:null,initCallback:null,setupCallback:null,reloadCallback:null,itemLoadCallback:null,itemFirstInCallback:null,itemFirstOutCallback:null,itemLastInCallback:null,itemLastOutCallback:null,itemVisibleInCallback:null,itemVisibleOutCallback:null,animationStepCallback:null,buttonNextHTML:"<div></div>",buttonPrevHTML:"<div></div>",buttonNextEvent:"click",buttonPrevEvent:"click", buttonNextCallback:null,buttonPrevCallback:null,itemFallbackDimension:null},m=!1;g(window).bind("load.jcarousel",function(){m=!0});g.jcarousel=function(a,c){this.options=g.extend({},q,c||{});this.autoStopped=this.locked=!1;this.buttonPrevState=this.buttonNextState=this.buttonPrev=this.buttonNext=this.list=this.clip=this.container=null;if(!c||c.rtl===void 0)this.options.rtl=(g(a).attr("dir")||g("html").attr("dir")||"").toLowerCase()=="rtl";this.wh=!this.options.vertical?"width":"height";this.lt=!this.options.vertical? this.options.rtl?"right":"left":"top";for(var b="",d=a.className.split(" "),f=0;f<d.length;f++)if(d[f].indexOf("jcarousel-skin")!=-1){g(a).removeClass(d[f]);b=d[f];break}a.nodeName.toUpperCase()=="UL"||a.nodeName.toUpperCase()=="OL"?(this.list=g(a),this.clip=this.list.parents(".jcarousel-clip"),this.container=this.list.parents(".jcarousel-container")):(this.container=g(a),this.list=this.container.find("ul,ol").eq(0),this.clip=this.container.find(".jcarousel-clip"));if(this.clip.length===0)this.clip= this.list.wrap("<div></div>").parent();if(this.container.length===0)this.container=this.clip.wrap("<div></div>").parent();b!==""&&this.container.parent()[0].className.indexOf("jcarousel-skin")==-1&&this.container.wrap('<div class=" '+b+'"></div>');this.buttonPrev=g(".jcarousel-prev",this.container);if(this.buttonPrev.length===0&&this.options.buttonPrevHTML!==null)this.buttonPrev=g(this.options.buttonPrevHTML).appendTo(this.container);this.buttonPrev.addClass(this.className("jcarousel-prev"));this.buttonNext= g(".jcarousel-next",this.container);if(this.buttonNext.length===0&&this.options.buttonNextHTML!==null)this.buttonNext=g(this.options.buttonNextHTML).appendTo(this.container);this.buttonNext.addClass(this.className("jcarousel-next"));this.clip.addClass(this.className("jcarousel-clip")).css({position:"relative"});this.list.addClass(this.className("jcarousel-list")).css({overflow:"hidden",position:"relative",top:0,margin:0,padding:0}).css(this.options.rtl?"right":"left",0);this.container.addClass(this.className("jcarousel-container")).css({position:"relative"}); !this.options.vertical&&this.options.rtl&&this.container.addClass("jcarousel-direction-rtl").attr("dir","rtl");var j=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible):null,b=this.list.children("li"),e=this;if(b.length>0){var h=0,i=this.options.offset;b.each(function(){e.format(this,i++);h+=e.dimension(this,j)});this.list.css(this.wh,h+100+"px");if(!c||c.size===void 0)this.options.size=b.length}this.container.css("display","block");this.buttonNext.css("display","block");this.buttonPrev.css("display", "block");this.funcNext=function(){e.next()};this.funcPrev=function(){e.prev()};this.funcResize=function(){e.resizeTimer&&clearTimeout(e.resizeTimer);e.resizeTimer=setTimeout(function(){e.reload()},100)};this.options.initCallback!==null&&this.options.initCallback(this,"init");!m&&g.browser.safari?(this.buttons(!1,!1),g(window).bind("load.jcarousel",function(){e.setup()})):this.setup()};var f=g.jcarousel;f.fn=f.prototype={jcarousel:"0.2.8"};f.fn.extend=f.extend=g.extend;f.fn.extend({setup:function(){this.prevLast= this.prevFirst=this.last=this.first=null;this.animating=!1;this.tail=this.resizeTimer=this.timer=null;this.inTail=!1;if(!this.locked){this.list.css(this.lt,this.pos(this.options.offset)+"px");var a=this.pos(this.options.start,!0);this.prevFirst=this.prevLast=null;this.animate(a,!1);g(window).unbind("resize.jcarousel",this.funcResize).bind("resize.jcarousel",this.funcResize);this.options.setupCallback!==null&&this.options.setupCallback(this)}},reset:function(){this.list.empty();this.list.css(this.lt, "0px");this.list.css(this.wh,"10px");this.options.initCallback!==null&&this.options.initCallback(this,"reset");this.setup()},reload:function(){this.tail!==null&&this.inTail&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+this.tail);this.tail=null;this.inTail=!1;this.options.reloadCallback!==null&&this.options.reloadCallback(this);if(this.options.visible!==null){var a=this,c=Math.ceil(this.clipping()/this.options.visible),b=0,d=0;this.list.children("li").each(function(f){b+=a.dimension(this, c);f+1<a.first&&(d=b)});this.list.css(this.wh,b+"px");this.list.css(this.lt,-d+"px")}this.scroll(this.first,!1)},lock:function(){this.locked=!0;this.buttons()},unlock:function(){this.locked=!1;this.buttons()},size:function(a){if(a!==void 0)this.options.size=a,this.locked||this.buttons();return this.options.size},has:function(a,c){if(c===void 0||!c)c=a;if(this.options.size!==null&&c>this.options.size)c=this.options.size;for(var b=a;b<=c;b++){var d=this.get(b);if(!d.length||d.hasClass("jcarousel-item-placeholder"))return!1}return!0}, get:function(a){return g(">.jcarousel-item-"+a,this.list)},add:function(a,c){var b=this.get(a),d=0,p=g(c);if(b.length===0)for(var j,e=f.intval(a),b=this.create(a);;){if(j=this.get(--e),e<=0||j.length){e<=0?this.list.prepend(b):j.after(b);break}}else d=this.dimension(b);p.get(0).nodeName.toUpperCase()=="LI"?(b.replaceWith(p),b=p):b.empty().append(c);this.format(b.removeClass(this.className("jcarousel-item-placeholder")),a);p=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible): null;d=this.dimension(b,p)-d;a>0&&a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))-d+"px");this.list.css(this.wh,f.intval(this.list.css(this.wh))+d+"px");return b},remove:function(a){var c=this.get(a);if(c.length&&!(a>=this.first&&a<=this.last)){var b=this.dimension(c);a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+b+"px");c.remove();this.list.css(this.wh,f.intval(this.list.css(this.wh))-b+"px")}},next:function(){this.tail!==null&&!this.inTail?this.scrollTail(!1): this.scroll((this.options.wrap=="both"||this.options.wrap=="last")&&this.options.size!==null&&this.last==this.options.size?1:this.first+this.options.scroll)},prev:function(){this.tail!==null&&this.inTail?this.scrollTail(!0):this.scroll((this.options.wrap=="both"||this.options.wrap=="first")&&this.options.size!==null&&this.first==1?this.options.size:this.first-this.options.scroll)},scrollTail:function(a){if(!this.locked&&!this.animating&&this.tail){this.pauseAuto();var c=f.intval(this.list.css(this.lt)), c=!a?c-this.tail:c+this.tail;this.inTail=!a;this.prevFirst=this.first;this.prevLast=this.last;this.animate(c)}},scroll:function(a,c){!this.locked&&!this.animating&&(this.pauseAuto(),this.animate(this.pos(a),c))},pos:function(a,c){var b=f.intval(this.list.css(this.lt));if(this.locked||this.animating)return b;this.options.wrap!="circular"&&(a=a<1?1:this.options.size&&a>this.options.size?this.options.size:a);for(var d=this.first>a,g=this.options.wrap!="circular"&&this.first<=1?1:this.first,j=d?this.get(g): this.get(this.last),e=d?g:g-1,h=null,i=0,k=!1,l=0;d?--e>=a:++e<a;){h=this.get(e);k=!h.length;if(h.length===0&&(h=this.create(e).addClass(this.className("jcarousel-item-placeholder")),j[d?"before":"after"](h),this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size)))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)));j=h;l=this.dimension(h);k&&(i+=l);if(this.first!==null&&(this.options.wrap=="circular"||e>=1&&(this.options.size===null||e<= this.options.size)))b=d?b+l:b-l}for(var g=this.clipping(),m=[],o=0,n=0,j=this.get(a-1),e=a;++o;){h=this.get(e);k=!h.length;if(h.length===0){h=this.create(e).addClass(this.className("jcarousel-item-placeholder"));if(j.length===0)this.list.prepend(h);else j[d?"before":"after"](h);if(this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)))}j=h;l=this.dimension(h);if(l===0)throw Error("jCarousel: No width/height set for items. This will cause an infinite loop. Aborting..."); this.options.wrap!="circular"&&this.options.size!==null&&e>this.options.size?m.push(h):k&&(i+=l);n+=l;if(n>=g)break;e++}for(h=0;h<m.length;h++)m[h].remove();i>0&&(this.list.css(this.wh,this.dimension(this.list)+i+"px"),d&&(b-=i,this.list.css(this.lt,f.intval(this.list.css(this.lt))-i+"px")));i=a+o-1;if(this.options.wrap!="circular"&&this.options.size&&i>this.options.size)i=this.options.size;if(e>i){o=0;e=i;for(n=0;++o;){h=this.get(e--);if(!h.length)break;n+=this.dimension(h);if(n>=g)break}}e=i-o+ 1;this.options.wrap!="circular"&&e<1&&(e=1);if(this.inTail&&d)b+=this.tail,this.inTail=!1;this.tail=null;if(this.options.wrap!="circular"&&i==this.options.size&&i-o+1>=1&&(d=f.intval(this.get(i).css(!this.options.vertical?"marginRight":"marginBottom")),n-d>g))this.tail=n-g-d;if(c&&a===this.options.size&&this.tail)b-=this.tail,this.inTail=!0;for(;a-- >e;)b+=this.dimension(this.get(a));this.prevFirst=this.first;this.prevLast=this.last;this.first=e;this.last=i;return b},animate:function(a,c){if(!this.locked&& !this.animating){this.animating=!0;var b=this,d=function(){b.animating=!1;a===0&&b.list.css(b.lt,0);!b.autoStopped&&(b.options.wrap=="circular"||b.options.wrap=="both"||b.options.wrap=="last"||b.options.size===null||b.last<b.options.size||b.last==b.options.size&&b.tail!==null&&!b.inTail)&&b.startAuto();b.buttons();b.notify("onAfterAnimation");if(b.options.wrap=="circular"&&b.options.size!==null)for(var c=b.prevFirst;c<=b.prevLast;c++)c!==null&&!(c>=b.first&&c<=b.last)&&(c<1||c>b.options.size)&&b.remove(c)}; this.notify("onBeforeAnimation");if(!this.options.animation||c===!1)this.list.css(this.lt,a+"px"),d();else{var f=!this.options.vertical?this.options.rtl?{right:a}:{left:a}:{top:a},d={duration:this.options.animation,easing:this.options.easing,complete:d};if(g.isFunction(this.options.animationStepCallback))d.step=this.options.animationStepCallback;this.list.animate(f,d)}}},startAuto:function(a){if(a!==void 0)this.options.auto=a;if(this.options.auto===0)return this.stopAuto();if(this.timer===null){this.autoStopped= !1;var c=this;this.timer=window.setTimeout(function(){c.next()},this.options.auto*1E3)}},stopAuto:function(){this.pauseAuto();this.autoStopped=!0},pauseAuto:function(){if(this.timer!==null)window.clearTimeout(this.timer),this.timer=null},buttons:function(a,c){if(a==null&&(a=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="first"||this.options.size===null||this.last<this.options.size),!this.locked&&(!this.options.wrap||this.options.wrap=="first")&&this.options.size!==null&& this.last>=this.options.size))a=this.tail!==null&&!this.inTail;if(c==null&&(c=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="last"||this.first>1),!this.locked&&(!this.options.wrap||this.options.wrap=="last")&&this.options.size!==null&&this.first==1))c=this.tail!==null&&this.inTail;var b=this;this.buttonNext.length>0?(this.buttonNext.unbind(this.options.buttonNextEvent+".jcarousel",this.funcNext),a&&this.buttonNext.bind(this.options.buttonNextEvent+".jcarousel",this.funcNext), this.buttonNext[a?"removeClass":"addClass"](this.className("jcarousel-next-disabled")).attr("disabled",a?!1:!0),this.options.buttonNextCallback!==null&&this.buttonNext.data("jcarouselstate")!=a&&this.buttonNext.each(function(){b.options.buttonNextCallback(b,this,a)}).data("jcarouselstate",a)):this.options.buttonNextCallback!==null&&this.buttonNextState!=a&&this.options.buttonNextCallback(b,null,a);this.buttonPrev.length>0?(this.buttonPrev.unbind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev), c&&this.buttonPrev.bind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev),this.buttonPrev[c?"removeClass":"addClass"](this.className("jcarousel-prev-disabled")).attr("disabled",c?!1:!0),this.options.buttonPrevCallback!==null&&this.buttonPrev.data("jcarouselstate")!=c&&this.buttonPrev.each(function(){b.options.buttonPrevCallback(b,this,c)}).data("jcarouselstate",c)):this.options.buttonPrevCallback!==null&&this.buttonPrevState!=c&&this.options.buttonPrevCallback(b,null,c);this.buttonNextState= a;this.buttonPrevState=c},notify:function(a){var c=this.prevFirst===null?"init":this.prevFirst<this.first?"next":"prev";this.callback("itemLoadCallback",a,c);this.prevFirst!==this.first&&(this.callback("itemFirstInCallback",a,c,this.first),this.callback("itemFirstOutCallback",a,c,this.prevFirst));this.prevLast!==this.last&&(this.callback("itemLastInCallback",a,c,this.last),this.callback("itemLastOutCallback",a,c,this.prevLast));this.callback("itemVisibleInCallback",a,c,this.first,this.last,this.prevFirst, this.prevLast);this.callback("itemVisibleOutCallback",a,c,this.prevFirst,this.prevLast,this.first,this.last)},callback:function(a,c,b,d,f,j,e){if(!(this.options[a]==null||typeof this.options[a]!="object"&&c!="onAfterAnimation")){var h=typeof this.options[a]=="object"?this.options[a][c]:this.options[a];if(g.isFunction(h)){var i=this;if(d===void 0)h(i,b,c);else if(f===void 0)this.get(d).each(function(){h(i,this,d,b,c)});else for(var a=function(a){i.get(a).each(function(){h(i,this,a,b,c)})},k=d;k<=f;k++)k!== null&&!(k>=j&&k<=e)&&a(k)}}},create:function(a){return this.format("<li></li>",a)},format:function(a,c){for(var a=g(a),b=a.get(0).className.split(" "),d=0;d<b.length;d++)b[d].indexOf("jcarousel-")!=-1&&a.removeClass(b[d]);a.addClass(this.className("jcarousel-item")).addClass(this.className("jcarousel-item-"+c)).css({"float":this.options.rtl?"right":"left","list-style":"none"}).attr("jcarouselindex",c);return a},className:function(a){return a+" "+a+(!this.options.vertical?"-horizontal":"-vertical")}, dimension:function(a,c){var b=g(a);if(c==null)return!this.options.vertical?b.outerWidth(!0)||f.intval(this.options.itemFallbackDimension):b.outerHeight(!0)||f.intval(this.options.itemFallbackDimension);else{var d=!this.options.vertical?c-f.intval(b.css("marginLeft"))-f.intval(b.css("marginRight")):c-f.intval(b.css("marginTop"))-f.intval(b.css("marginBottom"));g(b).css(this.wh,d+"px");return this.dimension(b)}},clipping:function(){return!this.options.vertical?this.clip[0].offsetWidth-f.intval(this.clip.css("borderLeftWidth"))- f.intval(this.clip.css("borderRightWidth")):this.clip[0].offsetHeight-f.intval(this.clip.css("borderTopWidth"))-f.intval(this.clip.css("borderBottomWidth"))},index:function(a,c){if(c==null)c=this.options.size;return Math.round(((a-1)/c-Math.floor((a-1)/c))*c)+1}});f.extend({defaults:function(a){return g.extend(q,a||{})},intval:function(a){a=parseInt(a,10);return isNaN(a)?0:a},windowLoaded:function(){m=!0}});g.fn.jcarousel=function(a){if(typeof a=="string"){var c=g(this).data("jcarousel"),b=Array.prototype.slice.call(arguments, 1);return c[a].apply(c,b)}else return this.each(function(){var b=g(this).data("jcarousel");b?(a&&g.extend(b.options,a),b.reload()):g(this).data("jcarousel",new f(this,a))})}})(jQuery);


/* ========================================
 FILE: /includes/js/jquery/poshytip/jquery.poshytip.js
 ==================== */

/*
 * Poshy Tip jQuery plugin v1.2
 * http://vadikom.com/tools/poshy-tip-jquery-plugin-for-stylish-tooltips/
 * Copyright 2010-2013, Vasil Dinkov, http://vadikom.com/
 */

(function($) {

	var tips = [],
	    reBgImage = /^url\(["']?([^"'\)]*)["']?\);?$/i,
	    rePNG = /\.png$/i,
	    ie6 = !!window.createPopup && ( typeof(document.documentElement.currentStyle) == 'undefined' || typeof(document.documentElement.currentStyle.minWidth) == 'undefined' );

	// make sure the tips' position is updated on resize
	function handleWindowResize() {
		$.each(tips, function() {
			this.refresh(true);
		});
	}
	$(window).resize(handleWindowResize);

	$.Poshytip = function(elm, options) {
		this.$elm = $(elm);
		this.opts = $.extend({}, $.fn.poshytip.defaults, options);
		this.$tip = $(['<div class="',this.opts.className,'">',
			'<div class="tip-inner tip-bg-image"></div>',
			'<div class="tip-arrow tip-arrow-top tip-arrow-right tip-arrow-bottom tip-arrow-left"></div>',
			'</div>'].join('')).appendTo(document.body);
		this.$arrow = this.$tip.find('div.tip-arrow');
		this.$inner = this.$tip.find('div.tip-inner');
		this.disabled = false;
		this.content = null;
		this.init();
	};

	$.Poshytip.prototype = {
		init: function() {
			tips.push(this);

			// save the original title and a reference to the Poshytip object
			var title = this.$elm.attr('title');
			this.$elm.data('title.poshytip', title !== undefined ? title : null)
				.data('poshytip', this);

			// hook element events
			if (this.opts.showOn != 'none') {
				this.$elm.bind({
					'mouseenter.poshytip': $.proxy(this.mouseenter, this),
					'mouseleave.poshytip': $.proxy(this.mouseleave, this)
				});
				switch (this.opts.showOn) {
					case 'hover':
						if (this.opts.alignTo == 'cursor')
							this.$elm.bind('mousemove.poshytip', $.proxy(this.mousemove, this));
						if (this.opts.allowTipHover)
							this.$tip.hover($.proxy(this.clearTimeouts, this), $.proxy(this.mouseleave, this));
						break;
					case 'focus':
						this.$elm.bind({
							'focus.poshytip': $.proxy(this.showDelayed, this),
							'blur.poshytip': $.proxy(this.hideDelayed, this)
						});
						break;
				}
			}
		},
		mouseenter: function(e) {
			if (this.disabled)
				return true;

			this.$elm.attr('title', '');
			if (this.opts.showOn == 'focus')
				return true;

			this.showDelayed();
		},
		mouseleave: function(e) {
			if (this.disabled || this.asyncAnimating && (this.$tip[0] === e.relatedTarget || jQuery.contains(this.$tip[0], e.relatedTarget)))
				return true;

			if (!this.$tip.data('active')) {
				var title = this.$elm.data('title.poshytip');
				if (title !== null)
					this.$elm.attr('title', title);
			}
			if (this.opts.showOn == 'focus')
				return true;

			this.hideDelayed();
		},
		mousemove: function(e) {
			if (this.disabled)
				return true;

			this.eventX = e.pageX;
			this.eventY = e.pageY;
			if (this.opts.followCursor && this.$tip.data('active')) {
				this.calcPos();
				this.$tip.css({left: this.pos.l, top: this.pos.t});
				if (this.pos.arrow)
					this.$arrow[0].className = 'tip-arrow tip-arrow-' + this.pos.arrow;
			}
		},
		show: function() {
			if (this.disabled || typeof this.$tip === 'undefined' || this.$tip.data('active'))
				return;

			this.reset();
			this.update();

			// don't proceed if we didn't get any content in update() (e.g. the element has an empty title attribute)
			if (!this.content)
				return;

			this.display();
			if (this.opts.timeOnScreen)
				this.hideDelayed(this.opts.timeOnScreen);
		},
		showDelayed: function(timeout) {
			this.clearTimeouts();
			this.showTimeout = setTimeout($.proxy(this.show, this), typeof timeout == 'number' ? timeout : this.opts.showTimeout);
		},
		hide: function() {
			if (this.disabled || typeof this.$tip === 'undefined' || !this.$tip.data('active'))
				return;

			this.display(true);
		},
		hideDelayed: function(timeout) {
			this.clearTimeouts();
			this.hideTimeout = setTimeout($.proxy(this.hide, this), typeof timeout == 'number' ? timeout : this.opts.hideTimeout);
		},
		reset: function() {
			this.$tip.queue([]).detach().css('visibility', 'hidden').data('active', false);
			this.$inner.find('*').poshytip('hide');
			if (this.opts.fade)
				this.$tip.css('opacity', this.opacity);
			this.$arrow[0].className = 'tip-arrow tip-arrow-top tip-arrow-right tip-arrow-bottom tip-arrow-left';
			this.asyncAnimating = false;
		},
		update: function(content, dontOverwriteOption) {
			if (this.disabled)
				return;

			var async = content !== undefined;
			if (async) {
				if (!dontOverwriteOption)
					this.opts.content = content;
				if (!this.$tip.data('active'))
					return;
			} else {
				content = this.opts.content;
			}

			// update content only if it has been changed since last time
			var self = this,
			    newContent = typeof content == 'function' ?
				    content.call(this.$elm[0], function(newContent) {
					    self.update(newContent);
				    }) :
				    content == '[title]' ? this.$elm.data('title.poshytip') : content;
			if (this.content !== newContent) {
				this.$inner.empty().append(newContent);
				this.content = newContent;
			}

			this.$tip.appendTo(document.body);

			this.refresh(async);
		},
		refresh: function(async) {
			if (this.disabled)
				return;

			if (async) {
				if (!this.$tip.data('active'))
					return;
				// save current position as we will need to animate
				var currPos = {left: this.$tip.css('left'), top: this.$tip.css('top')};
			}

			// reset position to avoid text wrapping, etc.
			this.$tip.css({left: 0, top: 0});

			// save default opacity
			if (this.opacity === undefined)
				this.opacity = this.$tip.css('opacity');

			// check for images - this code is here (i.e. executed each time we show the tip and not on init) due to some browser inconsistencies
			var bgImage = this.$tip.css('background-image').match(reBgImage),
			    arrow = this.$arrow.css('background-image').match(reBgImage);

			if (bgImage) {
				var bgImagePNG = rePNG.test(bgImage[1]);
				// fallback to background-color/padding/border in IE6 if a PNG is used
				if (ie6 && bgImagePNG) {
					this.$tip.css('background-image', 'none');
					this.$inner.css({margin: 0, border: 0, padding: 0});
					bgImage = bgImagePNG = false;
				} else {
					this.$tip.prepend('<table class="tip-table" border="0" cellpadding="0" cellspacing="0"><tr><td class="tip-top tip-bg-image" colspan="2"><span></span></td><td class="tip-right tip-bg-image" rowspan="2"><span></span></td></tr><tr><td class="tip-left tip-bg-image" rowspan="2"><span></span></td><td></td></tr><tr><td class="tip-bottom tip-bg-image" colspan="2"><span></span></td></tr></table>')
						.css({border: 0, padding: 0, 'background-image': 'none', 'background-color': 'transparent'})
						.find('.tip-bg-image').css('background-image', 'url("' + bgImage[1] +'")').end()
						.find('td').eq(3).append(this.$inner);
				}
				// disable fade effect in IE due to Alpha filter + translucent PNG issue
				if (bgImagePNG && !$.support.opacity)
					this.opts.fade = false;
			}
			// IE arrow fixes
			if (arrow && !$.support.opacity) {
				// disable arrow in IE6 if using a PNG
				if (ie6 && rePNG.test(arrow[1])) {
					arrow = false;
					this.$arrow.css('background-image', 'none');
				}
				// disable fade effect in IE due to Alpha filter + translucent PNG issue
				this.opts.fade = false;
			}

			var $table = this.$tip.find('> table.tip-table');
			if (ie6) {
				// fix min/max-width in IE6
				this.$tip[0].style.width = '';
				$table.width('auto').find('td').eq(3).width('auto');
				var tipW = this.$tip.width(),
				    minW = parseInt(this.$tip.css('min-width')),
				    maxW = parseInt(this.$tip.css('max-width'));
				if (!isNaN(minW) && tipW < minW)
					tipW = minW;
				else if (!isNaN(maxW) && tipW > maxW)
					tipW = maxW;
				this.$tip.add($table).width(tipW).eq(0).find('td').eq(3).width('100%');
			} else if ($table[0]) {
				// fix the table width if we are using a background image
				// IE9, FF4 use float numbers for width/height so use getComputedStyle for them to avoid text wrapping
				// for details look at: http://vadikom.com/dailies/offsetwidth-offsetheight-useless-in-ie9-firefox4/
				$table.width('auto').find('td').eq(3).width('auto').end().end().width(document.defaultView && document.defaultView.getComputedStyle && parseFloat(document.defaultView.getComputedStyle(this.$tip[0], null).width) || this.$tip.width()).find('td').eq(3).width('100%');
			}
			this.tipOuterW = this.$tip.outerWidth();
			this.tipOuterH = this.$tip.outerHeight();

			this.calcPos();

			// position and show the arrow image
			if (arrow && this.pos.arrow) {
				this.$arrow[0].className = 'tip-arrow tip-arrow-' + this.pos.arrow;
				this.$arrow.css('visibility', 'inherit');
			}

			if (async && this.opts.refreshAniDuration) {
				this.asyncAnimating = true;
				var self = this;
				this.$tip.css(currPos).animate({left: this.pos.l, top: this.pos.t}, this.opts.refreshAniDuration, function() { self.asyncAnimating = false; });
			} else {
				this.$tip.css({left: this.pos.l, top: this.pos.t});
			}
			if (typeof this.opts.onRefresh === 'function') this.opts.onRefresh();
		},
		display: function(hide) {
			var active = this.$tip.data('active');
			if (active && !hide || !active && hide)
				return;

			this.$tip.stop();
			if ((this.opts.slide && this.pos.arrow || this.opts.fade) && (hide && this.opts.hideAniDuration || !hide && this.opts.showAniDuration)) {
				var from = {}, to = {};
				// this.pos.arrow is only undefined when alignX == alignY == 'center' and we don't need to slide in that rare case
				if (this.opts.slide && this.pos.arrow) {
					var prop, arr;
					if (this.pos.arrow == 'bottom' || this.pos.arrow == 'top') {
						prop = 'top';
						arr = 'bottom';
					} else {
						prop = 'left';
						arr = 'right';
					}
					var val = parseInt(this.$tip.css(prop));
					from[prop] = val + (hide ? 0 : (this.pos.arrow == arr ? -this.opts.slideOffset : this.opts.slideOffset));
					to[prop] = val + (hide ? (this.pos.arrow == arr ? this.opts.slideOffset : -this.opts.slideOffset) : 0) + 'px';
				}
				if (this.opts.fade) {
					from.opacity = hide ? this.$tip.css('opacity') : 0;
					to.opacity = hide ? 0 : this.opacity;
				}
				this.$tip.css(from).animate(to, this.opts[hide ? 'hideAniDuration' : 'showAniDuration']);
			}
			hide ? this.$tip.queue($.proxy(this.reset, this)) : this.$tip.css('visibility', 'inherit');
			if (active) {
				var title = this.$elm.data('title.poshytip');
				if (title !== null)
					this.$elm.attr('title', title);
			}
			this.$tip.data('active', !active);
		},
		disable: function() {
			this.reset();
			this.disabled = true;
		},
		enable: function() {
			this.disabled = false;
		},
		destroy: function() {
			this.reset();
			this.$tip.remove();
			delete this.$tip;
			this.content = null;
			this.$elm.unbind('.poshytip').removeData('title.poshytip').removeData('poshytip');
			tips.splice($.inArray(this, tips), 1);
		},
		clearTimeouts: function() {
			if (this.showTimeout) {
				clearTimeout(this.showTimeout);
				this.showTimeout = 0;
			}
			if (this.hideTimeout) {
				clearTimeout(this.hideTimeout);
				this.hideTimeout = 0;
			}
		},
		calcPos: function() {
			var pos = {l: 0, t: 0, arrow: ''},
			    $win = $(window),
			    win = {
				    l: $win.scrollLeft(),
				    t: $win.scrollTop(),
				    w: $win.width(),
				    h: $win.height()
			    }, xL, xC, xR, yT, yC, yB;
			if (this.opts.alignTo == 'cursor') {
				xL = xC = xR = this.eventX;
				yT = yC = yB = this.eventY;
			} else { // this.opts.alignTo == 'target'
				var elmOffset = this.$elm.offset(),
				    elm = {
					    l: elmOffset.left,
					    t: elmOffset.top,
					    w: this.$elm.outerWidth(),
					    h: this.$elm.outerHeight()
				    };
				xL = elm.l + (this.opts.alignX != 'inner-right' ? 0 : elm.w);	// left edge
				xC = xL + Math.floor(elm.w / 2);				// h center
				xR = xL + (this.opts.alignX != 'inner-left' ? elm.w : 0);	// right edge
				yT = elm.t + (this.opts.alignY != 'inner-bottom' ? 0 : elm.h);	// top edge
				yC = yT + Math.floor(elm.h / 2);				// v center
				yB = yT + (this.opts.alignY != 'inner-top' ? elm.h : 0);	// bottom edge
			}

			if (typeof this.opts.alignXOrig !== 'undefined') this.opts.alignX = this.opts.alignXOrig;
			if (typeof this.opts.alignYOrig !== 'undefined') this.opts.alignY = this.opts.alignYOrig;

			// keep in viewport and calc arrow position
			switch (this.opts.alignX) {
				case 'right':
				case 'inner-left':
					pos.l = xR + this.opts.offsetX;
					if (this.opts.keepInViewport && pos.l + this.tipOuterW > win.l + win.w)
						pos.l = win.l + win.w - this.tipOuterW;
					if (this.opts.alignX == 'right' || this.opts.alignY == 'center')
						pos.arrow = 'left';
					break;
				case 'center':
					pos.l = xC - Math.floor(this.tipOuterW / 2);
					if (this.opts.keepInViewport) {
						if (pos.l + this.tipOuterW > win.l + win.w)
							pos.l = win.l + win.w - this.tipOuterW;
						else if (pos.l < win.l)
							pos.l = win.l;
					}
					break;
				default: // 'left' || 'inner-right'
					pos.l = xL - this.tipOuterW - this.opts.offsetX;
					if (this.opts.keepInViewport && pos.l < win.l)
						pos.l = win.l;
					if (this.opts.alignX == 'left' || this.opts.alignY == 'center')
						pos.arrow = 'right';
			}
			switch (this.opts.alignY) {
				case 'bottom':
				case 'inner-top':
					pos.t = yB + this.opts.offsetY;
					// 'left' and 'right' need priority for 'target'
					if (!pos.arrow || this.opts.alignTo == 'cursor')
						pos.arrow = 'top';
					if (this.opts.keepInViewport && pos.t + this.tipOuterH > win.t + win.h) {
						pos.t = yT - this.tipOuterH - this.opts.offsetY;
						if (pos.arrow == 'top')
							pos.arrow = 'bottom';
					}
					break;
				case 'center':
					pos.t = yC - Math.floor(this.tipOuterH / 2);
					if (this.opts.keepInViewport) {
						if (pos.t + this.tipOuterH > win.t + win.h)
							pos.t = win.t + win.h - this.tipOuterH;
						else if (pos.t < win.t)
							pos.t = win.t;
					}
					break;
				default: // 'top' || 'inner-bottom'
					pos.t = yT - this.tipOuterH - this.opts.offsetY;
					// 'left' and 'right' need priority for 'target'
					if (!pos.arrow || this.opts.alignTo == 'cursor')
						pos.arrow = 'bottom';
					if (this.opts.keepInViewport && pos.t < win.t) {
						pos.t = yB + this.opts.offsetY;
						if (pos.arrow == 'bottom')
							pos.arrow = 'top';
					}
			}

			if (pos.t < 0) pos.t = 0;

			this.pos = pos;
		}
	};

	$.fn.poshytip = function(options) {
		if (typeof options == 'string') {
			var args = arguments,
			    method = options;
			Array.prototype.shift.call(args);
			// unhook live events if 'destroy' is called
			if (method == 'destroy') {
				this.off ?
					this.off('mouseenter.poshytip').off('focus.poshytip') :
					$(document).undelegate(this.selector, 'mouseenter.poshytip').undelegate(this.selector, 'focus.poshytip');
			}
			return this.each(function() {
				var poshytip = $(this).data('poshytip');
				if (poshytip && poshytip[method])
					poshytip[method].apply(poshytip, args);
			});
		}

		var opts = $.extend({}, $.fn.poshytip.defaults, options);

		// generate CSS for this tip class if not already generated
		if (!$('#poshytip-css-' + opts.className)[0])
			$(['<style id="poshytip-css-',opts.className,'" type="text/css">',
				'div.',opts.className,'{visibility:hidden;position:absolute;top:0;left:0;}',
				'div.',opts.className,' table.tip-table, div.',opts.className,' table.tip-table td{margin:0;font-family:inherit;font-size:inherit;font-weight:inherit;font-style:inherit;font-variant:inherit;vertical-align:middle;}',
				'div.',opts.className,' td.tip-bg-image span{display:block;font:1px/1px sans-serif;height:',opts.bgImageFrameSize,'px;width:',opts.bgImageFrameSize,'px;overflow:hidden;}',
				'div.',opts.className,' td.tip-right{background-position:100% 0;}',
				'div.',opts.className,' td.tip-bottom{background-position:100% 100%;}',
				'div.',opts.className,' td.tip-left{background-position:0 100%;}',
				'div.',opts.className,' div.tip-inner{background-position:-',opts.bgImageFrameSize,'px -',opts.bgImageFrameSize,'px;}',
				'div.',opts.className,' div.tip-arrow{visibility:hidden;position:absolute;overflow:hidden;font:1px/1px sans-serif;}',
				'</style>'].join('')).appendTo('head');

		// check if we need to hook live events
		if (opts.liveEvents && opts.showOn != 'none') {
			var handler,
			    deadOpts = $.extend({}, opts, { liveEvents: false });
			switch (opts.showOn) {
				case 'hover':
					handler = function() {
						var $this = $(this);
						if (!$this.data('poshytip'))
							$this.poshytip(deadOpts).poshytip('mouseenter');
					};
					// support 1.4.2+ & 1.9+
					this.on ?
						this.on('mouseenter.poshytip', handler) :
						$(document).delegate(this.selector, 'mouseenter.poshytip', handler);
					break;
				case 'focus':
					handler = function() {
						var $this = $(this);
						if (!$this.data('poshytip'))
							$this.poshytip(deadOpts).poshytip('showDelayed');
					};
					this.on ?
						this.on('focus.poshytip', handler) :
						$(document).delegate(this.selector, 'focus.poshytip', handler);
					break;
			}
			return this;
		}

		return this.each(function() {
			new $.Poshytip(this, opts);
		});
	};

	// default settings
	$.fn.poshytip.defaults = {
		content: 		'[title]',	// content to display ('[title]', 'string', element, function(updateCallback){...}, jQuery)
		className:		'tip-yellow',	// class for the tips
		bgImageFrameSize:	10,		// size in pixels for the background-image (if set in CSS) frame around the inner content of the tip
		showTimeout:		500,		// timeout before showing the tip (in milliseconds 1000 == 1 second)
		hideTimeout:		100,		// timeout before hiding the tip
		timeOnScreen:		0,		// timeout before automatically hiding the tip after showing it (set to > 0 in order to activate)
		showOn:			'hover',	// handler for showing the tip ('hover', 'focus', 'none') - use 'none' to trigger it manually
		liveEvents:		false,		// use live events
		alignTo:		'cursor',	// align/position the tip relative to ('cursor', 'target')
		alignX:			'right',	// horizontal alignment for the tip relative to the mouse cursor or the target element
		// ('right', 'center', 'left', 'inner-left', 'inner-right') - 'inner-*' matter if alignTo:'target'
		alignY:			'top',		// vertical alignment for the tip relative to the mouse cursor or the target element
		// ('bottom', 'center', 'top', 'inner-bottom', 'inner-top') - 'inner-*' matter if alignTo:'target'
		offsetX:		-22,		// offset X pixels from the default position - doesn't matter if alignX:'center'
		offsetY:		18,		// offset Y pixels from the default position - doesn't matter if alignY:'center'
		keepInViewport:		true,		// reposition the tooltip if needed to make sure it always appears inside the viewport
		allowTipHover:		true,		// allow hovering the tip without hiding it onmouseout of the target - matters only if showOn:'hover'
		followCursor:		false,		// if the tip should follow the cursor - matters only if showOn:'hover' and alignTo:'cursor'
		fade: 			true,		// use fade animation
		slide: 			true,		// use slide animation
		slideOffset: 		8,		// slide animation offset
		showAniDuration: 	300,		// show animation duration - set to 0 if you don't want show animation
		hideAniDuration: 	300,		// hide animation duration - set to 0 if you don't want hide animation
		refreshAniDuration:	200		// refresh animation duration - set to 0 if you don't want animation when updating the tooltip asynchronously
	};

})(jQuery);

/* ========================================
 FILE: /includes/js/moment/moment.min.js
 ==================== */

// moment.js v.2.21.0
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var e,t;function n(){return e.apply(null,arguments)}function s(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function i(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function r(e){return void 0===e}function a(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function o(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function u(e,t){var n,s=[];for(n=0;n<e.length;++n)s.push(t(e[n],n));return s}function l(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function d(e,t){for(var n in t)l(t,n)&&(e[n]=t[n]);return l(t,"toString")&&(e.toString=t.toString),l(t,"valueOf")&&(e.valueOf=t.valueOf),e}function h(e,t,n,s){return Ot(e,t,n,s,!0).utc()}function c(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function f(e){if(null==e._isValid){var n=c(e),s=t.call(n.parsedDateParts,function(e){return null!=e}),i=!isNaN(e._d.getTime())&&n.overflow<0&&!n.empty&&!n.invalidMonth&&!n.invalidWeekday&&!n.weekdayMismatch&&!n.nullInput&&!n.invalidFormat&&!n.userInvalidated&&(!n.meridiem||n.meridiem&&s);if(e._strict&&(i=i&&0===n.charsLeftOver&&0===n.unusedTokens.length&&void 0===n.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return i;e._isValid=i}return e._isValid}function m(e){var t=h(NaN);return null!=e?d(c(t),e):c(t).userInvalidated=!0,t}t=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1};var _=n.momentProperties=[];function y(e,t){var n,s,i;if(r(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),r(t._i)||(e._i=t._i),r(t._f)||(e._f=t._f),r(t._l)||(e._l=t._l),r(t._strict)||(e._strict=t._strict),r(t._tzm)||(e._tzm=t._tzm),r(t._isUTC)||(e._isUTC=t._isUTC),r(t._offset)||(e._offset=t._offset),r(t._pf)||(e._pf=c(t)),r(t._locale)||(e._locale=t._locale),_.length>0)for(n=0;n<_.length;n++)r(i=t[s=_[n]])||(e[s]=i);return e}var g=!1;function p(e){y(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===g&&(g=!0,n.updateOffset(this),g=!1)}function v(e){return e instanceof p||null!=e&&null!=e._isAMomentObject}function w(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function M(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=w(t)),n}function S(e,t,n){var s,i=Math.min(e.length,t.length),r=Math.abs(e.length-t.length),a=0;for(s=0;s<i;s++)(n&&e[s]!==t[s]||!n&&M(e[s])!==M(t[s]))&&a++;return a+r}function D(e){!1===n.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function k(e,t){var s=!0;return d(function(){if(null!=n.deprecationHandler&&n.deprecationHandler(null,e),s){for(var i,r=[],a=0;a<arguments.length;a++){if(i="","object"==typeof arguments[a]){for(var o in i+="\n["+a+"] ",arguments[0])i+=o+": "+arguments[0][o]+", ";i=i.slice(0,-2)}else i=arguments[a];r.push(i)}D(e+"\nArguments: "+Array.prototype.slice.call(r).join("")+"\n"+(new Error).stack),s=!1}return t.apply(this,arguments)},t)}var Y,O={};function T(e,t){null!=n.deprecationHandler&&n.deprecationHandler(e,t),O[e]||(D(t),O[e]=!0)}function x(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function b(e,t){var n,s=d({},e);for(n in t)l(t,n)&&(i(e[n])&&i(t[n])?(s[n]={},d(s[n],e[n]),d(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)l(e,n)&&!l(t,n)&&i(e[n])&&(s[n]=d({},s[n]));return s}function P(e){null!=e&&this.set(e)}n.suppressDeprecationWarnings=!1,n.deprecationHandler=null,Y=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)l(e,t)&&n.push(t);return n};var W={};function H(e,t){var n=e.toLowerCase();W[n]=W[n+"s"]=W[t]=e}function R(e){return"string"==typeof e?W[e]||W[e.toLowerCase()]:void 0}function C(e){var t,n,s={};for(n in e)l(e,n)&&(t=R(n))&&(s[t]=e[n]);return s}var F={};function L(e,t){F[e]=t}function U(e,t,n){var s=""+Math.abs(e),i=t-s.length;return(e>=0?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+s}var N=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,G=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,V={},E={};function I(e,t,n,s){var i=s;"string"==typeof s&&(i=function(){return this[s]()}),e&&(E[e]=i),t&&(E[t[0]]=function(){return U(i.apply(this,arguments),t[1],t[2])}),n&&(E[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function A(e,t){return e.isValid()?(t=j(t,e.localeData()),V[t]=V[t]||function(e){var t,n,s,i=e.match(N);for(t=0,n=i.length;t<n;t++)E[i[t]]?i[t]=E[i[t]]:i[t]=(s=i[t]).match(/\[[\s\S]/)?s.replace(/^\[|\]$/g,""):s.replace(/\\/g,"");return function(t){var s,r="";for(s=0;s<n;s++)r+=x(i[s])?i[s].call(t,e):i[s];return r}}(t),V[t](e)):e.localeData().invalidDate()}function j(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(G.lastIndex=0;n>=0&&G.test(e);)e=e.replace(G,s),G.lastIndex=0,n-=1;return e}var Z=/\d/,z=/\d\d/,$=/\d{3}/,q=/\d{4}/,J=/[+-]?\d{6}/,B=/\d\d?/,Q=/\d\d\d\d?/,X=/\d\d\d\d\d\d?/,K=/\d{1,3}/,ee=/\d{1,4}/,te=/[+-]?\d{1,6}/,ne=/\d+/,se=/[+-]?\d+/,ie=/Z|[+-]\d\d:?\d\d/gi,re=/Z|[+-]\d\d(?::?\d\d)?/gi,ae=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,oe={};function ue(e,t,n){oe[e]=x(t)?t:function(e,s){return e&&n?n:t}}function le(e,t){return l(oe,e)?oe[e](t._strict,t._locale):new RegExp(de(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function de(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var he={};function ce(e,t){var n,s=t;for("string"==typeof e&&(e=[e]),a(t)&&(s=function(e,n){n[t]=M(e)}),n=0;n<e.length;n++)he[e[n]]=s}function fe(e,t){ce(e,function(e,n,s,i){s._w=s._w||{},t(e,s._w,s,i)})}var me=0,_e=1,ye=2,ge=3,pe=4,ve=5,we=6,Me=7,Se=8;function De(e){return ke(e)?366:365}function ke(e){return e%4==0&&e%100!=0||e%400==0}I("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),I(0,["YY",2],0,function(){return this.year()%100}),I(0,["YYYY",4],0,"year"),I(0,["YYYYY",5],0,"year"),I(0,["YYYYYY",6,!0],0,"year"),H("year","y"),L("year",1),ue("Y",se),ue("YY",B,z),ue("YYYY",ee,q),ue("YYYYY",te,J),ue("YYYYYY",te,J),ce(["YYYYY","YYYYYY"],me),ce("YYYY",function(e,t){t[me]=2===e.length?n.parseTwoDigitYear(e):M(e)}),ce("YY",function(e,t){t[me]=n.parseTwoDigitYear(e)}),ce("Y",function(e,t){t[me]=parseInt(e,10)}),n.parseTwoDigitYear=function(e){return M(e)+(M(e)>68?1900:2e3)};var Ye,Oe=Te("FullYear",!0);function Te(e,t){return function(s){return null!=s?(be(this,e,s),n.updateOffset(this,t),this):xe(this,e)}}function xe(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function be(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&ke(e.year())&&1===e.month()&&29===e.date()?e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),Pe(n,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](n))}function Pe(e,t){if(isNaN(e)||isNaN(t))return NaN;var n,s=(t%(n=12)+n)%n;return e+=(t-s)/12,1===s?ke(e)?29:28:31-s%7%2}Ye=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},I("M",["MM",2],"Mo",function(){return this.month()+1}),I("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),I("MMMM",0,0,function(e){return this.localeData().months(this,e)}),H("month","M"),L("month",8),ue("M",B),ue("MM",B,z),ue("MMM",function(e,t){return t.monthsShortRegex(e)}),ue("MMMM",function(e,t){return t.monthsRegex(e)}),ce(["M","MM"],function(e,t){t[_e]=M(e)-1}),ce(["MMM","MMMM"],function(e,t,n,s){var i=n._locale.monthsParse(e,s,n._strict);null!=i?t[_e]=i:c(n).invalidMonth=e});var We=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,He="January_February_March_April_May_June_July_August_September_October_November_December".split("_");var Re="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");function Ce(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=M(t);else if(!a(t=e.localeData().monthsParse(t)))return e;return n=Math.min(e.date(),Pe(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function Fe(e){return null!=e?(Ce(this,e),n.updateOffset(this,!0),this):xe(this,"Month")}var Le=ae;var Ue=ae;function Ne(){function e(e,t){return t.length-e.length}var t,n,s=[],i=[],r=[];for(t=0;t<12;t++)n=h([2e3,t]),s.push(this.monthsShort(n,"")),i.push(this.months(n,"")),r.push(this.months(n,"")),r.push(this.monthsShort(n,""));for(s.sort(e),i.sort(e),r.sort(e),t=0;t<12;t++)s[t]=de(s[t]),i[t]=de(i[t]);for(t=0;t<24;t++)r[t]=de(r[t]);this._monthsRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function Ge(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&e>=0&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function Ve(e,t,n){var s=7+t-n;return-((7+Ge(e,0,s).getUTCDay()-t)%7)+s-1}function Ee(e,t,n,s,i){var r,a,o=1+7*(t-1)+(7+n-s)%7+Ve(e,s,i);return o<=0?a=De(r=e-1)+o:o>De(e)?(r=e+1,a=o-De(e)):(r=e,a=o),{year:r,dayOfYear:a}}function Ie(e,t,n){var s,i,r=Ve(e.year(),t,n),a=Math.floor((e.dayOfYear()-r-1)/7)+1;return a<1?s=a+Ae(i=e.year()-1,t,n):a>Ae(e.year(),t,n)?(s=a-Ae(e.year(),t,n),i=e.year()+1):(i=e.year(),s=a),{week:s,year:i}}function Ae(e,t,n){var s=Ve(e,t,n),i=Ve(e+1,t,n);return(De(e)-s+i)/7}I("w",["ww",2],"wo","week"),I("W",["WW",2],"Wo","isoWeek"),H("week","w"),H("isoWeek","W"),L("week",5),L("isoWeek",5),ue("w",B),ue("ww",B,z),ue("W",B),ue("WW",B,z),fe(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=M(e)});I("d",0,"do","day"),I("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),I("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),I("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),I("e",0,0,"weekday"),I("E",0,0,"isoWeekday"),H("day","d"),H("weekday","e"),H("isoWeekday","E"),L("day",11),L("weekday",11),L("isoWeekday",11),ue("d",B),ue("e",B),ue("E",B),ue("dd",function(e,t){return t.weekdaysMinRegex(e)}),ue("ddd",function(e,t){return t.weekdaysShortRegex(e)}),ue("dddd",function(e,t){return t.weekdaysRegex(e)}),fe(["dd","ddd","dddd"],function(e,t,n,s){var i=n._locale.weekdaysParse(e,s,n._strict);null!=i?t.d=i:c(n).invalidWeekday=e}),fe(["d","e","E"],function(e,t,n,s){t[s]=M(e)});var je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");var Ze="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");var ze="Su_Mo_Tu_We_Th_Fr_Sa".split("_");var $e=ae;var qe=ae;var Je=ae;function Be(){function e(e,t){return t.length-e.length}var t,n,s,i,r,a=[],o=[],u=[],l=[];for(t=0;t<7;t++)n=h([2e3,1]).day(t),s=this.weekdaysMin(n,""),i=this.weekdaysShort(n,""),r=this.weekdays(n,""),a.push(s),o.push(i),u.push(r),l.push(s),l.push(i),l.push(r);for(a.sort(e),o.sort(e),u.sort(e),l.sort(e),t=0;t<7;t++)o[t]=de(o[t]),u[t]=de(u[t]),l[t]=de(l[t]);this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function Qe(){return this.hours()%12||12}function Xe(e,t){I(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function Ke(e,t){return t._meridiemParse}I("H",["HH",2],0,"hour"),I("h",["hh",2],0,Qe),I("k",["kk",2],0,function(){return this.hours()||24}),I("hmm",0,0,function(){return""+Qe.apply(this)+U(this.minutes(),2)}),I("hmmss",0,0,function(){return""+Qe.apply(this)+U(this.minutes(),2)+U(this.seconds(),2)}),I("Hmm",0,0,function(){return""+this.hours()+U(this.minutes(),2)}),I("Hmmss",0,0,function(){return""+this.hours()+U(this.minutes(),2)+U(this.seconds(),2)}),Xe("a",!0),Xe("A",!1),H("hour","h"),L("hour",13),ue("a",Ke),ue("A",Ke),ue("H",B),ue("h",B),ue("k",B),ue("HH",B,z),ue("hh",B,z),ue("kk",B,z),ue("hmm",Q),ue("hmmss",X),ue("Hmm",Q),ue("Hmmss",X),ce(["H","HH"],ge),ce(["k","kk"],function(e,t,n){var s=M(e);t[ge]=24===s?0:s}),ce(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),ce(["h","hh"],function(e,t,n){t[ge]=M(e),c(n).bigHour=!0}),ce("hmm",function(e,t,n){var s=e.length-2;t[ge]=M(e.substr(0,s)),t[pe]=M(e.substr(s)),c(n).bigHour=!0}),ce("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=M(e.substr(0,s)),t[pe]=M(e.substr(s,2)),t[ve]=M(e.substr(i)),c(n).bigHour=!0}),ce("Hmm",function(e,t,n){var s=e.length-2;t[ge]=M(e.substr(0,s)),t[pe]=M(e.substr(s))}),ce("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=M(e.substr(0,s)),t[pe]=M(e.substr(s,2)),t[ve]=M(e.substr(i))});var et,tt=Te("Hours",!0),nt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:He,monthsShort:Re,week:{dow:0,doy:6},weekdays:je,weekdaysMin:ze,weekdaysShort:Ze,meridiemParse:/[ap]\.?m?\.?/i},st={},it={};function rt(e){return e?e.toLowerCase().replace("_","-"):e}function at(e){var t=null;if(!st[e]&&"undefined"!=typeof module&&module&&module.exports)try{t=et._abbr,require("./locale/"+e),ot(t)}catch(e){}return st[e]}function ot(e,t){var n;return e&&((n=r(t)?lt(e):ut(e,t))?et=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),et._abbr}function ut(e,t){if(null!==t){var n,s=nt;if(t.abbr=e,null!=st[e])T("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),s=st[e]._config;else if(null!=t.parentLocale)if(null!=st[t.parentLocale])s=st[t.parentLocale]._config;else{if(null==(n=at(t.parentLocale)))return it[t.parentLocale]||(it[t.parentLocale]=[]),it[t.parentLocale].push({name:e,config:t}),null;s=n._config}return st[e]=new P(b(s,t)),it[e]&&it[e].forEach(function(e){ut(e.name,e.config)}),ot(e),st[e]}return delete st[e],null}function lt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return et;if(!s(e)){if(t=at(e))return t;e=[e]}return function(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=rt(e[r]).split("-")).length,n=(n=rt(e[r+1]))?n.split("-"):null;t>0;){if(s=at(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&S(i,n,!0)>=t-1)break;t--}r++}return et}(e)}function dt(e){var t,n=e._a;return n&&-2===c(e).overflow&&(t=n[_e]<0||n[_e]>11?_e:n[ye]<1||n[ye]>Pe(n[me],n[_e])?ye:n[ge]<0||n[ge]>24||24===n[ge]&&(0!==n[pe]||0!==n[ve]||0!==n[we])?ge:n[pe]<0||n[pe]>59?pe:n[ve]<0||n[ve]>59?ve:n[we]<0||n[we]>999?we:-1,c(e)._overflowDayOfYear&&(t<me||t>ye)&&(t=ye),c(e)._overflowWeeks&&-1===t&&(t=Me),c(e)._overflowWeekday&&-1===t&&(t=Se),c(e).overflow=t),e}function ht(e,t,n){return null!=e?e:null!=t?t:n}function ct(e){var t,s,i,r,a,o=[];if(!e._d){var u,l;for(u=e,l=new Date(n.now()),i=u._useUTC?[l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate()]:[l.getFullYear(),l.getMonth(),l.getDate()],e._w&&null==e._a[ye]&&null==e._a[_e]&&function(e){var t,n,s,i,r,a,o,u;if(null!=(t=e._w).GG||null!=t.W||null!=t.E)r=1,a=4,n=ht(t.GG,e._a[me],Ie(Tt(),1,4).year),s=ht(t.W,1),((i=ht(t.E,1))<1||i>7)&&(u=!0);else{r=e._locale._week.dow,a=e._locale._week.doy;var l=Ie(Tt(),r,a);n=ht(t.gg,e._a[me],l.year),s=ht(t.w,l.week),null!=t.d?((i=t.d)<0||i>6)&&(u=!0):null!=t.e?(i=t.e+r,(t.e<0||t.e>6)&&(u=!0)):i=r}s<1||s>Ae(n,r,a)?c(e)._overflowWeeks=!0:null!=u?c(e)._overflowWeekday=!0:(o=Ee(n,s,i,r,a),e._a[me]=o.year,e._dayOfYear=o.dayOfYear)}(e),null!=e._dayOfYear&&(a=ht(e._a[me],i[me]),(e._dayOfYear>De(a)||0===e._dayOfYear)&&(c(e)._overflowDayOfYear=!0),s=Ge(a,0,e._dayOfYear),e._a[_e]=s.getUTCMonth(),e._a[ye]=s.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=o[t]=i[t];for(;t<7;t++)e._a[t]=o[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[ge]&&0===e._a[pe]&&0===e._a[ve]&&0===e._a[we]&&(e._nextDay=!0,e._a[ge]=0),e._d=(e._useUTC?Ge:function(e,t,n,s,i,r,a){var o=new Date(e,t,n,s,i,r,a);return e<100&&e>=0&&isFinite(o.getFullYear())&&o.setFullYear(e),o}).apply(null,o),r=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ge]=24),e._w&&void 0!==e._w.d&&e._w.d!==r&&(c(e).weekdayMismatch=!0)}}var ft=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,mt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,_t=/Z|[+-]\d\d(?::?\d\d)?/,yt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],gt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],pt=/^\/?Date\((\-?\d+)/i;function vt(e){var t,n,s,i,r,a,o=e._i,u=ft.exec(o)||mt.exec(o);if(u){for(c(e).iso=!0,t=0,n=yt.length;t<n;t++)if(yt[t][1].exec(u[1])){i=yt[t][0],s=!1!==yt[t][2];break}if(null==i)return void(e._isValid=!1);if(u[3]){for(t=0,n=gt.length;t<n;t++)if(gt[t][1].exec(u[3])){r=(u[2]||" ")+gt[t][0];break}if(null==r)return void(e._isValid=!1)}if(!s&&null!=r)return void(e._isValid=!1);if(u[4]){if(!_t.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),kt(e)}else e._isValid=!1}var wt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;function Mt(e,t,n,s,i,r){var a=[function(e){var t=parseInt(e,10);{if(t<=49)return 2e3+t;if(t<=999)return 1900+t}return t}(e),Re.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&a.push(parseInt(r,10)),a}var St={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Dt(e){var t,n,s,i=wt.exec(e._i.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim());if(i){var r=Mt(i[4],i[3],i[2],i[5],i[6],i[7]);if(t=i[1],n=r,s=e,t&&Ze.indexOf(t)!==new Date(n[0],n[1],n[2]).getDay()&&(c(s).weekdayMismatch=!0,s._isValid=!1,1))return;e._a=r,e._tzm=function(e,t,n){if(e)return St[e];if(t)return 0;var s=parseInt(n,10),i=s%100;return(s-i)/100*60+i}(i[8],i[9],i[10]),e._d=Ge.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),c(e).rfc2822=!0}else e._isValid=!1}function kt(e){if(e._f!==n.ISO_8601)if(e._f!==n.RFC_2822){e._a=[],c(e).empty=!0;var t,s,i,r,a,o,u,d,h=""+e._i,f=h.length,m=0;for(i=j(e._f,e._locale).match(N)||[],t=0;t<i.length;t++)r=i[t],(s=(h.match(le(r,e))||[])[0])&&((a=h.substr(0,h.indexOf(s))).length>0&&c(e).unusedInput.push(a),h=h.slice(h.indexOf(s)+s.length),m+=s.length),E[r]?(s?c(e).empty=!1:c(e).unusedTokens.push(r),o=r,d=e,null!=(u=s)&&l(he,o)&&he[o](u,d._a,d,o)):e._strict&&!s&&c(e).unusedTokens.push(r);c(e).charsLeftOver=f-m,h.length>0&&c(e).unusedInput.push(h),e._a[ge]<=12&&!0===c(e).bigHour&&e._a[ge]>0&&(c(e).bigHour=void 0),c(e).parsedDateParts=e._a.slice(0),c(e).meridiem=e._meridiem,e._a[ge]=function(e,t,n){var s;if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((s=e.isPM(n))&&t<12&&(t+=12),s||12!==t||(t=0),t):t}(e._locale,e._a[ge],e._meridiem),ct(e),dt(e)}else Dt(e);else vt(e)}function Yt(e){var t,l,h,_,g=e._i,w=e._f;return e._locale=e._locale||lt(e._l),null===g||void 0===w&&""===g?m({nullInput:!0}):("string"==typeof g&&(e._i=g=e._locale.preparse(g)),v(g)?new p(dt(g)):(o(g)?e._d=g:s(w)?function(e){var t,n,s,i,r;if(0===e._f.length)return c(e).invalidFormat=!0,void(e._d=new Date(NaN));for(i=0;i<e._f.length;i++)r=0,t=y({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],kt(t),f(t)&&(r+=c(t).charsLeftOver,r+=10*c(t).unusedTokens.length,c(t).score=r,(null==s||r<s)&&(s=r,n=t));d(e,n||t)}(e):w?kt(e):r(l=(t=e)._i)?t._d=new Date(n.now()):o(l)?t._d=new Date(l.valueOf()):"string"==typeof l?(h=t,null===(_=pt.exec(h._i))?(vt(h),!1===h._isValid&&(delete h._isValid,Dt(h),!1===h._isValid&&(delete h._isValid,n.createFromInputFallback(h)))):h._d=new Date(+_[1])):s(l)?(t._a=u(l.slice(0),function(e){return parseInt(e,10)}),ct(t)):i(l)?function(e){if(!e._d){var t=C(e._i);e._a=u([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),ct(e)}}(t):a(l)?t._d=new Date(l):n.createFromInputFallback(t),f(e)||(e._d=null),e))}function Ot(e,t,n,r,a){var o,u={};return!0!==n&&!1!==n||(r=n,n=void 0),(i(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(e.hasOwnProperty(t))return!1;return!0}(e)||s(e)&&0===e.length)&&(e=void 0),u._isAMomentObject=!0,u._useUTC=u._isUTC=a,u._l=n,u._i=e,u._f=t,u._strict=r,(o=new p(dt(Yt(u))))._nextDay&&(o.add(1,"d"),o._nextDay=void 0),o}function Tt(e,t,n,s){return Ot(e,t,n,s,!1)}n.createFromInputFallback=k("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),n.ISO_8601=function(){},n.RFC_2822=function(){};var xt=k("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=Tt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:m()}),bt=k("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=Tt.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:m()});function Pt(e,t){var n,i;if(1===t.length&&s(t[0])&&(t=t[0]),!t.length)return Tt();for(n=t[0],i=1;i<t.length;++i)t[i].isValid()&&!t[i][e](n)||(n=t[i]);return n}var Wt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ht(e){var t=C(e),n=t.year||0,s=t.quarter||0,i=t.month||0,r=t.week||0,a=t.day||0,o=t.hour||0,u=t.minute||0,l=t.second||0,d=t.millisecond||0;this._isValid=function(e){for(var t in e)if(-1===Ye.call(Wt,t)||null!=e[t]&&isNaN(e[t]))return!1;for(var n=!1,s=0;s<Wt.length;++s)if(e[Wt[s]]){if(n)return!1;parseFloat(e[Wt[s]])!==M(e[Wt[s]])&&(n=!0)}return!0}(t),this._milliseconds=+d+1e3*l+6e4*u+1e3*o*60*60,this._days=+a+7*r,this._months=+i+3*s+12*n,this._data={},this._locale=lt(),this._bubble()}function Rt(e){return e instanceof Ht}function Ct(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,t){I(e,0,0,function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+U(~~(e/60),2)+t+U(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),ue("Z",re),ue("ZZ",re),ce(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Ut(re,e)});var Lt=/([\+\-]|\d\d)/gi;function Ut(e,t){var n=(t||"").match(e);if(null===n)return null;var s=((n[n.length-1]||[])+"").match(Lt)||["-",0,0],i=60*s[1]+M(s[2]);return 0===i?0:"+"===s[0]?i:-i}function Nt(e,t){var s,i;return t._isUTC?(s=t.clone(),i=(v(e)||o(e)?e.valueOf():Tt(e).valueOf())-s.valueOf(),s._d.setTime(s._d.valueOf()+i),n.updateOffset(s,!1),s):Tt(e).local()}function Gt(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Vt(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}n.updateOffset=function(){};var Et=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,It=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function At(e,t){var n,s,i,r=e,o=null;return Rt(e)?r={ms:e._milliseconds,d:e._days,M:e._months}:a(e)?(r={},t?r[t]=e:r.milliseconds=e):(o=Et.exec(e))?(n="-"===o[1]?-1:1,r={y:0,d:M(o[ye])*n,h:M(o[ge])*n,m:M(o[pe])*n,s:M(o[ve])*n,ms:M(Ct(1e3*o[we]))*n}):(o=It.exec(e))?(n="-"===o[1]?-1:(o[1],1),r={y:jt(o[2],n),M:jt(o[3],n),w:jt(o[4],n),d:jt(o[5],n),h:jt(o[6],n),m:jt(o[7],n),s:jt(o[8],n)}):null==r?r={}:"object"==typeof r&&("from"in r||"to"in r)&&(i=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Nt(t,e),e.isBefore(t)?n=Zt(e,t):((n=Zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(Tt(r.from),Tt(r.to)),(r={}).ms=i.milliseconds,r.M=i.months),s=new Ht(r),Rt(e)&&l(e,"_locale")&&(s._locale=e._locale),s}function jt(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function Zt(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function zt(e,t){return function(n,s){var i;return null===s||isNaN(+s)||(T(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),i=n,n=s,s=i),$t(this,At(n="string"==typeof n?+n:n,s),e),this}}function $t(e,t,s,i){var r=t._milliseconds,a=Ct(t._days),o=Ct(t._months);e.isValid()&&(i=null==i||i,o&&Ce(e,xe(e,"Month")+o*s),a&&be(e,"Date",xe(e,"Date")+a*s),r&&e._d.setTime(e._d.valueOf()+r*s),i&&n.updateOffset(e,a||o))}At.fn=Ht.prototype,At.invalid=function(){return At(NaN)};var qt=zt(1,"add"),Jt=zt(-1,"subtract");function Bt(e,t){var n=12*(t.year()-e.year())+(t.month()-e.month()),s=e.clone().add(n,"months");return-(n+(t-s<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(n+1,"months")-s)))||0}function Qt(e){var t;return void 0===e?this._locale._abbr:(null!=(t=lt(e))&&(this._locale=t),this)}n.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",n.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Xt=k("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}function en(e,t){I(0,[e,e.length],0,t)}function tn(e,t,n,s,i){var r;return null==e?Ie(this,s,i).year:(t>(r=Ae(e,s,i))&&(t=r),function(e,t,n,s,i){var r=Ee(e,t,n,s,i),a=Ge(r.year,0,r.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}.call(this,e,t,n,s,i))}I(0,["gg",2],0,function(){return this.weekYear()%100}),I(0,["GG",2],0,function(){return this.isoWeekYear()%100}),en("gggg","weekYear"),en("ggggg","weekYear"),en("GGGG","isoWeekYear"),en("GGGGG","isoWeekYear"),H("weekYear","gg"),H("isoWeekYear","GG"),L("weekYear",1),L("isoWeekYear",1),ue("G",se),ue("g",se),ue("GG",B,z),ue("gg",B,z),ue("GGGG",ee,q),ue("gggg",ee,q),ue("GGGGG",te,J),ue("ggggg",te,J),fe(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=M(e)}),fe(["gg","GG"],function(e,t,s,i){t[i]=n.parseTwoDigitYear(e)}),I("Q",0,"Qo","quarter"),H("quarter","Q"),L("quarter",7),ue("Q",Z),ce("Q",function(e,t){t[_e]=3*(M(e)-1)}),I("D",["DD",2],"Do","date"),H("date","D"),L("date",9),ue("D",B),ue("DD",B,z),ue("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),ce(["D","DD"],ye),ce("Do",function(e,t){t[ye]=M(e.match(B)[0])});var nn=Te("Date",!0);I("DDD",["DDDD",3],"DDDo","dayOfYear"),H("dayOfYear","DDD"),L("dayOfYear",4),ue("DDD",K),ue("DDDD",$),ce(["DDD","DDDD"],function(e,t,n){n._dayOfYear=M(e)}),I("m",["mm",2],0,"minute"),H("minute","m"),L("minute",14),ue("m",B),ue("mm",B,z),ce(["m","mm"],pe);var sn=Te("Minutes",!1);I("s",["ss",2],0,"second"),H("second","s"),L("second",15),ue("s",B),ue("ss",B,z),ce(["s","ss"],ve);var rn,an=Te("Seconds",!1);for(I("S",0,0,function(){return~~(this.millisecond()/100)}),I(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),I(0,["SSS",3],0,"millisecond"),I(0,["SSSS",4],0,function(){return 10*this.millisecond()}),I(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),I(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),I(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),I(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),I(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),H("millisecond","ms"),L("millisecond",16),ue("S",K,Z),ue("SS",K,z),ue("SSS",K,$),rn="SSSS";rn.length<=9;rn+="S")ue(rn,ne);function on(e,t){t[we]=M(1e3*("0."+e))}for(rn="S";rn.length<=9;rn+="S")ce(rn,on);var un=Te("Milliseconds",!1);I("z",0,0,"zoneAbbr"),I("zz",0,0,"zoneName");var ln=p.prototype;function dn(e){return e}ln.add=qt,ln.calendar=function(e,t){var s=e||Tt(),i=Nt(s,this).startOf("day"),r=n.calendarFormat(this,i)||"sameElse",a=t&&(x(t[r])?t[r].call(this,s):t[r]);return this.format(a||this.localeData().calendar(r,this,Tt(s)))},ln.clone=function(){return new p(this)},ln.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Nt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=R(t)){case"year":r=Bt(this,s)/12;break;case"month":r=Bt(this,s);break;case"quarter":r=Bt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:w(r)},ln.endOf=function(e){return void 0===(e=R(e))||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))},ln.format=function(e){e||(e=this.isUtc()?n.defaultFormatUtc:n.defaultFormat);var t=A(this,e);return this.localeData().postformat(t)},ln.from=function(e,t){return this.isValid()&&(v(e)&&e.isValid()||Tt(e).isValid())?At({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.fromNow=function(e){return this.from(Tt(),e)},ln.to=function(e,t){return this.isValid()&&(v(e)&&e.isValid()||Tt(e).isValid())?At({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.toNow=function(e){return this.to(Tt(),e)},ln.get=function(e){return x(this[e=R(e)])?this[e]():this},ln.invalidAt=function(){return c(this).overflow},ln.isAfter=function(e,t){var n=v(e)?e:Tt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=R(r(t)?"millisecond":t))?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},ln.isBefore=function(e,t){var n=v(e)?e:Tt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=R(r(t)?"millisecond":t))?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},ln.isBetween=function(e,t,n,s){return("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},ln.isSame=function(e,t){var n,s=v(e)?e:Tt(e);return!(!this.isValid()||!s.isValid())&&("millisecond"===(t=R(t||"millisecond"))?this.valueOf()===s.valueOf():(n=s.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},ln.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},ln.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},ln.isValid=function(){return f(this)},ln.lang=Xt,ln.locale=Qt,ln.localeData=Kt,ln.max=bt,ln.min=xt,ln.parsingFlags=function(){return d({},c(this))},ln.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t=[];for(var n in e)t.push({unit:n,priority:F[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}(e=C(e)),s=0;s<n.length;s++)this[n[s].unit](e[n[s].unit]);else if(x(this[e=R(e)]))return this[e](t);return this},ln.startOf=function(e){switch(e=R(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this},ln.subtract=Jt,ln.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},ln.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},ln.toDate=function(){return new Date(this.valueOf())},ln.toISOString=function(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||n.year()>9999?A(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):x(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",A(n,"Z")):A(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},ln.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var n="["+e+'("]',s=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i=t+'[")]';return this.format(n+s+"-MM-DD[T]HH:mm:ss.SSS"+i)},ln.toJSON=function(){return this.isValid()?this.toISOString():null},ln.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},ln.unix=function(){return Math.floor(this.valueOf()/1e3)},ln.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},ln.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},ln.year=Oe,ln.isLeapYear=function(){return ke(this.year())},ln.weekYear=function(e){return tn.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},ln.isoWeekYear=function(e){return tn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},ln.quarter=ln.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},ln.month=Fe,ln.daysInMonth=function(){return Pe(this.year(),this.month())},ln.week=ln.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},ln.isoWeek=ln.isoWeeks=function(e){var t=Ie(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},ln.weeksInYear=function(){var e=this.localeData()._week;return Ae(this.year(),e.dow,e.doy)},ln.isoWeeksInYear=function(){return Ae(this.year(),1,4)},ln.date=nn,ln.day=ln.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,s=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-s,"d")):s},ln.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},ln.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=(n=e,s=this.localeData(),"string"==typeof n?s.weekdaysParse(n)%7||7:isNaN(n)?null:n);return this.day(this.day()%7?t:t-7)}return this.day()||7;var n,s},ln.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},ln.hour=ln.hours=tt,ln.minute=ln.minutes=sn,ln.second=ln.seconds=an,ln.millisecond=ln.milliseconds=un,ln.utcOffset=function(e,t,s){var i,r=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if("string"==typeof e){if(null===(e=Ut(re,e)))return this}else Math.abs(e)<16&&!s&&(e*=60);return!this._isUTC&&t&&(i=Gt(this)),this._offset=e,this._isUTC=!0,null!=i&&this.add(i,"m"),r!==e&&(!t||this._changeInProgress?$t(this,At(e-r,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,n.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?r:Gt(this)},ln.utc=function(e){return this.utcOffset(0,e)},ln.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Gt(this),"m")),this},ln.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=Ut(ie,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},ln.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?Tt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},ln.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},ln.isLocal=function(){return!!this.isValid()&&!this._isUTC},ln.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},ln.isUtc=Vt,ln.isUTC=Vt,ln.zoneAbbr=function(){return this._isUTC?"UTC":""},ln.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},ln.dates=k("dates accessor is deprecated. Use date instead.",nn),ln.months=k("months accessor is deprecated. Use month instead",Fe),ln.years=k("years accessor is deprecated. Use year instead",Oe),ln.zone=k("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),ln.isDSTShifted=k("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!r(this._isDSTShifted))return this._isDSTShifted;var e={};if(y(e,this),(e=Yt(e))._a){var t=e._isUTC?h(e._a):Tt(e._a);this._isDSTShifted=this.isValid()&&S(e._a,t.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted});var hn=P.prototype;function cn(e,t,n,s){var i=lt(),r=h().set(s,t);return i[n](r,e)}function fn(e,t,n){if(a(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");var s,i=[];for(s=0;s<12;s++)i[s]=cn(e,s,n,"month");return i}function mn(e,t,n,s){"boolean"==typeof e?(a(t)&&(n=t,t=void 0),t=t||""):(n=t=e,e=!1,a(t)&&(n=t,t=void 0),t=t||"");var i,r=lt(),o=e?r._week.dow:0;if(null!=n)return cn(t,(n+o)%7,s,"day");var u=[];for(i=0;i<7;i++)u[i]=cn(t,(i+o)%7,s,"day");return u}hn.calendar=function(e,t,n){var s=this._calendar[e]||this._calendar.sameElse;return x(s)?s.call(t,n):s},hn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},hn.invalidDate=function(){return this._invalidDate},hn.ordinal=function(e){return this._ordinal.replace("%d",e)},hn.preparse=dn,hn.postformat=dn,hn.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return x(i)?i(e,t,n,s):i.replace(/%d/i,e)},hn.pastFuture=function(e,t){var n=this._relativeTime[e>0?"future":"past"];return x(n)?n(t):n.replace(/%s/i,t)},hn.set=function(e){var t,n;for(n in e)x(t=e[n])?this[n]=t:this["_"+n]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},hn.months=function(e,t){return e?s(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||We).test(t)?"format":"standalone"][e.month()]:s(this._months)?this._months:this._months.standalone},hn.monthsShort=function(e,t){return e?s(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[We.test(t)?"format":"standalone"][e.month()]:s(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},hn.monthsParse=function(e,t,n){var s,i,r;if(this._monthsParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=h([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=h([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(r="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(r.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},hn.monthsRegex=function(e){return this._monthsParseExact?(l(this,"_monthsRegex")||Ne.call(this),e?this._monthsStrictRegex:this._monthsRegex):(l(this,"_monthsRegex")||(this._monthsRegex=Ue),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},hn.monthsShortRegex=function(e){return this._monthsParseExact?(l(this,"_monthsRegex")||Ne.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(l(this,"_monthsShortRegex")||(this._monthsShortRegex=Le),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},hn.week=function(e){return Ie(e,this._week.dow,this._week.doy).week},hn.firstDayOfYear=function(){return this._week.doy},hn.firstDayOfWeek=function(){return this._week.dow},hn.weekdays=function(e,t){return e?s(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(t)?"format":"standalone"][e.day()]:s(this._weekdays)?this._weekdays:this._weekdays.standalone},hn.weekdaysMin=function(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin},hn.weekdaysShort=function(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort},hn.weekdaysParse=function(e,t,n){var s,i,r;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=h([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=h([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".",".?")+"$","i")),this._weekdaysParse[s]||(r="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(r.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},hn.weekdaysRegex=function(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(l(this,"_weekdaysRegex")||(this._weekdaysRegex=$e),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},hn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(l(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=qe),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},hn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(l(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Je),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},hn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},hn.meridiem=function(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"},ot("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===M(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),n.lang=k("moment.lang is deprecated. Use moment.locale instead.",ot),n.langData=k("moment.langData is deprecated. Use moment.localeData instead.",lt);var _n=Math.abs;function yn(e,t,n,s){var i=At(t,n);return e._milliseconds+=s*i._milliseconds,e._days+=s*i._days,e._months+=s*i._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function pn(e){return 4800*e/146097}function vn(e){return 146097*e/4800}function wn(e){return function(){return this.as(e)}}var Mn=wn("ms"),Sn=wn("s"),Dn=wn("m"),kn=wn("h"),Yn=wn("d"),On=wn("w"),Tn=wn("M"),xn=wn("y");function bn(e){return function(){return this.isValid()?this._data[e]:NaN}}var Pn=bn("milliseconds"),Wn=bn("seconds"),Hn=bn("minutes"),Rn=bn("hours"),Cn=bn("days"),Fn=bn("months"),Ln=bn("years");var Un=Math.round,Nn={ss:44,s:45,m:45,h:22,d:26,M:11};var Gn=Math.abs;function Vn(e){return(e>0)-(e<0)||+e}function En(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n=Gn(this._milliseconds)/1e3,s=Gn(this._days),i=Gn(this._months);t=w((e=w(n/60))/60),n%=60,e%=60;var r=w(i/12),a=i%=12,o=s,u=t,l=e,d=n?n.toFixed(3).replace(/\.?0+$/,""):"",h=this.asSeconds();if(!h)return"P0D";var c=h<0?"-":"",f=Vn(this._months)!==Vn(h)?"-":"",m=Vn(this._days)!==Vn(h)?"-":"",_=Vn(this._milliseconds)!==Vn(h)?"-":"";return c+"P"+(r?f+r+"Y":"")+(a?f+a+"M":"")+(o?m+o+"D":"")+(u||l||d?"T":"")+(u?_+u+"H":"")+(l?_+l+"M":"")+(d?_+d+"S":"")}var In=Ht.prototype;return In.isValid=function(){return this._isValid},In.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},In.add=function(e,t){return yn(this,e,t,1)},In.subtract=function(e,t){return yn(this,e,t,-1)},In.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=R(e))||"year"===e)return t=this._days+s/864e5,n=this._months+pn(t),"month"===e?n:n/12;switch(t=this._days+Math.round(vn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},In.asMilliseconds=Mn,In.asSeconds=Sn,In.asMinutes=Dn,In.asHours=kn,In.asDays=Yn,In.asWeeks=On,In.asMonths=Tn,In.asYears=xn,In.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*M(this._months/12):NaN},In._bubble=function(){var e,t,n,s,i,r=this._milliseconds,a=this._days,o=this._months,u=this._data;return r>=0&&a>=0&&o>=0||r<=0&&a<=0&&o<=0||(r+=864e5*gn(vn(o)+a),a=0,o=0),u.milliseconds=r%1e3,e=w(r/1e3),u.seconds=e%60,t=w(e/60),u.minutes=t%60,n=w(t/60),u.hours=n%24,o+=i=w(pn(a+=w(n/24))),a-=gn(vn(i)),s=w(o/12),o%=12,u.days=a,u.months=o,u.years=s,this},In.clone=function(){return At(this)},In.get=function(e){return e=R(e),this.isValid()?this[e+"s"]():NaN},In.milliseconds=Pn,In.seconds=Wn,In.minutes=Hn,In.hours=Rn,In.days=Cn,In.weeks=function(){return w(this.days()/7)},In.months=Fn,In.years=Ln,In.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t,n,s,i,r,a,o,u,l,d,h,c=this.localeData(),f=(n=!e,s=c,i=At(t=this).abs(),r=Un(i.as("s")),a=Un(i.as("m")),o=Un(i.as("h")),u=Un(i.as("d")),l=Un(i.as("M")),d=Un(i.as("y")),(h=r<=Nn.ss&&["s",r]||r<Nn.s&&["ss",r]||a<=1&&["m"]||a<Nn.m&&["mm",a]||o<=1&&["h"]||o<Nn.h&&["hh",o]||u<=1&&["d"]||u<Nn.d&&["dd",u]||l<=1&&["M"]||l<Nn.M&&["MM",l]||d<=1&&["y"]||["yy",d])[2]=n,h[3]=+t>0,h[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,h));return e&&(f=c.pastFuture(+this,f)),c.postformat(f)},In.toISOString=En,In.toString=En,In.toJSON=En,In.locale=Qt,In.localeData=Kt,In.toIsoString=k("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",En),In.lang=Xt,I("X",0,0,"unix"),I("x",0,0,"valueOf"),ue("x",se),ue("X",/[+-]?\d+(\.\d{1,3})?/),ce("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),ce("x",function(e,t,n){n._d=new Date(M(e))}),n.version="2.21.0",e=Tt,n.fn=ln,n.min=function(){return Pt("isBefore",[].slice.call(arguments,0))},n.max=function(){return Pt("isAfter",[].slice.call(arguments,0))},n.now=function(){return Date.now?Date.now():+new Date},n.utc=h,n.unix=function(e){return Tt(1e3*e)},n.months=function(e,t){return fn(e,t,"months")},n.isDate=o,n.locale=ot,n.invalid=m,n.duration=At,n.isMoment=v,n.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},n.parseZone=function(){return Tt.apply(null,arguments).parseZone()},n.localeData=lt,n.isDuration=Rt,n.monthsShort=function(e,t){return fn(e,t,"monthsShort")},n.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},n.defineLocale=ut,n.updateLocale=function(e,t){if(null!=t){var n,s,i=nt;null!=(s=at(e))&&(i=s._config),(n=new P(t=b(i,t))).parentLocale=st[e],st[e]=n,ot(e)}else null!=st[e]&&(null!=st[e].parentLocale?st[e]=st[e].parentLocale:null!=st[e]&&delete st[e]);return st[e]},n.locales=function(){return Y(st)},n.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},n.normalizeUnits=R,n.relativeTimeRounding=function(e){return void 0===e?Un:"function"==typeof e&&(Un=e,!0)},n.relativeTimeThreshold=function(e,t){return void 0!==Nn[e]&&(void 0===t?Nn[e]:(Nn[e]=t,"s"===e&&(Nn.ss=t-1),!0))},n.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},n.prototype=ln,n.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"YYYY-[W]WW",MONTH:"YYYY-MM"},n});

/* ========================================
 FILE: /components/com_shop/js/tabs/mm_tabpane.js
 ==================== */

// initialization hook up
if (typeof window.addEventListener != "undefined"){
	window.addEventListener( "load", setupAllTabs, false );
} else if ( typeof window.attachEvent != "undefined" ) {
	window.attachEvent( "onload", setupAllTabs );
	window.attachEvent( "onunload", disposeAllTabs );
} else {
	if ( window.onload != null ) {
		var oldOnload = window.onload;
		window.onload = function ( e ) {
			oldOnload( e );
			setupAllTabs();
		};
	} else { 
		window.onload = setupAllTabs;
	}
}

if ( typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled ) {
	if ( is_cs_user('taby_test') ) {
		jQuery(function (){
			function load_mmTabPane() {
				if (typeof(WebFXTabPane) != 'undefined' && typeof(WebFXTabPage) != 'undefined') {
					setupAllTabs();
				} else {
					setTimeout('load_mmTabPane()', 100);
				}
			}
			load_mmTabPane();
		});
	} else {
		function load_mmTabPane() {
			if (typeof(WebFXTabPane) != 'undefined' && typeof(WebFXTabPage) != 'undefined') {
				setupAllTabs();
			} else {
				setTimeout('load_mmTabPane()', 100);
			}
		}
		load_mmTabPane();
	}

} else {
	jQuery(function (){
		function load_mmTabPane() {
			if (typeof(WebFXTabPane) != 'undefined' && typeof(WebFXTabPage) != 'undefined') {
				setupAllTabs();
			} else {
				setTimeout('load_mmTabPane()', 100);
			}
		}
		load_mmTabPane();
	});
}


/* ========================================
 FILE: /includes/js/system/mm_tabpane.min.js
 ==================== */

/* Tab Pane 1.02 - Erik Arvidsson */
function hasSupport(){if("undefined"!=typeof hasSupport.support)return hasSupport.support;var e=/msie 5\.[56789]/i.test(navigator.userAgent);return hasSupport.support="undefined"!=typeof document.implementation&&document.implementation.hasFeature("html","1.0")||e,e&&(document._getElementsByTagName=document.getElementsByTagName,document.getElementsByTagName=function(e){return"*"==e?document.all:document._getElementsByTagName(e)}),hasSupport.support}function WebFXTabPane(e,t,a,s){if(hasSupport()&&null!=e){this.element=e,this.element.tabPane=this,this.pages=[],this.selectedIndex=null,this.useCookie=null!=t?t:!0,this.cookiePrefix=a,this.alt_cookie_name="undefined"!=typeof s?s:"",this.element.className=this.classNameTag+" "+this.element.className,this.tabRow=document.createElement("div"),this.tabRow.className="tab-row",e.insertBefore(this.tabRow,e.firstChild);var n=0;this.useCookie&&(n=Number(WebFXTabPane.getCookie((""==this.cookiePrefix?"":this.cookiePrefix+"_")+"webfxtab_"+(""!=this.alt_cookie_name?this.alt_cookie_name:this.element.id))),isNaN(n)&&(n=0)),this.selectedIndex=n;for(var i=e.childNodes,o=0;o<i.length;o++)1==i[o].nodeType&&i[o].className.indexOf("tab-page")>-1&&this.addTabPage(i[o])}}function WebFXTabPage(e,t,a){if(hasSupport()&&null!=e){this.element=e,this.element.tabPage=this,this.index=a,this.alreadyShowed=!1;for(var s=e.childNodes,n=0;n<s.length;n++)if(1==s[n].nodeType&&("tab"==s[n].className||s[n].classList.contains("tab"))){this.tab=s[n];break}if("undefined"==typeof this.tab)return;var i=document.createElement("A");for(this.aElement=i,i.href="#",i.onclick=function(){return!1};this.tab.hasChildNodes();)i.appendChild(this.tab.firstChild);this.tab.appendChild(i);var o=this;this.tab.onclick=function(){o.select()},this.tab.onmouseover=function(){WebFXTabPage.tabOver(o)},this.tab.onmouseout=function(){WebFXTabPage.tabOut(o)}}}function setupAllTabs(){if(hasSupport()){for(var e,t,a=document.getElementsByTagName("*"),s=a.length,n=/tab\-pane/,i=/tab\-page/,o=0;s>o;o++)t=a[o],e=t.className,""!=e&&(n.test(e)&&!t.tabPane?new WebFXTabPane(t):i.test(e)&&!t.tabPage&&n.test(t.parentNode.className)&&t.parentNode.tabPane.addTabPage(t));js_global_mmTabPane_loaded=!0}}function disposeAllTabs(){if(hasSupport()){for(var e,t,a=document.getElementsByTagName("*"),s=a.length,n=/tab\-pane/,i=[],o=0;s>o;o++)t=a[o],e=t.className,""!=e&&n.test(e)&&t.tabPane&&(i[i.length]=t.tabPane);for(var o=i.length-1;o>=0;o--)i[o].dispose(),i[o]=null}}WebFXTabPane.prototype.classNameTag="mm_dynamic-tab-pane-control",WebFXTabPane.prototype.setSelectedIndex=function(e){this.selectedIndex!=e&&(null!=this.selectedIndex&&null!=this.pages[this.selectedIndex]&&this.pages[this.selectedIndex].hide(),this.selectedIndex=e,this.pages[this.selectedIndex].show(),this.useCookie&&WebFXTabPane.setCookie((""==this.cookiePrefix?"":this.cookiePrefix+"_")+"webfxtab_"+(""!=this.alt_cookie_name?this.alt_cookie_name:this.element.id),e))},WebFXTabPane.prototype.getSelectedIndex=function(){return this.selectedIndex},WebFXTabPane.prototype.addTabPage=function(e){if(hasSupport()){if(e.tabPage==this)return e.tabPage;var t=this.pages.length,a=this.pages[t]=new WebFXTabPage(e,this,t);return a.tabPane=this,this.tabRow.appendChild(a.tab),t==this.selectedIndex?a.show():a.hide(),a}},WebFXTabPane.prototype.dispose=function(){this.element.tabPane=null,this.element=null,this.tabRow=null;for(var e=0;e<this.pages.length;e++)this.pages[e].dispose(),this.pages[e]=null;this.pages=null},WebFXTabPane.setCookie=function(e,t,a){var s="";if(a){var n=new Date;n.setTime(n.getTime()+24*a*60*60*1e3),s="; expires="+n.toGMTString()}document.cookie=e+"="+t+s+"; path=/"},WebFXTabPane.getCookie=function(e){var t=new RegExp("(;|^)[^;]*("+e+")=([^;]*)(;|$)"),a=t.exec(document.cookie);return null!=a?a[3]:null},WebFXTabPane.removeCookie=function(e){setCookie(e,"",-1)},WebFXTabPage.prototype.show=function(){var e=this.tab,t=e.className+" selected";if(t=t.replace(/ +/g," "),e.className=t,this.element.style.display="block","function"==typeof WebFXTabPageShowCallback){var a=!this.alreadyShowed,s=this.element.id;WebFXTabPageShowCallback(s,a),this.alreadyShowed=!0}},WebFXTabPage.prototype.hide=function(){var e=this.tab,t=e.className;if(t=t.replace(/ selected/g,""),e.className=t,this.element.style.display="none","function"==typeof WebFXTabPageHideCallback){var a=this.element.id;WebFXTabPageHideCallback(a)}},WebFXTabPage.prototype.select=function(){this.tabPane.setSelectedIndex(this.index)},WebFXTabPage.prototype.dispose=function(){this.aElement.onclick=null,this.aElement=null,this.element.tabPage=null,this.tab.onclick=null,this.tab.onmouseover=null,this.tab.onmouseout=null,this.tab=null,this.tabPane=null,this.element=null,this.alreadyShowed=null},WebFXTabPage.tabOver=function(e){var t=e.tab,a=t.className+" hover";a=a.replace(/ +/g," "),t.className=a},WebFXTabPage.tabOut=function(e){var t=e.tab,a=t.className;a=a.replace(/ hover/g,""),t.className=a};

/* ========================================
 FILE: /includes/js/system/frontend.js
 ==================== */

var sudoMoveHrefPosX,
    sudoMoveHrefPosY;

//načítanie všetkých tooltipsterov pre frontend
window.addEventListener('DOMContentLoaded', function() {
	//len je potrebné si vybrať classu a podľa nej nahodiť tooltipster
	jQuery('.quantity_modifications_tooltip').each(function() {
		//element má v sebe data-attributes



		var $this = jQuery(this);
		var content = (($this.data('minimum_quantity') + '<br>') || ' ') + (($this.data('forced_quantity') + '<br>') || ' ') + ($this.data('maximum_quantity') || ' ');

		$this.tooltipster({
			animation     : 'fade',
			delay         : 200,
			trigger       : 'hover',
			content       : content,
			theme         : 'cs_tooltipster_grey_theme',
			contentAsHTML : true,
		});

		//extra pridanie aj na pridaŤ do košíka button

		if ($this.closest('div.shop-category-product').length) {
			$this.closest('div.shop-category-product').find('input.categ_add_to_cart').tooltipster({
				animation     : 'fade',
				delay         : 200,
				trigger       : 'hover',
				content       : content,
				theme         : 'cs_tooltipster_grey_theme',
				contentAsHTML : true,
			});
		}
	});
});

// sudo slider iOS fix
function js_sudo_slider_ios_fix() {
	jQuery('.sudo_href').on('touchmove', function(e) {
        sudoMoveHrefPosX = e.originalEvent.touches[0].pageX;
        sudoMoveHrefPosY = e.originalEvent.touches[0].pageY;
    }).on('touchend', function(e) {
        var ths = jQuery(this),
            thsHref = ths.attr('href'),
            thsTarget = ths.attr('target');

        if ( sudoMoveHrefPosX == undefined && sudoMoveHrefPosY == undefined) {
            if ( thsTarget == '_blank' ) {
                window.open(thsHref, '_blank');
            } else {
                window.location.assign(thsHref);
            }
            return false;
        }
        sudoMoveHrefPosX = undefined;
        sudoMoveHrefPosY = undefined;
    });
}

function js_sudo_slider_sudo_href_fix() {
    var $sudoHrefElem,
        sudoHrefCursoruPosX,
        sudoHrefCursoruPosY;

	$sudoHrefElem = jQuery('.sudo_href');

	$sudoHrefElem.on('click', function(e) {
    	return false;
    });
	$sudoHrefElem.on('mousedown', function(e) {
        sudoHrefCursoruPosX = e.pageX;
        sudoHrefCursoruPosY = e.pageY;
    });

	$sudoHrefElem.on('mouseup', function(e) {
    	var target = jQuery(this).attr('href');
    	if ( sudoHrefCursoruPosX === e.pageX && sudoHrefCursoruPosY === e.pageY && target !== '#' ) {
            if ( jQuery(this).attr('target') == '_blank' ) {
                window.open(target, '_blank');
            } else {
                window.location.assign(target);
            }
        }
    });
}

jQuery.fn.startAjaxLoader = function ( loader_image_filename ) {
	if (this.data('ajax-loader-pre-html-content') == null) {
		this.data('ajax-loader-pre-html-content', this.html()).html('<span class="small_graph_ajax_loader"><img src="'+js_global_live_site+'/images/'+(loader_image_filename != null ? loader_image_filename : 'ajax-loader-05.gif')+'" alt="..." /></span>');
	}
	return this;
};

jQuery.fn.stopAjaxLoader = function () {
	if (this.data('ajax-loader-pre-html-content') != null) {
		this.html(this.data('ajax-loader-pre-html-content')).removeData('ajax-loader-pre-html-content');
	}
	return this;
};

function js_add_class_to_last_module( block_element ) {
	if (typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled) {
		return false;
	}

  block_element = jQuery(block_element);

  if ( block_element.find('.mp:first').length == 0 ) {
    return;
  }

  block_element = block_element.find('.mp:first').parent();
  block_element.children('.mp,.mp_placeholder,.mp_placeholder_1x').removeClass('mp_side_last');

  // aktualna sirka bloku v x
  var block_width_x = 5;

  if ( block_element.parents('#middle:first').length != 0 )
    block_width_x = parseInt( /middle_([0-9]+)x/.exec( jQuery('#middle').attr('class') )[1] );

  var placeholder_element = block_element.children('.mp_placeholder,.mp_placeholder_1x');
  var mp_last_element = block_element.children('.mp:last');

  if ( mp_last_element.hasClass('ui-sortable-helper') )
    mp_last_element = mp_last_element.prev('.mp');

  var last_found = false;

  if ( placeholder_element.length != 0 && (placeholder_element.index() > mp_last_element.index() || mp_last_element.length == 0) ) {

    placeholder_element.addClass('mp_side_last');
    last_found = true;
  }

  if ( !last_found && mp_last_element.length != 0 )
    mp_last_element.addClass('mp_side_last');

  //var module_count = block_element.children('.mp').length;

  // pridaj class aj pre kazdy posledny modul v riadku (ak je zobrazenych viac riadkov)

  var modules_width = 0;

  // sirku modulov v bloku si musime vypocitat
  block_element.children('.mp').each( function() {
	  var parsedWidth =  /mp_w([1-9]+)(\s|$)/.exec( jQuery(this).attr('class') );

	  if (parsedWidth !== null) {
		  modules_width += parseInt(parsedWidth[1]);
	  }
  });

  // moduly su na viac riadkov
  if ( modules_width > block_width_x ) {

    var module_last_class_set = false;
    var prev_module_element = null;
    var modules_row_width = 0;  // sucet sirky modulov (v x) pre kazdy riadok bloku
    var module_width = 0;  // v x

    block_element.children('.mp').each( function() {
    	if ( !jQuery(this).hasClass('mp') && !jQuery(this).hasClass('mp_placeholder') && !jQuery(this).hasClass('mp_placeholder_1x') )
    		return;
    	if ( jQuery(this).hasClass('ui-sortable-helper') )
    		return;

//     	module_width = Math.floor( (jQuery(this).width()+30)/180 );
		module_width = parseInt(/mp_w([0-9]+)/.exec( jQuery(this).attr('class') )[1] || 0);
    	modules_row_width += module_width;

		// sirky modulov v riadku nevychadzaju presne na jeho sirku
		if ( modules_row_width > block_width_x && prev_module_element != null ) {
			prev_module_element.addClass('mp_side_last');
			modules_row_width = module_width;
		}

		// posledny modul v bloku uz ma nastavenu class
		if ( jQuery(this).hasClass('mp_side_last') )
			return;

		// sirky modulov v riadku vychadzaju presne na jeho sirku
		if ( modules_row_width == block_width_x ) {
			jQuery(this).addClass('mp_side_last');
			modules_row_width = 0;
		}

		prev_module_element = jQuery(this);
    });
  }
}

// pre moduly v bloku left a right
function js_add_class_to_left_right_modules( block_element, class_prefix ) {
  block_element = jQuery(block_element);

  block_element.children('.mp').each( function(index) {

    jQuery(this).removeClass('mp_l0').removeClass('mp_l1');
    jQuery(this).removeClass('mp_r0').removeClass('mp_r1');

    if ( (index % 2) == 0 )
      jQuery(this).addClass(class_prefix+'0');
    else
      jQuery(this).addClass(class_prefix+'1');
  });
}

if ( typeof(js_reload_current_page) != 'function' ) {
	function js_reload_current_page() {
		document.location.href = (document.location.href).replace(/#[^#]*$/i,'');
	}
}

function js_prettyphoto_close() {
  jQuery.prettyPhoto.close();
  jQuery(document).off('keyup');
  return false;
}

function js_print_page(elem) {
	window.print();
	return false;
}
//------------------------------------
function js_prettyPhoto_tos_init() {
	jQuery('body').on('click', 'a.prettyPhoto_tos, a.prettyPhoto_tos_custom', function(event) {
		event.preventDefault();

		if (typeof js_custom_func_tos_nonsef_url !== 'function') {
			tos_nonsef_url = js_global_live_site +'/index2.php?option=com_content&task=blogcategory&id=98&Itemid=1419&no_html=1';
		} else {
			tos_nonsef_url = js_custom_func_tos_nonsef_url();
		}

		if (typeof js_CS_Config_gdpr_agree_info_custom_part_lang !== 'undefined' && typeof js_CS_Config_gdpr_agree_info_custom_part_lang.url !== 'undefined') {
			if (jQuery(event.target).hasClass('prettyPhoto_tos_custom')) {
				tos_nonsef_url = js_global_live_site + js_CS_Config_gdpr_agree_info_custom_part_lang.url;
			}
		}

		jQuery.get(tos_nonsef_url, function (res) {
			jQuery(event.target).parent().stopAjaxLoader();

			var resElem = jQuery('<div />').html(res);
			var titleElem = resElem.find('.contentheading :header:first');
			var vexData = {
				afterOpen: function(vexContent) {
					vexContent
						.find('.vex-close').css('right', '20px')
						.end()
						.closest('.vex').addClass('vex-tos');
				}
			};
			if(typeof js_Config_blog !== 'undefined' && js_Config_blog) {
				var titleHeading = resElem.find('.title').text();
				var inputHtml = jQuery(resElem);
				inputHtml.find('.article_preview').removeClass('article_preview_default_blog_system');
				inputHtml.find('.text_wrap .title').remove();
				inputHtml.find('.img_wrap').remove();
				vexData.title = titleHeading;
				vexData.input = inputHtml.html();
			} else if (titleElem.length) {
				vexData.title = titleElem.text();
				vexData.input = jQuery('<div />').append(jQuery('.contentheading', res).remove().end()).html();

			} else {
				vexData.input = resElem.html();
			}

			js_function_vex_open(vexData);
		});
	});

	return false;
}

function js_prettyphoto_newsletter() {
	// prettyPhoto_newsletter
	if(typeof js_Config_checkout_newsletter_inverse_checkbox !== 'undefined' && js_Config_checkout_newsletter_inverse_checkbox) {
		var newsletter_tooltip = js_newsletter_tooltip_inverse;
	} else {
		var newsletter_tooltip = js_newsletter_tooltip;
	}
	jQuery('body').on("mouseenter", ".prettyPhoto_newsletter", function () {
		if (!jQuery(this).hasClass("tooltipstered")) {
			jQuery(this).tooltipster({
				theme: "tooltipster-gdpr prettypPhoto_newsletter",
				contentAsHTML: true,
				trackTooltip: true,
				trackOrigin: true,
				content: newsletter_tooltip,
				trigger: "hover",
				selfDestruction: true
			}).tooltipster('open');
		}
	}).on("mouseenter", "#club_card_val_div #club_card_field", function () {
		if (!jQuery(this).hasClass("tooltipstered")) {
			jQuery(this).tooltipster({
				theme: "tooltipster-gdpr",
				contentAsHTML: true,
				trackTooltip: true,
				trackOrigin: true,
				content: js_lang_shuch_club_card_text,
				trigger: "hover",
				selfDestruction: true
			}).tooltipster('open');
		}
	});

}

function js_prettyphoto_gdpr_init() {

	jQuery('body').on("mouseenter", "a.prettyPhoto_gdpr", function () {
		if (!jQuery(this).hasClass("tooltipstered")) {
			var text = js_gdpr_tooltip;
			if( jQuery(this).hasClass("custom_text_reg") ) {
				text = js_gdpr_tooltip_reg;
			}
			if( !jQuery(this).hasClass("no_hover") ) {
				jQuery(this).tooltipster({
					theme: "tooltipster-gdpr",
					contentAsHTML: true,
					trackTooltip: true,
					trackOrigin: true,
					content: text,
					trigger: "hover",
					selfDestruction: true
				}).tooltipster('open');
			}

		}
	}).off("click", "a.prettyPhoto_gdpr").on('click', 'a.prettyPhoto_gdpr', function(event) {
		event.preventDefault();

		tos_nonsef_url = js_global_live_site +'/index2.php?option=com_content&task=blogcategory&id=4&Itemid=4&no_html=1';
		if( jQuery(this).hasClass("custom_text_reg") ) {
			tos_nonsef_url = js_global_live_site +'/index2.php?option=com_content&task=blogcategory&id=214&Itemid=1684&no_html=1';
		}
		if( jQuery(this).hasClass("custom_text_notify") ) {
			tos_nonsef_url += js_global_live_site +'/index2.php?option=com_content&task=blogcategory&id=215&Itemid=1685&no_html=1';
		}

		jQuery.get(tos_nonsef_url, function (res) {
			jQuery(event.target).parent().stopAjaxLoader();

			var resElem = jQuery('<div />').html(res);
			var titleElem = resElem.find('.contentheading :header:first');
			var vexData = {
				afterOpen: function(vexContent) {
					vexContent
						.find('.vex-close').css('right', '20px')
						.end()
						.closest('.vex').addClass('vex-tos');
				}
			};

			if(typeof js_Config_blog !== 'undefined' && js_Config_blog) {
				var titleHeading = resElem.find('.title').text();
				var inputHtml = jQuery(resElem);
				inputHtml.find('.article_preview').removeClass('article_preview_default_blog_system');
				inputHtml.find('.text_wrap .title').remove();
				inputHtml.find('.img_wrap').remove();
				vexData.title = titleHeading;
				vexData.input = inputHtml.html();
			} else if (titleElem.length) {
				vexData.title = titleElem.text();
				vexData.input = jQuery('<div />').append(jQuery('.contentheading', res).remove().end()).html();
			} else {
				vexData.input = resElem.html();
			}

			js_function_vex_open(vexData);
		});
	});

	return false;
}

function js_carousel_bind_rotate(params) {
	var carousel = params.carousel;
	var js_carousel_default_items_count = params.default_items_count;

	setTimeout(function () {
		jQuery(carousel.list).find('li:empty').each(function () {
			var jcarouselindex = jQuery(this).attr('jcarouselindex');

			if (jcarouselindex > 0) {	// next all
				jQuery(this).html( jQuery(carousel.list).find('li[jcarouselindex='+(jcarouselindex-js_carousel_default_items_count)+']').html());
			} else if (jcarouselindex < 0) {	// prev all
				var new_jcarouselindex = Math.abs(jcarouselindex)  ;
				while (Math.floor(new_jcarouselindex/js_carousel_default_items_count) > 0) {
					new_jcarouselindex = new_jcarouselindex - js_carousel_default_items_count;
				}
				jQuery(this).html( jQuery(carousel.list).find('li[jcarouselindex='+(js_carousel_default_items_count-new_jcarouselindex)+']').html());
			} else
				jQuery(this).html( jQuery(carousel.list).find('li[jcarouselindex='+js_carousel_default_items_count+']').html());
		});

		if (typeof(params.li_add_class) != 'undefined') {
			jQuery(carousel.list).children('li').addClass(params.li_add_class);
		}
	}, 100);

	return false;
}

function js_login_register_module_set(mod_class) {

	if (typeof(js_global_user_info) == "undefined" || js_global_user_info.name == "" || jQuery('body.admin_content').length)
		return;

	var module_class = typeof(mod_class) != 'undefined' ? mod_class : '.mp_id10714';

	// JAN user credit info
	var user_credits = (typeof js_global_user_info.ucri !== "undefined") ? '<span class="user_credits_info">&nbsp;('+js_global_user_info.ucri+' kreditov)</span>' : '';

	var href_lang = {
		'sk': '/sprava-uctu/',
		's2': '/sprava-uctu/',
		's3': '/sprava-uctu/',
		'cz': '/udrzba-uctu/',
		'c2': '/udrzba-uctu/',
		'en': '/account-details/',
		'de': '/account-details/',
		'at': '/account-details/',
		'pl': '/zarzadzanie-kontem/',
		'hu': '/szamlazas-reszletek/',
		'si': '/nastavitve-racuna/',
		'ro': '/drept-de-sine/',
		'ru': '/upravlenyie-utsheta/',
		'hr': '/uredivanje-racuna/'
	};

	var final_lang_manage_account = (typeof js_lang_manage_account !== "undefined") ? js_lang_manage_account : 'Správa Účtu';
    var final_href = (typeof href_lang[js_get_lang] !== "undefined") ? href_lang[js_get_lang] : '/sprava-uctu/';
    var final_lang_logout = (typeof js_lang_account_logout !== "undefined") ? js_lang_account_logout : 'Odhlásiť';

	jQuery(module_class+' .registration').attr('href', final_href).html('<span>' + final_lang_manage_account + '</span>' + user_credits);
	jQuery(module_class+' .login').addClass('no_content_design_link').attr('href', '/index.php?option=logout').html('<span>' + final_lang_logout + '</span>');
}

// type: 0 = native, 1 = shop.browse, 2 = product_snapshot
function showFullPriceInfo(myself, sku) {
	var type = 0;
	var target = null;
	if (jQuery(myself).parent().parent().hasClass('shop-category-product')) {
		target = jQuery(myself).parent().siblings(".full_price_info");
		type = 1;
	}
	else {
		target = jQuery(myself).siblings(".full_price_info");
		type = 2;
	}

	var check = (target.length == 0);

	if(check) {
		switch (type) {
			case 1:
				jQuery(myself).parent().parent().append('<div class="full_price_info"></div>');
				break;
			case 2:
				jQuery(myself).parent().append('<div class="full_price_info"></div>');
				break;
		}
		jQuery.post('/includes/system.cs_lib.ajax.php?ajax_call=1&use_sef=1&option=com_shop&ajax_func=get_full_price_info', {productSku: sku}, function (res) {
			var data = JSON.parse(res);

			var stringData = '';
			jQuery.each(data, function(key, value) {
				stringData += '<div class="full_price_info_price">' + key + ':<span class="full_price_info_value">' + value + '</span></div>';
			});
			jQuery(myself).parent().parent().find('.full_price_info').html(stringData);
		});
	}
}



// on ready
jQuery(function() {
	js_sudo_slider_ios_fix();
    js_sudo_slider_sudo_href_fix();

	var $nivoSlider = jQuery('.nivoSlider');

	jQuery(window).on("blur", function() {
		if($nivoSlider.length > 0) {
			$nivoSlider.each(function() {
				if(typeof(jQuery(this).data('nivoslider')) !== 'undefined' && document.hidden) {
					jQuery(this).data('nivoslider').stop();
				}
			});
		}
	}).on("focus", function() {
		if($nivoSlider.length > 0) {
			$nivoSlider.each(function() {
				if(typeof(jQuery(this).data('nivoslider')) !== 'undefined') {
					if ( typeof js_Config_in_viewport_optimalization !== 'undefined' && js_Config_in_viewport_optimalization && typeof isElementInView === 'function' ) {
						if ( isElementInView(jQuery(this)) ) {
							jQuery(this).data('nivoslider').start();
						}
					} else if ( jQuery(this).is(':in-viewport') ) {
						jQuery(this).data('nivoslider').start();
					}
				}
			});
		}
	}).on("scroll", function() {
		if($nivoSlider.length > 0) {
			$nivoSlider.each(function() {
				if(typeof(jQuery(this).data('nivoslider')) !== 'undefined') {
					if ( typeof js_Config_in_viewport_optimalization !== 'undefined' && js_Config_in_viewport_optimalization && typeof isElementInView === 'function' ) {
						if ( isElementInView(jQuery(this)) ) {
							jQuery(this).data('nivoslider').start();
						} else {
							jQuery(this).data('nivoslider').stop();
						}
					} else {
						if(jQuery(this).is(':in-viewport')) {
							jQuery(this).data('nivoslider').start();
						} else {
							jQuery(this).data('nivoslider').stop();
						}
					}
				}
			});
		}
	});

	jQuery('td.shop_addtocart_advanced_attribute_availability').on('click', function() {
		var newClass = jQuery(this).attr('class').split(' ')[1];
		jQuery('.shop_product_availability_value').attr('class', 'shop_product_availability_value ' + newClass);
	});

  js_login_register_module_set(); // nastavenie linkov pre modul prihlasenie

  // make active menu
  jQuery('.mainlevel-nav li a, .mainlevel-nav li ul li a, .mainlevel-nav li ul li ul li a').removeClass('cms_active_menu');

	jQuery('.mainlevel-nav li a, .mainlevel-nav li ul li a, .mainlevel-nav li ul li ul li a, .module_cont_custmenu li a').each(function () {
		if (typeof (js_global_live_site_sef) !== 'undefined' && js_global_live_site_sef === jQuery(this).attr('href')) {
				jQuery(this).addClass('cms_active_menu');
				if (jQuery(this).hasClass('mi_u')) {
					jQuery(this).addClass('active');
					jQuery(this).parent().addClass('active');
				}
		}
	});

	if (!(typeof (categ_add_to_cart_unsaleable_poshy_disabled) !== 'undefined' && categ_add_to_cart_unsaleable_poshy_disabled == '1') && typeof (cms_js_lang_cart_product_is_unsaleable_msg) !== 'undefined') {
		jQuery(document).on('mouseenter click', '.categ_add_to_cart_unsaleable', function (event) {
//          if (!jQuery(this).hasClass("tooltipstered")) {
			var $currentTarget = jQuery(event.currentTarget);
			var $elemWrap = $currentTarget.closest('tr');
			if ($elemWrap.find('input.product_quantity').val() > 0 || $currentTarget.hasClass('categ_add_to_cart_unsaleable')) {
				jQuery(this).tooltipster({
					theme          : "tooltipster-gdpr",
					contentAsHTML  : true,
					trackTooltip   : true,
					trackOrigin    : true,
					content        : cms_js_lang_cart_product_is_unsaleable_msg,
					selfDestruction: true
				}).tooltipster('open');
			}
//          }
		});
		jQuery(document).on('mouseout', '.categ_add_to_cart_unsaleable', function (event) {
			var $this = jQuery(this);
			if ($this.hasClass('tooltipstered')) {
				$this.tooltipster('hide');
			}
			jQuery(".tooltipstered").tooltipster('destroy');
		});
	}
	// product size table preview init
	if (typeof js_prod_size_table_dir !== 'undefined' && js_prod_size_table_dir != '' && jQuery('.shop_page_class_shop_product_details').length > 0) {
		jQuery(document).on('click', '.size-table-img', function (event) {
			event.preventDefault();
			var img = new Image();
			img.src = this.href;
			js_function_vex_open({
				input: img.outerHTML,
				className: 'vex-cs vex-size-table-img',
			});
		});
	}

	/**
	 * Scroll to size table || open size table in vex
	 */
	if (typeof js_Config_product_size_table !== 'undefined' && js_Config_product_size_table && jQuery('.size-table-link-button').length > 0) {
		jQuery('.size-table-link-button').on('click', function () {
			if (typeof js_Config_product_size_table_in_vex !== 'undefined' && js_Config_product_size_table_in_vex) {

				var requestData = {
					productId: jQuery('.flypage-cart input[name="product_id"]').val()
				};

				if (typeof requestData.productId === 'undefined') {
					return;
				}

				new AjaxRequest(requestData)
					.setController('Product')
					.setAction('getProductSizeTableHtml')
					.onSuccess(function (response) {
						vex.open({
							content: response.data.html,
							className: 'vex-cs html_size_table'
						});
					})
					.onError(function (response) {
						//console.log(response);
					})
					.send();
			} else {
				var sizeTableTopOffset = jQuery('.size_chart_html_table').offset().top;

				if (jQuery('body').hasClass('fixed_header') || jQuery('body').hasClass('g_fixed_header') || is_responsive()) {
					sizeTableTopOffset -= parseFloat(jQuery('#header_container').css('height'));
				}

				jQuery('html,body').animate({
					scrollTop: sizeTableTopOffset
				}, 300);
			}
		});
	}

	// hover nad pexf name filter
  jQuery('.pexf_container')
	.on("mouseenter", function () {
		jQuery(this).find('.pexf_name:first').addClass('hover');
	})
	.on("mouseleave", function () {
		jQuery(this).find('.pexf_name:first').removeClass('hover');
	});

	// compare page - compare table multivalue height init
	jQuery('.product-compare-table .sub_group-params .param-line').each(function () {
		jQuery(this).find('.param-value').height(jQuery(this).outerHeight());
	});

	js_prettyphoto_gdpr_init();
	js_prettyphoto_newsletter();
});

if (typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled) {
	window.addEventListener("load", function () {
		var unavailText;//
		if (jQuery('.flypage-image').length && jQuery('.unavailable_product .shop_page_class_shop_product_details').length) {
			if (jQuery('.oos2pu_product .shop_page_class_shop_product_details').length) {
				unavailText = jQuery('<span class="prod_unavailable_title">' + js_lang_phpshop_product_oos2pu + '</span>');
			} else {
				unavailText = jQuery('<span class="prod_unavailable_title">' + js_lang_phpshop_product_unavailable + '</span>');
			}
			jQuery('.flypage-image').append(unavailText);
		}
	});
} else {
	jQuery(function () {
		// produkt trvalo nedostupny
		var unavailText;
		if (jQuery('.unavailable_product .shop_page_class_shop_product_details').length) {
			if (jQuery('.oos2pu_product .shop_page_class_shop_product_details').length) {
				unavailText = jQuery('<span class="prod_unavailable_title">' + js_lang_phpshop_product_oos2pu + '</span>');
			} else {
				unavailText = jQuery('<span class="prod_unavailable_title">' + js_lang_phpshop_product_unavailable + '</span>');
			}
			jQuery('.flypage-image').append(unavailText);
		}
	});
}

// overovanie tel čísla vo formulari
function formTelVerify() {
	var phone = jQuery('#phone_1_field');
	var phonelabel = jQuery('#phone_1_div');

	if ( phone.closest('#materialDesignRegistration').length ) {
		return;
	}

	if(phone.length > 0 ){
// 		formTelVerifyColorSetter(phone, phonelabel);

		if( typeof js_CS_Config_change_input_to_button !== 'undefined' && js_CS_Config_change_input_to_button ) {
			phone.on('keyup', function() {
				formTelVerifyColorSetter(phone, phonelabel);
			})
			.on('blur', function() {
				formTelVerifyColorSetter(phone, phonelabel);
			})
			.parents('form:first').find('button.button').on('click', function() {
				formTelVerifyMessageSetter(phone, formTelVerifyColorSetter(phone, phonelabel), true);
			});
		} else {
			phone.on('keyup', function() {
				formTelVerifyColorSetter(phone, phonelabel);
			})
			.on('blur', function() {
				formTelVerifyColorSetter(phone, phonelabel);
			})
			.parents('form:first').find('input.button').on('click', function() {
				formTelVerifyMessageSetter(phone, formTelVerifyColorSetter(phone, phonelabel), true);
			});
		}

	}
}

function formTelVerifyMessageSetter (phone, errorCode, showAlert) {
	if (typeof showAlert === 'undefined') {
		showAlert = false;
	}

	if (typeof js_get_lang === 'undefined') {
		js_get_lang = 'sk';
	}

	if ( is_cs_user('new_phone_validation') && typeof js_CS_Config_new_phone_validation !== 'undefined' && js_CS_Config_new_phone_validation ) {
		var js_phone_max_length = {
			'sk': 'Minimálne 6 číslic.',
			's2': 'Minimálne 6 číslic.',
			's3': 'Minimálne 6 číslic.',
			'cz': 'Minimálně 6 číslic.',
			'en': 'min 6 digits.',
			'de': 'mindestens 6 Stellen.',
			'hu': 'minimum 6 számjegy.',
			'pl': 'minimum 6 cyfr.',
			'ro': 'minimă de 6 cifre.',
			'ru': 'минимум 6 цифр.'
		};
	} else {
		var js_phone_max_length = {
			'sk': 'Minimálne 9 znakov.',
			's2': 'Minimálne 9 znakov.',
			's3': 'Minimálne 9 znakov.',
			'cz': 'minimálně 9 znaků.',
			'en': 'min 9 characters.',
			'de': 'mindestens 9 Zeichen.',
			'hu': 'minimum 9 karakter.',
			'pl': 'minimum 9 znaków.',
			'ro': 'minimă de 9 caractere.',
			'ru': 'минимум 9 символов.'
		};
	}

	var js_phone_correct = {
		'sk': 'Prosím vylpňte správne tel. kontakt.',
		's2': 'Prosím vylpňte správne tel. kontakt.',
		's3': 'Prosím vylpňte správne tel. kontakt.',
		'cz': 'Prosím vylpňte správne tel. kontakt.',
		'en': 'Please insert a phone number in correct form.',
		'de': 'Bitte füllen Sie das richtige Telefon. Kontakt.',
		'pl': 'Proszę wypełnić w odpowiedniej telefonu kontakt.',
		'hu': 'Kérjük, töltse ki a megfelelő telefont érintkezés.',
		'ru': 'Пожалуйста, заполните корректно телефону контакт.',
		'ro': 'Vă rugăm să completați în telefon corect contact.'
	};

	var msg = (typeof js_lang_phone_correct_msg !== 'undefined' ? js_lang_phone_correct_msg : (typeof js_phone_correct[js_get_lang] !== 'undefined' ? js_phone_correct[js_get_lang] : 'Please insert a phone number in correct form.'));

	var errorMessage = '';
	var errspan = jQuery('<span class="tel_error" style="color:#FF0000;font-size:11px;"></span>');

	switch (errorCode) {
		case 1:
			errorMessage = (typeof js_phone_max_length[js_get_lang] !== 'undefined' ? js_phone_max_length[js_get_lang] : js_phone_max_length.en);
			break;
		case 2:
			errorMessage = msg;
			break;
		case 3:
			errorMessage = (typeof js_phone_max_length[js_get_lang] !== 'undefined' ? js_phone_max_length[js_get_lang] : js_phone_max_length.en) + "\n" + msg;
			break;
		default:
			errorMessage = '';
			break;
	}

	if (showAlert && errorMessage.length) {
		//alert(errorMessage);
	} else {
		errspan.text(errorMessage).insertAfter(phone);
	}
}

function formTelVerifyColorSetter (phone, phonelabel) {
	var phoneval = jQuery.trim(phone.val());
	// phone_validation
	if ( is_cs_user('new_phone_validation') && typeof js_CS_Config_new_phone_validation !== 'undefined' && js_CS_Config_new_phone_validation ) {
		var errorCode = 0;

		if (!is_correct_length_phone_number(phoneval)) {
			errorCode += 1;
		}

		if (!is_valid_phone_number(phoneval)) {
			errorCode += 2;
		}
	} else {
		var badChar  = phoneval.match(/[^0-9+\-–\/ ]/) != null;
		var errorCode = 0;
		errorCode += (phoneval.length < 9) ? 1 : 0;
		errorCode += (badChar) ? 2 : 0;
	}

	jQuery('span.tel_error').remove();
	if (!errorCode)
		phonelabel.css('color', '#000');
	else {
		phonelabel.css('color', '#f00');
		formTelVerifyMessageSetter (phone, errorCode);
	}
	return errorCode;
}

function formTinVerify() {
	var tinField = jQuery('#company_tin_id_field');
	var tinLabel = jQuery('#company_tin_id_div');

	var tinLength = {
		'sk': 12,
		'cz': 12,
		'hu': 10
	};

	if ( js_get_lang === 'undefined' ) {
		js_get_lang = 'sk';
	}

	if ( tinField.length > 0 ) {

		if ( tinLength[js_get_lang] !== 'undefined' ) {
			tinField.prop('maxlength', tinLength[js_get_lang]);
		}

		tinField.on('keyup', function() {
			formTinVerifyColorSetter(tinField, tinLabel);
		});

		tinField.on('blur', function() {
			formTinVerifyColorSetter(tinField, tinLabel);
		})
			.parents('form:first').find('input.button').on('click', function() {
			formTelVerifyMessageSetter(tinField, formTinVerifyColorSetter(tinField, tinLabel), true);
		});
	}
}

function formVatVerify( vatField ) {
	if ( !is_cs_user('rxi215') ) {
		return false;
	}

	if ( typeof js_get_lang === 'undefined' ) {
		js_get_lang = 'sk';
	}

	var vatRegex = {
		'SVK': '^[0-9]{9,10}$',
		'CZE': '^[0-9]{9}$|^CZ[0-9]{8}$',
		'HUN': '^[0-9]{10,11}$',
		'BEL': '^[0-9]{11}$|^0[0-9]{9}$',
		'BGR': '^[0-9]{10}$|^[0-9]{9}$|^307[0-9]{7}$|^[0-9]{13}$',
		'CY': '^[09]{1}[0-9]{7}[A-Z]{1}$|^[13459]{1}[0-9]{7}[A-Z]{1}$',
		'HRV': '^[0-9]{11}$|^[0-9]{11}$',
		'DNK': '^[0-9]{10}$|^DK[0-9]{8}$',
		'EST': '^[0-9]{11}$|^[0-9]{8}$',
		'FRA': '^[0123]{1}[0-9]{12}$|^[0-9]{9}$',
		'FIN': '^[0-9]{6}[A+-]{1}[0-9]{3}[A-Z0-9]{1}$|^[0-9]{7}-[0-9]{1}$',
		'HOL': '^[0-9]{9}$',
		'LIT': '^[0-9]{11}$|^[0-9]{9}$',
		'LVA': '^[0-9]{11}$|^[0-9]{11}$',
		'LUX': '^[0-9]{13}$|^[0-9]{11}$',
		'DEU': '^[0-9]{11}$',
		'POR': '^[0-9]{9}$',
		'PLN': '^[0-9]{10,11}$',
		'AUT': '^[0-9]{9}$',
		'ROM': '^[0-9]{13}$|^[0-9]{2,10}$',
		'SVN': '^[0-9]{8}$',
		'ITA': '^[A-Z]{6}[0-9]{2}[A-Z]{1}[0-9]{2}[A-Z]{1}[0-9]{3}[A-Z]{1}$|^[0-9]{11}$',
		'ESP': '^[LKMXYZ0-9]{1}[0-9]{7}[A-Z]{1}$|^[ABCDEFGHJNPQRSUVW]{1}[0-9]{7}[A-Z0-9]{1}$',
		'SWE': '^[0-9]{10}$',
		'MT': '^[0-9]{7}[MGAPLHBZ]{1}$|^[0-9]{9}$|^[0-9]{9}$',
		'EL': '^[0-9]{9}$',
		'IE': '^[0-9]{7}[A-z]{1,2}$|^[0-9]{7}[A-Z]{1,2}$',
	};

	var vatCountryCode = '';
	if ( jQuery('#country').length > 0 ) {
		vatCountryCode = jQuery('#country').val();
	} else {
		vatCountryCode = jQuery('#country_field').val();
	}

	var vatCheck = false;
	if ( vatCountryCode != '' ) {
		vatCheck = RegExp(vatRegex[vatCountryCode]).test(jQuery.trim(vatField.val()));
	} else {
		vatCheck = RegExp(vatRegex.SVK).test(jQuery.trim(vatField.val()));
	}
	return vatCheck;
}

function formTinVerifyColorSetter (tinField, tinLabel) {
	// tin_validation
	if ( typeof js_get_lang === 'undefined' ) {
		js_get_lang = 'sk';
	}

	// TODO: use getTinCountryCode() instead of countryCodes
	var countryCodes = {
		'SVK': 'SK',
		'CZE': 'CZ',
		'HUN': 'HU',
		'BEL': 'BE',
		'BGR': 'BG',
		'CY': 'CY',
		'HRV': 'HR',
		'DNK': 'DK',
		'EST': 'EE',
		'FRA': 'FR',
		'FIN': 'FI',
		'HOL': 'NL',
		'LIT': 'LT',
		'LVA': 'LV',
		'LUX': 'LU',
		'DEU': 'DE',
		'POR': 'PT',
		'PLN': 'PL',
		'AUT': 'AT',
		'ROM': 'RO',
		'SVN': 'SI',
		'ITA': 'IT',
		'ESP': 'ES',
		'SWE': 'SE',
		'MT': 'MT',
		'EL': 'EL',
		'IE': 'IE',
	};

	var tinLength = {
		'SK': 12,
		'CZ': 12,
		'HU': 10,
		'BE': 12,
		'BG': 12,
		'CY': 11,
		'HR': 13,
		'DK': 13,
		'EE': 11,
		'FR': 14,
		'FI': 10,
		'NL': 14,
		'LT': 14,
		'LV': 13,
		'LU': 10,
		'DE': 11,
		'PT': 11,
		'PL': 12,
		'AT': 11,
		'RO': 12,
		'SI': 10,
		'IT': 13,
		'ES': 11,
		'SE': 14,
		'MT': 10,
		'EL': 11,
		'IE': 11,
	};

	var tinCountryCode = '';
	var selectedCountryCode = '';
	if ( tinField.val().length >= 2 ) {
		selectedCountryCode = tinField.val().substring(0,2);
		if ( Object.values(countryCodes).indexOf(selectedCountryCode) > -1 ) {
			tinCountryCode = selectedCountryCode;
		} else {
			if ( jQuery('#country').length > 0 ) {
				tinCountryCode = countryCodes[jQuery('#country').val()];
			} else {
				tinCountryCode = countryCodes[jQuery('#country_field').val()];
			}
		}
	} else {
		if ( jQuery('#country').length > 0 ) {
			tinCountryCode = countryCodes[jQuery('#country').val()];
		} else {
			tinCountryCode = countryCodes[jQuery('#country_field').val()];
		}
	}

	if ( tinLength[tinCountryCode] !== 'undefined' && tinField.prop('maxlength') != tinLength[tinCountryCode] ) {
		tinField.prop('maxlength', tinLength[tinCountryCode]);
	}

	if (tinField.val().length > tinField.prop('maxlength')) {
		tinField.val(tinField.val().substring(0, tinField.prop('maxlength')));
	}

	var badChar = true;
	if (tinCountryCode != '' ) {
		badChar = !validTin(tinField.val(), tinCountryCode);
	}

	jQuery('span.tin_error').remove();
	if (!badChar) {
		if ( !tinField.parent().hasClass('field') ) {
			tinLabel.css('color', '#545454');
		}
	} else {
		if ( !tinField.parent().hasClass('field') ) {
			tinLabel.css('color', '#f60');
		}
		formTinVerifyMessageSetter (tinField, badChar, tinCountryCode);
	}
	return badChar;
}

function validTin(tinValue, country) {
	country = typeof country === 'undefined' ? 'SK' : getTinCountryCode(country);

	var tinRegex = {
		'SK': '^SK[0-9]{10}$',
		'CZ': '^CZ[0-9]{8,10}$',
		'HU': '^HU[0-9]{8}$',
		'BE': '^BE[01]{1}[0-9]{9}$',
		'BG': '^BG[0-9]{9,10}$',
		'CY': '^CY[0-9]{8}[A-Z]{1}$',
		'HR': '^HR[0-9]{11}$',
		'DK': '^DK\\d{2} \\d{2} \\d{2} \\d{2}$',
		'EE': '^EE[0-9]{9}$',
		'FR': '^FR[A-Z0-9]{2} [0-9]{9}$',
		'FI': '^FI[0-9]{8}$',
		'NL': '^NL[A-Z0-9+*]{12}$',
		'LT': '^LT[0-9]{9}$|^LT[0-9]{12}$',
		'LV': '^LV[0-9]{11}$',
		'LU': '^LU[0-9]{8}$',
		'DE': '^DE[0-9]{9}$',
		'PT': '^PT[0-9]{9}$',
		'PL': '^PL[0-9]{10}$',
		'AT': '^ATU[0-9]{8}$',
		'RO': '^RO[0-9]{2,10}$',
		'SI': '^SI[0-9]{8}$',
		'IT': '^IT[0-9]{11}$',
		'ES': '^ES[A-Z]{1}\\d{7}[A-Z]{1}$|^ES[A-Z0-9]{1}\\d{7}[A-Z]{1}$|^ES[A-Z]{1}\\d{7}[A-Z0-9]{1}$',
		'SE': '^SE[0-9]{12}$',
		'MT': '^MT[0-9]{8}$',
		'EL': '^EL[0-9]{9}$',
		'IE': '^IE[0-9]{1}[A-Z0-9+*]{1}[0-9]{5}[A-Z]{1}$|^IE[0-9]{7}WI$',
	};

	return RegExp(tinRegex[country]).test(jQuery.trim(tinValue));
}

function getTinCountryCode(country) {
	if (country.length == 2) {
		return country;
	}

	var countryCodes = {
		'SVK': 'SK',
		'CZE': 'CZ',
		'HUN': 'HU',
		'BEL': 'BE',
		'BGR': 'BG',
		'CY': 'CY',
		'HRV': 'HR',
		'DNK': 'DK',
		'EST': 'EE',
		'FRA': 'FR',
		'FIN': 'FI',
		'HOL': 'NL',
		'LIT': 'LT',
		'LVA': 'LV',
		'LUX': 'LU',
		'DEU': 'DE',
		'POR': 'PT',
		'PLN': 'PL',
		'AUT': 'AT',
		'ROM': 'RO',
		'SVN': 'SI',
		'ITA': 'IT',
		'ESP': 'ES',
		'SWE': 'SE',
		'MLT': 'MT',
		'GRC': 'EL',
		'IRL': 'IE',
	};

	return countryCodes[country];
}

function formTinVerifyMessageGetHint ( countryCode ) {
	// TODO: use getTinCountryCode() instead of countryCodes
	var countryCodes = {
		'SVK': 'SK',
		'CZE': 'CZ',
		'HUN': 'HU',
		'BEL': 'BE',
		'BGR': 'BG',
		'CY': 'CY',
		'HRV': 'HR',
		'DNK': 'DK',
		'EST': 'EE',
		'FRA': 'FR',
		'FIN': 'FI',
		'HOL': 'NL',
		'LIT': 'LT',
		'LVA': 'LV',
		'LUX': 'LU',
		'DEU': 'DE',
		'POR': 'PT',
		'PLN': 'PL',
		'AUT': 'AT',
		'ROM': 'RO',
		'SVN': 'SI',
		'ITA': 'IT',
		'ESP': 'ES',
		'SWE': 'SE',
		'MT': 'MT',
		'EL': 'EL',
		'IE': 'IE',
	};

	var tinAllowedFormat = {
		'SK': 'SK1234567890',
		'CZ': 'CZ1234567890',
		'HU': 'HU12345678',
		'BE': 'BE0999999999, BE1999999999',
		'BG': 'BG999999999, BG9999999999',
		'CY': 'CY99999999X',
		'HR': 'HR99999999999',
		'DK': 'DK99 99 99 99',
		'EE': 'EE999999999',
		'FR': 'FRXX 999999999',
		'FI': 'FI99999999',
		'NL': 'NLXXXXXXXXXXXX',
		'LT': 'LT999999999, LT999999999999',
		'LV': 'LV99999999999',
		'LU': 'LU99999999',
		'DE': 'DE999999999',
		'PT': 'PT999999999',
		'PL': 'PL9999999999',
		'AT': 'ATU99999999',
		'RO': 'RO999999999',
		'SI': 'SI99999999',
		'IT': 'IT99999999999',
		'ES': 'ESX9999999X',
		'SE': 'SE999999999999',
		'MT': 'MT99999999',
		'EL': 'EL999999999',
		'IE': 'IE9S99999L, IE9999999WI'
	};

	if ( countryCode in tinAllowedFormat ) {
		return tinAllowedFormat[countryCode];
	} else {
		if ( jQuery('#country').length > 0 ) {
			var selectedState = jQuery('#country').val();
		} else {
			var selectedState = jQuery('#country_field').val();
		}

		if ( selectedState !== 'undefined' && selectedState in countryCodes ) {
			return tinAllowedFormat[countryCodes[selectedState]];
		} else {
			return tinAllowedFormat.SK;
		}
	}
}

function formTinVerifyMessageSetter (tinField, errorCode, countryCode) {
	if ( typeof errorCode === 'undefined' ) {
		errorCode = false;
	}

	if ( countryCode === '' ) {
		countryCode = 'SK';
	}

	var errorMessage = '';
	var errorSpan = jQuery('<span class="tin_error" style="color:#f60;font-size:11px;"></span>');
	if ( errorCode && !tinField.parent().hasClass('field') ) {
		errorMessage = js_lang_one_step_checkout_company_tin_expected_format + ': ' + formTinVerifyMessageGetHint(countryCode);
		errorSpan.text(errorMessage).insertAfter(tinField);
	}
}

// jQuery(function() {
jQuery(function () {
	formTelVerify();
	js_modify_cart_item();

	if ( typeof js_Config_reqistration_company_tin_required !== 'undefined' && js_Config_reqistration_company_tin_required ) {
		formTinVerify();
	}

	// setnutioe do cookie ak som sa do flypage dostal cez shop_browse
    jQuery('#product_list').on('click', '.shop-category-product a', function(){
        Cookies.set('uWd1XhE4VhMPeRAa', 1, { path: '/', expires: 0.000057 } );
    });
});

function js_modify_cart_item(){

	if (typeof modify_cart_item == 'undefined' || jQuery.isEmptyObject(modify_cart_item)) return;

	jQuery('input[name="dim_a"]').val(modify_cart_item.dim_a);
	jQuery('input[name="dim_b"]').val(modify_cart_item.dim_b);
	jQuery('input[name="quantity"]').val(modify_cart_item.dim_qty);
	jQuery('input[name="modify_cart_item"]').val(modify_cart_item.cart_item);
	jQuery('.prod_dim_box').prepend('<div class="modify_cart">'+js_lang_dynamic_attributes_modify_item+'</div>');
}


function js_ajax_cart_open_disabled() {
	return (jQuery('#m1').hasClass('shop_page_class_shop_cart')
			|| jQuery('#checkout_one_step').length);
}

function switch_browse(elm, toggle) {
	var categoryId = jQuery(elm).data('category_id');
	var getUrl = "/administrator/components/com_shop/html/shop.browse.ajax.php?ajax_call=1&ajax_func=set_shop_browse_as_listing_toggle&category_id=" + categoryId;

	if (typeof toggle !== 'undefined') {
		getUrl += "&toggle=" + toggle;
	}

	jQuery.get(getUrl, function(res) {
		if(jQuery.trim(res) == '1') {
			location.reload();
		}
	});
}

function js_browse_count_control_btn_click (elem, action) {
	var input = jQuery(elem).parents('.quantity_wrapper:first').find('.shop-addtocart-quantity-inputbox');
	var value = parseInt(input.val());
	if (action == 'down' && value > 1) {
		input.val(value - 1);
	} else if (action == 'up') {
		input.val(value + 1);
	}
}

function flypage_img_click(mainImage){
	// ak ma shop easyzoom a novy fancybox
	if (typeof mainImage !== 'undefined' && mainImage) {
		var href = jQuery('.flypage-lightbox-image-a').attr('href');
		jQuery('[href="' + href + '"]:not(.flypage-lightbox-image-a)').trigger('click');
		return false;
	}

	var img_count = jQuery('.flypage-image a');
	if( img_count.length == 1 ){ // vacsinou TATO(situacia) v template je v .flypage-image jeden obrazok ( hlavny )
		jQuery('.flypage-image a').trigger('click');
		return false;
	}
	if( img_count.length > 1 ){ // niekedy v template .flypage-image je viacero obrazkov pri hlavnok a pri lightboxe potom pri kliku na obrazkok nenajde hlavy *alltoys.sk*
		jQuery('a.flypage-lightbox-image-a').trigger('click');
		return false;
	}
}

function product_3d_image_preview_init(url) {
	vex.open({
		content: '<iframe src="'+ url +'" id="product_3d_image_preview_iframe" width="800" height="800" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" frameborder="0"></iframe>',
		//showCloseButton: true,
		//overlayClosesOnClick: true,
		className: 'vex vex-cs app_vex_wrap vex_3d_preview_image',
	});
}

function dynamic_shipping_change_country(elem) {
	var jElem = jQuery(elem);

	if (jElem.hasClass('active')) return;


	var dataElem = jElem.closest('.choose_country_btn_wrap').find('.choose_country_btn');
	var selectedCountry = jElem.data('active_country');
	var countryDiv = jQuery('.flypage_dynamic_shipping_inner.' + selectedCountry);

	if (countryDiv.hasClass('selected')) return;

	if (!countryDiv.children().length > 0) {
		//jQuery(countrySelect).startAjaxLoader();

		var requestData = {
			productId: dataElem.data('id'),
			country: selectedCountry,
			price: dataElem.data('price'),
			weight: dataElem.data('weight')
		};

		if (typeof requestData.productId === 'undefined') {
			return;
		}

		new AjaxRequest(requestData)
			.setController('Product')
			.setAction('getProductDynamicShippingForCountry')
			.onSuccess(function (result) {
				//jQuery(countrySelect).stopAjaxLoader()
				jQuery('.choose_country_item').removeClass('active');
				jElem.addClass('active');
				jQuery('.choose_country_btn').html(jElem.html());


				jQuery('.flypage_dynamic_shipping_inner').removeClass('selected').hide();
				countryDiv.html(result.data);
				countryDiv.show().addClass('selected');
			})
			.onError(function (result) {
				//jQuery(countrySelect).stopAjaxLoader();
			})
			.send();
	} else {
		jQuery('.choose_country_item').removeClass('active');
		jElem.addClass('active');
		jQuery('.choose_country_btn').html(jElem.html());

		jQuery('.flypage_dynamic_shipping_inner').removeClass('selected').hide();
		countryDiv.show().addClass('selected');
	}
}

function dynamic_shipping_toggle_class(elem) {
	var jElem = jQuery(elem);
	jElem.closest('.flypage_dynamic_shipping').addClass('show_more_shippings');
}

function filterShippingChange(elem) {
	var $elem = jQuery(elem);
	var name = $elem.attr('name');
	var value = $elem.val();

	var parent = $elem.closest('.setting');

	//dotatocne odstranenie error classy
	jQuery('body').removeClass('voucher_delivery_error');

	parent.find('.setting_option').removeClass('option_active');
	$elem.closest('.setting_option').addClass('option_active');

	var params = {};
	params[name] = value;

	new AjaxRequest({params: params})
			.setController('Shipping')
			.setAction('setModuleFilterShipping')
			.onSuccess(function (result) {
				if( typeof result.data.refresh !== 'undefined' && result.data.refresh ) {
					// vycisti historiu (inak by duplikovalo requesty z kosika cartAdd, cartUpdate, cartDelete)
					if ( window.history.replaceState ) {
						window.history.replaceState( null, '', window.location.href );
					}

					window.location.reload();
				}
			})
			.onError(function (result) {
			})
			.send();
}

function changeGiftWrapShippingOption(product_id) {

	new AjaxRequest({product_id: product_id})
		.setController('Shipping')
		.setAction('changeGiftWrapShippingOption')
		.onSuccess(function (result) {
			if (result.success && result.data.changed) {
				jQuery('#bt_diff:first').trigger('change');
			}
		})
		.onError(function () {
		})
		.send();
}

function showAvailabilityDescription(elem) {
	var elem = jQuery(elem);
	var productAvailability = elem.data('availability');

	elem.tooltipster({
		content: productAvailability,
	});
}

//
jQuery(function() {
	if (typeof js_rotate_active_images === 'object' && typeof js_rotate_active_images_data === 'object') {
		js_rotate_active_images.init(js_rotate_active_images_data);

		if (typeof sphf !== 'undefined') {
			var timeStarted = jQuery.now();
			var sphfWait = function() {
				var sphfOnBrowseRequestFn = sphf.options.onBrowseRequest;

				if (sphf.initialized) {
					sphf.options.onBrowseRequest = function() {
						if (typeof sphfOnBrowseRequestFn === 'function') {
							sphfOnBrowseRequestFn();
						}

						if (typeof js_rotate_active_images_data === 'object') {
							js_rotate_active_images.init(js_rotate_active_images_data);
						}
					};

				} else if (timeStarted + 30000 >= jQuery.now()) {
					setTimeout(function() {
						sphfWait();

					}, 100);
				}
			};

			sphfWait();
		}
	}

	if (typeof js_rotate_active_images_detail_data === 'object') {
		js_rotate_active_images_detail.init(js_rotate_active_images_detail_data);
	}

	var $sideContactForm = jQuery('#sideContactForm');
	if ($sideContactForm.length > 0) {
		var contactForm = $sideContactForm;

		contactForm.find('.sideButton').on({
			'click': function() {
				contactForm.toggleClass('open');
			},
			'mouseover': function() {
				contactForm.addClass('open');
			}
		});

		contactForm.on('mouseleave', function() {
			if(jQuery(this).find('input:focus, textarea:focus').length == 0) {
				contactForm.removeClass('open');
			}
		});

		jQuery(document).on('click', function (e) {
			var closeWindow = true;

			contactForm.find("input[type=text], textarea").each(function() {
				if(jQuery(this).val() != '') {
					closeWindow = false;
				}
			});

			if (!jQuery(e.target).closest(contactForm).length && closeWindow) {
				contactForm.removeClass('open');
			}
		});
	}

	var showAvailabilityDescription = typeof js_Config_product_availability_description !== 'undefined' && js_Config_product_availability_description;

	if (showAvailabilityDescription) {
		var availabilityElements = jQuery('span[class*="shop_product_availability_value"]');

		availabilityElements.each(function () {
			var $this = jQuery(this);
			var availabilityDescription = $this.data('description');

			if (availabilityDescription) {
				var isProductDetail = $this.closest('.flypage-top').length;
				var inModule = $this.closest('.module-navst').length;
				var isBrowse = $this.closest('.shop-category-product').length || inModule;
				var isBasket = $this.closest('.shop_page_class_shop_cart').length;
				var isNsuOrderDetail = $this.closest('.shop_page_class_account_index').length;
				var isHomePage = $this.closest('.is_frontpage').length;
				var canShowInProductDetail = typeof js_Config_product_availability_description !== 'undefined' ? js_Config_product_availability_description.productDetails : false;
				var canShowInBrowse = typeof js_Config_product_availability_description !== 'undefined' ? js_Config_product_availability_description.browse : false;
				var canShowInBasket = false;
				var canShowInNsuOrderDetail = typeof js_Config_show_product_future_availability !== 'undefined' ? js_Config_show_product_future_availability.nsuOrderDetail : false;

				var tooltipsterSettings = typeof availabilityDescriptionSettings !== 'undefined' && availabilityDescriptionSettings ? availabilityDescriptionSettings : null;

				if (isProductDetail && canShowInProductDetail) {
					var tooltipsterCustomSettings = tooltipsterSettings && availabilityDescriptionSettings.productDetail ? availabilityDescriptionSettings.productDetail : null;
					var tooltipsterSide = tooltipsterCustomSettings && tooltipsterCustomSettings.side ? tooltipsterCustomSettings.side : 'right';
					var tooltipsterMaxWidth = tooltipsterCustomSettings && tooltipsterCustomSettings.maxWidth ? tooltipsterCustomSettings.maxWidth : 250;

					$this.tooltipster({
						content: availabilityDescription,
						side: tooltipsterSide,
						maxWidth: tooltipsterMaxWidth,
					});
				}

				if (isBrowse && canShowInBrowse) {
					var tooltipsterCustomSettings = tooltipsterSettings && availabilityDescriptionSettings.browse ? availabilityDescriptionSettings.browse : null;
					var tooltipsterSide = tooltipsterCustomSettings && tooltipsterCustomSettings.side ? tooltipsterCustomSettings.side : 'top';
					var tooltipsterMaxWidth = tooltipsterCustomSettings && tooltipsterCustomSettings.maxWidth ? tooltipsterCustomSettings.maxWidth : 250;

					$this.tooltipster({
						content: availabilityDescription,
						side: tooltipsterSide,
						maxWidth: tooltipsterMaxWidth,
					});
				}

				if ( canShowInBasket && isBasket ) {
					var tooltipsterCustomSettings = tooltipsterSettings && availabilityDescriptionSettings.browse ? availabilityDescriptionSettings.browse : null;
					var tooltipsterSide = tooltipsterCustomSettings && tooltipsterCustomSettings.side ? tooltipsterCustomSettings.side : 'top';
					var tooltipsterMaxWidth = tooltipsterCustomSettings && tooltipsterCustomSettings.maxWidth ? tooltipsterCustomSettings.maxWidth : 250;

					$this.tooltipster({
						content: availabilityDescription,
						side: tooltipsterSide,
						maxWidth: tooltipsterMaxWidth,
					});
				}

				if ( canShowInNsuOrderDetail && isNsuOrderDetail ) {
					var tooltipsterCustomSettings = tooltipsterSettings && availabilityDescriptionSettings.browse ? availabilityDescriptionSettings.browse : null;
					var tooltipsterSide = tooltipsterCustomSettings && tooltipsterCustomSettings.side ? tooltipsterCustomSettings.side : 'top';
					var tooltipsterMaxWidth = tooltipsterCustomSettings && tooltipsterCustomSettings.maxWidth ? tooltipsterCustomSettings.maxWidth : 250;

					$this.tooltipster({
						content: availabilityDescription,
						side: tooltipsterSide,
						maxWidth: tooltipsterMaxWidth,
					});
				}
			}
		});
	}

	if (typeof phpdebugbar !== 'undefined') {
		jQuery(document).ajaxComplete(function(event, jqXHR) {
			phpdebugbar.ajaxHandler.handle(jqXHR);
		});
	}
});


/* ========================================
 FILE: /includes/js/jquery/prettyphoto/js/jquery.prettyPhoto.js
 ==================== */

/* ------------------------------------------------------------------------
 * Class: prettyPhoto
 * Use: Lightbox clone for jQuery
 * Author: Stephane Caron (http://www.no-margin-for-errors.com)
 * Version: 3.0.1
 * ------------------------------------------------------------------------- */

(function($){$.prettyPhoto={version:'3.0'};$.fn.prettyPhoto=function(pp_settings){pp_settings=jQuery.extend({animation_speed:'fast',pp_full_res_custom_class:'',slideshow:false,autoplay_slideshow:false,opacity:0.80,show_title:true,allow_resize:true,default_width:500,default_height:344,counter_separator_label:'/',theme:'facebook',hideflash:false,wmode:'opaque',autoplay:true,modal:false,overlay_gallery:true,keyboard_shortcuts:false,changepicturecallback:function(){},callback:function(){},markup:'<div class="pp_pic_holder"> \
      <div class="ppt">&nbsp;</div> \
      <div class="pp_top"> \
       <div class="pp_left"></div> \
       <div class="pp_middle"></div> \
       <div class="pp_right"></div> \
      </div> \
      <div class="pp_content_container"> \
       <div class="pp_left"> \
       <div class="pp_right"> \
        <div class="pp_content"> \
         <div class="pp_loaderIcon"></div> \
         <div class="pp_fade"> \
          <a href="#" class="pp_expand" title="Expand the image">Expand</a> \
          <div class="pp_hoverContainer"> \
           <a class="pp_next" href="#">next</a> \
           <a class="pp_previous" href="#">previous</a> \
          </div> \
          <div id="pp_full_res"></div> \
          <div class="pp_details clearfix"> \
           <p class="pp_description"></p> \
           <a class="pp_close" href="#">Close</a> \
           <div class="pp_nav"> \
            <a href="#" class="pp_arrow_previous">Previous</a> \
            <p class="currentTextHolder">0/0</p> \
            <a href="#" class="pp_arrow_next">Next</a> \
           </div> \
          </div> \
         </div> \
        </div> \
       </div> \
       </div> \
      </div> \
      <div class="pp_bottom"> \
       <div class="pp_left"></div> \
       <div class="pp_middle"></div> \
       <div class="pp_right"></div> \
      </div> \
     </div> \
     <div class="pp_overlay"></div>',gallery_markup:'<div class="pp_gallery"> \
        <a href="#" class="pp_arrow_previous">Previous</a> \
        <ul> \
         {gallery} \
        </ul> \
        <a href="#" class="pp_arrow_next">Next</a> \
       </div>',image_markup:'<img id="fullResImage" src="" />',flash_markup:'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',quicktime_markup:'<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',iframe_markup:'<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',youtube_markup: '<iframe type="text/html" width="{width}" height="{height}" src ="{path}" frameborder="0" allowfullscreen="allowfullscreen" allowscriptaccess="allowscriptaccess" wmode="opaque"></iframe>',inline_markup:'<div class="pp_inline clearfix">{content}</div>',custom_markup:''},pp_settings);var matchedObjects=this,percentBased=false,correctSizes,pp_open,pp_contentHeight,pp_contentWidth,pp_containerHeight,pp_containerWidth,windowHeight=$(window).height(),windowWidth=$(window).width(),pp_slideshow;doresize=true,scroll_pos=_get_scroll();$(window).unbind('resize').resize(function(){_center_overlay();_resize_overlay();});if(pp_settings.keyboard_shortcuts){$(document).unbind('keydown').keydown(function(e){if(typeof $pp_pic_holder!='undefined'){if($pp_pic_holder.is(':visible')){switch(e.keyCode){case 37:$.prettyPhoto.changePage('previous');break;case 39:$.prettyPhoto.changePage('next');break;case 27:if(!settings.modal)
$.prettyPhoto.close();break;};return false;};};});}
$.prettyPhoto.initialize=function(){settings=pp_settings;
  if ( typeof(settings.pp_full_res_custom_class) != 'undefined' && settings.pp_full_res_custom_class != '' )
    settings.markup = settings.markup.replace('<div id="pp_full_res"></div>', '<div id="pp_full_res" class="' + settings.pp_full_res_custom_class + '"></div>'); 
  if($.browser.msie&&parseInt($.browser.version)==6)settings.theme="light_square";_buildOverlay(this);if(settings.allow_resize)
$(window).scroll(function(){_center_overlay();});_center_overlay();set_position=jQuery.inArray($(this).attr('href'),pp_images);$.prettyPhoto.open();return false;};
$.prettyPhoto.open=function(event){if(typeof settings=="undefined"){settings=pp_settings;if($.browser.msie&&$.browser.version==6)settings.theme="light_square";_buildOverlay(event.target);pp_images=$.makeArray(arguments[0]);pp_titles=(arguments[1])?$.makeArray(arguments[1]):$.makeArray("");pp_descriptions=(arguments[2])?$.makeArray(arguments[2]):$.makeArray("");isSet=(pp_images.length>1)?true:false;set_position=0;}
if($.browser.msie&&$.browser.version==6)$('select').css('visibility','hidden');if(settings.hideflash)$('object,embed').css('visibility','hidden');_checkPosition($(pp_images).length);$('.pp_loaderIcon').show();if($ppt.is(':hidden'))$ppt.css('opacity',0).show();$pp_overlay.show().fadeTo(settings.animation_speed,settings.opacity);$pp_pic_holder.find('.currentTextHolder').text((set_position+1)+settings.counter_separator_label+$(pp_images).length);$pp_pic_holder.find('.pp_description').show().html(unescape(pp_descriptions[set_position]));(settings.show_title&&pp_titles[set_position]!=""&&typeof pp_titles[set_position]!="undefined")?$ppt.html(unescape(pp_titles[set_position])):$ppt.html('&nbsp;');

movie_width=(parseFloat(grab_param('width',pp_images[set_position])))?grab_param('width',pp_images[set_position]):settings.default_width.toString();
movie_height=(parseFloat(grab_param('height',pp_images[set_position])))?grab_param('height',pp_images[set_position]):settings.default_height.toString();
// movie_width = movie_height = '100%'; 
if(movie_width.indexOf('%')!=-1||movie_height.indexOf('%')!=-1){movie_height=parseFloat(($(window).height()*parseFloat(movie_height)/100)-150);movie_width=parseFloat(($(window).width()*parseFloat(movie_width)/100)-150);percentBased=true;}else{percentBased=false;}
$pp_pic_holder.fadeIn(function(){imgPreloader="";switch(_getFileType(pp_images[set_position])){case'image':imgPreloader=new Image();nextImage=new Image();if(isSet&&set_position>$(pp_images).length)nextImage.src=pp_images[set_position+1];prevImage=new Image();if(isSet&&pp_images[set_position-1])prevImage.src=pp_images[set_position-1];$pp_pic_holder.find('#pp_full_res')[0].innerHTML=settings.image_markup;$pp_pic_holder.find('#fullResImage').attr('src',pp_images[set_position]);imgPreloader.onload=function(){correctSizes=_fitToViewport(imgPreloader.width,imgPreloader.height);_showContent();};imgPreloader.onerror=function(){alert('Image cannot be loaded. Make sure the path is correct and image exist.');$.prettyPhoto.close();};imgPreloader.src=pp_images[set_position];break;case'youtube':if (grab_param('resize_to',pp_images[set_position])=='height')movie_width=Math.floor(movie_height*1.77)-38;correctSizes=_fitToViewport(movie_width,movie_height);movie='//www.youtube.com/embed/'+grab_param('v',pp_images[set_position])+'?';if(settings.autoplay)movie+="?autoplay=1";
			
// if(grab_param('hd',pp_images[set_position])) movie+="&hd="+grab_param('hd',pp_images[set_position]);
if(grab_param('hd',pp_images[set_position])) movie+="&vq=hd720";
if(grab_param('fs',pp_images[set_position])) movie+="&fs="+grab_param('fs',pp_images[set_position]);
if(grab_param('showinfo',pp_images[set_position])) movie+="&showinfo="+grab_param('showinfo',pp_images[set_position]);
if (typeof(console) != 'undefined') console.log('YT-movie', movie);

if(grab_param('t',pp_images[set_position])) movie+="&start="+grab_param('t',pp_images[set_position]);movie+="&showsearch=0&rel=0";toInject=settings.youtube_markup.replace(/{width}/g,correctSizes.width).replace(/{height}/g,correctSizes.height).replace(/{path}/g,movie);break;case'vimeo':correctSizes=_fitToViewport(movie_width,movie_height);movie_id=pp_images[set_position];var regExp=/http:\/\/(www\.)?vimeo.com\/(\d+)/;var match=movie_id.match(regExp);movie='http://player.vimeo.com/video/'+match[2]+'?title=0&amp;byline=0&amp;portrait=0';if(settings.autoplay)movie+="&autoplay=1;";vimeo_width=correctSizes.width+'/embed/?moog_width='+correctSizes.width;toInject=settings.iframe_markup.replace(/{width}/g,vimeo_width).replace(/{height}/g,correctSizes.height).replace(/{path}/g,movie);break;case'quicktime':correctSizes=_fitToViewport(movie_width,movie_height);correctSizes.height+=15;correctSizes.contentHeight+=15;correctSizes.containerHeight+=15;toInject=settings.quicktime_markup.replace(/{width}/g,correctSizes.width).replace(/{height}/g,correctSizes.height).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,pp_images[set_position]).replace(/{autoplay}/g,settings.autoplay);break;case'flash':correctSizes=_fitToViewport(movie_width,movie_height);flash_vars=pp_images[set_position];flash_vars=flash_vars.substring(pp_images[set_position].indexOf('flashvars')+10,pp_images[set_position].length);filename=pp_images[set_position];filename=filename.substring(0,filename.indexOf('?'));toInject=settings.flash_markup.replace(/{width}/g,correctSizes.width).replace(/{height}/g,correctSizes.height).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars);break;case'iframe':correctSizes=_fitToViewport(movie_width,movie_height);frame_url=pp_images[set_position];frame_url=frame_url.substr(0,frame_url.indexOf('iframe')-1);toInject=settings.iframe_markup.replace(/{width}/g,correctSizes.width).replace(/{height}/g,correctSizes.height).replace(/{path}/g,frame_url);break;case'custom':correctSizes=_fitToViewport(movie_width,movie_height);toInject=settings.custom_markup;break;case'inline':myClone=$(pp_images[set_position]).clone().css({'width':settings.default_width}).wrapInner('<div id="pp_full_res"><div class="pp_inline clearfix"></div></div>').appendTo($('body'));correctSizes=_fitToViewport($(myClone).width(),$(myClone).height());$(myClone).remove();toInject=settings.inline_markup.replace(/{content}/g,$(pp_images[set_position]).html());break;};if(!imgPreloader){$pp_pic_holder.find('#pp_full_res')[0].innerHTML=toInject;_showContent();};});return false;};$.prettyPhoto.changePage=function(direction){currentGalleryPage=0;if(direction=='previous'){set_position--;if(set_position<0){set_position=0;return;};}else if(direction=='next'){set_position++;if(set_position>$(pp_images).length-1){set_position=0;}}else{set_position=direction;};if(!doresize)doresize=true;$('.pp_contract').removeClass('pp_contract').addClass('pp_expand');_hideContent(function(){$.prettyPhoto.open();});};$.prettyPhoto.changeGalleryPage=function(direction){if(direction=='next'){currentGalleryPage++;if(currentGalleryPage>totalPage){currentGalleryPage=0;};}else if(direction=='previous'){currentGalleryPage--;if(currentGalleryPage<0){currentGalleryPage=totalPage;};}else{currentGalleryPage=direction;};itemsToSlide=(currentGalleryPage==totalPage)?pp_images.length-((totalPage)*itemsPerPage):itemsPerPage;$pp_pic_holder.find('.pp_gallery li').each(function(i){$(this).animate({'left':(i*itemWidth)-((itemsToSlide*itemWidth)*currentGalleryPage)});});};$.prettyPhoto.startSlideshow=function(){if(typeof pp_slideshow=='undefined'){$pp_pic_holder.find('.pp_play').unbind('click').removeClass('pp_play').addClass('pp_pause').click(function(){$.prettyPhoto.stopSlideshow();return false;});pp_slideshow=setInterval($.prettyPhoto.startSlideshow,settings.slideshow);}else{$.prettyPhoto.changePage('next');};};
$.prettyPhoto.stopSlideshow=function(){$pp_pic_holder.find('.pp_pause').unbind('click').removeClass('pp_pause').addClass('pp_play').click(function(){$.prettyPhoto.startSlideshow();return false;});clearInterval(pp_slideshow);pp_slideshow=undefined;};
$.prettyPhoto.close=function(){clearInterval(pp_slideshow);$pp_pic_holder.stop().find('object,embed').css('visibility','hidden');$('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed,function(){$(this).remove();});$pp_overlay.fadeOut(settings.animation_speed,function(){if($.browser.msie&&$.browser.version==6)$('select').css('visibility','visible');if(settings.hideflash)$('object,embed').css('visibility','visible');$(this).remove();settings.callback();doresize=true;pp_open=false;delete settings;});};_showContent=function(){$('.pp_loaderIcon').hide();$ppt.fadeTo(settings.animation_speed,1);if ( isNaN(correctSizes.contentHeight) )correctSizes.contentHeight = 1;projectedTop=scroll_pos.scrollTop+((windowHeight/2)-(correctSizes.containerHeight/2));if(projectedTop<0)projectedTop=0;if ( isNaN(projectedTop) )projectedTop = 1;$pp_pic_holder.find('.pp_content').animate({'height':correctSizes.contentHeight},settings.animation_speed);$pp_pic_holder.animate({'top':projectedTop,'left':(windowWidth/2)-(correctSizes.containerWidth/2),'width':correctSizes.containerWidth},settings.animation_speed,function(){$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes.height).width(correctSizes.width);$pp_pic_holder.find('.pp_fade').fadeIn(settings.animation_speed);if(isSet&&_getFileType(pp_images[set_position])=="image"){$pp_pic_holder.find('.pp_hoverContainer').show();}else{$pp_pic_holder.find('.pp_hoverContainer').hide();}
if(correctSizes.resized)$('a.pp_expand,a.pp_contract').fadeIn(settings.animation_speed);if(settings.autoplay_slideshow&&!pp_slideshow&&!pp_open)$.prettyPhoto.startSlideshow();settings.changepicturecallback();pp_open=true;});_insert_gallery();};function _hideContent(callback){$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');$pp_pic_holder.find('.pp_fade').fadeOut(settings.animation_speed,function(){$('.pp_loaderIcon').show();callback();});};function _checkPosition(setCount){if(set_position==setCount-1){$pp_pic_holder.find('a.pp_next').css('visibility','hidden');$pp_pic_holder.find('a.pp_next').addClass('disabled').unbind('click');}else{$pp_pic_holder.find('a.pp_next').css('visibility','visible');$pp_pic_holder.find('a.pp_next.disabled').removeClass('disabled').bind('click',function(){$.prettyPhoto.changePage('next');return false;});};if(set_position==0){$pp_pic_holder.find('a.pp_previous').css('visibility','hidden').addClass('disabled').unbind('click');}else{$pp_pic_holder.find('a.pp_previous.disabled').css('visibility','visible').removeClass('disabled').bind('click',function(){$.prettyPhoto.changePage('previous');return false;});};(setCount>1)?$('.pp_nav').show():$('.pp_nav').hide();};function _fitToViewport(width,height){resized=false;_getDimensions(width,height);imageWidth=width,imageHeight=height;if(((pp_containerWidth>windowWidth)||(pp_containerHeight>windowHeight))&&doresize&&settings.allow_resize&&!percentBased){resized=true,fitting=false;while(!fitting){if((pp_containerWidth>windowWidth)){imageWidth=(windowWidth-200);imageHeight=(height/width)*imageWidth;}else if((pp_containerHeight>windowHeight)){imageHeight=(windowHeight-200);imageWidth=(width/height)*imageHeight;}else{fitting=true;};pp_containerHeight=imageHeight,pp_containerWidth=imageWidth;};_getDimensions(imageWidth,imageHeight);};return{width:Math.floor(imageWidth),height:Math.floor(imageHeight),containerHeight:Math.floor(pp_containerHeight),containerWidth:Math.floor(pp_containerWidth)+40,contentHeight:Math.floor(pp_contentHeight),contentWidth:Math.floor(pp_contentWidth),resized:resized};};function _getDimensions(width,height){width=parseFloat(width);height=parseFloat(height);$pp_details=$pp_pic_holder.find('.pp_details');$pp_details.width(width);detailsHeight=parseFloat($pp_details.css('marginTop'))+parseFloat($pp_details.css('marginBottom'));$pp_details=$pp_details.clone().appendTo($('body')).css({'position':'absolute','top':-10000});detailsHeight+=$pp_details.height();detailsHeight=(detailsHeight<=34)?36:detailsHeight;if($.browser.msie&&$.browser.version==7)detailsHeight+=8;$pp_details.remove();pp_contentHeight=height+detailsHeight;pp_contentWidth=width;pp_containerHeight=pp_contentHeight+$ppt.height()+$pp_pic_holder.find('.pp_top').height()+$pp_pic_holder.find('.pp_bottom').height();pp_containerWidth=width;}
function _getFileType(itemSrc){if(itemSrc.match(/youtube\.com/i)){return'youtube';}else if(itemSrc.match(/vimeo\.com/i)){return'vimeo';}else if(itemSrc.indexOf('.mov')!=-1){return'quicktime';}else if(itemSrc.indexOf('.swf')!=-1){return'flash';}else if(itemSrc.indexOf('iframe')!=-1){return'iframe';}else if(itemSrc.indexOf('custom')!=-1){return'custom';}else if(itemSrc.substr(0,1)=='#'){return'inline';}else{return'image';};};function _center_overlay(){if(doresize&&typeof $pp_pic_holder!='undefined'){scroll_pos=_get_scroll();titleHeight=$ppt.height(),contentHeight=$pp_pic_holder.height(),contentwidth=$pp_pic_holder.width();projectedTop=(windowHeight/2)+scroll_pos.scrollTop-(contentHeight/2);$pp_pic_holder.css({'top':projectedTop,'left':(windowWidth/2)+scroll_pos.scrollLeft-(contentwidth/2)});};};function _get_scroll(){if(self.pageYOffset){return{scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};}else if(document.documentElement&&document.documentElement.scrollTop){return{scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};}else if(document.body){return{scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};};};function _resize_overlay(){windowHeight=$(window).height(),windowWidth=$(window).width();if(typeof $pp_overlay!="undefined")$pp_overlay.height($(document).height());};function _insert_gallery(){if(isSet&&settings.overlay_gallery&&_getFileType(pp_images[set_position])=="image"){itemWidth=52+5;navWidth=(settings.theme=="facebook")?58:38;itemsPerPage=Math.floor((correctSizes.containerWidth-100-navWidth)/itemWidth);itemsPerPage=(itemsPerPage<pp_images.length)?itemsPerPage:pp_images.length;totalPage=Math.ceil(pp_images.length/itemsPerPage)-1;if(totalPage==0){navWidth=0;$pp_pic_holder.find('.pp_gallery .pp_arrow_next,.pp_gallery .pp_arrow_previous').hide();}else{$pp_pic_holder.find('.pp_gallery .pp_arrow_next,.pp_gallery .pp_arrow_previous').show();};galleryWidth=itemsPerPage*itemWidth+navWidth;$pp_pic_holder.find('.pp_gallery').width(galleryWidth).css('margin-left',-(galleryWidth/2));$pp_pic_holder.find('.pp_gallery ul').width(itemsPerPage*itemWidth).find('li.selected').removeClass('selected');goToPage=(Math.floor(set_position/itemsPerPage)<=totalPage)?Math.floor(set_position/itemsPerPage):totalPage;if(itemsPerPage){$pp_pic_holder.find('.pp_gallery').hide().show().removeClass('disabled');}else{$pp_pic_holder.find('.pp_gallery').hide().addClass('disabled');}
$.prettyPhoto.changeGalleryPage(goToPage);$pp_pic_holder.find('.pp_gallery ul li:eq('+set_position+')').addClass('selected');}else{$pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave');$pp_pic_holder.find('.pp_gallery').hide();}}
function _buildOverlay(caller){theRel=$(caller).attr('rel');galleryRegExp=/\[(?:.*)\]/;isSet=(galleryRegExp.exec(theRel))?true:false;pp_images=(isSet)?jQuery.map(matchedObjects,function(n,i){if($(n).attr('rel').indexOf(theRel)!=-1)return $(n).attr('href');}):$.makeArray($(caller).attr('href'));pp_titles=(isSet)?jQuery.map(matchedObjects,function(n,i){if($(n).attr('rel').indexOf(theRel)!=-1)return($(n).find('img').attr('alt'))?$(n).find('img').attr('alt'):"";}):$.makeArray($(caller).find('img').attr('alt'));pp_descriptions=(isSet)?jQuery.map(matchedObjects,function(n,i){if($(n).attr('rel').indexOf(theRel)!=-1)return($(n).attr('title'))?$(n).attr('title'):"";}):$.makeArray($(caller).attr('title'));$('body').append(settings.markup);$pp_pic_holder=$('.pp_pic_holder'),$ppt=$('.ppt'),$pp_overlay=$('div.pp_overlay');if(isSet&&settings.overlay_gallery){currentGalleryPage=0;toInject="";for(var i=0;i<pp_images.length;i++){var regex=new RegExp("(.*?)\.(jpg|jpeg|png|gif)$");var results=regex.exec(pp_images[i]);if(!results){classname='default';}else{classname='';}
toInject+="<li class='"+classname+"'><a href='#'><img src='"+pp_images[i]+"' width='50' alt='' /></a></li>";};toInject=settings.gallery_markup.replace(/{gallery}/g,toInject);$pp_pic_holder.find('#pp_full_res').after(toInject);$pp_pic_holder.find('.pp_gallery .pp_arrow_next').click(function(){$.prettyPhoto.changeGalleryPage('next');$.prettyPhoto.stopSlideshow();return false;});$pp_pic_holder.find('.pp_gallery .pp_arrow_previous').click(function(){$.prettyPhoto.changeGalleryPage('previous');$.prettyPhoto.stopSlideshow();return false;});$pp_pic_holder.find('.pp_content').hover(function(){$pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeIn();},function(){$pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeOut();});itemWidth=52+5;$pp_pic_holder.find('.pp_gallery ul li').each(function(i){$(this).css({'position':'absolute','left':i*itemWidth});$(this).find('a').unbind('click').click(function(){$.prettyPhoto.changePage(i);$.prettyPhoto.stopSlideshow();return false;});});};if(settings.slideshow){$pp_pic_holder.find('.pp_nav').prepend('<a href="#" class="pp_play">Play</a>');
$pp_pic_holder.find('.pp_nav .pp_play').click(function(){$.prettyPhoto.startSlideshow();return false;});}
$pp_pic_holder.attr('class','pp_pic_holder '+settings.theme);$pp_overlay.css({'opacity':0/*,'height':'100%'*/,'height':$(document).height()/*,'width':$(document).width()*/}).bind('click',function(){if(!settings.modal)js_prettyphoto_close();});$('a.pp_close').bind('click',function(){$.prettyPhoto.close();return false;});$('a.pp_expand').bind('click',function(e){if($(this).hasClass('pp_expand')){$(this).removeClass('pp_expand').addClass('pp_contract');doresize=false;}else{$(this).removeClass('pp_contract').addClass('pp_expand');doresize=true;};_hideContent(function(){$.prettyPhoto.open();});return false;});$pp_pic_holder.find('.pp_previous, .pp_nav .pp_arrow_previous').bind('click',function(){$.prettyPhoto.changePage('previous');$.prettyPhoto.stopSlideshow();return false;});$pp_pic_holder.find('.pp_next, .pp_nav .pp_arrow_next').bind('click',function(){$.prettyPhoto.changePage('next');$.prettyPhoto.stopSlideshow();return false;});_center_overlay();};return this.unbind('click').click($.prettyPhoto.initialize);};function grab_param(name,url){name=name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");var regexS="[\\?&]"+name+"=([^&#]*)";var regex=new RegExp(regexS);var results=regex.exec(url);return(results==null)?"":results[1];}})(jQuery);


/* ========================================
 FILE: /includes/js/jquery/fancybox3.5.7/jquery.fancybox.js
 ==================== */

// ==================================================
// fancyBox v3.5.7
//
// Licensed GPLv3 for open source use
// or fancyBox Commercial License for commercial use
//
// http://fancyapps.com/fancybox/
// Copyright 2019 fancyApps
//
// ==================================================
(function (window, document, $, undefined) {
  "use strict";

  window.console = window.console || {
    info: function (stuff) {}
  };

  // If there's no jQuery, fancyBox can't work
  // =========================================

  if (!$) {
    return;
  }

  // Check if fancyBox is already initialized
  // ========================================

  if ($.fn.fancybox) {
    console.info("fancyBox already initialized");

    return;
  }

  // Private default settings
  // ========================

  var defaults = {
    // Close existing modals
    // Set this to false if you do not need to stack multiple instances
    closeExisting: false,

    // Enable infinite gallery navigation
    loop: false,

    // Horizontal space between slides
    gutter: 50,

    // Enable keyboard navigation
    keyboard: true,

    // Should allow caption to overlap the content
    preventCaptionOverlap: true,

    // Should display navigation arrows at the screen edges
    arrows: true,

    // Should display counter at the top left corner
    infobar: true,

    // Should display close button (using `btnTpl.smallBtn` template) over the content
    // Can be true, false, "auto"
    // If "auto" - will be automatically enabled for "html", "inline" or "ajax" items
    smallBtn: "auto",

    // Should display toolbar (buttons at the top)
    // Can be true, false, "auto"
    // If "auto" - will be automatically hidden if "smallBtn" is enabled
    toolbar: "auto",

    // What buttons should appear in the top right corner.
    // Buttons will be created using templates from `btnTpl` option
    // and they will be placed into toolbar (class="fancybox-toolbar"` element)
    buttons: [
      "zoom",
      //"share",
      "slideShow",
      //"fullScreen",
      //"download",
      "thumbs",
      "close"
    ],

    // Detect "idle" time in seconds
    idleTime: 3,

    // Disable right-click and use simple image protection for images
    protect: false,

    // Shortcut to make content "modal" - disable keyboard navigtion, hide buttons, etc
    modal: false,

    image: {
      // Wait for images to load before displaying
      //   true  - wait for image to load and then display;
      //   false - display thumbnail and load the full-sized image over top,
      //           requires predefined image dimensions (`data-width` and `data-height` attributes)
      preload: false
    },

    ajax: {
      // Object containing settings for ajax request
      settings: {
        // This helps to indicate that request comes from the modal
        // Feel free to change naming
        data: {
          fancybox: true
        }
      }
    },

    iframe: {
      // Iframe template
      tpl: '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" allowfullscreen="allowfullscreen" allow="autoplay; fullscreen" src=""></iframe>',

      // Preload iframe before displaying it
      // This allows to calculate iframe content width and height
      // (note: Due to "Same Origin Policy", you can't get cross domain data).
      preload: true,

      // Custom CSS styling for iframe wrapping element
      // You can use this to set custom iframe dimensions
      css: {},

      // Iframe tag attributes
      attr: {
        scrolling: "auto"
      }
    },

    // For HTML5 video only
    video: {
      tpl: '<video class="fancybox-video" controls controlsList="nodownload" poster="{{poster}}">' +
        '<source src="{{src}}" type="{{format}}" />' +
        'Sorry, your browser doesn\'t support embedded videos, <a href="{{src}}">download</a> and watch with your favorite video player!' +
        "</video>",
      format: "", // custom video format
      autoStart: true
    },

    // Default content type if cannot be detected automatically
    defaultType: "image",

    // Open/close animation type
    // Possible values:
    //   false            - disable
    //   "zoom"           - zoom images from/to thumbnail
    //   "fade"
    //   "zoom-in-out"
    //
    animationEffect: "zoom",

    // Duration in ms for open/close animation
    animationDuration: 366,

    // Should image change opacity while zooming
    // If opacity is "auto", then opacity will be changed if image and thumbnail have different aspect ratios
    zoomOpacity: "auto",

    // Transition effect between slides
    //
    // Possible values:
    //   false            - disable
    //   "fade'
    //   "slide'
    //   "circular'
    //   "tube'
    //   "zoom-in-out'
    //   "rotate'
    //
    transitionEffect: "fade",

    // Duration in ms for transition animation
    transitionDuration: 366,

    // Custom CSS class for slide element
    slideClass: "",

    // Custom CSS class for layout
    baseClass: "",

    // Base template for layout
    baseTpl: '<div class="fancybox-container" role="dialog" tabindex="-1">' +
      '<div class="fancybox-bg"></div>' +
      '<div class="fancybox-inner">' +
      '<div class="fancybox-infobar"><span data-fancybox-index></span>&nbsp;/&nbsp;<span data-fancybox-count></span></div>' +
      '<div class="fancybox-toolbar">{{buttons}}</div>' +
      '<div class="fancybox-navigation">{{arrows}}</div>' +
      '<div class="fancybox-stage"></div>' +
      '<div class="fancybox-caption"><div class="fancybox-caption__body"></div></div>' +
      "</div>" +
      "</div>",

    // Loading indicator template
    spinnerTpl: '<div class="fancybox-loading"></div>',

    // Error message template
    errorTpl: '<div class="fancybox-error"><p>{{ERROR}}</p></div>',

    btnTpl: {
      download: '<a download data-fancybox-download class="fancybox-button fancybox-button--download" title="{{DOWNLOAD}}" href="javascript:;">' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18.62 17.09V19H5.38v-1.91zm-2.97-6.96L17 11.45l-5 4.87-5-4.87 1.36-1.32 2.68 2.64V5h1.92v7.77z"/></svg>' +
        "</a>",

      zoom: '<button data-fancybox-zoom class="fancybox-button fancybox-button--zoom" title="{{ZOOM}}">' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18.7 17.3l-3-3a5.9 5.9 0 0 0-.6-7.6 5.9 5.9 0 0 0-8.4 0 5.9 5.9 0 0 0 0 8.4 5.9 5.9 0 0 0 7.7.7l3 3a1 1 0 0 0 1.3 0c.4-.5.4-1 0-1.5zM8.1 13.8a4 4 0 0 1 0-5.7 4 4 0 0 1 5.7 0 4 4 0 0 1 0 5.7 4 4 0 0 1-5.7 0z"/></svg>' +
        "</button>",

      close: '<button data-fancybox-close class="fancybox-button fancybox-button--close" title="{{CLOSE}}">' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 10.6L6.6 5.2 5.2 6.6l5.4 5.4-5.4 5.4 1.4 1.4 5.4-5.4 5.4 5.4 1.4-1.4-5.4-5.4 5.4-5.4-1.4-1.4-5.4 5.4z"/></svg>' +
        "</button>",

      // Arrows
      arrowLeft: '<button data-fancybox-prev class="fancybox-button fancybox-button--arrow_left" title="{{PREV}}">' +
        '<div><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M11.28 15.7l-1.34 1.37L5 12l4.94-5.07 1.34 1.38-2.68 2.72H19v1.94H8.6z"/></svg></div>' +
        "</button>",

      arrowRight: '<button data-fancybox-next class="fancybox-button fancybox-button--arrow_right" title="{{NEXT}}">' +
        '<div><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.4 12.97l-2.68 2.72 1.34 1.38L19 12l-4.94-5.07-1.34 1.38 2.68 2.72H5v1.94z"/></svg></div>' +
        "</button>",

      // This small close button will be appended to your html/inline/ajax content by default,
      // if "smallBtn" option is not set to false
      smallBtn: '<button type="button" data-fancybox-close class="fancybox-button fancybox-close-small" title="{{CLOSE}}">' +
        '<svg xmlns="http://www.w3.org/2000/svg" version="1" viewBox="0 0 24 24"><path d="M13 12l5-5-1-1-5 5-5-5-1 1 5 5-5 5 1 1 5-5 5 5 1-1z"/></svg>' +
        "</button>"
    },

    // Container is injected into this element
    parentEl: "body",

    // Hide browser vertical scrollbars; use at your own risk
    hideScrollbar: true,

    // Focus handling
    // ==============

    // Try to focus on the first focusable element after opening
    autoFocus: true,

    // Put focus back to active element after closing
    backFocus: true,

    // Do not let user to focus on element outside modal content
    trapFocus: true,

    // Module specific options
    // =======================

    fullScreen: {
      autoStart: false
    },

    // Set `touch: false` to disable panning/swiping
    touch: {
      vertical: true, // Allow to drag content vertically
      momentum: true // Continue movement after releasing mouse/touch when panning
    },

    // Hash value when initializing manually,
    // set `false` to disable hash change
    hash: null,

    // Customize or add new media types
    // Example:
    /*
      media : {
        youtube : {
          params : {
            autoplay : 0
          }
        }
      }
    */
    media: {},

    slideShow: {
      autoStart: false,
      speed: 3000
    },

    thumbs: {
      autoStart: false, // Display thumbnails on opening
      hideOnClose: true, // Hide thumbnail grid when closing animation starts
      parentEl: ".fancybox-container", // Container is injected into this element
      axis: "y" // Vertical (y) or horizontal (x) scrolling
    },

    // Use mousewheel to navigate gallery
    // If 'auto' - enabled for images only
    wheel: "auto",

    // Callbacks
    //==========

    // See Documentation/API/Events for more information
    // Example:
    /*
      afterShow: function( instance, current ) {
        console.info( 'Clicked element:' );
        console.info( current.opts.$orig );
      }
    */

    onInit: $.noop, // When instance has been initialized

    beforeLoad: $.noop, // Before the content of a slide is being loaded
    afterLoad: $.noop, // When the content of a slide is done loading

    beforeShow: $.noop, // Before open animation starts
    afterShow: $.noop, // When content is done loading and animating

    beforeClose: $.noop, // Before the instance attempts to close. Return false to cancel the close.
    afterClose: $.noop, // After instance has been closed

    onActivate: $.noop, // When instance is brought to front
    onDeactivate: $.noop, // When other instance has been activated

    // Interaction
    // ===========

    // Use options below to customize taken action when user clicks or double clicks on the fancyBox area,
    // each option can be string or method that returns value.
    //
    // Possible values:
    //   "close"           - close instance
    //   "next"            - move to next gallery item
    //   "nextOrClose"     - move to next gallery item or close if gallery has only one item
    //   "toggleControls"  - show/hide controls
    //   "zoom"            - zoom image (if loaded)
    //   false             - do nothing

    // Clicked on the content
    clickContent: function (current, event) {
      return current.type === "image" ? "zoom" : false;
    },

    // Clicked on the slide
    clickSlide: "close",

    // Clicked on the background (backdrop) element;
    // if you have not changed the layout, then most likely you need to use `clickSlide` option
    clickOutside: "close",

    // Same as previous two, but for double click
    dblclickContent: false,
    dblclickSlide: false,
    dblclickOutside: false,

    // Custom options when mobile device is detected
    // =============================================

    mobile: {
      preventCaptionOverlap: false,
      idleTime: false,
      clickContent: function (current, event) {
        return current.type === "image" ? "toggleControls" : false;
      },
      clickSlide: function (current, event) {
        return current.type === "image" ? "toggleControls" : "close";
      },
      dblclickContent: function (current, event) {
        return current.type === "image" ? "zoom" : false;
      },
      dblclickSlide: function (current, event) {
        return current.type === "image" ? "zoom" : false;
      }
    },

    // Internationalization
    // ====================

    lang: "en",
    i18n: {
      en: {
        CLOSE: "Close",
        NEXT: "Next",
        PREV: "Previous",
        ERROR: "The requested content cannot be loaded. <br/> Please try again later.",
        PLAY_START: "Start slideshow",
        PLAY_STOP: "Pause slideshow",
        FULL_SCREEN: "Full screen",
        THUMBS: "Thumbnails",
        DOWNLOAD: "Download",
        SHARE: "Share",
        ZOOM: "Zoom"
      },
      de: {
        CLOSE: "Schlie&szlig;en",
        NEXT: "Weiter",
        PREV: "Zur&uuml;ck",
        ERROR: "Die angeforderten Daten konnten nicht geladen werden. <br/> Bitte versuchen Sie es sp&auml;ter nochmal.",
        PLAY_START: "Diaschau starten",
        PLAY_STOP: "Diaschau beenden",
        FULL_SCREEN: "Vollbild",
        THUMBS: "Vorschaubilder",
        DOWNLOAD: "Herunterladen",
        SHARE: "Teilen",
        ZOOM: "Vergr&ouml;&szlig;ern"
      }
    }
  };

  // Few useful variables and methods
  // ================================

  var $W = $(window);
  var $D = $(document);

  var called = 0;

  // Check if an object is a jQuery object and not a native JavaScript object
  // ========================================================================
  var isQuery = function (obj) {
    return obj && obj.hasOwnProperty && obj instanceof $;
  };

  // Handle multiple browsers for "requestAnimationFrame" and "cancelAnimationFrame"
  // ===============================================================================
  var requestAFrame = (function () {
    return (
      window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      // if all else fails, use setTimeout
      function (callback) {
        return window.setTimeout(callback, 1000 / 60);
      }
    );
  })();

  var cancelAFrame = (function () {
    return (
      window.cancelAnimationFrame ||
      window.webkitCancelAnimationFrame ||
      window.mozCancelAnimationFrame ||
      window.oCancelAnimationFrame ||
      function (id) {
        window.clearTimeout(id);
      }
    );
  })();

  // Detect the supported transition-end event property name
  // =======================================================
  var transitionEnd = (function () {
    var el = document.createElement("fakeelement"),
      t;

    var transitions = {
      transition: "transitionend",
      OTransition: "oTransitionEnd",
      MozTransition: "transitionend",
      WebkitTransition: "webkitTransitionEnd"
    };

    for (t in transitions) {
      if (el.style[t] !== undefined) {
        return transitions[t];
      }
    }

    return "transitionend";
  })();

  // Force redraw on an element.
  // This helps in cases where the browser doesn't redraw an updated element properly
  // ================================================================================
  var forceRedraw = function ($el) {
    return $el && $el.length && $el[0].offsetHeight;
  };

  // Exclude array (`buttons`) options from deep merging
  // ===================================================
  var mergeOpts = function (opts1, opts2) {
    var rez = $.extend(true, {}, opts1, opts2);

    $.each(opts2, function (key, value) {
      if ($.isArray(value)) {
        rez[key] = value;
      }
    });

    return rez;
  };

  // How much of an element is visible in viewport
  // =============================================

  var inViewport = function (elem) {
    var elemCenter, rez;

    if (!elem || elem.ownerDocument !== document) {
      return false;
    }

    $(".fancybox-container").css("pointer-events", "none");

    elemCenter = {
      x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
      y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
    };

    rez = document.elementFromPoint(elemCenter.x, elemCenter.y) === elem;

    $(".fancybox-container").css("pointer-events", "");

    return rez;
  };

  // Class definition
  // ================

  var FancyBox = function (content, opts, index) {
    var self = this;

    self.opts = mergeOpts({
      index: index
    }, $.fancybox.defaults);

    if ($.isPlainObject(opts)) {
      self.opts = mergeOpts(self.opts, opts);
    }

    if ($.fancybox.isMobile) {
      self.opts = mergeOpts(self.opts, self.opts.mobile);
    }

    self.id = self.opts.id || ++called;

    self.currIndex = parseInt(self.opts.index, 10) || 0;
    self.prevIndex = null;

    self.prevPos = null;
    self.currPos = 0;

    self.firstRun = true;

    // All group items
    self.group = [];

    // Existing slides (for current, next and previous gallery items)
    self.slides = {};

    // Create group elements
    self.addContent(content);

    if (!self.group.length) {
      return;
    }

    self.init();
  };

  $.extend(FancyBox.prototype, {
    // Create DOM structure
    // ====================

    init: function () {
      var self = this,
        firstItem = self.group[self.currIndex],
        firstItemOpts = firstItem.opts,
        $container,
        buttonStr;

      if (firstItemOpts.closeExisting) {
        $.fancybox.close(true);
      }

      // Hide scrollbars
      // ===============

      $("body").addClass("fancybox-active");

      if (
        !$.fancybox.getInstance() &&
        firstItemOpts.hideScrollbar !== false &&
        !$.fancybox.isMobile &&
        document.body.scrollHeight > window.innerHeight
      ) {
        $("head").append(
          '<style id="fancybox-style-noscroll" type="text/css">.compensate-for-scrollbar{margin-right:' +
          (window.innerWidth - document.documentElement.clientWidth) +
          "px;}</style>"
        );

        $("body").addClass("compensate-for-scrollbar");
      }

      // Build html markup and set references
      // ====================================

      // Build html code for buttons and insert into main template
      buttonStr = "";

      $.each(firstItemOpts.buttons, function (index, value) {
        buttonStr += firstItemOpts.btnTpl[value] || "";
      });

      // Create markup from base template, it will be initially hidden to
      // avoid unnecessary work like painting while initializing is not complete
      $container = $(
          self.translate(
            self,
            firstItemOpts.baseTpl
            .replace("{{buttons}}", buttonStr)
            .replace("{{arrows}}", firstItemOpts.btnTpl.arrowLeft + firstItemOpts.btnTpl.arrowRight)
          )
        )
        .attr("id", "fancybox-container-" + self.id)
        .addClass(firstItemOpts.baseClass)
        .data("FancyBox", self)
        .appendTo(firstItemOpts.parentEl);

      // Create object holding references to jQuery wrapped nodes
      self.$refs = {
        container: $container
      };

      ["bg", "inner", "infobar", "toolbar", "stage", "caption", "navigation"].forEach(function (item) {
        self.$refs[item] = $container.find(".fancybox-" + item);
      });

      self.trigger("onInit");

      // Enable events, deactive previous instances
      self.activate();

      // Build slides, load and reveal content
      self.jumpTo(self.currIndex);
    },

    // Simple i18n support - replaces object keys found in template
    // with corresponding values
    // ============================================================

    translate: function (obj, str) {
      var arr = obj.opts.i18n[obj.opts.lang] || obj.opts.i18n.en;

      return str.replace(/\{\{(\w+)\}\}/g, function (match, n) {
        return arr[n] === undefined ? match : arr[n];
      });
    },

    // Populate current group with fresh content
    // Check if each object has valid type and content
    // ===============================================

    addContent: function (content) {
      var self = this,
        items = $.makeArray(content),
        thumbs;

      $.each(items, function (i, item) {
        var obj = {},
          opts = {},
          $item,
          type,
          found,
          src,
          srcParts;

        // Step 1 - Make sure we have an object
        // ====================================

        if ($.isPlainObject(item)) {
          // We probably have manual usage here, something like
          // $.fancybox.open( [ { src : "image.jpg", type : "image" } ] )

          obj = item;
          opts = item.opts || item;
        } else if ($.type(item) === "object" && $(item).length) {
          // Here we probably have jQuery collection returned by some selector
          $item = $(item);

          // Support attributes like `data-options='{"touch" : false}'` and `data-touch='false'`
          opts = $item.data() || {};
          opts = $.extend(true, {}, opts, opts.options);

          // Here we store clicked element
          opts.$orig = $item;

          obj.src = self.opts.src || opts.src || $item.attr("href");

          // Assume that simple syntax is used, for example:
          //   `$.fancybox.open( $("#test"), {} );`
          if (!obj.type && !obj.src) {
            obj.type = "inline";
            obj.src = item;
          }
        } else {
          // Assume we have a simple html code, for example:
          //   $.fancybox.open( '<div><h1>Hi!</h1></div>' );
          obj = {
            type: "html",
            src: item + ""
          };
        }

        // Each gallery object has full collection of options
        obj.opts = $.extend(true, {}, self.opts, opts);

        // Do not merge buttons array
        if ($.isArray(opts.buttons)) {
          obj.opts.buttons = opts.buttons;
        }

        if ($.fancybox.isMobile && obj.opts.mobile) {
          obj.opts = mergeOpts(obj.opts, obj.opts.mobile);
        }

        // Step 2 - Make sure we have content type, if not - try to guess
        // ==============================================================

        type = obj.type || obj.opts.type;
        src = obj.src || "";

        if (!type && src) {
          if ((found = src.match(/\.(mp4|mov|ogv|webm)((\?|#).*)?$/i))) {
            type = "video";

            if (!obj.opts.video.format) {
              obj.opts.video.format = "video/" + (found[1] === "ogv" ? "ogg" : found[1]);
            }
          } else if (src.match(/(^data:image\/[a-z0-9+\/=]*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg|ico|avif)((\?|#).*)?$)/i)) {
            type = "image";
          } else if (src.match(/\.(pdf)((\?|#).*)?$/i)) {
            type = "iframe";
            obj = $.extend(true, obj, {
              contentType: "pdf",
              opts: {
                iframe: {
                  preload: false
                }
              }
            });
          } else if (src.charAt(0) === "#") {
            type = "inline";
          }
        }

        if (type) {
          obj.type = type;
        } else {
          self.trigger("objectNeedsType", obj);
        }

        if (!obj.contentType) {
          obj.contentType = $.inArray(obj.type, ["html", "inline", "ajax"]) > -1 ? "html" : obj.type;
        }

        // Step 3 - Some adjustments
        // =========================

        obj.index = self.group.length;

        if (obj.opts.smallBtn == "auto") {
          obj.opts.smallBtn = $.inArray(obj.type, ["html", "inline", "ajax"]) > -1;
        }

        if (obj.opts.toolbar === "auto") {
          obj.opts.toolbar = !obj.opts.smallBtn;
        }

        // Find thumbnail image, check if exists and if is in the viewport
        obj.$thumb = obj.opts.$thumb || null;

        if (obj.opts.$trigger && obj.index === self.opts.index) {
          obj.$thumb = obj.opts.$trigger.find("img:first");

          if (obj.$thumb.length) {
            obj.opts.$orig = obj.opts.$trigger;
          }
        }

        if (!(obj.$thumb && obj.$thumb.length) && obj.opts.$orig) {
          obj.$thumb = obj.opts.$orig.find("img:first");
        }

        if (obj.$thumb && !obj.$thumb.length) {
          obj.$thumb = null;
        }

        obj.thumb = obj.opts.thumb || (obj.$thumb ? obj.$thumb[0].src : null);

        // "caption" is a "special" option, it can be used to customize caption per gallery item
        if ($.type(obj.opts.caption) === "function") {
          obj.opts.caption = obj.opts.caption.apply(item, [self, obj]);
        }

        if ($.type(self.opts.caption) === "function") {
          obj.opts.caption = self.opts.caption.apply(item, [self, obj]);
        }

        // Make sure we have caption as a string or jQuery object
        if (!(obj.opts.caption instanceof $)) {
          obj.opts.caption = obj.opts.caption === undefined ? "" : obj.opts.caption + "";
        }

        // Check if url contains "filter" used to filter the content
        // Example: "ajax.html #something"
        if (obj.type === "ajax") {
          srcParts = src.split(/\s+/, 2);

          if (srcParts.length > 1) {
            obj.src = srcParts.shift();

            obj.opts.filter = srcParts.shift();
          }
        }

        // Hide all buttons and disable interactivity for modal items
        if (obj.opts.modal) {
          obj.opts = $.extend(true, obj.opts, {
            trapFocus: true,
            // Remove buttons
            infobar: 0,
            toolbar: 0,

            smallBtn: 0,

            // Disable keyboard navigation
            keyboard: 0,

            // Disable some modules
            slideShow: 0,
            fullScreen: 0,
            thumbs: 0,
            touch: 0,

            // Disable click event handlers
            clickContent: false,
            clickSlide: false,
            clickOutside: false,
            dblclickContent: false,
            dblclickSlide: false,
            dblclickOutside: false
          });
        }

        // Step 4 - Add processed object to group
        // ======================================

        self.group.push(obj);
      });

      // Update controls if gallery is already opened
      if (Object.keys(self.slides).length) {
        self.updateControls();

        // Update thumbnails, if needed
        thumbs = self.Thumbs;

        if (thumbs && thumbs.isActive) {
          thumbs.create();

          thumbs.focus();
        }
      }
    },

    // Attach an event handler functions for:
    //   - navigation buttons
    //   - browser scrolling, resizing;
    //   - focusing
    //   - keyboard
    //   - detecting inactivity
    // ======================================

    addEvents: function () {
      var self = this;

      self.removeEvents();

      // Make navigation elements clickable
      // ==================================

      self.$refs.container
        .on("click.fb-close", "[data-fancybox-close]", function (e) {
          e.stopPropagation();
          e.preventDefault();

          self.close(e);
        })
        .on("touchstart.fb-prev click.fb-prev", "[data-fancybox-prev]", function (e) {
          e.stopPropagation();
          e.preventDefault();

          self.previous();
        })
        .on("touchstart.fb-next click.fb-next", "[data-fancybox-next]", function (e) {
          e.stopPropagation();
          e.preventDefault();

          self.next();
        })
        .on("click.fb", "[data-fancybox-zoom]", function (e) {
          // Click handler for zoom button
          self[self.isScaledDown() ? "scaleToActual" : "scaleToFit"]();
        });

      // Handle page scrolling and browser resizing
      // ==========================================

      $W.on("orientationchange.fb resize.fb", function (e) {
        if (e && e.originalEvent && e.originalEvent.type === "resize") {
          if (self.requestId) {
            cancelAFrame(self.requestId);
          }

          self.requestId = requestAFrame(function () {
            self.update(e);
          });
        } else {
          if (self.current && self.current.type === "iframe") {
            self.$refs.stage.hide();
          }

          setTimeout(
            function () {
              self.$refs.stage.show();

              self.update(e);
            },
            $.fancybox.isMobile ? 600 : 250
          );
        }
      });

      $D.on("keydown.fb", function (e) {
        var instance = $.fancybox ? $.fancybox.getInstance() : null,
          current = instance.current,
          keycode = e.keyCode || e.which;

        // Trap keyboard focus inside of the modal
        // =======================================

        if (keycode == 9) {
          if (current.opts.trapFocus) {
            self.focus(e);
          }

          return;
        }

        // Enable keyboard navigation
        // ==========================

        if (!current.opts.keyboard || e.ctrlKey || e.altKey || e.shiftKey || $(e.target).is("input,textarea,video,audio,select")) {
          return;
        }

        // Backspace and Esc keys
        if (keycode === 8 || keycode === 27) {
          e.preventDefault();

          self.close(e);

          return;
        }

        // Left arrow and Up arrow
        if (keycode === 37 || keycode === 38) {
          e.preventDefault();

          self.previous();

          return;
        }

        // Righ arrow and Down arrow
        if (keycode === 39 || keycode === 40) {
          e.preventDefault();

          self.next();

          return;
        }

        self.trigger("afterKeydown", e, keycode);
      });

      // Hide controls after some inactivity period
      if (self.group[self.currIndex].opts.idleTime) {
        self.idleSecondsCounter = 0;

        $D.on(
          "mousemove.fb-idle mouseleave.fb-idle mousedown.fb-idle touchstart.fb-idle touchmove.fb-idle scroll.fb-idle keydown.fb-idle",
          function (e) {
            self.idleSecondsCounter = 0;

            if (self.isIdle) {
              self.showControls();
            }

            self.isIdle = false;
          }
        );

        self.idleInterval = window.setInterval(function () {
          self.idleSecondsCounter++;

          if (self.idleSecondsCounter >= self.group[self.currIndex].opts.idleTime && !self.isDragging) {
            self.isIdle = true;
            self.idleSecondsCounter = 0;

            self.hideControls();
          }
        }, 1000);
      }
    },

    // Remove events added by the core
    // ===============================

    removeEvents: function () {
      var self = this;

      $W.off("orientationchange.fb resize.fb");
      $D.off("keydown.fb .fb-idle");

      this.$refs.container.off(".fb-close .fb-prev .fb-next");

      if (self.idleInterval) {
        window.clearInterval(self.idleInterval);

        self.idleInterval = null;
      }
    },

    // Change to previous gallery item
    // ===============================

    previous: function (duration) {
      return this.jumpTo(this.currPos - 1, duration);
    },

    // Change to next gallery item
    // ===========================

    next: function (duration) {
      return this.jumpTo(this.currPos + 1, duration);
    },

    // Switch to selected gallery item
    // ===============================

    jumpTo: function (pos, duration) {
      var self = this,
        groupLen = self.group.length,
        firstRun,
        isMoved,
        loop,
        current,
        previous,
        slidePos,
        stagePos,
        prop,
        diff;

      if (self.isDragging || self.isClosing || (self.isAnimating && self.firstRun)) {
        return;
      }

      // Should loop?
      pos = parseInt(pos, 10);
      loop = self.current ? self.current.opts.loop : self.opts.loop;

      if (!loop && (pos < 0 || pos >= groupLen)) {
        return false;
      }

      // Check if opening for the first time; this helps to speed things up
      firstRun = self.firstRun = !Object.keys(self.slides).length;

      // Create slides
      previous = self.current;

      self.prevIndex = self.currIndex;
      self.prevPos = self.currPos;

      current = self.createSlide(pos);

      if (groupLen > 1) {
        if (loop || current.index < groupLen - 1) {
          self.createSlide(pos + 1);
        }

        if (loop || current.index > 0) {
          self.createSlide(pos - 1);
        }
      }

      self.current = current;
      self.currIndex = current.index;
      self.currPos = current.pos;

      self.trigger("beforeShow", firstRun);

      self.updateControls();

      // Validate duration length
      current.forcedDuration = undefined;

      if ($.isNumeric(duration)) {
        current.forcedDuration = duration;
      } else {
        duration = current.opts[firstRun ? "animationDuration" : "transitionDuration"];
      }

      duration = parseInt(duration, 10);

      // Check if user has swiped the slides or if still animating
      isMoved = self.isMoved(current);

      // Make sure current slide is visible
      current.$slide.addClass("fancybox-slide--current");

      // Fresh start - reveal container, current slide and start loading content
      if (firstRun) {
        if (current.opts.animationEffect && duration) {
          self.$refs.container.css("transition-duration", duration + "ms");
        }

        self.$refs.container.addClass("fancybox-is-open").trigger("focus");

        // Attempt to load content into slide
        // This will later call `afterLoad` -> `revealContent`
        self.loadSlide(current);

        self.preload("image");

        return;
      }

      // Get actual slide/stage positions (before cleaning up)
      slidePos = $.fancybox.getTranslate(previous.$slide);
      stagePos = $.fancybox.getTranslate(self.$refs.stage);

      // Clean up all slides
      $.each(self.slides, function (index, slide) {
        $.fancybox.stop(slide.$slide, true);
      });

      if (previous.pos !== current.pos) {
        previous.isComplete = false;
      }

      previous.$slide.removeClass("fancybox-slide--complete fancybox-slide--current");

      // If slides are out of place, then animate them to correct position
      if (isMoved) {
        // Calculate horizontal swipe distance
        diff = slidePos.left - (previous.pos * slidePos.width + previous.pos * previous.opts.gutter);

        $.each(self.slides, function (index, slide) {
          slide.$slide.removeClass("fancybox-animated").removeClass(function (index, className) {
            return (className.match(/(^|\s)fancybox-fx-\S+/g) || []).join(" ");
          });

          // Make sure that each slide is in equal distance
          // This is mostly needed for freshly added slides, because they are not yet positioned
          var leftPos = slide.pos * slidePos.width + slide.pos * slide.opts.gutter;

          $.fancybox.setTranslate(slide.$slide, {
            top: 0,
            left: leftPos - stagePos.left + diff
          });

          if (slide.pos !== current.pos) {
            slide.$slide.addClass("fancybox-slide--" + (slide.pos > current.pos ? "next" : "previous"));
          }

          // Redraw to make sure that transition will start
          forceRedraw(slide.$slide);

          // Animate the slide
          $.fancybox.animate(
            slide.$slide, {
              top: 0,
              left: (slide.pos - current.pos) * slidePos.width + (slide.pos - current.pos) * slide.opts.gutter
            },
            duration,
            function () {
              slide.$slide
                .css({
                  transform: "",
                  opacity: ""
                })
                .removeClass("fancybox-slide--next fancybox-slide--previous");

              if (slide.pos === self.currPos) {
                self.complete();
              }
            }
          );
        });
      } else if (duration && current.opts.transitionEffect) {
        // Set transition effect for previously active slide
        prop = "fancybox-animated fancybox-fx-" + current.opts.transitionEffect;

        previous.$slide.addClass("fancybox-slide--" + (previous.pos > current.pos ? "next" : "previous"));

        $.fancybox.animate(
          previous.$slide,
          prop,
          duration,
          function () {
            previous.$slide.removeClass(prop).removeClass("fancybox-slide--next fancybox-slide--previous");
          },
          false
        );
      }

      if (current.isLoaded) {
        self.revealContent(current);
      } else {
        self.loadSlide(current);
      }

      self.preload("image");
    },

    // Create new "slide" element
    // These are gallery items  that are actually added to DOM
    // =======================================================

    createSlide: function (pos) {
      var self = this,
        $slide,
        index;

      index = pos % self.group.length;
      index = index < 0 ? self.group.length + index : index;

      if (!self.slides[pos] && self.group[index]) {
        $slide = $('<div class="fancybox-slide"></div>').appendTo(self.$refs.stage);

        self.slides[pos] = $.extend(true, {}, self.group[index], {
          pos: pos,
          $slide: $slide,
          isLoaded: false
        });

        self.updateSlide(self.slides[pos]);
      }

      return self.slides[pos];
    },

    // Scale image to the actual size of the image;
    // x and y values should be relative to the slide
    // ==============================================

    scaleToActual: function (x, y, duration) {
      var self = this,
        current = self.current,
        $content = current.$content,
        canvasWidth = $.fancybox.getTranslate(current.$slide).width,
        canvasHeight = $.fancybox.getTranslate(current.$slide).height,
        newImgWidth = current.width,
        newImgHeight = current.height,
        imgPos,
        posX,
        posY,
        scaleX,
        scaleY;

      if (self.isAnimating || self.isMoved() || !$content || !(current.type == "image" && current.isLoaded && !current.hasError)) {
        return;
      }

      self.isAnimating = true;

      $.fancybox.stop($content);

      x = x === undefined ? canvasWidth * 0.5 : x;
      y = y === undefined ? canvasHeight * 0.5 : y;

      imgPos = $.fancybox.getTranslate($content);

      imgPos.top -= $.fancybox.getTranslate(current.$slide).top;
      imgPos.left -= $.fancybox.getTranslate(current.$slide).left;

      scaleX = newImgWidth / imgPos.width;
      scaleY = newImgHeight / imgPos.height;

      // Get center position for original image
      posX = canvasWidth * 0.5 - newImgWidth * 0.5;
      posY = canvasHeight * 0.5 - newImgHeight * 0.5;

      // Make sure image does not move away from edges
      if (newImgWidth > canvasWidth) {
        posX = imgPos.left * scaleX - (x * scaleX - x);

        if (posX > 0) {
          posX = 0;
        }

        if (posX < canvasWidth - newImgWidth) {
          posX = canvasWidth - newImgWidth;
        }
      }

      if (newImgHeight > canvasHeight) {
        posY = imgPos.top * scaleY - (y * scaleY - y);

        if (posY > 0) {
          posY = 0;
        }

        if (posY < canvasHeight - newImgHeight) {
          posY = canvasHeight - newImgHeight;
        }
      }

      self.updateCursor(newImgWidth, newImgHeight);

      $.fancybox.animate(
        $content, {
          top: posY,
          left: posX,
          scaleX: scaleX,
          scaleY: scaleY
        },
        duration || 366,
        function () {
          self.isAnimating = false;
        }
      );

      // Stop slideshow
      if (self.SlideShow && self.SlideShow.isActive) {
        self.SlideShow.stop();
      }
    },

    // Scale image to fit inside parent element
    // ========================================

    scaleToFit: function (duration) {
      var self = this,
        current = self.current,
        $content = current.$content,
        end;

      if (self.isAnimating || self.isMoved() || !$content || !(current.type == "image" && current.isLoaded && !current.hasError)) {
        return;
      }

      self.isAnimating = true;

      $.fancybox.stop($content);

      end = self.getFitPos(current);

      self.updateCursor(end.width, end.height);

      $.fancybox.animate(
        $content, {
          top: end.top,
          left: end.left,
          scaleX: end.width / $content.width(),
          scaleY: end.height / $content.height()
        },
        duration || 366,
        function () {
          self.isAnimating = false;
        }
      );
    },

    // Calculate image size to fit inside viewport
    // ===========================================

    getFitPos: function (slide) {
      var self = this,
        $content = slide.$content,
        $slide = slide.$slide,
        width = slide.width || slide.opts.width,
        height = slide.height || slide.opts.height,
        maxWidth,
        maxHeight,
        minRatio,
        aspectRatio,
        rez = {};

      if (!slide.isLoaded || !$content || !$content.length) {
        return false;
      }

      maxWidth = $.fancybox.getTranslate(self.$refs.stage).width;
      maxHeight = $.fancybox.getTranslate(self.$refs.stage).height;

      maxWidth -=
        parseFloat($slide.css("paddingLeft")) +
        parseFloat($slide.css("paddingRight")) +
        parseFloat($content.css("marginLeft")) +
        parseFloat($content.css("marginRight"));

      maxHeight -=
        parseFloat($slide.css("paddingTop")) +
        parseFloat($slide.css("paddingBottom")) +
        parseFloat($content.css("marginTop")) +
        parseFloat($content.css("marginBottom"));

      if (!width || !height) {
        width = maxWidth;
        height = maxHeight;
      }

      minRatio = Math.min(1, maxWidth / width, maxHeight / height);

      width = minRatio * width;
      height = minRatio * height;

      // Adjust width/height to precisely fit into container
      if (width > maxWidth - 0.5) {
        width = maxWidth;
      }

      if (height > maxHeight - 0.5) {
        height = maxHeight;
      }

      if (slide.type === "image") {
        rez.top = Math.floor((maxHeight - height) * 0.5) + parseFloat($slide.css("paddingTop"));
        rez.left = Math.floor((maxWidth - width) * 0.5) + parseFloat($slide.css("paddingLeft"));
      } else if (slide.contentType === "video") {
        // Force aspect ratio for the video
        // "I say the whole world must learn of our peaceful ways… by force!"
        aspectRatio = slide.opts.width && slide.opts.height ? width / height : slide.opts.ratio || 16 / 9;

        if (height > width / aspectRatio) {
          height = width / aspectRatio;
        } else if (width > height * aspectRatio) {
          width = height * aspectRatio;
        }
      }

      rez.width = width;
      rez.height = height;

      return rez;
    },

    // Update content size and position for all slides
    // ==============================================

    update: function (e) {
      var self = this;

      $.each(self.slides, function (key, slide) {
        self.updateSlide(slide, e);
      });
    },

    // Update slide content position and size
    // ======================================

    updateSlide: function (slide, e) {
      var self = this,
        $content = slide && slide.$content,
        width = slide.width || slide.opts.width,
        height = slide.height || slide.opts.height,
        $slide = slide.$slide;

      // First, prevent caption overlap, if needed
      self.adjustCaption(slide);

      // Then resize content to fit inside the slide
      if ($content && (width || height || slide.contentType === "video") && !slide.hasError) {
        $.fancybox.stop($content);

        $.fancybox.setTranslate($content, self.getFitPos(slide));

        if (slide.pos === self.currPos) {
          self.isAnimating = false;

          self.updateCursor();
        }
      }

      // Then some adjustments
      self.adjustLayout(slide);

      if ($slide.length) {
        $slide.trigger("refresh");

        if (slide.pos === self.currPos) {
          self.$refs.toolbar
            .add(self.$refs.navigation.find(".fancybox-button--arrow_right"))
            .toggleClass("compensate-for-scrollbar", $slide.get(0).scrollHeight > $slide.get(0).clientHeight);
        }
      }

      self.trigger("onUpdate", slide, e);
    },

    // Horizontally center slide
    // =========================

    centerSlide: function (duration) {
      var self = this,
        current = self.current,
        $slide = current.$slide;

      if (self.isClosing || !current) {
        return;
      }

      $slide.siblings().css({
        transform: "",
        opacity: ""
      });

      $slide
        .parent()
        .children()
        .removeClass("fancybox-slide--previous fancybox-slide--next");

      $.fancybox.animate(
        $slide, {
          top: 0,
          left: 0,
          opacity: 1
        },
        duration === undefined ? 0 : duration,
        function () {
          // Clean up
          $slide.css({
            transform: "",
            opacity: ""
          });

          if (!current.isComplete) {
            self.complete();
          }
        },
        false
      );
    },

    // Check if current slide is moved (swiped)
    // ========================================

    isMoved: function (slide) {
      var current = slide || this.current,
        slidePos,
        stagePos;

      if (!current) {
        return false;
      }

      stagePos = $.fancybox.getTranslate(this.$refs.stage);
      slidePos = $.fancybox.getTranslate(current.$slide);

      return (
        !current.$slide.hasClass("fancybox-animated") &&
        (Math.abs(slidePos.top - stagePos.top) > 0.5 || Math.abs(slidePos.left - stagePos.left) > 0.5)
      );
    },

    // Update cursor style depending if content can be zoomed
    // ======================================================

    updateCursor: function (nextWidth, nextHeight) {
      var self = this,
        current = self.current,
        $container = self.$refs.container,
        canPan,
        isZoomable;

      if (!current || self.isClosing || !self.Guestures) {
        return;
      }

      $container.removeClass("fancybox-is-zoomable fancybox-can-zoomIn fancybox-can-zoomOut fancybox-can-swipe fancybox-can-pan");

      canPan = self.canPan(nextWidth, nextHeight);

      isZoomable = canPan ? true : self.isZoomable();

      $container.toggleClass("fancybox-is-zoomable", isZoomable);

      $("[data-fancybox-zoom]").prop("disabled", !isZoomable);

      if (canPan) {
        $container.addClass("fancybox-can-pan");
      } else if (
        isZoomable &&
        (current.opts.clickContent === "zoom" || ($.isFunction(current.opts.clickContent) && current.opts.clickContent(current) == "zoom"))
      ) {
        $container.addClass("fancybox-can-zoomIn");
      } else if (current.opts.touch && (current.opts.touch.vertical || self.group.length > 1) && current.contentType !== "video") {
        $container.addClass("fancybox-can-swipe");
      }
    },

    // Check if current slide is zoomable
    // ==================================

    isZoomable: function () {
      var self = this,
        current = self.current,
        fitPos;

      // Assume that slide is zoomable if:
      //   - image is still loading
      //   - actual size of the image is smaller than available area
      if (current && !self.isClosing && current.type === "image" && !current.hasError) {
        if (!current.isLoaded) {
          return true;
        }

        fitPos = self.getFitPos(current);

        if (fitPos && (current.width > fitPos.width || current.height > fitPos.height)) {
          return true;
        }
      }

      return false;
    },

    // Check if current image dimensions are smaller than actual
    // =========================================================

    isScaledDown: function (nextWidth, nextHeight) {
      var self = this,
        rez = false,
        current = self.current,
        $content = current.$content;

      if (nextWidth !== undefined && nextHeight !== undefined) {
        rez = nextWidth < current.width && nextHeight < current.height;
      } else if ($content) {
        rez = $.fancybox.getTranslate($content);
        rez = rez.width < current.width && rez.height < current.height;
      }

      return rez;
    },

    // Check if image dimensions exceed parent element
    // ===============================================

    canPan: function (nextWidth, nextHeight) {
      var self = this,
        current = self.current,
        pos = null,
        rez = false;

      if (current.type === "image" && (current.isComplete || (nextWidth && nextHeight)) && !current.hasError) {
        rez = self.getFitPos(current);

        if (nextWidth !== undefined && nextHeight !== undefined) {
          pos = {
            width: nextWidth,
            height: nextHeight
          };
        } else if (current.isComplete) {
          pos = $.fancybox.getTranslate(current.$content);
        }

        if (pos && rez) {
          rez = Math.abs(pos.width - rez.width) > 1.5 || Math.abs(pos.height - rez.height) > 1.5;
        }
      }

      return rez;
    },

    // Load content into the slide
    // ===========================

    loadSlide: function (slide) {
      var self = this,
        type,
        $slide,
        ajaxLoad;

      if (slide.isLoading || slide.isLoaded) {
        return;
      }

      slide.isLoading = true;

      if (self.trigger("beforeLoad", slide) === false) {
        slide.isLoading = false;

        return false;
      }

      type = slide.type;
      $slide = slide.$slide;

      $slide
        .off("refresh")
        .trigger("onReset")
        .addClass(slide.opts.slideClass);

      // Create content depending on the type
      switch (type) {
        case "image":
          self.setImage(slide);

          break;

        case "iframe":
          self.setIframe(slide);

          break;

        case "html":
          self.setContent(slide, slide.src || slide.content);

          break;

        case "video":
          self.setContent(
            slide,
            slide.opts.video.tpl
            .replace(/\{\{src\}\}/gi, slide.src)
            .replace("{{format}}", slide.opts.videoFormat || slide.opts.video.format || "")
            .replace("{{poster}}", slide.thumb || "")
          );

          break;

        case "inline":
          if ($(slide.src).length) {
            self.setContent(slide, $(slide.src));
          } else {
            self.setError(slide);
          }

          break;

        case "ajax":
          self.showLoading(slide);

          ajaxLoad = $.ajax(
            $.extend({}, slide.opts.ajax.settings, {
              url: slide.src,
              success: function (data, textStatus) {
                if (textStatus === "success") {
                  self.setContent(slide, data);
                }
              },
              error: function (jqXHR, textStatus) {
                if (jqXHR && textStatus !== "abort") {
                  self.setError(slide);
                }
              }
            })
          );

          $slide.one("onReset", function () {
            ajaxLoad.abort();
          });

          break;

        default:
          self.setError(slide);

          break;
      }

      return true;
    },

    // Use thumbnail image, if possible
    // ================================

    setImage: function (slide) {
      var self = this,
        ghost;

      // Check if need to show loading icon
      setTimeout(function () {
        var $img = slide.$image;

        if (!self.isClosing && slide.isLoading && (!$img || !$img.length || !$img[0].complete) && !slide.hasError) {
          self.showLoading(slide);
        }
      }, 50);

      //Check if image has srcset
      self.checkSrcset(slide);

      // This will be wrapper containing both ghost and actual image
      slide.$content = $('<div class="fancybox-content"></div>')
        .addClass("fancybox-is-hidden")
        .appendTo(slide.$slide.addClass("fancybox-slide--image"));

      // If we have a thumbnail, we can display it while actual image is loading
      // Users will not stare at black screen and actual image will appear gradually
      if (slide.opts.preload !== false && slide.opts.width && slide.opts.height && slide.thumb) {
        slide.width = slide.opts.width;
        slide.height = slide.opts.height;

        ghost = document.createElement("img");

        ghost.onerror = function () {
          $(this).remove();

          slide.$ghost = null;
        };

        ghost.onload = function () {
          self.afterLoad(slide);
        };

        slide.$ghost = $(ghost)
          .addClass("fancybox-image")
          .appendTo(slide.$content)
          .attr("src", slide.thumb);
      }

      // Start loading actual image
      self.setBigImage(slide);
    },

    // Check if image has srcset and get the source
    // ============================================
    checkSrcset: function (slide) {
      var srcset = slide.opts.srcset || slide.opts.image.srcset,
        found,
        temp,
        pxRatio,
        windowWidth;

      // If we have "srcset", then we need to find first matching "src" value.
      // This is necessary, because when you set an src attribute, the browser will preload the image
      // before any javascript or even CSS is applied.
      if (srcset) {
        pxRatio = window.devicePixelRatio || 1;
        windowWidth = window.innerWidth * pxRatio;

        temp = srcset.split(",").map(function (el) {
          var ret = {};

          el.trim()
            .split(/\s+/)
            .forEach(function (el, i) {
              var value = parseInt(el.substring(0, el.length - 1), 10);

              if (i === 0) {
                return (ret.url = el);
              }

              if (value) {
                ret.value = value;
                ret.postfix = el[el.length - 1];
              }
            });

          return ret;
        });

        // Sort by value
        temp.sort(function (a, b) {
          return a.value - b.value;
        });

        // Ok, now we have an array of all srcset values
        for (var j = 0; j < temp.length; j++) {
          var el = temp[j];

          if ((el.postfix === "w" && el.value >= windowWidth) || (el.postfix === "x" && el.value >= pxRatio)) {
            found = el;
            break;
          }
        }

        // If not found, take the last one
        if (!found && temp.length) {
          found = temp[temp.length - 1];
        }

        if (found) {
          slide.src = found.url;

          // If we have default width/height values, we can calculate height for matching source
          if (slide.width && slide.height && found.postfix == "w") {
            slide.height = (slide.width / slide.height) * found.value;
            slide.width = found.value;
          }

          slide.opts.srcset = srcset;
        }
      }
    },

    // Create full-size image
    // ======================

    setBigImage: function (slide) {
      var self = this,
        img = document.createElement("img"),
        $img = $(img);

      slide.$image = $img
        .one("error", function () {
          self.setError(slide);
        })
        .one("load", function () {
          var sizes;

          if (!slide.$ghost) {
            self.resolveImageSlideSize(slide, this.naturalWidth, this.naturalHeight);

            self.afterLoad(slide);
          }

          if (self.isClosing) {
            return;
          }

          if (slide.opts.srcset) {
            sizes = slide.opts.sizes;

            if (!sizes || sizes === "auto") {
              sizes =
                (slide.width / slide.height > 1 && $W.width() / $W.height() > 1 ? "100" : Math.round((slide.width / slide.height) * 100)) +
                "vw";
            }

            $img.attr("sizes", sizes).attr("srcset", slide.opts.srcset);
          }

          // Hide temporary image after some delay
          if (slide.$ghost) {
            setTimeout(function () {
              if (slide.$ghost && !self.isClosing) {
                slide.$ghost.hide();
              }
            }, Math.min(300, Math.max(1000, slide.height / 1600)));
          }

          self.hideLoading(slide);
        })
        .addClass("fancybox-image")
        .attr("src", slide.src)
        .appendTo(slide.$content);

      if ((img.complete || img.readyState == "complete") && $img.naturalWidth && $img.naturalHeight) {
        $img.trigger("load");
      } else if (img.error) {
        $img.trigger("error");
      }
    },

    // Computes the slide size from image size and maxWidth/maxHeight
    // ==============================================================

    resolveImageSlideSize: function (slide, imgWidth, imgHeight) {
      var maxWidth = parseInt(slide.opts.width, 10),
        maxHeight = parseInt(slide.opts.height, 10);

      // Sets the default values from the image
      slide.width = imgWidth;
      slide.height = imgHeight;

      if (maxWidth > 0) {
        slide.width = maxWidth;
        slide.height = Math.floor((maxWidth * imgHeight) / imgWidth);
      }

      if (maxHeight > 0) {
        slide.width = Math.floor((maxHeight * imgWidth) / imgHeight);
        slide.height = maxHeight;
      }
    },

    // Create iframe wrapper, iframe and bindings
    // ==========================================

    setIframe: function (slide) {
      var self = this,
        opts = slide.opts.iframe,
        $slide = slide.$slide,
        $iframe;

      slide.$content = $('<div class="fancybox-content' + (opts.preload ? " fancybox-is-hidden" : "") + '"></div>')
        .css(opts.css)
        .appendTo($slide);

      $slide.addClass("fancybox-slide--" + slide.contentType);

      slide.$iframe = $iframe = $(opts.tpl.replace(/\{rnd\}/g, new Date().getTime()))
        .attr(opts.attr)
        .appendTo(slide.$content);

      if (opts.preload) {
        self.showLoading(slide);

        // Unfortunately, it is not always possible to determine if iframe is successfully loaded
        // (due to browser security policy)

        $iframe.on("load.fb error.fb", function (e) {
          this.isReady = 1;

          slide.$slide.trigger("refresh");

          self.afterLoad(slide);
        });

        // Recalculate iframe content size
        // ===============================

        $slide.on("refresh.fb", function () {
          var $content = slide.$content,
            frameWidth = opts.css.width,
            frameHeight = opts.css.height,
            $contents,
            $body;

          if ($iframe[0].isReady !== 1) {
            return;
          }

          try {
            $contents = $iframe.contents();
            $body = $contents.find("body");
          } catch (ignore) {}

          // Calculate content dimensions, if it is accessible
          if ($body && $body.length && $body.children().length) {
            // Avoid scrolling to top (if multiple instances)
            $slide.css("overflow", "visible");

            $content.css({
              width: "100%",
              "max-width": "100%",
              height: "9999px"
            });

            if (frameWidth === undefined) {
              frameWidth = Math.ceil(Math.max($body[0].clientWidth, $body.outerWidth(true)));
            }

            $content.css("width", frameWidth ? frameWidth : "").css("max-width", "");

            if (frameHeight === undefined) {
              frameHeight = Math.ceil(Math.max($body[0].clientHeight, $body.outerHeight(true)));
            }

            $content.css("height", frameHeight ? frameHeight : "");

            $slide.css("overflow", "auto");
          }

          $content.removeClass("fancybox-is-hidden");
        });
      } else {
        self.afterLoad(slide);
      }

      $iframe.attr("src", slide.src);

      // Remove iframe if closing or changing gallery item
      $slide.one("onReset", function () {
        // This helps IE not to throw errors when closing
        try {
          $(this)
            .find("iframe")
            .hide()
            .unbind()
            .attr("src", "//about:blank");
        } catch (ignore) {}

        $(this)
          .off("refresh.fb")
          .empty();

        slide.isLoaded = false;
        slide.isRevealed = false;
      });
    },

    // Wrap and append content to the slide
    // ======================================

    setContent: function (slide, content) {
      var self = this;

      if (self.isClosing) {
        return;
      }

      self.hideLoading(slide);

      if (slide.$content) {
        $.fancybox.stop(slide.$content);
      }

      slide.$slide.empty();

      // If content is a jQuery object, then it will be moved to the slide.
      // The placeholder is created so we will know where to put it back.
      if (isQuery(content) && content.parent().length) {
        // Make sure content is not already moved to fancyBox
        if (content.hasClass("fancybox-content") || content.parent().hasClass("fancybox-content")) {
          content.parents(".fancybox-slide").trigger("onReset");
        }

        // Create temporary element marking original place of the content
        slide.$placeholder = $("<div>")
          .hide()
          .insertAfter(content);

        // Make sure content is visible
        content.css("display", "inline-block");
      } else if (!slide.hasError) {
        // If content is just a plain text, try to convert it to html
        if ($.type(content) === "string") {
          content = $("<div>")
            .append($.trim(content))
            .contents();
        }

        // If "filter" option is provided, then filter content
        if (slide.opts.filter) {
          content = $("<div>")
            .html(content)
            .find(slide.opts.filter);
        }
      }

      slide.$slide.one("onReset", function () {
        // Pause all html5 video/audio
        $(this)
          .find("video,audio")
          .trigger("pause");

        // Put content back
        if (slide.$placeholder) {
          slide.$placeholder.after(content.removeClass("fancybox-content").hide()).remove();

          slide.$placeholder = null;
        }

        // Remove custom close button
        if (slide.$smallBtn) {
          slide.$smallBtn.remove();

          slide.$smallBtn = null;
        }

        // Remove content and mark slide as not loaded
        if (!slide.hasError) {
          $(this).empty();

          slide.isLoaded = false;
          slide.isRevealed = false;
        }
      });

      $(content).appendTo(slide.$slide);

      if ($(content).is("video,audio")) {
        $(content).addClass("fancybox-video");

        $(content).wrap("<div></div>");

        slide.contentType = "video";

        slide.opts.width = slide.opts.width || $(content).attr("width");
        slide.opts.height = slide.opts.height || $(content).attr("height");
      }

      slide.$content = slide.$slide
        .children()
        .filter("div,form,main,video,audio,article,.fancybox-content")
        .first();

      slide.$content.siblings().hide();

      // Re-check if there is a valid content
      // (in some cases, ajax response can contain various elements or plain text)
      if (!slide.$content.length) {
        slide.$content = slide.$slide
          .wrapInner("<div></div>")
          .children()
          .first();
      }

      slide.$content.addClass("fancybox-content");

      slide.$slide.addClass("fancybox-slide--" + slide.contentType);

      self.afterLoad(slide);
    },

    // Display error message
    // =====================

    setError: function (slide) {
      slide.hasError = true;

      slide.$slide
        .trigger("onReset")
        .removeClass("fancybox-slide--" + slide.contentType)
        .addClass("fancybox-slide--error");

      slide.contentType = "html";

      this.setContent(slide, this.translate(slide, slide.opts.errorTpl));

      if (slide.pos === this.currPos) {
        this.isAnimating = false;
      }
    },

    // Show loading icon inside the slide
    // ==================================

    showLoading: function (slide) {
      var self = this;

      slide = slide || self.current;

      if (slide && !slide.$spinner) {
        slide.$spinner = $(self.translate(self, self.opts.spinnerTpl))
          .appendTo(slide.$slide)
          .hide()
          .fadeIn("fast");
      }
    },

    // Remove loading icon from the slide
    // ==================================

    hideLoading: function (slide) {
      var self = this;

      slide = slide || self.current;

      if (slide && slide.$spinner) {
        slide.$spinner.stop().remove();

        delete slide.$spinner;
      }
    },

    // Adjustments after slide content has been loaded
    // ===============================================

    afterLoad: function (slide) {
      var self = this;

      if (self.isClosing) {
        return;
      }

      slide.isLoading = false;
      slide.isLoaded = true;

      self.trigger("afterLoad", slide);

      self.hideLoading(slide);

      // Add small close button
      if (slide.opts.smallBtn && (!slide.$smallBtn || !slide.$smallBtn.length)) {
        slide.$smallBtn = $(self.translate(slide, slide.opts.btnTpl.smallBtn)).appendTo(slide.$content);
      }

      // Disable right click
      if (slide.opts.protect && slide.$content && !slide.hasError) {
        slide.$content.on("contextmenu.fb", function (e) {
          if (e.button == 2) {
            e.preventDefault();
          }

          return true;
        });

        // Add fake element on top of the image
        // This makes a bit harder for user to select image
        if (slide.type === "image") {
          $('<div class="fancybox-spaceball"></div>').appendTo(slide.$content);
        }
      }

      self.adjustCaption(slide);

      self.adjustLayout(slide);

      if (slide.pos === self.currPos) {
        self.updateCursor();
      }

      self.revealContent(slide);
    },

    // Prevent caption overlap,
    // fix css inconsistency across browsers
    // =====================================

    adjustCaption: function (slide) {
      var self = this,
        current = slide || self.current,
        caption = current.opts.caption,
        preventOverlap = current.opts.preventCaptionOverlap,
        $caption = self.$refs.caption,
        $clone,
        captionH = false;

      $caption.toggleClass("fancybox-caption--separate", preventOverlap);

      if (preventOverlap && caption && caption.length) {
        if (current.pos !== self.currPos) {
          $clone = $caption.clone().appendTo($caption.parent());

          $clone
            .children()
            .eq(0)
            .empty()
            .html(caption);

          captionH = $clone.outerHeight(true);

          $clone.empty().remove();
        } else if (self.$caption) {
          captionH = self.$caption.outerHeight(true);
        }

        current.$slide.css("padding-bottom", captionH || "");
      }
    },

    // Simple hack to fix inconsistency across browsers, described here (affects Edge, too):
    // https://bugzilla.mozilla.org/show_bug.cgi?id=748518
    // ====================================================================================

    adjustLayout: function (slide) {
      var self = this,
        current = slide || self.current,
        scrollHeight,
        marginBottom,
        inlinePadding,
        actualPadding;

      if (current.isLoaded && current.opts.disableLayoutFix !== true) {
        current.$content.css("margin-bottom", "");

        // If we would always set margin-bottom for the content,
        // then it would potentially break vertical align
        if (current.$content.outerHeight() > current.$slide.height() + 0.5) {
          inlinePadding = current.$slide[0].style["padding-bottom"];
          actualPadding = current.$slide.css("padding-bottom");

          if (parseFloat(actualPadding) > 0) {
            scrollHeight = current.$slide[0].scrollHeight;

            current.$slide.css("padding-bottom", 0);

            if (Math.abs(scrollHeight - current.$slide[0].scrollHeight) < 1) {
              marginBottom = actualPadding;
            }

            current.$slide.css("padding-bottom", inlinePadding);
          }
        }

        current.$content.css("margin-bottom", marginBottom);
      }
    },

    // Make content visible
    // This method is called right after content has been loaded or
    // user navigates gallery and transition should start
    // ============================================================

    revealContent: function (slide) {
      var self = this,
        $slide = slide.$slide,
        end = false,
        start = false,
        isMoved = self.isMoved(slide),
        isRevealed = slide.isRevealed,
        effect,
        effectClassName,
        duration,
        opacity;

      slide.isRevealed = true;

      effect = slide.opts[self.firstRun ? "animationEffect" : "transitionEffect"];
      duration = slide.opts[self.firstRun ? "animationDuration" : "transitionDuration"];

      duration = parseInt(slide.forcedDuration === undefined ? duration : slide.forcedDuration, 10);

      if (isMoved || slide.pos !== self.currPos || !duration) {
        effect = false;
      }

      // Check if can zoom
      if (effect === "zoom") {
        if (slide.pos === self.currPos && duration && slide.type === "image" && !slide.hasError && (start = self.getThumbPos(slide))) {
          end = self.getFitPos(slide);
        } else {
          effect = "fade";
        }
      }

      // Zoom animation
      // ==============
      if (effect === "zoom") {
        self.isAnimating = true;

        end.scaleX = end.width / start.width;
        end.scaleY = end.height / start.height;

        // Check if we need to animate opacity
        opacity = slide.opts.zoomOpacity;

        if (opacity == "auto") {
          opacity = Math.abs(slide.width / slide.height - start.width / start.height) > 0.1;
        }

        if (opacity) {
          start.opacity = 0.1;
          end.opacity = 1;
        }

        // Draw image at start position
        $.fancybox.setTranslate(slide.$content.removeClass("fancybox-is-hidden"), start);

        forceRedraw(slide.$content);

        // Start animation
        $.fancybox.animate(slide.$content, end, duration, function () {
          self.isAnimating = false;

          self.complete();
        });

        return;
      }

      self.updateSlide(slide);

      // Simply show content if no effect
      // ================================
      if (!effect) {
        slide.$content.removeClass("fancybox-is-hidden");

        if (!isRevealed && isMoved && slide.type === "image" && !slide.hasError) {
          slide.$content.hide().fadeIn("fast");
        }

        if (slide.pos === self.currPos) {
          self.complete();
        }

        return;
      }

      // Prepare for CSS transiton
      // =========================
      $.fancybox.stop($slide);

      //effectClassName = "fancybox-animated fancybox-slide--" + (slide.pos >= self.prevPos ? "next" : "previous") + " fancybox-fx-" + effect;
      effectClassName = "fancybox-slide--" + (slide.pos >= self.prevPos ? "next" : "previous") + " fancybox-animated fancybox-fx-" + effect;

      $slide.addClass(effectClassName).removeClass("fancybox-slide--current"); //.addClass(effectClassName);

      slide.$content.removeClass("fancybox-is-hidden");

      // Force reflow
      forceRedraw($slide);

      if (slide.type !== "image") {
        slide.$content.hide().show(0);
      }

      $.fancybox.animate(
        $slide,
        "fancybox-slide--current",
        duration,
        function () {
          $slide.removeClass(effectClassName).css({
            transform: "",
            opacity: ""
          });

          if (slide.pos === self.currPos) {
            self.complete();
          }
        },
        true
      );
    },

    // Check if we can and have to zoom from thumbnail
    //================================================

    getThumbPos: function (slide) {
      var rez = false,
        $thumb = slide.$thumb,
        thumbPos,
        btw,
        brw,
        bbw,
        blw;

      if (!$thumb || !inViewport($thumb[0])) {
        return false;
      }

      thumbPos = $.fancybox.getTranslate($thumb);

      btw = parseFloat($thumb.css("border-top-width") || 0);
      brw = parseFloat($thumb.css("border-right-width") || 0);
      bbw = parseFloat($thumb.css("border-bottom-width") || 0);
      blw = parseFloat($thumb.css("border-left-width") || 0);

      rez = {
        top: thumbPos.top + btw,
        left: thumbPos.left + blw,
        width: thumbPos.width - brw - blw,
        height: thumbPos.height - btw - bbw,
        scaleX: 1,
        scaleY: 1
      };

      return thumbPos.width > 0 && thumbPos.height > 0 ? rez : false;
    },

    // Final adjustments after current gallery item is moved to position
    // and it`s content is loaded
    // ==================================================================

    complete: function () {
      var self = this,
        current = self.current,
        slides = {},
        $el;

      if (self.isMoved() || !current.isLoaded) {
        return;
      }

      if (!current.isComplete) {
        current.isComplete = true;

        current.$slide.siblings().trigger("onReset");

        self.preload("inline");

        // Trigger any CSS transiton inside the slide
        forceRedraw(current.$slide);

        current.$slide.addClass("fancybox-slide--complete");

        // Remove unnecessary slides
        $.each(self.slides, function (key, slide) {
          if (slide.pos >= self.currPos - 1 && slide.pos <= self.currPos + 1) {
            slides[slide.pos] = slide;
          } else if (slide) {
            $.fancybox.stop(slide.$slide);

            slide.$slide.off().remove();
          }
        });

        self.slides = slides;
      }

      self.isAnimating = false;

      self.updateCursor();

      self.trigger("afterShow");

      // Autoplay first html5 video/audio
      if (!!current.opts.video.autoStart) {
        current.$slide
          .find("video,audio")
          .filter(":visible:first")
          .trigger("play")
          .one("ended", function () {
            if (Document.exitFullscreen) {
              Document.exitFullscreen();
            } else if (this.webkitExitFullscreen) {
              this.webkitExitFullscreen();
            }

            self.next();
          });
      }

      // Try to focus on the first focusable element
      if (current.opts.autoFocus && current.contentType === "html") {
        // Look for the first input with autofocus attribute
        $el = current.$content.find("input[autofocus]:enabled:visible:first");

        if ($el.length) {
          $el.trigger("focus");
        } else {
          self.focus(null, true);
        }
      }

      // Avoid jumping
      current.$slide.scrollTop(0).scrollLeft(0);
    },

    // Preload next and previous slides
    // ================================

    preload: function (type) {
      var self = this,
        prev,
        next;

      if (self.group.length < 2) {
        return;
      }

      next = self.slides[self.currPos + 1];
      prev = self.slides[self.currPos - 1];

      if (prev && prev.type === type) {
        self.loadSlide(prev);
      }

      if (next && next.type === type) {
        self.loadSlide(next);
      }
    },

    // Try to find and focus on the first focusable element
    // ====================================================

    focus: function (e, firstRun) {
      var self = this,
        focusableStr = [
          "a[href]",
          "area[href]",
          'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',
          "select:not([disabled]):not([aria-hidden])",
          "textarea:not([disabled]):not([aria-hidden])",
          "button:not([disabled]):not([aria-hidden])",
          "iframe",
          "object",
          "embed",
          "video",
          "audio",
          "[contenteditable]",
          '[tabindex]:not([tabindex^="-"])'
        ].join(","),
        focusableItems,
        focusedItemIndex;

      if (self.isClosing) {
        return;
      }

      if (e || !self.current || !self.current.isComplete) {
        // Focus on any element inside fancybox
        focusableItems = self.$refs.container.find("*:visible");
      } else {
        // Focus inside current slide
        focusableItems = self.current.$slide.find("*:visible" + (firstRun ? ":not(.fancybox-close-small)" : ""));
      }

      focusableItems = focusableItems.filter(focusableStr).filter(function () {
        return $(this).css("visibility") !== "hidden" && !$(this).hasClass("disabled");
      });

      if (focusableItems.length) {
        focusedItemIndex = focusableItems.index(document.activeElement);

        if (e && e.shiftKey) {
          // Back tab
          if (focusedItemIndex < 0 || focusedItemIndex == 0) {
            e.preventDefault();

            focusableItems.eq(focusableItems.length - 1).trigger("focus");
          }
        } else {
          // Outside or Forward tab
          if (focusedItemIndex < 0 || focusedItemIndex == focusableItems.length - 1) {
            if (e) {
              e.preventDefault();
            }

            focusableItems.eq(0).trigger("focus");
          }
        }
      } else {
        self.$refs.container.trigger("focus");
      }
    },

    // Activates current instance - brings container to the front and enables keyboard,
    // notifies other instances about deactivating
    // =================================================================================

    activate: function () {
      var self = this;

      // Deactivate all instances
      $(".fancybox-container").each(function () {
        var instance = $(this).data("FancyBox");

        // Skip self and closing instances
        if (instance && instance.id !== self.id && !instance.isClosing) {
          instance.trigger("onDeactivate");

          instance.removeEvents();

          instance.isVisible = false;
        }
      });

      self.isVisible = true;

      if (self.current || self.isIdle) {
        self.update();

        self.updateControls();
      }

      self.trigger("onActivate");

      self.addEvents();
    },

    // Start closing procedure
    // This will start "zoom-out" animation if needed and clean everything up afterwards
    // =================================================================================

    close: function (e, d) {
      var self = this,
        current = self.current,
        effect,
        duration,
        $content,
        domRect,
        opacity,
        start,
        end;

      var done = function () {
        self.cleanUp(e);
      };

      if (self.isClosing) {
        return false;
      }

      self.isClosing = true;

      // If beforeClose callback prevents closing, make sure content is centered
      if (self.trigger("beforeClose", e) === false) {
        self.isClosing = false;

        requestAFrame(function () {
          self.update();
        });

        return false;
      }

      // Remove all events
      // If there are multiple instances, they will be set again by "activate" method
      self.removeEvents();

      $content = current.$content;
      effect = current.opts.animationEffect;
      duration = $.isNumeric(d) ? d : effect ? current.opts.animationDuration : 0;

      current.$slide.removeClass("fancybox-slide--complete fancybox-slide--next fancybox-slide--previous fancybox-animated");

      if (e !== true) {
        $.fancybox.stop(current.$slide);
      } else {
        effect = false;
      }

      // Remove other slides
      current.$slide
        .siblings()
        .trigger("onReset")
        .remove();

      // Trigger animations
      if (duration) {
        self.$refs.container
          .removeClass("fancybox-is-open")
          .addClass("fancybox-is-closing")
          .css("transition-duration", duration + "ms");
      }

      // Clean up
      self.hideLoading(current);

      self.hideControls(true);

      self.updateCursor();

      // Check if possible to zoom-out
      if (
        effect === "zoom" &&
        !($content && duration && current.type === "image" && !self.isMoved() && !current.hasError && (end = self.getThumbPos(current)))
      ) {
        effect = "fade";
      }

      if (effect === "zoom") {
        $.fancybox.stop($content);

        domRect = $.fancybox.getTranslate($content);

        start = {
          top: domRect.top,
          left: domRect.left,
          scaleX: domRect.width / end.width,
          scaleY: domRect.height / end.height,
          width: end.width,
          height: end.height
        };

        // Check if we need to animate opacity
        opacity = current.opts.zoomOpacity;

        if (opacity == "auto") {
          opacity = Math.abs(current.width / current.height - end.width / end.height) > 0.1;
        }

        if (opacity) {
          end.opacity = 0;
        }

        $.fancybox.setTranslate($content, start);

        forceRedraw($content);

        $.fancybox.animate($content, end, duration, done);

        return true;
      }

      if (effect && duration) {
        $.fancybox.animate(
          current.$slide.addClass("fancybox-slide--previous").removeClass("fancybox-slide--current"),
          "fancybox-animated fancybox-fx-" + effect,
          duration,
          done
        );
      } else {
        // If skip animation
        if (e === true) {
          setTimeout(done, duration);
        } else {
          done();
        }
      }

      return true;
    },

    // Final adjustments after removing the instance
    // =============================================

    cleanUp: function (e) {
      var self = this,
        instance,
        $focus = self.current.opts.$orig,
        x,
        y;

      self.current.$slide.trigger("onReset");

      self.$refs.container.empty().remove();

      self.trigger("afterClose", e);

      // Place back focus
      if (!!self.current.opts.backFocus) {
        if (!$focus || !$focus.length || !$focus.is(":visible")) {
          $focus = self.$trigger;
        }

        if ($focus && $focus.length) {
          x = window.scrollX;
          y = window.scrollY;

          $focus.trigger("focus");

          $("html, body")
            .scrollTop(y)
            .scrollLeft(x);
        }
      }

      self.current = null;

      // Check if there are other instances
      instance = $.fancybox.getInstance();

      if (instance) {
        instance.activate();
      } else {
        $("body").removeClass("fancybox-active compensate-for-scrollbar");

        $("#fancybox-style-noscroll").remove();
      }
    },

    // Call callback and trigger an event
    // ==================================

    trigger: function (name, slide) {
      var args = Array.prototype.slice.call(arguments, 1),
        self = this,
        obj = slide && slide.opts ? slide : self.current,
        rez;

      if (obj) {
        args.unshift(obj);
      } else {
        obj = self;
      }

      args.unshift(self);

      if ($.isFunction(obj.opts[name])) {
        rez = obj.opts[name].apply(obj, args);
      }

      if (rez === false) {
        return rez;
      }

      if (name === "afterClose" || !self.$refs) {
        $D.trigger(name + ".fb", args);
      } else {
        self.$refs.container.trigger(name + ".fb", args);
      }
    },

    // Update infobar values, navigation button states and reveal caption
    // ==================================================================

    updateControls: function () {
      var self = this,
        current = self.current,
        index = current.index,
        $container = self.$refs.container,
        $caption = self.$refs.caption,
        caption = current.opts.caption;

      // Recalculate content dimensions
      current.$slide.trigger("refresh");

      // Set caption
      if (caption && caption.length) {
        self.$caption = $caption;

        $caption
          .children()
          .eq(0)
          .html(caption);
      } else {
        self.$caption = null;
      }

      if (!self.hasHiddenControls && !self.isIdle) {
        self.showControls();
      }

      // Update info and navigation elements
      $container.find("[data-fancybox-count]").html(self.group.length);
      $container.find("[data-fancybox-index]").html(index + 1);

      $container.find("[data-fancybox-prev]").prop("disabled", !current.opts.loop && index <= 0);
      $container.find("[data-fancybox-next]").prop("disabled", !current.opts.loop && index >= self.group.length - 1);

      if (current.type === "image") {
        // Re-enable buttons; update download button source
        $container
          .find("[data-fancybox-zoom]")
          .show()
          .end()
          .find("[data-fancybox-download]")
          .attr("href", current.opts.image.src || current.src)
          .show();
      } else if (current.opts.toolbar) {
        $container.find("[data-fancybox-download],[data-fancybox-zoom]").hide();
      }

      // Make sure focus is not on disabled button/element
      if ($(document.activeElement).is(":hidden,[disabled]")) {
        self.$refs.container.trigger("focus");
      }
    },

    // Hide toolbar and caption
    // ========================

    hideControls: function (andCaption) {
      var self = this,
        arr = ["infobar", "toolbar", "nav"];

      if (andCaption || !self.current.opts.preventCaptionOverlap) {
        arr.push("caption");
      }

      this.$refs.container.removeClass(
        arr
        .map(function (i) {
          return "fancybox-show-" + i;
        })
        .join(" ")
      );

      this.hasHiddenControls = true;
    },

    showControls: function () {
      var self = this,
        opts = self.current ? self.current.opts : self.opts,
        $container = self.$refs.container;

      self.hasHiddenControls = false;
      self.idleSecondsCounter = 0;

      $container
        .toggleClass("fancybox-show-toolbar", !!(opts.toolbar && opts.buttons))
        .toggleClass("fancybox-show-infobar", !!(opts.infobar && self.group.length > 1))
        .toggleClass("fancybox-show-caption", !!self.$caption)
        .toggleClass("fancybox-show-nav", !!(opts.arrows && self.group.length > 1))
        .toggleClass("fancybox-is-modal", !!opts.modal);
    },

    // Toggle toolbar and caption
    // ==========================

    toggleControls: function () {
      if (this.hasHiddenControls) {
        this.showControls();
      } else {
        this.hideControls();
      }
    }
  });

  $.fancybox = {
    version: "3.5.7",
    defaults: defaults,

    // Get current instance and execute a command.
    //
    // Examples of usage:
    //
    //   $instance = $.fancybox.getInstance();
    //   $.fancybox.getInstance().jumpTo( 1 );
    //   $.fancybox.getInstance( 'jumpTo', 1 );
    //   $.fancybox.getInstance( function() {
    //       console.info( this.currIndex );
    //   });
    // ======================================================

    getInstance: function (command) {
      var instance = $('.fancybox-container:not(".fancybox-is-closing"):last').data("FancyBox"),
        args = Array.prototype.slice.call(arguments, 1);

      if (instance instanceof FancyBox) {
        if ($.type(command) === "string") {
          instance[command].apply(instance, args);
        } else if ($.type(command) === "function") {
          command.apply(instance, args);
        }

        return instance;
      }

      return false;
    },

    // Create new instance
    // ===================

    open: function (items, opts, index) {
      return new FancyBox(items, opts, index);
    },

    // Close current or all instances
    // ==============================

    close: function (all) {
      var instance = this.getInstance();

      if (instance) {
        instance.close();

        // Try to find and close next instance
        if (all === true) {
          this.close(all);
        }
      }
    },

    // Close all instances and unbind all events
    // =========================================

    destroy: function () {
      this.close(true);

      $D.add("body").off("click.fb-start", "**");
    },

    // Try to detect mobile devices
    // ============================

    isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),

    // Detect if 'translate3d' support is available
    // ============================================

    use3d: (function () {
      var div = document.createElement("div");

      return (
        window.getComputedStyle &&
        window.getComputedStyle(div) &&
        window.getComputedStyle(div).getPropertyValue("transform") &&
        !(document.documentMode && document.documentMode < 11)
      );
    })(),

    // Helper function to get current visual state of an element
    // returns array[ top, left, horizontal-scale, vertical-scale, opacity ]
    // =====================================================================

    getTranslate: function ($el) {
      var domRect;

      if (!$el || !$el.length) {
        return false;
      }

      domRect = $el[0].getBoundingClientRect();

      return {
        top: domRect.top || 0,
        left: domRect.left || 0,
        width: domRect.width,
        height: domRect.height,
        opacity: parseFloat($el.css("opacity"))
      };
    },

    // Shortcut for setting "translate3d" properties for element
    // Can set be used to set opacity, too
    // ========================================================

    setTranslate: function ($el, props) {
      var str = "",
        css = {};

      if (!$el || !props) {
        return;
      }

      if (props.left !== undefined || props.top !== undefined) {
        str =
          (props.left === undefined ? $el.position().left : props.left) +
          "px, " +
          (props.top === undefined ? $el.position().top : props.top) +
          "px";

        if (this.use3d) {
          str = "translate3d(" + str + ", 0px)";
        } else {
          str = "translate(" + str + ")";
        }
      }

      if (props.scaleX !== undefined && props.scaleY !== undefined) {
        str += " scale(" + props.scaleX + ", " + props.scaleY + ")";
      } else if (props.scaleX !== undefined) {
        str += " scaleX(" + props.scaleX + ")";
      }

      if (str.length) {
        css.transform = str;
      }

      if (props.opacity !== undefined) {
        css.opacity = props.opacity;
      }

      if (props.width !== undefined) {
        css.width = props.width;
      }

      if (props.height !== undefined) {
        css.height = props.height;
      }

      return $el.css(css);
    },

    // Simple CSS transition handler
    // =============================

    animate: function ($el, to, duration, callback, leaveAnimationName) {
      var self = this,
        from;

      if ($.isFunction(duration)) {
        callback = duration;
        duration = null;
      }

      self.stop($el);

      from = self.getTranslate($el);

      $el.on(transitionEnd, function (e) {
        // Skip events from child elements and z-index change
        if (e && e.originalEvent && (!$el.is(e.originalEvent.target) || e.originalEvent.propertyName == "z-index")) {
          return;
        }

        self.stop($el);

        if ($.isNumeric(duration)) {
          $el.css("transition-duration", "");
        }

        if ($.isPlainObject(to)) {
          if (to.scaleX !== undefined && to.scaleY !== undefined) {
            self.setTranslate($el, {
              top: to.top,
              left: to.left,
              width: from.width * to.scaleX,
              height: from.height * to.scaleY,
              scaleX: 1,
              scaleY: 1
            });
          }
        } else if (leaveAnimationName !== true) {
          $el.removeClass(to);
        }

        if ($.isFunction(callback)) {
          callback(e);
        }
      });

      if ($.isNumeric(duration)) {
        $el.css("transition-duration", duration + "ms");
      }

      // Start animation by changing CSS properties or class name
      if ($.isPlainObject(to)) {
        if (to.scaleX !== undefined && to.scaleY !== undefined) {
          delete to.width;
          delete to.height;

          if ($el.parent().hasClass("fancybox-slide--image")) {
            $el.parent().addClass("fancybox-is-scaling");
          }
        }

        $.fancybox.setTranslate($el, to);
      } else {
        $el.addClass(to);
      }

      // Make sure that `transitionend` callback gets fired
      $el.data(
        "timer",
        setTimeout(function () {
          $el.trigger(transitionEnd);
        }, duration + 33)
      );
    },

    stop: function ($el, callCallback) {
      if ($el && $el.length) {
        clearTimeout($el.data("timer"));

        if (callCallback) {
          $el.trigger(transitionEnd);
        }

        $el.off(transitionEnd).css("transition-duration", "");

        $el.parent().removeClass("fancybox-is-scaling");
      }
    }
  };

  // Default click handler for "fancyboxed" links
  // ============================================

  function _run(e, opts) {
    var items = [],
      index = 0,
      $target,
      value,
      instance;

    // Avoid opening multiple times
    if (e && e.isDefaultPrevented()) {
      return;
    }

    e.preventDefault();

    opts = opts || {};

    if (e && e.data) {
      opts = mergeOpts(e.data.options, opts);
    }

    $target = opts.$target || $(e.currentTarget).trigger("blur");
    instance = $.fancybox.getInstance();

    if (instance && instance.$trigger && instance.$trigger.is($target)) {
      return;
    }

    if (opts.selector) {
      items = $(opts.selector);
    } else {
      // Get all related items and find index for clicked one
      value = $target.attr("data-fancybox") || "";

      if (value) {
        items = e.data ? e.data.items : [];
        items = items.length ? items.filter('[data-fancybox="' + value + '"]') : $('[data-fancybox="' + value + '"]');
      } else {
        items = [$target];
      }
    }

    index = $(items).index($target);

    // Sometimes current item can not be found
    if (index < 0) {
      index = 0;
    }

    instance = $.fancybox.open(items, opts, index);

    // Save last active element
    instance.$trigger = $target;
  }

  // Create a jQuery plugin
  // ======================

  $.fn.fancybox = function (options) {
    var selector;

    options = options || {};
    selector = options.selector || false;

    if (selector) {
      // Use body element instead of document so it executes first
      $("body")
        .off("click.fb-start", selector)
        .on("click.fb-start", selector, {
          options: options
        }, _run);
    } else {
      this.off("click.fb-start").on(
        "click.fb-start", {
          items: this,
          options: options
        },
        _run
      );
    }

    return this;
  };

  // Self initializing plugin for all elements having `data-fancybox` attribute
  // ==========================================================================

  $D.on("click.fb-start", "[data-fancybox]", _run);

  // Enable "trigger elements"
  // =========================

  $D.on("click.fb-start", "[data-fancybox-trigger]", function (e) {
    $('[data-fancybox="' + $(this).attr("data-fancybox-trigger") + '"]')
      .eq($(this).attr("data-fancybox-index") || 0)
      .trigger("click.fb-start", {
        $trigger: $(this)
      });
  });

  // Track focus event for better accessibility styling
  // ==================================================
  (function () {
    var buttonStr = ".fancybox-button",
      focusStr = "fancybox-focus",
      $pressed = null;

    $D.on("mousedown mouseup focus blur", buttonStr, function (e) {
      switch (e.type) {
        case "mousedown":
          $pressed = $(this);
          break;
        case "mouseup":
          $pressed = null;
          break;
        case "focusin":
          $(buttonStr).removeClass(focusStr);

          if (!$(this).is($pressed) && !$(this).is("[disabled]")) {
            $(this).addClass(focusStr);
          }
          break;
        case "focusout":
          $(buttonStr).removeClass(focusStr);
          break;
      }
    });
  })();
})(window, document, jQuery);
// ==========================================================================
//
// Media
// Adds additional media type support
//
// ==========================================================================
(function ($) {
  "use strict";

  // Object containing properties for each media type
  var defaults = {
    youtube: {
      matcher: /(youtube\.com|youtu\.be|youtube\-nocookie\.com)\/(watch\?(.*&)?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*))(.*)/i,
      params: {
        autoplay: 1,
        autohide: 1,
        fs: 1,
        rel: 0,
        hd: 1,
        wmode: "transparent",
        enablejsapi: 1,
        html5: 1
      },
      paramPlace: 8,
      type: "iframe",
      url: "https://www.youtube-nocookie.com/embed/$4",
      thumb: "https://img.youtube.com/vi/$4/hqdefault.jpg"
    },

    vimeo: {
      matcher: /^.+vimeo.com\/(.*\/)?([\d]+)(.*)?/,
      params: {
        autoplay: 1,
        hd: 1,
        show_title: 1,
        show_byline: 1,
        show_portrait: 0,
        fullscreen: 1
      },
      paramPlace: 3,
      type: "iframe",
      url: "//player.vimeo.com/video/$2"
    },

    instagram: {
      matcher: /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i,
      type: "image",
      url: "//$1/p/$2/media/?size=l"
    },

    // Examples:
    // http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16
    // https://www.google.com/maps/@37.7852006,-122.4146355,14.65z
    // https://www.google.com/maps/@52.2111123,2.9237542,6.61z?hl=en
    // https://www.google.com/maps/place/Googleplex/@37.4220041,-122.0833494,17z/data=!4m5!3m4!1s0x0:0x6c296c66619367e0!8m2!3d37.4219998!4d-122.0840572
    gmap_place: {
      matcher: /(maps\.)?google\.([a-z]{2,3}(\.[a-z]{2})?)\/(((maps\/(place\/(.*)\/)?\@(.*),(\d+.?\d+?)z))|(\?ll=))(.*)?/i,
      type: "iframe",
      url: function (rez) {
        return (
          "//maps.google." +
          rez[2] +
          "/?ll=" +
          (rez[9] ? rez[9] + "&z=" + Math.floor(rez[10]) + (rez[12] ? rez[12].replace(/^\//, "&") : "") : rez[12] + "").replace(/\?/, "&") +
          "&output=" +
          (rez[12] && rez[12].indexOf("layer=c") > 0 ? "svembed" : "embed")
        );
      }
    },

    // Examples:
    // https://www.google.com/maps/search/Empire+State+Building/
    // https://www.google.com/maps/search/?api=1&query=centurylink+field
    // https://www.google.com/maps/search/?api=1&query=47.5951518,-122.3316393
    gmap_search: {
      matcher: /(maps\.)?google\.([a-z]{2,3}(\.[a-z]{2})?)\/(maps\/search\/)(.*)/i,
      type: "iframe",
      url: function (rez) {
        return "//maps.google." + rez[2] + "/maps?q=" + rez[5].replace("query=", "q=").replace("api=1", "") + "&output=embed";
      }
    }
  };

  // Formats matching url to final form
  var format = function (url, rez, params) {
    if (!url) {
      return;
    }

    params = params || "";

    if ($.type(params) === "object") {
      params = $.param(params, true);
    }

    $.each(rez, function (key, value) {
      url = url.replace("$" + key, value || "");
    });

    if (params.length) {
      url += (url.indexOf("?") > 0 ? "&" : "?") + params;
    }

    return url;
  };

  $(document).on("objectNeedsType.fb", function (e, instance, item) {
    var url = item.src || "",
      type = false,
      media,
      thumb,
      rez,
      params,
      urlParams,
      paramObj,
      provider;

    media = $.extend(true, {}, defaults, item.opts.media);

    // Look for any matching media type
    $.each(media, function (providerName, providerOpts) {
      rez = url.match(providerOpts.matcher);

      if (!rez) {
        return;
      }

      type = providerOpts.type;
      provider = providerName;
      paramObj = {};

      if (providerOpts.paramPlace && rez[providerOpts.paramPlace]) {
        urlParams = rez[providerOpts.paramPlace];

        if (urlParams[0] == "?") {
          urlParams = urlParams.substring(1);
        }

        urlParams = urlParams.split("&");

        for (var m = 0; m < urlParams.length; ++m) {
          var p = urlParams[m].split("=", 2);

          if (p.length == 2) {
            paramObj[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
          }
        }
      }

      params = $.extend(true, {}, providerOpts.params, item.opts[providerName], paramObj);

      url =
        $.type(providerOpts.url) === "function" ? providerOpts.url.call(this, rez, params, item) : format(providerOpts.url, rez, params);

      thumb =
        $.type(providerOpts.thumb) === "function" ? providerOpts.thumb.call(this, rez, params, item) : format(providerOpts.thumb, rez);

      if (providerName === "youtube") {
        url = url.replace(/&t=((\d+)m)?(\d+)s/, function (match, p1, m, s) {
          return "&start=" + ((m ? parseInt(m, 10) * 60 : 0) + parseInt(s, 10));
        });
      } else if (providerName === "vimeo") {
        url = url.replace("&%23", "#");
      }

      return false;
    });

    // If it is found, then change content type and update the url

    if (type) {
      if (!item.opts.thumb && !(item.opts.$thumb && item.opts.$thumb.length)) {
        item.opts.thumb = thumb;
      }

      if (type === "iframe") {
        item.opts = $.extend(true, item.opts, {
          iframe: {
            preload: false,
            attr: {
              scrolling: "no"
            }
          }
        });
      }

      $.extend(item, {
        type: type,
        src: url,
        origSrc: item.src,
        contentSource: provider,
        contentType: type === "image" ? "image" : provider == "gmap_place" || provider == "gmap_search" ? "map" : "video"
      });
    } else if (url) {
      item.type = item.opts.defaultType;
    }
  });

  // Load YouTube/Video API on request to detect when video finished playing
  var VideoAPILoader = {
    youtube: {
      src: "https://www.youtube.com/iframe_api",
      class: "YT",
      loading: false,
      loaded: false
    },

    vimeo: {
      src: "https://player.vimeo.com/api/player.js",
      class: "Vimeo",
      loading: false,
      loaded: false
    },

    load: function (vendor) {
      var _this = this,
        script;

      if (this[vendor].loaded) {
        setTimeout(function () {
          _this.done(vendor);
        });
        return;
      }

      if (this[vendor].loading) {
        return;
      }

      this[vendor].loading = true;

      script = document.createElement("script");
      script.type = "text/javascript";
      script.src = this[vendor].src;

      if (vendor === "youtube") {
        window.onYouTubeIframeAPIReady = function () {
          _this[vendor].loaded = true;
          _this.done(vendor);
        };
      } else {
        script.onload = function () {
          _this[vendor].loaded = true;
          _this.done(vendor);
        };
      }

      document.body.appendChild(script);
    },
    done: function (vendor) {
      var instance, $el, player;

      if (vendor === "youtube") {
        delete window.onYouTubeIframeAPIReady;
      }

      instance = $.fancybox.getInstance();

      if (instance) {
        $el = instance.current.$content.find("iframe");

        if (vendor === "youtube" && YT !== undefined && YT) {
          player = new YT.Player($el.attr("id"), {
            events: {
              onStateChange: function (e) {
                if (e.data == 0) {
                  instance.next();
                }
              }
            }
          });
        } else if (vendor === "vimeo" && Vimeo !== undefined && Vimeo) {
          player = new Vimeo.Player($el);

          player.on("ended", function () {
            instance.next();
          });
        }
      }
    }
  };

  $(document).on({
    "afterShow.fb": function (e, instance, current) {
      if (instance.group.length > 1 && (current.contentSource === "youtube" || current.contentSource === "vimeo")) {
        VideoAPILoader.load(current.contentSource);
      }
    }
  });
})(jQuery);
// ==========================================================================
//
// Guestures
// Adds touch guestures, handles click and tap events
//
// ==========================================================================
(function (window, document, $) {
  "use strict";

  var requestAFrame = (function () {
    return (
      window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      // if all else fails, use setTimeout
      function (callback) {
        return window.setTimeout(callback, 1000 / 60);
      }
    );
  })();

  var cancelAFrame = (function () {
    return (
      window.cancelAnimationFrame ||
      window.webkitCancelAnimationFrame ||
      window.mozCancelAnimationFrame ||
      window.oCancelAnimationFrame ||
      function (id) {
        window.clearTimeout(id);
      }
    );
  })();

  var getPointerXY = function (e) {
    var result = [];

    e = e.originalEvent || e || window.e;
    e = e.touches && e.touches.length ? e.touches : e.changedTouches && e.changedTouches.length ? e.changedTouches : [e];

    for (var key in e) {
      if (e[key].pageX) {
        result.push({
          x: e[key].pageX,
          y: e[key].pageY
        });
      } else if (e[key].clientX) {
        result.push({
          x: e[key].clientX,
          y: e[key].clientY
        });
      }
    }

    return result;
  };

  var distance = function (point2, point1, what) {
    if (!point1 || !point2) {
      return 0;
    }

    if (what === "x") {
      return point2.x - point1.x;
    } else if (what === "y") {
      return point2.y - point1.y;
    }

    return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
  };

  var isClickable = function ($el) {
    if (
      $el.is('a,area,button,[role="button"],input,label,select,summary,textarea,video,audio,iframe') ||
      $.isFunction($el.get(0).onclick) ||
      $el.data("selectable")
    ) {
      return true;
    }

    // Check for attributes like data-fancybox-next or data-fancybox-close
    for (var i = 0, atts = $el[0].attributes, n = atts.length; i < n; i++) {
      if (atts[i].nodeName.substr(0, 14) === "data-fancybox-") {
        return true;
      }
    }

    return false;
  };

  var hasScrollbars = function (el) {
    var overflowY = window.getComputedStyle(el)["overflow-y"],
      overflowX = window.getComputedStyle(el)["overflow-x"],
      vertical = (overflowY === "scroll" || overflowY === "auto") && el.scrollHeight > el.clientHeight,
      horizontal = (overflowX === "scroll" || overflowX === "auto") && el.scrollWidth > el.clientWidth;

    return vertical || horizontal;
  };

  var isScrollable = function ($el) {
    var rez = false;

    while (true) {
      rez = hasScrollbars($el.get(0));

      if (rez) {
        break;
      }

      $el = $el.parent();

      if (!$el.length || $el.hasClass("fancybox-stage") || $el.is("body")) {
        break;
      }
    }

    return rez;
  };

  var Guestures = function (instance) {
    var self = this;

    self.instance = instance;

    self.$bg = instance.$refs.bg;
    self.$stage = instance.$refs.stage;
    self.$container = instance.$refs.container;

    self.destroy();

    self.$container.on("touchstart.fb.touch mousedown.fb.touch", $.proxy(self, "ontouchstart"));
  };

  Guestures.prototype.destroy = function () {
    var self = this;

    self.$container.off(".fb.touch");

    $(document).off(".fb.touch");

    if (self.requestId) {
      cancelAFrame(self.requestId);
      self.requestId = null;
    }

    if (self.tapped) {
      clearTimeout(self.tapped);
      self.tapped = null;
    }
  };

  Guestures.prototype.ontouchstart = function (e) {
    var self = this,
      $target = $(e.target),
      instance = self.instance,
      current = instance.current,
      $slide = current.$slide,
      $content = current.$content,
      isTouchDevice = e.type == "touchstart";

    // Do not respond to both (touch and mouse) events
    if (isTouchDevice) {
      self.$container.off("mousedown.fb.touch");
    }

    // Ignore right click
    if (e.originalEvent && e.originalEvent.button == 2) {
      return;
    }

    // Ignore taping on links, buttons, input elements
    if (!$slide.length || !$target.length || isClickable($target) || isClickable($target.parent())) {
      return;
    }
    // Ignore clicks on the scrollbar
    if (!$target.is("img") && e.originalEvent.clientX > $target[0].clientWidth + $target.offset().left) {
      return;
    }

    // Ignore clicks while zooming or closing
    if (!current || instance.isAnimating || current.$slide.hasClass("fancybox-animated")) {
      e.stopPropagation();
      e.preventDefault();

      return;
    }

    self.realPoints = self.startPoints = getPointerXY(e);

    if (!self.startPoints.length) {
      return;
    }

    // Allow other scripts to catch touch event if "touch" is set to false
    if (current.touch) {
      e.stopPropagation();
    }

    self.startEvent = e;

    self.canTap = true;
    self.$target = $target;
    self.$content = $content;
    self.opts = current.opts.touch;

    self.isPanning = false;
    self.isSwiping = false;
    self.isZooming = false;
    self.isScrolling = false;
    self.canPan = instance.canPan();

    self.startTime = new Date().getTime();
    self.distanceX = self.distanceY = self.distance = 0;

    self.canvasWidth = Math.round($slide[0].clientWidth);
    self.canvasHeight = Math.round($slide[0].clientHeight);

    self.contentLastPos = null;
    self.contentStartPos = $.fancybox.getTranslate(self.$content) || {
      top: 0,
      left: 0
    };
    self.sliderStartPos = $.fancybox.getTranslate($slide);

    // Since position will be absolute, but we need to make it relative to the stage
    self.stagePos = $.fancybox.getTranslate(instance.$refs.stage);

    self.sliderStartPos.top -= self.stagePos.top;
    self.sliderStartPos.left -= self.stagePos.left;

    self.contentStartPos.top -= self.stagePos.top;
    self.contentStartPos.left -= self.stagePos.left;

    $(document)
      .off(".fb.touch")
      .on(isTouchDevice ? "touchend.fb.touch touchcancel.fb.touch" : "mouseup.fb.touch mouseleave.fb.touch", $.proxy(self, "ontouchend"))
      .on(isTouchDevice ? "touchmove.fb.touch" : "mousemove.fb.touch", $.proxy(self, "ontouchmove"));

    if ($.fancybox.isMobile) {
      document.addEventListener("scroll", self.onscroll, true);
    }

    // Skip if clicked outside the sliding area
    if (!(self.opts || self.canPan) || !($target.is(self.$stage) || self.$stage.find($target).length)) {
      if ($target.is(".fancybox-image")) {
        e.preventDefault();
      }

      if (!($.fancybox.isMobile && $target.parents(".fancybox-caption").length)) {
        return;
      }
    }

    self.isScrollable = isScrollable($target) || isScrollable($target.parent());

    // Check if element is scrollable and try to prevent default behavior (scrolling)
    if (!($.fancybox.isMobile && self.isScrollable)) {
      e.preventDefault();
    }

    // One finger or mouse click - swipe or pan an image
    if (self.startPoints.length === 1 || current.hasError) {
      if (self.canPan) {
        $.fancybox.stop(self.$content);

        self.isPanning = true;
      } else {
        self.isSwiping = true;
      }

      self.$container.addClass("fancybox-is-grabbing");
    }

    // Two fingers - zoom image
    if (self.startPoints.length === 2 && current.type === "image" && (current.isLoaded || current.$ghost)) {
      self.canTap = false;
      self.isSwiping = false;
      self.isPanning = false;

      self.isZooming = true;

      $.fancybox.stop(self.$content);

      self.centerPointStartX = (self.startPoints[0].x + self.startPoints[1].x) * 0.5 - $(window).scrollLeft();
      self.centerPointStartY = (self.startPoints[0].y + self.startPoints[1].y) * 0.5 - $(window).scrollTop();

      self.percentageOfImageAtPinchPointX = (self.centerPointStartX - self.contentStartPos.left) / self.contentStartPos.width;
      self.percentageOfImageAtPinchPointY = (self.centerPointStartY - self.contentStartPos.top) / self.contentStartPos.height;

      self.startDistanceBetweenFingers = distance(self.startPoints[0], self.startPoints[1]);
    }
  };

  Guestures.prototype.onscroll = function (e) {
    var self = this;

    self.isScrolling = true;

    document.removeEventListener("scroll", self.onscroll, true);
  };

  Guestures.prototype.ontouchmove = function (e) {
    var self = this;

    // Make sure user has not released over iframe or disabled element
    if (e.originalEvent.buttons !== undefined && e.originalEvent.buttons === 0) {
      self.ontouchend(e);
      return;
    }

    if (self.isScrolling) {
      self.canTap = false;
      return;
    }

    self.newPoints = getPointerXY(e);

    if (!(self.opts || self.canPan) || !self.newPoints.length || !self.newPoints.length) {
      return;
    }

    if (!(self.isSwiping && self.isSwiping === true)) {
      e.preventDefault();
    }

    self.distanceX = distance(self.newPoints[0], self.startPoints[0], "x");
    self.distanceY = distance(self.newPoints[0], self.startPoints[0], "y");

    self.distance = distance(self.newPoints[0], self.startPoints[0]);

    // Skip false ontouchmove events (Chrome)
    if (self.distance > 0) {
      if (self.isSwiping) {
        self.onSwipe(e);
      } else if (self.isPanning) {
        self.onPan();
      } else if (self.isZooming) {
        self.onZoom();
      }
    }
  };

  Guestures.prototype.onSwipe = function (e) {
    var self = this,
      instance = self.instance,
      swiping = self.isSwiping,
      left = self.sliderStartPos.left || 0,
      angle;

    // If direction is not yet determined
    if (swiping === true) {
      // We need at least 10px distance to correctly calculate an angle
      if (Math.abs(self.distance) > 10) {
        self.canTap = false;

        if (instance.group.length < 2 && self.opts.vertical) {
          self.isSwiping = "y";
        } else if (instance.isDragging || self.opts.vertical === false || (self.opts.vertical === "auto" && $(window).width() > 800)) {
          self.isSwiping = "x";
        } else {
          angle = Math.abs((Math.atan2(self.distanceY, self.distanceX) * 180) / Math.PI);

          self.isSwiping = angle > 45 && angle < 135 ? "y" : "x";
        }

        if (self.isSwiping === "y" && $.fancybox.isMobile && self.isScrollable) {
          self.isScrolling = true;

          return;
        }

        instance.isDragging = self.isSwiping;

        // Reset points to avoid jumping, because we dropped first swipes to calculate the angle
        self.startPoints = self.newPoints;

        $.each(instance.slides, function (index, slide) {
          var slidePos, stagePos;

          $.fancybox.stop(slide.$slide);

          slidePos = $.fancybox.getTranslate(slide.$slide);
          stagePos = $.fancybox.getTranslate(instance.$refs.stage);

          slide.$slide
            .css({
              transform: "",
              opacity: "",
              "transition-duration": ""
            })
            .removeClass("fancybox-animated")
            .removeClass(function (index, className) {
              return (className.match(/(^|\s)fancybox-fx-\S+/g) || []).join(" ");
            });

          if (slide.pos === instance.current.pos) {
            self.sliderStartPos.top = slidePos.top - stagePos.top;
            self.sliderStartPos.left = slidePos.left - stagePos.left;
          }

          $.fancybox.setTranslate(slide.$slide, {
            top: slidePos.top - stagePos.top,
            left: slidePos.left - stagePos.left
          });
        });

        // Stop slideshow
        if (instance.SlideShow && instance.SlideShow.isActive) {
          instance.SlideShow.stop();
        }
      }

      return;
    }

    // Sticky edges
    if (swiping == "x") {
      if (
        self.distanceX > 0 &&
        (self.instance.group.length < 2 || (self.instance.current.index === 0 && !self.instance.current.opts.loop))
      ) {
        left = left + Math.pow(self.distanceX, 0.8);
      } else if (
        self.distanceX < 0 &&
        (self.instance.group.length < 2 ||
          (self.instance.current.index === self.instance.group.length - 1 && !self.instance.current.opts.loop))
      ) {
        left = left - Math.pow(-self.distanceX, 0.8);
      } else {
        left = left + self.distanceX;
      }
    }

    self.sliderLastPos = {
      top: swiping == "x" ? 0 : self.sliderStartPos.top + self.distanceY,
      left: left
    };

    if (self.requestId) {
      cancelAFrame(self.requestId);

      self.requestId = null;
    }

    self.requestId = requestAFrame(function () {
      if (self.sliderLastPos) {
        $.each(self.instance.slides, function (index, slide) {
          var pos = slide.pos - self.instance.currPos;

          $.fancybox.setTranslate(slide.$slide, {
            top: self.sliderLastPos.top,
            left: self.sliderLastPos.left + pos * self.canvasWidth + pos * slide.opts.gutter
          });
        });

        self.$container.addClass("fancybox-is-sliding");
      }
    });
  };

  Guestures.prototype.onPan = function () {
    var self = this;

    // Prevent accidental movement (sometimes, when tapping casually, finger can move a bit)
    if (distance(self.newPoints[0], self.realPoints[0]) < ($.fancybox.isMobile ? 10 : 5)) {
      self.startPoints = self.newPoints;
      return;
    }

    self.canTap = false;

    self.contentLastPos = self.limitMovement();

    if (self.requestId) {
      cancelAFrame(self.requestId);
    }

    self.requestId = requestAFrame(function () {
      $.fancybox.setTranslate(self.$content, self.contentLastPos);
    });
  };

  // Make panning sticky to the edges
  Guestures.prototype.limitMovement = function () {
    var self = this;

    var canvasWidth = self.canvasWidth;
    var canvasHeight = self.canvasHeight;

    var distanceX = self.distanceX;
    var distanceY = self.distanceY;

    var contentStartPos = self.contentStartPos;

    var currentOffsetX = contentStartPos.left;
    var currentOffsetY = contentStartPos.top;

    var currentWidth = contentStartPos.width;
    var currentHeight = contentStartPos.height;

    var minTranslateX, minTranslateY, maxTranslateX, maxTranslateY, newOffsetX, newOffsetY;

    if (currentWidth > canvasWidth) {
      newOffsetX = currentOffsetX + distanceX;
    } else {
      newOffsetX = currentOffsetX;
    }

    newOffsetY = currentOffsetY + distanceY;

    // Slow down proportionally to traveled distance
    minTranslateX = Math.max(0, canvasWidth * 0.5 - currentWidth * 0.5);
    minTranslateY = Math.max(0, canvasHeight * 0.5 - currentHeight * 0.5);

    maxTranslateX = Math.min(canvasWidth - currentWidth, canvasWidth * 0.5 - currentWidth * 0.5);
    maxTranslateY = Math.min(canvasHeight - currentHeight, canvasHeight * 0.5 - currentHeight * 0.5);

    //   ->
    if (distanceX > 0 && newOffsetX > minTranslateX) {
      newOffsetX = minTranslateX - 1 + Math.pow(-minTranslateX + currentOffsetX + distanceX, 0.8) || 0;
    }

    //    <-
    if (distanceX < 0 && newOffsetX < maxTranslateX) {
      newOffsetX = maxTranslateX + 1 - Math.pow(maxTranslateX - currentOffsetX - distanceX, 0.8) || 0;
    }

    //   \/
    if (distanceY > 0 && newOffsetY > minTranslateY) {
      newOffsetY = minTranslateY - 1 + Math.pow(-minTranslateY + currentOffsetY + distanceY, 0.8) || 0;
    }

    //   /\
    if (distanceY < 0 && newOffsetY < maxTranslateY) {
      newOffsetY = maxTranslateY + 1 - Math.pow(maxTranslateY - currentOffsetY - distanceY, 0.8) || 0;
    }

    return {
      top: newOffsetY,
      left: newOffsetX
    };
  };

  Guestures.prototype.limitPosition = function (newOffsetX, newOffsetY, newWidth, newHeight) {
    var self = this;

    var canvasWidth = self.canvasWidth;
    var canvasHeight = self.canvasHeight;

    if (newWidth > canvasWidth) {
      newOffsetX = newOffsetX > 0 ? 0 : newOffsetX;
      newOffsetX = newOffsetX < canvasWidth - newWidth ? canvasWidth - newWidth : newOffsetX;
    } else {
      // Center horizontally
      newOffsetX = Math.max(0, canvasWidth / 2 - newWidth / 2);
    }

    if (newHeight > canvasHeight) {
      newOffsetY = newOffsetY > 0 ? 0 : newOffsetY;
      newOffsetY = newOffsetY < canvasHeight - newHeight ? canvasHeight - newHeight : newOffsetY;
    } else {
      // Center vertically
      newOffsetY = Math.max(0, canvasHeight / 2 - newHeight / 2);
    }

    return {
      top: newOffsetY,
      left: newOffsetX
    };
  };

  Guestures.prototype.onZoom = function () {
    var self = this;

	if ( typeof self.newPoints === 'undefined' || typeof self.newPoints[0] === 'undefined' || typeof self.newPoints[1] === 'undefined' ) return;

    // Calculate current distance between points to get pinch ratio and new width and height
    var contentStartPos = self.contentStartPos;

    var currentWidth = contentStartPos.width;
    var currentHeight = contentStartPos.height;

    var currentOffsetX = contentStartPos.left;
    var currentOffsetY = contentStartPos.top;

    var endDistanceBetweenFingers = distance(self.newPoints[0], self.newPoints[1]);

    var pinchRatio = endDistanceBetweenFingers / self.startDistanceBetweenFingers;

    var newWidth = Math.floor(currentWidth * pinchRatio);
    var newHeight = Math.floor(currentHeight * pinchRatio);

    // This is the translation due to pinch-zooming
    var translateFromZoomingX = (currentWidth - newWidth) * self.percentageOfImageAtPinchPointX;
    var translateFromZoomingY = (currentHeight - newHeight) * self.percentageOfImageAtPinchPointY;

    // Point between the two touches
    var centerPointEndX = (self.newPoints[0].x + self.newPoints[1].x) / 2 - $(window).scrollLeft();
    var centerPointEndY = (self.newPoints[0].y + self.newPoints[1].y) / 2 - $(window).scrollTop();

    // And this is the translation due to translation of the centerpoint
    // between the two fingers
    var translateFromTranslatingX = centerPointEndX - self.centerPointStartX;
    var translateFromTranslatingY = centerPointEndY - self.centerPointStartY;

    // The new offset is the old/current one plus the total translation
    var newOffsetX = currentOffsetX + (translateFromZoomingX + translateFromTranslatingX);
    var newOffsetY = currentOffsetY + (translateFromZoomingY + translateFromTranslatingY);

    var newPos = {
      top: newOffsetY,
      left: newOffsetX,
      scaleX: pinchRatio,
      scaleY: pinchRatio
    };

    self.canTap = false;

    self.newWidth = newWidth;
    self.newHeight = newHeight;

    self.contentLastPos = newPos;

    if (self.requestId) {
      cancelAFrame(self.requestId);
    }

    self.requestId = requestAFrame(function () {
      $.fancybox.setTranslate(self.$content, self.contentLastPos);
    });
  };

  Guestures.prototype.ontouchend = function (e) {
    var self = this;

    var swiping = self.isSwiping;
    var panning = self.isPanning;
    var zooming = self.isZooming;
    var scrolling = self.isScrolling;

    self.endPoints = getPointerXY(e);
    self.dMs = Math.max(new Date().getTime() - self.startTime, 1);

    self.$container.removeClass("fancybox-is-grabbing");

    $(document).off(".fb.touch");

    document.removeEventListener("scroll", self.onscroll, true);

    if (self.requestId) {
      cancelAFrame(self.requestId);

      self.requestId = null;
    }

    self.isSwiping = false;
    self.isPanning = false;
    self.isZooming = false;
    self.isScrolling = false;

    self.instance.isDragging = false;

    if (self.canTap) {
      return self.onTap(e);
    }

    self.speed = 100;

    // Speed in px/ms
    self.velocityX = (self.distanceX / self.dMs) * 0.5;
    self.velocityY = (self.distanceY / self.dMs) * 0.5;

    if (panning) {
      self.endPanning();
    } else if (zooming) {
      self.endZooming();
    } else {
      self.endSwiping(swiping, scrolling);
    }

    return;
  };

  Guestures.prototype.endSwiping = function (swiping, scrolling) {
    var self = this,
      ret = false,
      len = self.instance.group.length,
      distanceX = Math.abs(self.distanceX),
      canAdvance = swiping == "x" && len > 1 && ((self.dMs > 130 && distanceX > 10) || distanceX > 50),
      speedX = 300;

    self.sliderLastPos = null;

    // Close if swiped vertically / navigate if horizontally
    if (swiping == "y" && !scrolling && Math.abs(self.distanceY) > 50) {
      // Continue vertical movement
      $.fancybox.animate(
        self.instance.current.$slide, {
          top: self.sliderStartPos.top + self.distanceY + self.velocityY * 150,
          opacity: 0
        },
        200
      );
      ret = self.instance.close(true, 250);
    } else if (canAdvance && self.distanceX > 0) {
      ret = self.instance.previous(speedX);
    } else if (canAdvance && self.distanceX < 0) {
      ret = self.instance.next(speedX);
    }

    if (ret === false && (swiping == "x" || swiping == "y")) {
      self.instance.centerSlide(200);
    }

    self.$container.removeClass("fancybox-is-sliding");
  };

  // Limit panning from edges
  // ========================
  Guestures.prototype.endPanning = function () {
    var self = this,
      newOffsetX,
      newOffsetY,
      newPos;

    if (!self.contentLastPos) {
      return;
    }

    if (self.opts.momentum === false || self.dMs > 350) {
      newOffsetX = self.contentLastPos.left;
      newOffsetY = self.contentLastPos.top;
    } else {
      // Continue movement
      newOffsetX = self.contentLastPos.left + self.velocityX * 500;
      newOffsetY = self.contentLastPos.top + self.velocityY * 500;
    }

    newPos = self.limitPosition(newOffsetX, newOffsetY, self.contentStartPos.width, self.contentStartPos.height);

    newPos.width = self.contentStartPos.width;
    newPos.height = self.contentStartPos.height;

    $.fancybox.animate(self.$content, newPos, 366);
  };

  Guestures.prototype.endZooming = function () {
    var self = this;

    var current = self.instance.current;

    var newOffsetX, newOffsetY, newPos, reset;

    var newWidth = self.newWidth;
    var newHeight = self.newHeight;

    if (!self.contentLastPos) {
      return;
    }

    newOffsetX = self.contentLastPos.left;
    newOffsetY = self.contentLastPos.top;

    reset = {
      top: newOffsetY,
      left: newOffsetX,
      width: newWidth,
      height: newHeight,
      scaleX: 1,
      scaleY: 1
    };

    // Reset scalex/scaleY values; this helps for perfomance and does not break animation
    $.fancybox.setTranslate(self.$content, reset);

    if (newWidth < self.canvasWidth && newHeight < self.canvasHeight) {
      self.instance.scaleToFit(150);
    } else if (newWidth > current.width || newHeight > current.height) {
      self.instance.scaleToActual(self.centerPointStartX, self.centerPointStartY, 150);
    } else {
      newPos = self.limitPosition(newOffsetX, newOffsetY, newWidth, newHeight);

      $.fancybox.animate(self.$content, newPos, 150);
    }
  };

  Guestures.prototype.onTap = function (e) {
    var self = this;
    var $target = $(e.target);

    var instance = self.instance;
    var current = instance.current;

    var endPoints = (e && getPointerXY(e)) || self.startPoints;

    var tapX = endPoints[0] ? endPoints[0].x - $(window).scrollLeft() - self.stagePos.left : 0;
    var tapY = endPoints[0] ? endPoints[0].y - $(window).scrollTop() - self.stagePos.top : 0;

    var where;

    var process = function (prefix) {
      var action = current.opts[prefix];

      if ($.isFunction(action)) {
        action = action.apply(instance, [current, e]);
      }

      if (!action) {
        return;
      }

      switch (action) {
        case "close":
          instance.close(self.startEvent);

          break;

        case "toggleControls":
          instance.toggleControls();

          break;

        case "next":
          instance.next();

          break;

        case "nextOrClose":
          if (instance.group.length > 1) {
            instance.next();
          } else {
            instance.close(self.startEvent);
          }

          break;

        case "zoom":
          if (current.type == "image" && (current.isLoaded || current.$ghost)) {
            if (instance.canPan()) {
              instance.scaleToFit();
            } else if (instance.isScaledDown()) {
              instance.scaleToActual(tapX, tapY);
            } else if (instance.group.length < 2) {
              instance.close(self.startEvent);
            }
          }

          break;
      }
    };

    // Ignore right click
    if (e.originalEvent && e.originalEvent.button == 2) {
      return;
    }

    // Skip if clicked on the scrollbar
    if (!$target.is("img") && tapX > $target[0].clientWidth + $target.offset().left) {
      return;
    }

    // Check where is clicked
    if ($target.is(".fancybox-bg,.fancybox-inner,.fancybox-outer,.fancybox-container")) {
      where = "Outside";
    } else if ($target.is(".fancybox-slide")) {
      where = "Slide";
    } else if (
      instance.current.$content &&
      instance.current.$content
      .find($target)
      .addBack()
      .filter($target).length
    ) {
      where = "Content";
    } else {
      return;
    }

    // Check if this is a double tap
    if (self.tapped) {
      // Stop previously created single tap
      clearTimeout(self.tapped);
      self.tapped = null;

      // Skip if distance between taps is too big
      if (Math.abs(tapX - self.tapX) > 50 || Math.abs(tapY - self.tapY) > 50) {
        return this;
      }

      // OK, now we assume that this is a double-tap
      process("dblclick" + where);
    } else {
      // Single tap will be processed if user has not clicked second time within 300ms
      // or there is no need to wait for double-tap
      self.tapX = tapX;
      self.tapY = tapY;

      if (current.opts["dblclick" + where] && current.opts["dblclick" + where] !== current.opts["click" + where]) {
        self.tapped = setTimeout(function () {
          self.tapped = null;

          if (!instance.isAnimating) {
            process("click" + where);
          }
        }, 500);
      } else {
        process("click" + where);
      }
    }

    return this;
  };

  $(document)
    .on("onActivate.fb", function (e, instance) {
      if (instance && !instance.Guestures) {
        instance.Guestures = new Guestures(instance);
      }
    })
    .on("beforeClose.fb", function (e, instance) {
      if (instance && instance.Guestures) {
        instance.Guestures.destroy();
      }
    });
})(window, document, jQuery);
// ==========================================================================
//
// SlideShow
// Enables slideshow functionality
//
// Example of usage:
// $.fancybox.getInstance().SlideShow.start()
//
// ==========================================================================
(function (document, $) {
  "use strict";

  $.extend(true, $.fancybox.defaults, {
    btnTpl: {
      slideShow: '<button data-fancybox-play class="fancybox-button fancybox-button--play" title="{{PLAY_START}}">' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6.5 5.4v13.2l11-6.6z"/></svg>' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8.33 5.75h2.2v12.5h-2.2V5.75zm5.15 0h2.2v12.5h-2.2V5.75z"/></svg>' +
        "</button>"
    },
    slideShow: {
      autoStart: false,
      speed: 3000,
      progress: true
    }
  });

  var SlideShow = function (instance) {
    this.instance = instance;
    this.init();
  };

  $.extend(SlideShow.prototype, {
    timer: null,
    isActive: false,
    $button: null,

    init: function () {
      var self = this,
        instance = self.instance,
        opts = instance.group[instance.currIndex].opts.slideShow;

      self.$button = instance.$refs.toolbar.find("[data-fancybox-play]").on("click", function () {
        self.toggle();
      });

      if (instance.group.length < 2 || !opts) {
        self.$button.hide();
      } else if (opts.progress) {
        self.$progress = $('<div class="fancybox-progress"></div>').appendTo(instance.$refs.inner);
      }
    },

    set: function (force) {
      var self = this,
        instance = self.instance,
        current = instance.current;

      // Check if reached last element
      if (current && (force === true || current.opts.loop || instance.currIndex < instance.group.length - 1)) {
        if (self.isActive && current.contentType !== "video") {
          if (self.$progress) {
            $.fancybox.animate(self.$progress.show(), {
              scaleX: 1
            }, current.opts.slideShow.speed);
          }

          self.timer = setTimeout(function () {
            if (!instance.current.opts.loop && instance.current.index == instance.group.length - 1) {
              instance.jumpTo(0);
            } else {
              instance.next();
            }
          }, current.opts.slideShow.speed);
        }
      } else {
        self.stop();
        instance.idleSecondsCounter = 0;
        instance.showControls();
      }
    },

    clear: function () {
      var self = this;

      clearTimeout(self.timer);

      self.timer = null;

      if (self.$progress) {
        self.$progress.removeAttr("style").hide();
      }
    },

    start: function () {
      var self = this,
        current = self.instance.current;

      if (current) {
        self.$button
          .attr("title", (current.opts.i18n[current.opts.lang] || current.opts.i18n.en).PLAY_STOP)
          .removeClass("fancybox-button--play")
          .addClass("fancybox-button--pause");

        self.isActive = true;

        if (current.isComplete) {
          self.set(true);
        }

        self.instance.trigger("onSlideShowChange", true);
      }
    },

    stop: function () {
      var self = this,
        current = self.instance.current;

      self.clear();

      self.$button
        .attr("title", (current.opts.i18n[current.opts.lang] || current.opts.i18n.en).PLAY_START)
        .removeClass("fancybox-button--pause")
        .addClass("fancybox-button--play");

      self.isActive = false;

      self.instance.trigger("onSlideShowChange", false);

      if (self.$progress) {
        self.$progress.removeAttr("style").hide();
      }
    },

    toggle: function () {
      var self = this;

      if (self.isActive) {
        self.stop();
      } else {
        self.start();
      }
    }
  });

  $(document).on({
    "onInit.fb": function (e, instance) {
      if (instance && !instance.SlideShow) {
        instance.SlideShow = new SlideShow(instance);
      }
    },

    "beforeShow.fb": function (e, instance, current, firstRun) {
      var SlideShow = instance && instance.SlideShow;

      if (firstRun) {
        if (SlideShow && current.opts.slideShow.autoStart) {
          SlideShow.start();
        }
      } else if (SlideShow && SlideShow.isActive) {
        SlideShow.clear();
      }
    },

    "afterShow.fb": function (e, instance, current) {
      var SlideShow = instance && instance.SlideShow;

      if (SlideShow && SlideShow.isActive) {
        SlideShow.set();
      }
    },

    "afterKeydown.fb": function (e, instance, current, keypress, keycode) {
      var SlideShow = instance && instance.SlideShow;

      // "P" or Spacebar
      if (SlideShow && current.opts.slideShow && (keycode === 80 || keycode === 32) && !$(document.activeElement).is("button,a,input")) {
        keypress.preventDefault();

        SlideShow.toggle();
      }
    },

    "beforeClose.fb onDeactivate.fb": function (e, instance) {
      var SlideShow = instance && instance.SlideShow;

      if (SlideShow) {
        SlideShow.stop();
      }
    }
  });

  // Page Visibility API to pause slideshow when window is not active
  $(document).on("visibilitychange", function () {
    var instance = $.fancybox.getInstance(),
      SlideShow = instance && instance.SlideShow;

    if (SlideShow && SlideShow.isActive) {
      if (document.hidden) {
        SlideShow.clear();
      } else {
        SlideShow.set();
      }
    }
  });
})(document, jQuery);
// ==========================================================================
//
// FullScreen
// Adds fullscreen functionality
//
// ==========================================================================
(function (document, $) {
  "use strict";

  // Collection of methods supported by user browser
  var fn = (function () {
    var fnMap = [
      ["requestFullscreen", "exitFullscreen", "fullscreenElement", "fullscreenEnabled", "fullscreenchange", "fullscreenerror"],
      // new WebKit
      [
        "webkitRequestFullscreen",
        "webkitExitFullscreen",
        "webkitFullscreenElement",
        "webkitFullscreenEnabled",
        "webkitfullscreenchange",
        "webkitfullscreenerror"
      ],
      // old WebKit (Safari 5.1)
      [
        "webkitRequestFullScreen",
        "webkitCancelFullScreen",
        "webkitCurrentFullScreenElement",
        "webkitCancelFullScreen",
        "webkitfullscreenchange",
        "webkitfullscreenerror"
      ],
      [
        "mozRequestFullScreen",
        "mozCancelFullScreen",
        "mozFullScreenElement",
        "mozFullScreenEnabled",
        "mozfullscreenchange",
        "mozfullscreenerror"
      ],
      ["msRequestFullscreen", "msExitFullscreen", "msFullscreenElement", "msFullscreenEnabled", "MSFullscreenChange", "MSFullscreenError"]
    ];

    var ret = {};

    for (var i = 0; i < fnMap.length; i++) {
      var val = fnMap[i];

      if (val && val[1] in document) {
        for (var j = 0; j < val.length; j++) {
          ret[fnMap[0][j]] = val[j];
        }

        return ret;
      }
    }

    return false;
  })();

  if (fn) {
    var FullScreen = {
      request: function (elem) {
        elem = elem || document.documentElement;

        elem[fn.requestFullscreen](elem.ALLOW_KEYBOARD_INPUT);
      },
      exit: function () {
        document[fn.exitFullscreen]();
      },
      toggle: function (elem) {
        elem = elem || document.documentElement;

        if (this.isFullscreen()) {
          this.exit();
        } else {
          this.request(elem);
        }
      },
      isFullscreen: function () {
        return Boolean(document[fn.fullscreenElement]);
      },
      enabled: function () {
        return Boolean(document[fn.fullscreenEnabled]);
      }
    };

    $.extend(true, $.fancybox.defaults, {
      btnTpl: {
        fullScreen: '<button data-fancybox-fullscreen class="fancybox-button fancybox-button--fsenter" title="{{FULL_SCREEN}}">' +
          '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>' +
          '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 16h3v3h2v-5H5zm3-8H5v2h5V5H8zm6 11h2v-3h3v-2h-5zm2-11V5h-2v5h5V8z"/></svg>' +
          "</button>"
      },
      fullScreen: {
        autoStart: false
      }
    });

    $(document).on(fn.fullscreenchange, function () {
      var isFullscreen = FullScreen.isFullscreen(),
        instance = $.fancybox.getInstance();

      if (instance) {
        // If image is zooming, then force to stop and reposition properly
        if (instance.current && instance.current.type === "image" && instance.isAnimating) {
          instance.isAnimating = false;

          instance.update(true, true, 0);

          if (!instance.isComplete) {
            instance.complete();
          }
        }

        instance.trigger("onFullscreenChange", isFullscreen);

        instance.$refs.container.toggleClass("fancybox-is-fullscreen", isFullscreen);

        instance.$refs.toolbar
          .find("[data-fancybox-fullscreen]")
          .toggleClass("fancybox-button--fsenter", !isFullscreen)
          .toggleClass("fancybox-button--fsexit", isFullscreen);
      }
    });
  }

  $(document).on({
    "onInit.fb": function (e, instance) {
      var $container;

      if (!fn) {
        instance.$refs.toolbar.find("[data-fancybox-fullscreen]").remove();

        return;
      }

      if (instance && instance.group[instance.currIndex].opts.fullScreen) {
        $container = instance.$refs.container;

        $container.on("click.fb-fullscreen", "[data-fancybox-fullscreen]", function (e) {
          e.stopPropagation();
          e.preventDefault();

          FullScreen.toggle();
        });

        if (instance.opts.fullScreen && instance.opts.fullScreen.autoStart === true) {
          FullScreen.request();
        }

        // Expose API
        instance.FullScreen = FullScreen;
      } else if (instance) {
        instance.$refs.toolbar.find("[data-fancybox-fullscreen]").hide();
      }
    },

    "afterKeydown.fb": function (e, instance, current, keypress, keycode) {
      // "F"
      if (instance && instance.FullScreen && keycode === 70) {
        keypress.preventDefault();

        instance.FullScreen.toggle();
      }
    },

    "beforeClose.fb": function (e, instance) {
      if (instance && instance.FullScreen && instance.$refs.container.hasClass("fancybox-is-fullscreen")) {
        FullScreen.exit();
      }
    }
  });
})(document, jQuery);
// ==========================================================================
//
// Thumbs
// Displays thumbnails in a grid
//
// ==========================================================================
(function (document, $) {
  "use strict";

  var CLASS = "fancybox-thumbs",
    CLASS_ACTIVE = CLASS + "-active";

  // Make sure there are default values
  $.fancybox.defaults = $.extend(
    true, {
      btnTpl: {
        thumbs: '<button data-fancybox-thumbs class="fancybox-button fancybox-button--thumbs" title="{{THUMBS}}">' +
          '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14.59 14.59h3.76v3.76h-3.76v-3.76zm-4.47 0h3.76v3.76h-3.76v-3.76zm-4.47 0h3.76v3.76H5.65v-3.76zm8.94-4.47h3.76v3.76h-3.76v-3.76zm-4.47 0h3.76v3.76h-3.76v-3.76zm-4.47 0h3.76v3.76H5.65v-3.76zm8.94-4.47h3.76v3.76h-3.76V5.65zm-4.47 0h3.76v3.76h-3.76V5.65zm-4.47 0h3.76v3.76H5.65V5.65z"/></svg>' +
          "</button>"
      },
      thumbs: {
        autoStart: false, // Display thumbnails on opening
        hideOnClose: true, // Hide thumbnail grid when closing animation starts
        parentEl: ".fancybox-container", // Container is injected into this element
        axis: "y" // Vertical (y) or horizontal (x) scrolling
      }
    },
    $.fancybox.defaults
  );

  var FancyThumbs = function (instance) {
    this.init(instance);
  };

  $.extend(FancyThumbs.prototype, {
    $button: null,
    $grid: null,
    $list: null,
    isVisible: false,
    isActive: false,

    init: function (instance) {
      var self = this,
        group = instance.group,
        enabled = 0;

      self.instance = instance;
      self.opts = group[instance.currIndex].opts.thumbs;

      instance.Thumbs = self;

      self.$button = instance.$refs.toolbar.find("[data-fancybox-thumbs]");

      // Enable thumbs if at least two group items have thumbnails
      for (var i = 0, len = group.length; i < len; i++) {
        if (group[i].thumb) {
          enabled++;
        }

        if (enabled > 1) {
          break;
        }
      }

      if (enabled > 1 && !!self.opts) {
        self.$button.removeAttr("style").on("click", function () {
          self.toggle();
        });

        self.isActive = true;
      } else {
        self.$button.hide();
      }
    },

    create: function () {
      var self = this,
        instance = self.instance,
        parentEl = self.opts.parentEl,
        list = [],
        src;

      if (!self.$grid) {
        // Create main element
        self.$grid = $('<div class="' + CLASS + " " + CLASS + "-" + self.opts.axis + '"></div>').appendTo(
          instance.$refs.container
          .find(parentEl)
          .addBack()
          .filter(parentEl)
        );

        // Add "click" event that performs gallery navigation
        self.$grid.on("click", "a", function () {
          instance.jumpTo($(this).attr("data-index"));
        });
      }

      // Build the list
      if (!self.$list) {
        self.$list = $('<div class="' + CLASS + '__list">').appendTo(self.$grid);
      }

      $.each(instance.group, function (i, item) {
        src = item.thumb;

        if (!src && item.type === "image") {
          src = item.src;
        }

        list.push(
          '<a href="javascript:;" tabindex="0" data-index="' +
          i +
          '"' +
          (src && src.length ? ' style="background-image:url(' + src + ')"' : 'class="fancybox-thumbs-missing"') +
          "></a>"
        );
      });

      self.$list[0].innerHTML = list.join("");

      if (self.opts.axis === "x") {
        // Set fixed width for list element to enable horizontal scrolling
        self.$list.width(
          parseInt(self.$grid.css("padding-right"), 10) +
          instance.group.length *
          self.$list
          .children()
          .eq(0)
          .outerWidth(true)
        );
      }
    },

    focus: function (duration) {
      var self = this,
        $list = self.$list,
        $grid = self.$grid,
        thumb,
        thumbPos;

      if (!self.instance.current) {
        return;
      }

      thumb = $list
        .children()
        .removeClass(CLASS_ACTIVE)
        .filter('[data-index="' + self.instance.current.index + '"]')
        .addClass(CLASS_ACTIVE);

      thumbPos = thumb.position();

      // Check if need to scroll to make current thumb visible
      if (self.opts.axis === "y" && (thumbPos.top < 0 || thumbPos.top > $list.height() - thumb.outerHeight())) {
        $list.stop().animate({
            scrollTop: $list.scrollTop() + thumbPos.top
          },
          duration
        );
      } else if (
        self.opts.axis === "x" &&
        (thumbPos.left < $grid.scrollLeft() || thumbPos.left > $grid.scrollLeft() + ($grid.width() - thumb.outerWidth()))
      ) {
        $list
          .parent()
          .stop()
          .animate({
              scrollLeft: thumbPos.left
            },
            duration
          );
      }
    },

    update: function () {
      var that = this;
      that.instance.$refs.container.toggleClass("fancybox-show-thumbs", this.isVisible);

      if (that.isVisible) {
        if (!that.$grid) {
          that.create();
        }

        that.instance.trigger("onThumbsShow");

        that.focus(0);
      } else if (that.$grid) {
        that.instance.trigger("onThumbsHide");
      }

      // Update content position
      that.instance.update();
    },

    hide: function () {
      this.isVisible = false;
      this.update();
    },

    show: function () {
      this.isVisible = true;
      this.update();
    },

    toggle: function () {
      this.isVisible = !this.isVisible;
      this.update();
    }
  });

  $(document).on({
    "onInit.fb": function (e, instance) {
      var Thumbs;

      if (instance && !instance.Thumbs) {
        Thumbs = new FancyThumbs(instance);

        if (Thumbs.isActive && Thumbs.opts.autoStart === true) {
          Thumbs.show();
        }
      }
    },

    "beforeShow.fb": function (e, instance, item, firstRun) {
      var Thumbs = instance && instance.Thumbs;

      if (Thumbs && Thumbs.isVisible) {
        Thumbs.focus(firstRun ? 0 : 250);
      }
    },

    "afterKeydown.fb": function (e, instance, current, keypress, keycode) {
      var Thumbs = instance && instance.Thumbs;

      // "G"
      if (Thumbs && Thumbs.isActive && keycode === 71) {
        keypress.preventDefault();

        Thumbs.toggle();
      }
    },

    "beforeClose.fb": function (e, instance) {
      var Thumbs = instance && instance.Thumbs;

      if (Thumbs && Thumbs.isVisible && Thumbs.opts.hideOnClose !== false) {
        Thumbs.$grid.hide();
      }
    }
  });
})(document, jQuery);
//// ==========================================================================
//
// Share
// Displays simple form for sharing current url
//
// ==========================================================================
(function (document, $) {
  "use strict";

  $.extend(true, $.fancybox.defaults, {
    btnTpl: {
      share: '<button data-fancybox-share class="fancybox-button fancybox-button--share" title="{{SHARE}}">' +
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2.55 19c1.4-8.4 9.1-9.8 11.9-9.8V5l7 7-7 6.3v-3.5c-2.8 0-10.5 2.1-11.9 4.2z"/></svg>' +
        "</button>"
    },
    share: {
      url: function (instance, item) {
        return (
          (!instance.currentHash && !(item.type === "inline" || item.type === "html") ? item.origSrc || item.src : false) || window.location
        );
      },
      tpl: '<div class="fancybox-share">' +
        "<h1>{{SHARE}}</h1>" +
        "<p>" +
        '<a class="fancybox-share__button fancybox-share__button--fb" href="https://www.facebook.com/sharer/sharer.php?u={{url}}">' +
        '<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="m287 456v-299c0-21 6-35 35-35h38v-63c-7-1-29-3-55-3-54 0-91 33-91 94v306m143-254h-205v72h196" /></svg>' +
        "<span>Facebook</span>" +
        "</a>" +
        '<a class="fancybox-share__button fancybox-share__button--tw" href="https://twitter.com/intent/tweet?url={{url}}&text={{descr}}">' +
        '<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="m456 133c-14 7-31 11-47 13 17-10 30-27 37-46-15 10-34 16-52 20-61-62-157-7-141 75-68-3-129-35-169-85-22 37-11 86 26 109-13 0-26-4-37-9 0 39 28 72 65 80-12 3-25 4-37 2 10 33 41 57 77 57-42 30-77 38-122 34 170 111 378-32 359-208 16-11 30-25 41-42z" /></svg>' +
        "<span>Twitter</span>" +
        "</a>" +
        '<a class="fancybox-share__button fancybox-share__button--pt" href="https://www.pinterest.com/pin/create/button/?url={{url}}&description={{descr}}&media={{media}}">' +
        '<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="m265 56c-109 0-164 78-164 144 0 39 15 74 47 87 5 2 10 0 12-5l4-19c2-6 1-8-3-13-9-11-15-25-15-45 0-58 43-110 113-110 62 0 96 38 96 88 0 67-30 122-73 122-24 0-42-19-36-44 6-29 20-60 20-81 0-19-10-35-31-35-25 0-44 26-44 60 0 21 7 36 7 36l-30 125c-8 37-1 83 0 87 0 3 4 4 5 2 2-3 32-39 42-75l16-64c8 16 31 29 56 29 74 0 124-67 124-157 0-69-58-132-146-132z" fill="#fff"/></svg>' +
        "<span>Pinterest</span>" +
        "</a>" +
        "</p>" +
        '<p><input class="fancybox-share__input" type="text" value="{{url_raw}}" onclick="select()" /></p>' +
        "</div>"
    }
  });

  function escapeHtml(string) {
    var entityMap = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;",
      "/": "&#x2F;",
      "`": "&#x60;",
      "=": "&#x3D;"
    };

    return String(string).replace(/[&<>"'`=\/]/g, function (s) {
      return entityMap[s];
    });
  }

  $(document).on("click", "[data-fancybox-share]", function () {
    var instance = $.fancybox.getInstance(),
      current = instance.current || null,
      url,
      tpl;

    if (!current) {
      return;
    }

    if ($.type(current.opts.share.url) === "function") {
      url = current.opts.share.url.apply(current, [instance, current]);
    }

    tpl = current.opts.share.tpl
      .replace(/\{\{media\}\}/g, current.type === "image" ? encodeURIComponent(current.src) : "")
      .replace(/\{\{url\}\}/g, encodeURIComponent(url))
      .replace(/\{\{url_raw\}\}/g, escapeHtml(url))
      .replace(/\{\{descr\}\}/g, instance.$caption ? encodeURIComponent(instance.$caption.text()) : "");

    $.fancybox.open({
      src: instance.translate(instance, tpl),
      type: "html",
      opts: {
        touch: false,
        animationEffect: false,
        afterLoad: function (shareInstance, shareCurrent) {
          // Close self if parent instance is closing
          instance.$refs.container.one("beforeClose.fb", function () {
            shareInstance.close(null, 0);
          });

          // Opening links in a popup window
          shareCurrent.$content.find(".fancybox-share__button").click(function () {
            window.open(this.href, "Share", "width=550, height=450");
            return false;
          });
        },
        mobile: {
          autoFocus: false
        }
      }
    });
  });
})(document, jQuery);
// ==========================================================================
//
// Hash
// Enables linking to each modal
//
// ==========================================================================
(function (window, document, $) {
  "use strict";

  // Simple $.escapeSelector polyfill (for jQuery prior v3)
  if (!$.escapeSelector) {
    $.escapeSelector = function (sel) {
      var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;
      var fcssescape = function (ch, asCodePoint) {
        if (asCodePoint) {
          // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
          if (ch === "\0") {
            return "\uFFFD";
          }

          // Control characters and (dependent upon position) numbers get escaped as code points
          return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
        }

        // Other potentially-special ASCII characters get backslash-escaped
        return "\\" + ch;
      };

      return (sel + "").replace(rcssescape, fcssescape);
    };
  }

  // Get info about gallery name and current index from url
  function parseUrl() {
    var hash = window.location.hash.substr(1),
      rez = hash.split("-"),
      index = rez.length > 1 && /^\+?\d+$/.test(rez[rez.length - 1]) ? parseInt(rez.pop(-1), 10) || 1 : 1,
      gallery = rez.join("-");

    return {
      hash: hash,
      /* Index is starting from 1 */
      index: index < 1 ? 1 : index,
      gallery: gallery
    };
  }

  // Trigger click evnt on links to open new fancyBox instance
  function triggerFromUrl(url) {
    if (url.gallery !== "") {
      // If we can find element matching 'data-fancybox' atribute,
      // then triggering click event should start fancyBox
      $("[data-fancybox='" + $.escapeSelector(url.gallery) + "']")
        .eq(url.index - 1)
        .focus()
        .trigger("click.fb-start");
    }
  }

  // Get gallery name from current instance
  function getGalleryID(instance) {
    var opts, ret;

    if (!instance) {
      return false;
    }

    opts = instance.current ? instance.current.opts : instance.opts;
    ret = opts.hash || (opts.$orig ? opts.$orig.data("fancybox") || opts.$orig.data("fancybox-trigger") : "");

    return ret === "" ? false : ret;
  }

  // Start when DOM becomes ready
  $(function () {
    // Check if user has disabled this module
    if ($.fancybox.defaults.hash === false) {
      return;
    }

    // Update hash when opening/closing fancyBox
    $(document).on({
      "onInit.fb": function (e, instance) {
        var url, gallery;

        if (instance.group[instance.currIndex].opts.hash === false) {
          return;
        }

        url = parseUrl();
        gallery = getGalleryID(instance);

        // Make sure gallery start index matches index from hash
        if (gallery && url.gallery && gallery == url.gallery) {
          instance.currIndex = url.index - 1;
        }
      },

      "beforeShow.fb": function (e, instance, current, firstRun) {
        var gallery;

        if (!current || current.opts.hash === false) {
          return;
        }

        // Check if need to update window hash
        gallery = getGalleryID(instance);

        if (!gallery) {
          return;
        }

        // Variable containing last hash value set by fancyBox
        // It will be used to determine if fancyBox needs to close after hash change is detected
        instance.currentHash = gallery + (instance.group.length > 1 ? "-" + (current.index + 1) : "");

        // If current hash is the same (this instance most likely is opened by hashchange), then do nothing
        if (window.location.hash === "#" + instance.currentHash) {
          return;
        }

        if (firstRun && !instance.origHash) {
          instance.origHash = window.location.hash;
        }

        if (instance.hashTimer) {
          clearTimeout(instance.hashTimer);
        }

        // Update hash
        instance.hashTimer = setTimeout(function () {
          if ("replaceState" in window.history) {
            window.history[firstRun ? "pushState" : "replaceState"]({},
              document.title,
              window.location.pathname + window.location.search + "#" + instance.currentHash
            );

            if (firstRun) {
              instance.hasCreatedHistory = true;
            }
          } else {
            window.location.hash = instance.currentHash;
          }

          instance.hashTimer = null;
        }, 300);
      },

      "beforeClose.fb": function (e, instance, current) {
        if (!current || current.opts.hash === false) {
          return;
        }

        clearTimeout(instance.hashTimer);

        // Goto previous history entry
        if (instance.currentHash && instance.hasCreatedHistory) {
          window.history.back();
        } else if (instance.currentHash) {
          if ("replaceState" in window.history) {
            window.history.replaceState({}, document.title, window.location.pathname + window.location.search + (instance.origHash || ""));
          } else {
            window.location.hash = instance.origHash;
          }
        }

        instance.currentHash = null;
      }
    });

    // Check if need to start/close after url has changed
    $(window).on("hashchange.fb", function () {
      var url = parseUrl(),
        fb = null;

      // Find last fancyBox instance that has "hash"
      $.each(
        $(".fancybox-container")
        .get()
        .reverse(),
        function (index, value) {
          var tmp = $(value).data("FancyBox");

          if (tmp && tmp.currentHash) {
            fb = tmp;
            return false;
          }
        }
      );

      if (fb) {
        // Now, compare hash values
        if (fb.currentHash !== url.gallery + "-" + url.index && !(url.index === 1 && fb.currentHash == url.gallery)) {
          fb.currentHash = null;

          fb.close();
        }
      } else if (url.gallery !== "") {
        triggerFromUrl(url);
      }
    });

    // Check current hash and trigger click event on matching element to start fancyBox, if needed
    setTimeout(function () {
      if (!$.fancybox.getInstance()) {
        triggerFromUrl(parseUrl());
      }
    }, 50);
  });
})(window, document, jQuery);
// ==========================================================================
//
// Wheel
// Basic mouse weheel support for gallery navigation
//
// ==========================================================================
(function (document, $) {
  "use strict";

  var prevTime = new Date().getTime();

  $(document).on({
    "onInit.fb": function (e, instance, current) {
      instance.$refs.stage.on("mousewheel DOMMouseScroll wheel MozMousePixelScroll", function (e) {
        var current = instance.current,
          currTime = new Date().getTime();

        if (instance.group.length < 2 || current.opts.wheel === false || (current.opts.wheel === "auto" && current.type !== "image")) {
          return;
        }

        e.preventDefault();
        e.stopPropagation();

        if (current.$slide.hasClass("fancybox-animated")) {
          return;
        }

        e = e.originalEvent || e;

        if (currTime - prevTime < 250) {
          return;
        }

        prevTime = currTime;

        instance[(-e.deltaY || -e.deltaX || e.wheelDelta || -e.detail) < 0 ? "next" : "previous"]();
      });
    }
  });
})(document, jQuery);

/* ========================================
 FILE: /includes/js/jquery/fancybox3.5.7/cs_custom_fancybox_settings.js
 ==================== */

/*
 * Creativesites s.r.o.
 * Custom Fancybox 3.5.7 Settings
 *
 * Tu su vsetky zmeny defaultnych nastaveni
 */

jQuery.fancybox.defaults.hash = false;

jQuery.fancybox.defaults.i18n.sk = {
	CLOSE       : 'Zavrieť',
	NEXT        : 'Ďalší',
	PREV        : 'Predchádzajúci',
	ERROR       : 'Požadovaný obsah nie je možné načítať. <br/> Skúste to znova neskôr.',
	PLAY_START  : 'Spustiť prezentáciu',
	PLAY_STOP   : 'Pozastaviť prezentáciu',
	FULL_SCREEN : 'Celá obrazovka',
	THUMBS      : 'Náhľady',
	DOWNLOAD    : 'Stiahnuť',
	SHARE       : 'Zdieľať',
	ZOOM        : 'Priblížiť'
};

jQuery.fancybox.defaults.i18n.cz = {
	CLOSE       : 'Zavřít',
	NEXT        : 'Další',
	PREV        : 'Předchozí',
	ERROR       : 'Požadovaný obsah nelze načíst. <br/> Zkuste to znovu později.',
	PLAY_START  : 'Spustit prezentaci',
	PLAY_STOP   : 'Pozastavit prezentaci',
	FULL_SCREEN : 'Celá obrazovka',
	THUMBS      : 'Náhledy',
	DOWNLOAD    : 'Stáhnout',
	SHARE       : 'Sdílet',
	ZOOM        : 'Přiblížit'
};

if ( typeof js_get_lang !== 'undefined' ) jQuery.fancybox.defaults.lang = js_get_lang;

//function is_cs_user(cookieValue) {
//	if (typeof cookieValue !== 'undefined')
//		return (Cookies.get('cs_whois') !== null && Cookies.get('cs_whois') == cookieValue);
//
//	return (typeof js_global_is_csu !== 'undefined') ? js_global_is_csu : false;
//}

function changeFancyboxThumbsScroll() {
	var currenctThumbIndex = jQuery.fancybox.getInstance().currIndex;
	var thumbsElement = jQuery('.fancybox-thumbs__list');

	var thumb = thumbsElement.find('a');
	var thumbWidth = thumb.width();

	var marginRight = parseInt(thumbsElement.find('.fancybox-thumbs-active').css('margin-right'));
	var marginLeft = parseInt(thumbsElement.find('.fancybox-thumbs-active').css('margin-left'));
	
	var margins = marginLeft + marginRight;

	thumbsElement.animate({
		scrollLeft: (currenctThumbIndex * thumbWidth + margins) - (thumbWidth + margins),
	}, 300);
}

if (jQuery.fancybox.isMobile) {
	jQuery.fancybox.defaults.beforeLoad = function () {
		changeFancyboxThumbsScroll();
	};
}

function initFancybox() {
	if ( typeof is_responsive !== 'undefined' && is_responsive()) {
		var $mainImage = jQuery('.flypage-lightbox-image-a');
		var href = $mainImage.attr('href');
		var $duplicateMainImage = jQuery('.product_activeimages_image_div:not(.product_3d_image_preview) a[href="' + href + '"]');
		$duplicateMainImage.removeAttr('data-fancybox');

		// medical-uniforms fix
		if ( typeof js_Config_flypage_img_recursive_call_fix === 'undefined' ) {
			$duplicateMainImage.attr('onclick', 'flypage_img_click(); return false;');
		}

		$mainImage.attr('data-fancybox', 'gallery');
		$mainImage.attr('data-options', $duplicateMainImage.attr('data-options'));
	}

	var fancyboxElem = jQuery('[data-fancybox="gallery"], .module_lightbox_gallery [data-fancybox]');
	var options = {
		loop: true,
		backFocus: false
	};

	if ( typeof fancyboxOptions === 'undefined' ) fancyboxOptions = options;

	fancyboxOptions.afterClose = function () {
		if (window.location.href.indexOf('opened=yes') > 0) {
			history.replaceState({}, '', window.location.href.replace('?opened=yes', '').replace('&opened=yes', ''));
		}
	};

	fancyboxElem.fancybox(fancyboxOptions);

	if ( typeof fancyboxOptions.creativesites !== 'undefined' ) {
		if ( fancyboxOptions.creativesites.toggleThumbsOnStartup ) {
			fancyboxElem.on('click', function() {
				jQuery.fancybox.getInstance().Thumbs.toggle();
			});
		}
	}

	fancyboxElem.on('click', function() {
		var getParam;
		if (document.location.href.indexOf('opened=yes') < 0 ) {
			if (document.location.href.indexOf('?') > 0) {
				getParam = "&opened=yes";
			} else {
				getParam = "?opened=yes";
			}
		}
	});
}

window.addEventListener('DOMContentLoaded', initFancybox);

(function () {
	window.replaceSrcForLazyloadedImages = function () {
		var lazyloadedImages = document.querySelectorAll('a[data-fancybox^="gallery"] img[data-srcset]:not(.lazyloaded)');
		for (var i = 0; i < lazyloadedImages.length; i++) {
			lazyloadedImages[i].src = lazyloadedImages[i].src.replace('(', '%28').replace(')', '%29');
			lazyloadedImages[i].addEventListener('lazyloaded', function () {
				var image = this;
				if ( typeof image.srcset !== 'undefined' ) {
					image.src = image.srcset.replace('(', '%28').replace(')', '%29');
				}
			});
		}
	};

	window.setSrcAttrOfFancyboxImages = function () {
		var galleryImages = document.querySelectorAll('a[data-fancybox^="gallery"] img[data-srcset]');
		for (var i = 0; i < galleryImages.length; i++) {
			galleryImages[i].addEventListener('click', function () {
				for (var j = 0; j < galleryImages.length; j++) {
					galleryImages[j].src = galleryImages[j].dataset.srcset.replace('(', '%28').replace(')', '%29');
				}
			});
		}
	};

	window.addEventListener('DOMContentLoaded', function() {
		replaceSrcForLazyloadedImages();
		setSrcAttrOfFancyboxImages();
	});
})();
//if ( !is_cs_user('separate_js') ) {
//}



/* ========================================
 FILE: /includes/js/jquery/jquery-ui-1.14.0/jquery-ui.js
 ==================== */

/*! jQuery UI - v1.14.0 - 2024-08-05
* https://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-patch.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
* Copyright OpenJS Foundation and other contributors; Licensed MIT */

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.ui = $.ui || {};

var version = $.ui.version = "1.14.0";


/*!
 * jQuery UI Widget 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: https://api.jqueryui.com/jQuery.widget/
//>>demos: https://jqueryui.com/widget/


var widgetUuid = 0;
var widgetHasOwnProperty = Array.prototype.hasOwnProperty;
var widgetSlice = Array.prototype.slice;

$.cleanData = ( function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {

			// Only trigger remove when necessary to save time
			events = $._data( elem, "events" );
			if ( events && events.remove ) {
				$( elem ).triggerHandler( "remove" );
			}
		}
		orig( elems );
	};
} )( $.cleanData );

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

	var namespace = name.split( "." )[ 0 ];
	name = name.split( "." )[ 1 ];
	var fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	if ( Array.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

	// Create selector for plugin
	$.expr.pseudos[ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this || !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

	// We need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( typeof value !== "function" ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = ( function() {
			function _super() {
				return base.prototype[ prop ].apply( this, arguments );
			}

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	} );

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( widgetHasOwnProperty.call( input[ inputIndex ], key ) && value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string";
		var args = widgetSlice.call( arguments, 1 );
		var returnValue = this;

		if ( isMethodCall ) {

			// If this is an empty collection, we need to have the instance method
			// return undefined instead of the jQuery instance
			if ( !this.length && options === "instance" ) {
				returnValue = undefined;
			} else {
				this.each( function() {
					var methodValue;
					var instance = $.data( this, fullName );

					if ( options === "instance" ) {
						returnValue = instance;
						return false;
					}

					if ( !instance ) {
						return $.error( "cannot call methods on " + name +
							" prior to initialization; " +
							"attempted to call method '" + options + "'" );
					}

					if ( typeof instance[ options ] !== "function" ||
						options.charAt( 0 ) === "_" ) {
						return $.error( "no such method '" + options + "' for " + name +
							" widget instance" );
					}

					methodValue = instance[ options ].apply( instance, args );

					if ( methodValue !== instance && methodValue !== undefined ) {
						returnValue = methodValue && methodValue.jquery ?
							returnValue.pushStack( methodValue.get() ) :
							methodValue;
						return false;
					}
				} );
			}
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat( args ) );
			}

			this.each( function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			} );
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;
		var parts;
		var curOption;
		var i;

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

			// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

		// If the widget is becoming disabled, then nothing is interactive
		if ( value ) {
			this._removeClass( this.hoverable, null, "ui-state-hover" );
			this._removeClass( this.focusable, null, "ui-state-focus" );
		}
	},

	enable: function() {
		return this._setOptions( { disabled: false } );
	},

	disable: function() {
		return this._setOptions( { disabled: true } );
	},

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function bindRemoveEvent() {
			var nodesToBind = [];

			options.element.each( function( _, element ) {
				var isTracked = $.map( that.classesElementLookup, function( elements ) {
					return elements;
				} )
					.some( function( elements ) {
						return elements.is( element );
					} );

				if ( !isTracked ) {
					nodesToBind.push( element );
				}
			} );

			that._on( $( nodesToBind ), {
				remove: "_untrackClassesElement"
			} );
		}

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i < classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					bindRemoveEvent();
					current = $( $.uniqueSort( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption && options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_untrackClassesElement: function( event ) {
		var that = this;
		$.each( that.classesElementLookup, function( key, value ) {
			if ( $.inArray( event.target, value ) !== -1 ) {
				that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
			}
		} );

		this._off( $( event.target ) );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement;
		var instance = this;

		// No suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// No element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

				// Allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
						$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// Copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

	_off: function( element, eventName ) {
		eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.off( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
			},
			mouseleave: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
			}
		} );
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
			},
			focusout: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
			}
		} );
	},

	_trigger: function( type, event, data ) {
		var prop, orig;
		var callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// Copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( typeof callback === "function" &&
			callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		} else if ( options === true ) {
			options = {};
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

var widget = $.widget;


/*!
 * jQuery UI Position 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 *
 * https://api.jqueryui.com/position/
 */

//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: https://api.jqueryui.com/position/
//>>demos: https://jqueryui.com/position/


( function() {
var cachedScrollbarWidth,
	max = Math.max,
	abs = Math.abs,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function isWindow( obj ) {
	return obj != null && obj === obj.window;
}

function getDimensions( elem ) {
	var raw = elem[ 0 ];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div style=" +
				"'display:block;position:absolute;width:200px;height:200px;overflow:hidden;'>" +
				"<div style='height:300px;width:auto;'></div></div>" ),
			innerDiv = div.children()[ 0 ];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[ 0 ].clientWidth;
		}

		div.remove();

		return ( cachedScrollbarWidth = w1 - w2 );
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isElemWindow = isWindow( withinElement[ 0 ] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
			hasOffset = !isElemWindow && !isDocument;
		return {
			element: withinElement,
			isWindow: isElemWindow,
			isDocument: isDocument,
			offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),
			width: withinElement.outerWidth(),
			height: withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// Make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,

		// Make sure string options are treated as CSS selectors
		target = typeof options.of === "string" ?
			$( document ).find( options.of ) :
			$( options.of ),

		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[ 0 ].preventDefault ) {

		// Force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;

	// Clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// Force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1 ) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// Calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// Reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	} );

	// Normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each( function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
				scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
				scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				} );
			}
		} );

		if ( options.using ) {

			// Adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	} );
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// Element is wider than within
			if ( data.collisionWidth > outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;

			// Too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;

			// Adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// Element is taller than within
			if ( data.collisionHeight > outerHeight ) {

				// Element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;

			// Too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;

			// Adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
					outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
					atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
					outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
					offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

} )();

var position = $.ui.position;


/*!
 * jQuery UI :data 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: https://api.jqueryui.com/data-selector/


var data = $.extend( $.expr.pseudos, {
	data: $.expr.createPseudo( function( dataName ) {
		return function( elem ) {
			return !!$.data( elem, dataName );
		};
	} )
} );

/*!
 * jQuery UI Disable Selection 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: https://api.jqueryui.com/disableSelection/

// This file is deprecated

var disableSelection = $.fn.extend( {
	disableSelection: ( function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.on( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			} );
		};
	} )(),

	enableSelection: function() {
		return this.off( ".ui-disableSelection" );
	}
} );



// Create a local jQuery because jQuery Color relies on it and the
// global may not exist with AMD and a custom build (#10199).
// This module is a noop if used as a regular AMD module.
// eslint-disable-next-line no-unused-vars
var jQuery = $;


/*!
 * jQuery Color Animations v3.0.0
 * https://github.com/jquery/jquery-color
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 *
 * Date: Wed May 15 16:49:44 2024 +0200
 */


	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
		"borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	class2type = {},
	toString = class2type.toString,

	// plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,

	// a set of RE's that can match strings and generate color tuples.
	stringParsers = [ {
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {

			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 ),
					execResult[ 4 ] ?
						( parseInt( execResult[ 4 ], 16 ) / 255 ).toFixed( 2 ) :
						1
				];
			}
		}, {

			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ),
					execResult[ 4 ] ?
						( parseInt( execResult[ 4 ] + execResult[ 4 ], 16 ) / 255 )
							.toFixed( 2 ) :
						1
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		} ],

	// jQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		rgba: {
			props: {
				red: {
					idx: 0,
					type: "byte"
				},
				green: {
					idx: 1,
					type: "byte"
				},
				blue: {
					idx: 2,
					type: "byte"
				}
			}
		},

		hsla: {
			props: {
				hue: {
					idx: 0,
					type: "degrees"
				},
				saturation: {
					idx: 1,
					type: "percent"
				},
				lightness: {
					idx: 2,
					type: "percent"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},

	// colors = jQuery.Color.names
	colors,

	// local aliases of functions called often
	each = jQuery.each;

// define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
	space.cache = "_" + spaceName;
	space.props.alpha = {
		idx: 3,
		type: "percent",
		def: 1
	};
} );

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
	function( _i, name ) {
		class2type[ "[object " + name + "]" ] = name.toLowerCase();
	} );

function getType( obj ) {
	if ( obj == null ) {
		return obj + "";
	}

	return typeof obj === "object" ?
		class2type[ toString.call( obj ) ] || "object" :
		typeof obj;
}

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return ( allowEmpty || !prop.def ) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	if ( type.mod ) {

		// we add mod before modding to make sure that negatives values
		// get converted properly: -10 -> 350
		return ( value + type.mod ) % type.mod;
	}

	// for now all property types without mod have min and max
	return Math.min( type.max, Math.max( 0, value ) );
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( _i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// if this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// exit each( stringParsers ) here because we matched
			return false;
		}
	} );

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// if this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = getType( red ),
			rgba = this._rgba = [];

		// more than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( _key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			} );
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( _spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				} );
			} else {
				each( spaces, function( _spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// if the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// if the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// this is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					} );

					// everything defined but alpha?
					if ( inst[ cache ] && jQuery.inArray(
						null,
						inst[ cache ].slice( 0, 3 )
					) < 0 ) {

						// use the default of 1
						if ( inst[ cache ][ 3 ] == null ) {
							inst[ cache ][ 3 ] = 1;
						}

						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				} );
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if ( isCache ) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				} );
			}
			return same;
		} );
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		} );
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( _key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// if null, don't override start value
			if ( endValue === null ) {
				return;
			}

			// if null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		} );
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {

		// if we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		} ) );
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				if ( v != null ) {
					return v;
				}
				return i > 2 ? 1 : 0;
			} );

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join( ", " ) + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			} );

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join( ", " ) + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// default to 0 when nulls exist
			return ( "0" + ( v || 0 ).toString( 16 ) ).substr( -2 );
		} ).join( "" );
	},
	toString: function() {
		return this.toRgbaString();
	}
} );
color.fn.parse.prototype = color.fn;

// hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

function hue2rgb( p, q, h ) {
	h = ( h + 1 ) % 1;
	if ( h * 6 < 1 ) {
		return p + ( q - p ) * h * 6;
	}
	if ( h * 2 < 1 ) {
		return q;
	}
	if ( h * 3 < 2 ) {
		return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
	}
	return p;
}

spaces.hsla.to = function( rgba ) {
	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
		return [ null, null, null, rgba[ 3 ] ];
	}
	var r = rgba[ 0 ] / 255,
		g = rgba[ 1 ] / 255,
		b = rgba[ 2 ] / 255,
		a = rgba[ 3 ],
		max = Math.max( r, g, b ),
		min = Math.min( r, g, b ),
		diff = max - min,
		add = max + min,
		l = add * 0.5,
		h, s;

	if ( min === max ) {
		h = 0;
	} else if ( r === max ) {
		h = ( 60 * ( g - b ) / diff ) + 360;
	} else if ( g === max ) {
		h = ( 60 * ( b - r ) / diff ) + 120;
	} else {
		h = ( 60 * ( r - g ) / diff ) + 240;
	}

	// chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
	// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
	if ( diff === 0 ) {
		s = 0;
	} else if ( l <= 0.5 ) {
		s = diff / add;
	} else {
		s = diff / ( 2 - add );
	}
	return [ Math.round( h ) % 360, s, l, a == null ? 1 : a ];
};

spaces.hsla.from = function( hsla ) {
	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
		return [ null, null, null, hsla[ 3 ] ];
	}
	var h = hsla[ 0 ] / 360,
		s = hsla[ 1 ],
		l = hsla[ 2 ],
		a = hsla[ 3 ],
		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
		p = 2 * l - q;

	return [
		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
		Math.round( hue2rgb( p, q, h ) * 255 ),
		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
		a
	];
};


each( spaces, function( spaceName, space ) {
	var props = space.props,
		cache = space.cache,
		to = space.to,
		from = space.from;

	// makes rgba() and hsla()
	color.fn[ spaceName ] = function( value ) {

		// generate a cache for this space if it doesn't exist
		if ( to && !this[ cache ] ) {
			this[ cache ] = to( this._rgba );
		}
		if ( value === undefined ) {
			return this[ cache ].slice();
		}

		var ret,
			type = getType( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		} );

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {

		// alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var local, cur, match, fn,
				vtype = getType( value );

			if ( key === "alpha" ) {
				fn = this._hsla ? "hsla" : "rgba";
			} else {
				fn = spaceName;
			}
			local = this[ fn ]();
			cur = local[ prop.idx ];

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = getType( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	} );
} );

// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( _i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed;

				if ( value !== "transparent" &&
					( getType( value ) !== "string" ||
						( parsed = stringParse( value ) ) ) ) {
					value = color( parsed || value );
					value = value.toRgbaString();
				}
				elem.style[ hook ] = value;
			}
		};
		jQuery.fx.step[ hook ] = function( fx ) {
			if ( !fx.colorInit ) {
				fx.start = color( fx.elem, hook );
				fx.end = color( fx.end );
				fx.colorInit = true;
			}
			jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
		};
	} );

};

color.hook( stepHooks );

jQuery.cssHooks.borderColor = {
	expand: function( value ) {
		var expanded = {};

		each( [ "Top", "Right", "Bottom", "Left" ], function( _i, part ) {
			expanded[ "border" + part + "Color" ] = value;
		} );
		return expanded;
	}
};

// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {

	// 4.1. Basic color keywords
	aqua: "#00ffff",
	black: "#000000",
	blue: "#0000ff",
	fuchsia: "#ff00ff",
	gray: "#808080",
	green: "#008000",
	lime: "#00ff00",
	maroon: "#800000",
	navy: "#000080",
	olive: "#808000",
	purple: "#800080",
	red: "#ff0000",
	silver: "#c0c0c0",
	teal: "#008080",
	white: "#ffffff",
	yellow: "#ffff00",

	// 4.2.3. "transparent" color keyword
	transparent: [ null, null, null, 0 ],

	_default: "#ffffff"
};


/*!
 * jQuery UI Effects 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Effects Core
//>>group: Effects
/* eslint-disable max-len */
//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
/* eslint-enable max-len */
//>>docs: https://api.jqueryui.com/category/effects-core/
//>>demos: https://jqueryui.com/effect/


var dataSpace = "ui-effects-",
	dataSpaceStyle = "ui-effects-style",
	dataSpaceAnimated = "ui-effects-animated";

$.effects = {
	effect: {}
};

/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
( function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each(
	[ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ],
	function( _, prop ) {
		$.fx.step[ prop ] = function( fx ) {
			if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
				jQuery.style( fx.elem, prop, fx.end );
				fx.setAttr = true;
			}
		};
	}
);

function camelCase( string ) {
	return string.replace( /-([\da-z])/gi, function( all, letter ) {
		return letter.toUpperCase();
	} );
}

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView.getComputedStyle( elem ),
		styles = {};

	len = style.length;
	while ( len-- ) {
		key = style[ len ];
		if ( typeof style[ key ] === "string" ) {
			styles[ camelCase( key ) ] = style[ key ];
		}
	}

	return styles;
}

function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// Map the animated objects to store the original styles.
		allAnimations = allAnimations.map( function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		} );

		// Apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function( i, action ) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			} );
		};
		applyClassChange();

		// Map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map( function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		} );

		// Apply original class
		animated.attr( "class", baseClass );

		// Map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map( function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend( {}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				} );

			this.el.animate( this.diff, opts );
			return dfd.promise();
		} );

		// Once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done( function() {

			// Set the final class
			applyClassChange();

			// For each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function( key ) {
					el.css( key, "" );
				} );
			} );

			// This is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		} );
	} );
};

$.fn.extend( {
	addClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.addClass ),

	removeClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.removeClass ),

	toggleClass: ( function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {

					// Without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						( force ? { add: classNames } : { remove: classNames } ),
						speed, easing, callback );
				}
			} else {

				// Without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	} )( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback ) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
} );

} )();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

( function() {

if ( $.expr && $.expr.pseudos && $.expr.pseudos.animated ) {
	$.expr.pseudos.animated = ( function( orig ) {
		return function( elem ) {
			return !!$( elem ).data( dataSpaceAnimated ) || orig( elem );
		};
	} )( $.expr.pseudos.animated );
}

if ( $.uiBackCompat === true ) {
	$.extend( $.effects, {

		// Saves a set of properties in a data storage
		save: function( element, set ) {
			var i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
				}
			}
		},

		// Restores a set of previously saved properties from a data storage
		restore: function( element, set ) {
			var val, i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					val = element.data( dataSpace + set[ i ] );
					element.css( set[ i ], val );
				}
			}
		},

		setMode: function( el, mode ) {
			if ( mode === "toggle" ) {
				mode = el.is( ":hidden" ) ? "show" : "hide";
			}
			return mode;
		},

		// Wraps the element around a wrapper that copies position properties
		createWrapper: function( element ) {

			// If the element is already wrapped, return it
			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				return element.parent();
			}

			// Wrap the element
			var props = {
					width: element.outerWidth( true ),
					height: element.outerHeight( true ),
					"float": element.css( "float" )
				},
				wrapper = $( "<div></div>" )
					.addClass( "ui-effects-wrapper" )
					.css( {
						fontSize: "100%",
						background: "transparent",
						border: "none",
						margin: 0,
						padding: 0
					} ),

				// Store the size in case width/height are defined in % - Fixes #5245
				size = {
					width: element.width(),
					height: element.height()
				},
				active = document.activeElement;

			// Support: Firefox
			// Firefox incorrectly exposes anonymous content
			// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
			try {
				// eslint-disable-next-line no-unused-expressions
				active.id;
			} catch ( e ) {
				active = document.body;
			}

			element.wrap( wrapper );

			// Fixes #7595 - Elements lose focus when wrapped.
			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
				$( active ).trigger( "focus" );
			}

			// Hotfix for jQuery 1.4 since some change in wrap() seems to actually
			// lose the reference to the wrapped element
			wrapper = element.parent();

			// Transfer positioning properties to the wrapper
			if ( element.css( "position" ) === "static" ) {
				wrapper.css( { position: "relative" } );
				element.css( { position: "relative" } );
			} else {
				$.extend( props, {
					position: element.css( "position" ),
					zIndex: element.css( "z-index" )
				} );
				$.each( [ "top", "left", "bottom", "right" ], function( i, pos ) {
					props[ pos ] = element.css( pos );
					if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
						props[ pos ] = "auto";
					}
				} );
				element.css( {
					position: "relative",
					top: 0,
					left: 0,
					right: "auto",
					bottom: "auto"
				} );
			}
			element.css( size );

			return wrapper.css( props ).show();
		},

		removeWrapper: function( element ) {
			var active = document.activeElement;

			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				element.parent().replaceWith( element );

				// Fixes #7595 - Elements lose focus when wrapped.
				if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
					$( active ).trigger( "focus" );
				}
			}

			return element;
		}
	} );
}

$.extend( $.effects, {
	version: "1.14.0",

	define: function( name, mode, effect ) {
		if ( !effect ) {
			effect = mode;
			mode = "effect";
		}

		$.effects.effect[ name ] = effect;
		$.effects.effect[ name ].mode = mode;

		return effect;
	},

	scaledDimensions: function( element, percent, direction ) {
		if ( percent === 0 ) {
			return {
				height: 0,
				width: 0,
				outerHeight: 0,
				outerWidth: 0
			};
		}

		var x = direction !== "horizontal" ? ( ( percent || 100 ) / 100 ) : 1,
			y = direction !== "vertical" ? ( ( percent || 100 ) / 100 ) : 1;

		return {
			height: element.height() * y,
			width: element.width() * x,
			outerHeight: element.outerHeight() * y,
			outerWidth: element.outerWidth() * x
		};

	},

	clipToBox: function( animation ) {
		return {
			width: animation.clip.right - animation.clip.left,
			height: animation.clip.bottom - animation.clip.top,
			left: animation.clip.left,
			top: animation.clip.top
		};
	},

	// Injects recently queued functions to be first in line (after "inprogress")
	unshift: function( element, queueLength, count ) {
		var queue = element.queue();

		if ( queueLength > 1 ) {
			queue.splice.apply( queue,
				[ 1, 0 ].concat( queue.splice( queueLength, count ) ) );
		}
		element.dequeue();
	},

	saveStyle: function( element ) {
		element.data( dataSpaceStyle, element[ 0 ].style.cssText );
	},

	restoreStyle: function( element ) {
		element[ 0 ].style.cssText = element.data( dataSpaceStyle ) || "";
		element.removeData( dataSpaceStyle );
	},

	mode: function( element, mode ) {
		var hidden = element.is( ":hidden" );

		if ( mode === "toggle" ) {
			mode = hidden ? "show" : "hide";
		}
		if ( hidden ? mode === "hide" : mode === "show" ) {
			mode = "none";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	getBaseline: function( origin, original ) {
		var y, x;

		switch ( origin[ 0 ] ) {
		case "top":
			y = 0;
			break;
		case "middle":
			y = 0.5;
			break;
		case "bottom":
			y = 1;
			break;
		default:
			y = origin[ 0 ] / original.height;
		}

		switch ( origin[ 1 ] ) {
		case "left":
			x = 0;
			break;
		case "center":
			x = 0.5;
			break;
		case "right":
			x = 1;
			break;
		default:
			x = origin[ 1 ] / original.width;
		}

		return {
			x: x,
			y: y
		};
	},

	// Creates a placeholder element so that the original element can be made absolute
	createPlaceholder: function( element ) {
		var placeholder,
			cssPosition = element.css( "position" ),
			position = element.position();

		// Lock in margins first to account for form elements, which
		// will change margin if you explicitly set height
		// see: https://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
		// Support: Safari
		element.css( {
			marginTop: element.css( "marginTop" ),
			marginBottom: element.css( "marginBottom" ),
			marginLeft: element.css( "marginLeft" ),
			marginRight: element.css( "marginRight" )
		} )
		.outerWidth( element.outerWidth() )
		.outerHeight( element.outerHeight() );

		if ( /^(static|relative)/.test( cssPosition ) ) {
			cssPosition = "absolute";

			placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {

				// Convert inline to inline block to account for inline elements
				// that turn to inline block based on content (like img)
				display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
					"inline-block" :
					"block",
				visibility: "hidden",

				// Margins need to be set to account for margin collapse
				marginTop: element.css( "marginTop" ),
				marginBottom: element.css( "marginBottom" ),
				marginLeft: element.css( "marginLeft" ),
				marginRight: element.css( "marginRight" ),
				"float": element.css( "float" )
			} )
			.outerWidth( element.outerWidth() )
			.outerHeight( element.outerHeight() )
			.addClass( "ui-effects-placeholder" );

			element.data( dataSpace + "placeholder", placeholder );
		}

		element.css( {
			position: cssPosition,
			left: position.left,
			top: position.top
		} );

		return placeholder;
	},

	removePlaceholder: function( element ) {
		var dataKey = dataSpace + "placeholder",
				placeholder = element.data( dataKey );

		if ( placeholder ) {
			placeholder.remove();
			element.removeData( dataKey );
		}
	},

	// Removes a placeholder if it exists and restores
	// properties that were modified during placeholder creation
	cleanUp: function( element ) {
		$.effects.restoreStyle( element );
		$.effects.removePlaceholder( element );
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		} );
		return value;
	}
} );

// Return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// Allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// Convert to an object
	effect = { effect: effect };

	// Catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// Catch (effect, callback)
	if ( typeof options === "function" ) {
		callback = options;
		speed = null;
		options = {};
	}

	// Catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// Catch (effect, options, callback)
	if ( typeof speed === "function" ) {
		callback = speed;
		speed = null;
	}

	// Add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {

	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( typeof option === "function" ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend( {
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			effectMethod = $.effects.effect[ args.effect ],
			defaultMode = effectMethod.mode,
			queue = args.queue,
			queueName = queue || "fx",
			complete = args.complete,
			mode = args.mode,
			modes = [],
			prefilter = function( next ) {
				var el = $( this ),
					normalizedMode = $.effects.mode( el, mode ) || defaultMode;

				// Sentinel for duck-punching the :animated pseudo-selector
				el.data( dataSpaceAnimated, true );

				// Save effect mode for later use,
				// we can't just call $.effects.mode again later,
				// as the .show() below destroys the initial state
				modes.push( normalizedMode );

				// See $.uiBackCompat inside of run() for removal of defaultMode in 1.14
				if ( defaultMode && ( normalizedMode === "show" ||
						( normalizedMode === defaultMode && normalizedMode === "hide" ) ) ) {
					el.show();
				}

				if ( !defaultMode || normalizedMode !== "none" ) {
					$.effects.saveStyle( el );
				}

				if ( typeof next === "function" ) {
					next();
				}
			};

		if ( $.fx.off || !effectMethod ) {

			// Delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, complete );
			} else {
				return this.each( function() {
					if ( complete ) {
						complete.call( this );
					}
				} );
			}
		}

		function run( next ) {
			var elem = $( this );

			function cleanup() {
				elem.removeData( dataSpaceAnimated );

				$.effects.cleanUp( elem );

				if ( args.mode === "hide" ) {
					elem.hide();
				}

				done();
			}

			function done() {
				if ( typeof complete === "function" ) {
					complete.call( elem[ 0 ] );
				}

				if ( typeof next === "function" ) {
					next();
				}
			}

			// Override mode option on a per element basis,
			// as toggle can be either show or hide depending on element state
			args.mode = modes.shift();

			if ( $.uiBackCompat === true && !defaultMode ) {
				if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, done );
				}
			} else {
				if ( args.mode === "none" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, cleanup );
				}
			}
		}

		// Run prefilter on all elements first to ensure that
		// any showing or hiding happens before placeholder creation,
		// which ensures that any layout changes are correctly captured.
		return queue === false ?
			this.each( prefilter ).each( run ) :
			this.queue( queueName, prefilter ).queue( queueName, run );
	},

	show: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "show";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.show ),

	hide: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "hide";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.hide ),

	toggle: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "toggle";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.toggle ),

	cssUnit: function( key ) {
		var style = this.css( key ),
			val = [];

		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
			if ( style.indexOf( unit ) > 0 ) {
				val = [ parseFloat( style ), unit ];
			}
		} );
		return val;
	},

	cssClip: function( clipObj ) {
		if ( clipObj ) {
			return this.css( "clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " +
				clipObj.bottom + "px " + clipObj.left + "px)" );
		}
		return parseClip( this.css( "clip" ), this );
	},

	transfer: function( options, done ) {
		var element = $( this ),
			target = $( options.to ),
			targetFixed = target.css( "position" ) === "fixed",
			body = $( "body" ),
			fixTop = targetFixed ? body.scrollTop() : 0,
			fixLeft = targetFixed ? body.scrollLeft() : 0,
			endPosition = target.offset(),
			animation = {
				top: endPosition.top - fixTop,
				left: endPosition.left - fixLeft,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = element.offset(),
			transfer = $( "<div class='ui-effects-transfer'></div>" );

		transfer
			.appendTo( "body" )
			.addClass( options.className )
			.css( {
				top: startPosition.top - fixTop,
				left: startPosition.left - fixLeft,
				height: element.innerHeight(),
				width: element.innerWidth(),
				position: targetFixed ? "fixed" : "absolute"
			} )
			.animate( animation, options.duration, options.easing, function() {
				transfer.remove();
				if ( typeof done === "function" ) {
					done();
				}
			} );
	}
} );

function parseClip( str, element ) {
		var outerWidth = element.outerWidth(),
			outerHeight = element.outerHeight(),
			clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,
			values = clipRegex.exec( str ) || [ "", 0, outerWidth, outerHeight, 0 ];

		return {
			top: parseFloat( values[ 1 ] ) || 0,
			right: values[ 2 ] === "auto" ? outerWidth : parseFloat( values[ 2 ] ),
			bottom: values[ 3 ] === "auto" ? outerHeight : parseFloat( values[ 3 ] ),
			left: parseFloat( values[ 4 ] ) || 0
		};
}

$.fx.step.clip = function( fx ) {
	if ( !fx.clipInit ) {
		fx.start = $( fx.elem ).cssClip();
		if ( typeof fx.end === "string" ) {
			fx.end = parseClip( fx.end, fx.elem );
		}
		fx.clipInit = true;
	}

	$( fx.elem ).cssClip( {
		top: fx.pos * ( fx.end.top - fx.start.top ) + fx.start.top,
		right: fx.pos * ( fx.end.right - fx.start.right ) + fx.start.right,
		bottom: fx.pos * ( fx.end.bottom - fx.start.bottom ) + fx.start.bottom,
		left: fx.pos * ( fx.end.left - fx.start.left ) + fx.start.left
	} );
};

} )();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

( function() {

// Based on easing equations from Robert Penner (http://robertpenner.com/easing)

var baseEasings = {};

$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
	baseEasings[ name ] = function( p ) {
		return Math.pow( p, i + 2 );
	};
} );

$.extend( baseEasings, {
	Sine: function( p ) {
		return 1 - Math.cos( p * Math.PI / 2 );
	},
	Circ: function( p ) {
		return 1 - Math.sqrt( 1 - p * p );
	},
	Elastic: function( p ) {
		return p === 0 || p === 1 ? p :
			-Math.pow( 2, 8 * ( p - 1 ) ) * Math.sin( ( ( p - 1 ) * 80 - 7.5 ) * Math.PI / 15 );
	},
	Back: function( p ) {
		return p * p * ( 3 * p - 2 );
	},
	Bounce: function( p ) {
		var pow2,
			bounce = 4;

		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
	}
} );

$.each( baseEasings, function( name, easeIn ) {
	$.easing[ "easeIn" + name ] = easeIn;
	$.easing[ "easeOut" + name ] = function( p ) {
		return 1 - easeIn( 1 - p );
	};
	$.easing[ "easeInOut" + name ] = function( p ) {
		return p < 0.5 ?
			easeIn( p * 2 ) / 2 :
			1 - easeIn( p * -2 + 2 ) / 2;
	};
} );

} )();

var effect = $.effects;


/*!
 * jQuery UI Effects Blind 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Blind Effect
//>>group: Effects
//>>description: Blinds the element.
//>>docs: https://api.jqueryui.com/blind-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectBlind = $.effects.define( "blind", "hide", function( options, done ) {
	var map = {
			up: [ "bottom", "top" ],
			vertical: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			horizontal: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		element = $( this ),
		direction = options.direction || "up",
		start = element.cssClip(),
		animate = { clip: $.extend( {}, start ) },
		placeholder = $.effects.createPlaceholder( element );

	animate.clip[ map[ direction ][ 0 ] ] = animate.clip[ map[ direction ][ 1 ] ];

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animate ) );
		}

		animate.clip = start;
	}

	if ( placeholder ) {
		placeholder.animate( $.effects.clipToBox( animate ), options.duration, options.easing );
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Bounce 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Bounce Effect
//>>group: Effects
//>>description: Bounces an element horizontally or vertically n times.
//>>docs: https://api.jqueryui.com/bounce-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectBounce = $.effects.define( "bounce", function( options, done ) {
	var upAnim, downAnim, refValue,
		element = $( this ),

		// Defaults:
		mode = options.mode,
		hide = mode === "hide",
		show = mode === "show",
		direction = options.direction || "up",
		distance = options.distance,
		times = options.times || 5,

		// Number of internal animations
		anims = times * 2 + ( show || hide ? 1 : 0 ),
		speed = options.duration / anims,
		easing = options.easing,

		// Utility:
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ),
		i = 0,

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	refValue = element.css( ref );

	// Default distance for the BIGGEST bounce is the outer Distance / 3
	if ( !distance ) {
		distance = element[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
	}

	if ( show ) {
		downAnim = { opacity: 1 };
		downAnim[ ref ] = refValue;

		// If we are showing, force opacity 0 and set the initial position
		// then do the "first" animation
		element
			.css( "opacity", 0 )
			.css( ref, motion ? -distance * 2 : distance * 2 )
			.animate( downAnim, speed, easing );
	}

	// Start at the smallest distance if we are hiding
	if ( hide ) {
		distance = distance / Math.pow( 2, times - 1 );
	}

	downAnim = {};
	downAnim[ ref ] = refValue;

	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
	for ( ; i < times; i++ ) {
		upAnim = {};
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element
			.animate( upAnim, speed, easing )
			.animate( downAnim, speed, easing );

		distance = hide ? distance * 2 : distance / 2;
	}

	// Last Bounce when Hiding
	if ( hide ) {
		upAnim = { opacity: 0 };
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element.animate( upAnim, speed, easing );
	}

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Clip 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Clip Effect
//>>group: Effects
//>>description: Clips the element on and off like an old TV.
//>>docs: https://api.jqueryui.com/clip-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectClip = $.effects.define( "clip", "hide", function( options, done ) {
	var start,
		animate = {},
		element = $( this ),
		direction = options.direction || "vertical",
		both = direction === "both",
		horizontal = both || direction === "horizontal",
		vertical = both || direction === "vertical";

	start = element.cssClip();
	animate.clip = {
		top: vertical ? ( start.bottom - start.top ) / 2 : start.top,
		right: horizontal ? ( start.right - start.left ) / 2 : start.right,
		bottom: vertical ? ( start.bottom - start.top ) / 2 : start.bottom,
		left: horizontal ? ( start.right - start.left ) / 2 : start.left
	};

	$.effects.createPlaceholder( element );

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		animate.clip = start;
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );

} );


/*!
 * jQuery UI Effects Drop 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Drop Effect
//>>group: Effects
//>>description: Moves an element in one direction and hides it at the same time.
//>>docs: https://api.jqueryui.com/drop-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectDrop = $.effects.define( "drop", "hide", function( options, done ) {

	var distance,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ) ? "-=" : "+=",
		oppositeMotion = ( motion === "+=" ) ? "-=" : "+=",
		animation = {
			opacity: 0
		};

	$.effects.createPlaceholder( element );

	distance = options.distance ||
		element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2;

	animation[ ref ] = motion + distance;

	if ( show ) {
		element.css( animation );

		animation[ ref ] = oppositeMotion + distance;
		animation.opacity = 1;
	}

	// Animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Explode 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Explode Effect
//>>group: Effects
/* eslint-disable max-len */
//>>description: Explodes an element in all directions into n pieces. Implodes an element to its original wholeness.
/* eslint-enable max-len */
//>>docs: https://api.jqueryui.com/explode-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectExplode = $.effects.define( "explode", "hide", function( options, done ) {

	var i, j, left, top, mx, my,
		rows = options.pieces ? Math.round( Math.sqrt( options.pieces ) ) : 3,
		cells = rows,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",

		// Show and then visibility:hidden the element before calculating offset
		offset = element.show().css( "visibility", "hidden" ).offset(),

		// Width and height of a piece
		width = Math.ceil( element.outerWidth() / cells ),
		height = Math.ceil( element.outerHeight() / rows ),
		pieces = [];

	// Children animate complete:
	function childComplete() {
		pieces.push( this );
		if ( pieces.length === rows * cells ) {
			animComplete();
		}
	}

	// Clone the element for each row and cell.
	for ( i = 0; i < rows; i++ ) { // ===>
		top = offset.top + i * height;
		my = i - ( rows - 1 ) / 2;

		for ( j = 0; j < cells; j++ ) { // |||
			left = offset.left + j * width;
			mx = j - ( cells - 1 ) / 2;

			// Create a clone of the now hidden main element that will be absolute positioned
			// within a wrapper div off the -left and -top equal to size of our pieces
			element
				.clone()
				.appendTo( "body" )
				.wrap( "<div></div>" )
				.css( {
					position: "absolute",
					visibility: "visible",
					left: -j * width,
					top: -i * height
				} )

				// Select the wrapper - make it overflow: hidden and absolute positioned based on
				// where the original was located +left and +top equal to the size of pieces
				.parent()
					.addClass( "ui-effects-explode" )
					.css( {
						position: "absolute",
						overflow: "hidden",
						width: width,
						height: height,
						left: left + ( show ? mx * width : 0 ),
						top: top + ( show ? my * height : 0 ),
						opacity: show ? 0 : 1
					} )
					.animate( {
						left: left + ( show ? 0 : mx * width ),
						top: top + ( show ? 0 : my * height ),
						opacity: show ? 1 : 0
					}, options.duration || 500, options.easing, childComplete );
		}
	}

	function animComplete() {
		element.css( {
			visibility: "visible"
		} );
		$( pieces ).remove();
		done();
	}
} );


/*!
 * jQuery UI Effects Fade 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Fade Effect
//>>group: Effects
//>>description: Fades the element.
//>>docs: https://api.jqueryui.com/fade-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectFade = $.effects.define( "fade", "toggle", function( options, done ) {
	var show = options.mode === "show";

	$( this )
		.css( "opacity", show ? 0 : 1 )
		.animate( {
			opacity: show ? 1 : 0
		}, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );


/*!
 * jQuery UI Effects Fold 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Fold Effect
//>>group: Effects
//>>description: Folds an element first horizontally and then vertically.
//>>docs: https://api.jqueryui.com/fold-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectFold = $.effects.define( "fold", "hide", function( options, done ) {

	// Create element
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		size = options.size || 15,
		percent = /([0-9]+)%/.exec( size ),
		horizFirst = !!options.horizFirst,
		ref = horizFirst ? [ "right", "bottom" ] : [ "bottom", "right" ],
		duration = options.duration / 2,

		placeholder = $.effects.createPlaceholder( element ),

		start = element.cssClip(),
		animation1 = { clip: $.extend( {}, start ) },
		animation2 = { clip: $.extend( {}, start ) },

		distance = [ start[ ref[ 0 ] ], start[ ref[ 1 ] ] ],

		queuelen = element.queue().length;

	if ( percent ) {
		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
	}
	animation1.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 1 ] ] = 0;

	if ( show ) {
		element.cssClip( animation2.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animation2 ) );
		}

		animation2.clip = start;
	}

	// Animate
	element
		.queue( function( next ) {
			if ( placeholder ) {
				placeholder
					.animate( $.effects.clipToBox( animation1 ), duration, options.easing )
					.animate( $.effects.clipToBox( animation2 ), duration, options.easing );
			}

			next();
		} )
		.animate( animation1, duration, options.easing )
		.animate( animation2, duration, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, 4 );
} );


/*!
 * jQuery UI Effects Highlight 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Highlight Effect
//>>group: Effects
//>>description: Highlights the background of an element in a defined color for a custom duration.
//>>docs: https://api.jqueryui.com/highlight-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectHighlight = $.effects.define( "highlight", "show", function( options, done ) {
	var element = $( this ),
		animation = {
			backgroundColor: element.css( "backgroundColor" )
		};

	if ( options.mode === "hide" ) {
		animation.opacity = 0;
	}

	$.effects.saveStyle( element );

	element
		.css( {
			backgroundImage: "none",
			backgroundColor: options.color || "#ffff99"
		} )
		.animate( animation, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );


/*!
 * jQuery UI Effects Size 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Size Effect
//>>group: Effects
//>>description: Resize an element to a specified width and height.
//>>docs: https://api.jqueryui.com/size-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectSize = $.effects.define( "size", function( options, done ) {

	// Create element
	var baseline, factor, temp,
		element = $( this ),

		// Copy for children
		cProps = [ "fontSize" ],
		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],

		// Set options
		mode = options.mode,
		restore = mode !== "effect",
		scale = options.scale || "both",
		origin = options.origin || [ "middle", "center" ],
		position = element.css( "position" ),
		pos = element.position(),
		original = $.effects.scaledDimensions( element ),
		from = options.from || original,
		to = options.to || $.effects.scaledDimensions( element, 0 );

	$.effects.createPlaceholder( element );

	if ( mode === "show" ) {
		temp = from;
		from = to;
		to = temp;
	}

	// Set scaling factor
	factor = {
		from: {
			y: from.height / original.height,
			x: from.width / original.width
		},
		to: {
			y: to.height / original.height,
			x: to.width / original.width
		}
	};

	// Scale the css box
	if ( scale === "box" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, vProps, factor.from.y, from );
			to = $.effects.setTransition( element, vProps, factor.to.y, to );
		}

		// Horizontal props scaling
		if ( factor.from.x !== factor.to.x ) {
			from = $.effects.setTransition( element, hProps, factor.from.x, from );
			to = $.effects.setTransition( element, hProps, factor.to.x, to );
		}
	}

	// Scale the content
	if ( scale === "content" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, cProps, factor.from.y, from );
			to = $.effects.setTransition( element, cProps, factor.to.y, to );
		}
	}

	// Adjust the position properties based on the provided origin points
	if ( origin ) {
		baseline = $.effects.getBaseline( origin, original );
		from.top = ( original.outerHeight - from.outerHeight ) * baseline.y + pos.top;
		from.left = ( original.outerWidth - from.outerWidth ) * baseline.x + pos.left;
		to.top = ( original.outerHeight - to.outerHeight ) * baseline.y + pos.top;
		to.left = ( original.outerWidth - to.outerWidth ) * baseline.x + pos.left;
	}
	delete from.outerHeight;
	delete from.outerWidth;
	element.css( from );

	// Animate the children if desired
	if ( scale === "content" || scale === "both" ) {

		vProps = vProps.concat( [ "marginTop", "marginBottom" ] ).concat( cProps );
		hProps = hProps.concat( [ "marginLeft", "marginRight" ] );

		// Only animate children with width attributes specified
		// TODO: is this right? should we include anything with css width specified as well
		element.find( "*[width]" ).each( function() {
			var child = $( this ),
				childOriginal = $.effects.scaledDimensions( child ),
				childFrom = {
					height: childOriginal.height * factor.from.y,
					width: childOriginal.width * factor.from.x,
					outerHeight: childOriginal.outerHeight * factor.from.y,
					outerWidth: childOriginal.outerWidth * factor.from.x
				},
				childTo = {
					height: childOriginal.height * factor.to.y,
					width: childOriginal.width * factor.to.x,
					outerHeight: childOriginal.height * factor.to.y,
					outerWidth: childOriginal.width * factor.to.x
				};

			// Vertical props scaling
			if ( factor.from.y !== factor.to.y ) {
				childFrom = $.effects.setTransition( child, vProps, factor.from.y, childFrom );
				childTo = $.effects.setTransition( child, vProps, factor.to.y, childTo );
			}

			// Horizontal props scaling
			if ( factor.from.x !== factor.to.x ) {
				childFrom = $.effects.setTransition( child, hProps, factor.from.x, childFrom );
				childTo = $.effects.setTransition( child, hProps, factor.to.x, childTo );
			}

			if ( restore ) {
				$.effects.saveStyle( child );
			}

			// Animate children
			child.css( childFrom );
			child.animate( childTo, options.duration, options.easing, function() {

				// Restore children
				if ( restore ) {
					$.effects.restoreStyle( child );
				}
			} );
		} );
	}

	// Animate
	element.animate( to, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: function() {

			var offset = element.offset();

			if ( to.opacity === 0 ) {
				element.css( "opacity", from.opacity );
			}

			if ( !restore ) {
				element
					.css( "position", position === "static" ? "relative" : position )
					.offset( offset );

				// Need to save style here so that automatic style restoration
				// doesn't restore to the original styles from before the animation.
				$.effects.saveStyle( element );
			}

			done();
		}
	} );

} );


/*!
 * jQuery UI Effects Scale 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Scale Effect
//>>group: Effects
//>>description: Grows or shrinks an element and its content.
//>>docs: https://api.jqueryui.com/scale-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectScale = $.effects.define( "scale", function( options, done ) {

	// Create element
	var el = $( this ),
		mode = options.mode,
		percent = parseInt( options.percent, 10 ) ||
			( parseInt( options.percent, 10 ) === 0 ? 0 : ( mode !== "effect" ? 0 : 100 ) ),

		newOptions = $.extend( true, {
			from: $.effects.scaledDimensions( el ),
			to: $.effects.scaledDimensions( el, percent, options.direction || "both" ),
			origin: options.origin || [ "middle", "center" ]
		}, options );

	// Fade option to support puff
	if ( options.fade ) {
		newOptions.from.opacity = 1;
		newOptions.to.opacity = 0;
	}

	$.effects.effect.size.call( this, newOptions, done );
} );


/*!
 * jQuery UI Effects Puff 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Puff Effect
//>>group: Effects
//>>description: Creates a puff effect by scaling the element up and hiding it at the same time.
//>>docs: https://api.jqueryui.com/puff-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectPuff = $.effects.define( "puff", "hide", function( options, done ) {
	var newOptions = $.extend( true, {}, options, {
		fade: true,
		percent: parseInt( options.percent, 10 ) || 150
	} );

	$.effects.effect.scale.call( this, newOptions, done );
} );


/*!
 * jQuery UI Effects Pulsate 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Pulsate Effect
//>>group: Effects
//>>description: Pulsates an element n times by changing the opacity to zero and back.
//>>docs: https://api.jqueryui.com/pulsate-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectPulsate = $.effects.define( "pulsate", "show", function( options, done ) {
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		showhide = show || hide,

		// Showing or hiding leaves off the "last" animation
		anims = ( ( options.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
		duration = options.duration / anims,
		animateTo = 0,
		i = 1,
		queuelen = element.queue().length;

	if ( show || !element.is( ":visible" ) ) {
		element.css( "opacity", 0 ).show();
		animateTo = 1;
	}

	// Anims - 1 opacity "toggles"
	for ( ; i < anims; i++ ) {
		element.animate( { opacity: animateTo }, duration, options.easing );
		animateTo = 1 - animateTo;
	}

	element.animate( { opacity: animateTo }, duration, options.easing );

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Shake 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Shake Effect
//>>group: Effects
//>>description: Shakes an element horizontally or vertically n times.
//>>docs: https://api.jqueryui.com/shake-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectShake = $.effects.define( "shake", function( options, done ) {

	var i = 1,
		element = $( this ),
		direction = options.direction || "left",
		distance = options.distance || 20,
		times = options.times || 3,
		anims = times * 2 + 1,
		speed = Math.round( options.duration / anims ),
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		animation = {},
		animation1 = {},
		animation2 = {},

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	// Animation
	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;

	// Animate
	element.animate( animation, speed, options.easing );

	// Shakes
	for ( ; i < times; i++ ) {
		element
			.animate( animation1, speed, options.easing )
			.animate( animation2, speed, options.easing );
	}

	element
		.animate( animation1, speed, options.easing )
		.animate( animation, speed / 2, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Slide 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Slide Effect
//>>group: Effects
//>>description: Slides an element in and out of the viewport.
//>>docs: https://api.jqueryui.com/slide-effect/
//>>demos: https://jqueryui.com/effect/


var effectsEffectSlide = $.effects.define( "slide", "show", function( options, done ) {
	var startClip, startRef,
		element = $( this ),
		map = {
			up: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		mode = options.mode,
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		distance = options.distance ||
			element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ),
		animation = {};

	$.effects.createPlaceholder( element );

	startClip = element.cssClip();
	startRef = element.position()[ ref ];

	// Define hide animation
	animation[ ref ] = ( positiveMotion ? -1 : 1 ) * distance + startRef;
	animation.clip = element.cssClip();
	animation.clip[ map[ direction ][ 1 ] ] = animation.clip[ map[ direction ][ 0 ] ];

	// Reverse the animation if we're showing
	if ( mode === "show" ) {
		element.cssClip( animation.clip );
		element.css( ref, animation[ ref ] );
		animation.clip = startClip;
		animation[ ref ] = startRef;
	}

	// Actually animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Transfer 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Transfer Effect
//>>group: Effects
//>>description: Displays a transfer effect from one element to another.
//>>docs: https://api.jqueryui.com/transfer-effect/
//>>demos: https://jqueryui.com/effect/


var effect;
if ( $.uiBackCompat === true ) {
	effect = $.effects.define( "transfer", function( options, done ) {
		$( this ).transfer( options, done );
	} );
}
var effectsEffectTransfer = effect;


/*!
 * jQuery UI Focusable 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: https://api.jqueryui.com/focusable-selector/


// Selectors
$.ui.focusable = function( element, hasTabindex ) {
	var map, mapName, img, focusableIfVisible, fieldset,
		nodeName = element.nodeName.toLowerCase();

	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap='#" + mapName + "']" );
		return img.length > 0 && img.is( ":visible" );
	}

	if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
		focusableIfVisible = !element.disabled;

		if ( focusableIfVisible ) {

			// Form controls within a disabled fieldset are disabled.
			// However, controls within the fieldset's legend do not get disabled.
			// Since controls generally aren't placed inside legends, we skip
			// this portion of the check.
			fieldset = $( element ).closest( "fieldset" )[ 0 ];
			if ( fieldset ) {
				focusableIfVisible = !fieldset.disabled;
			}
		}
	} else if ( "a" === nodeName ) {
		focusableIfVisible = element.href || hasTabindex;
	} else {
		focusableIfVisible = hasTabindex;
	}

	return focusableIfVisible && $( element ).is( ":visible" ) &&
		$( element ).css( "visibility" ) === "visible";
};

$.extend( $.expr.pseudos, {
	focusable: function( element ) {
		return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
	}
} );

var focusable = $.ui.focusable;


/*!
 * jQuery UI Form Reset Mixin 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Form Reset Mixin
//>>group: Core
//>>description: Refresh input widgets when their form is reset
//>>docs: https://api.jqueryui.com/form-reset-mixin/


var formResetMixin = $.ui.formResetMixin = {
	_formResetHandler: function() {
		var form = $( this );

		// Wait for the form reset to actually happen before refreshing
		setTimeout( function() {
			var instances = form.data( "ui-form-reset-instances" );
			$.each( instances, function() {
				this.refresh();
			} );
		} );
	},

	_bindFormResetHandler: function() {
		this.form = $( this.element.prop( "form" ) );
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" ) || [];
		if ( !instances.length ) {

			// We don't use _on() here because we use a single event handler per form
			this.form.on( "reset.ui-form-reset", this._formResetHandler );
		}
		instances.push( this );
		this.form.data( "ui-form-reset-instances", instances );
	},

	_unbindFormResetHandler: function() {
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" );
		instances.splice( $.inArray( this, instances ), 1 );
		if ( instances.length ) {
			this.form.data( "ui-form-reset-instances", instances );
		} else {
			this.form
				.removeData( "ui-form-reset-instances" )
				.off( "reset.ui-form-reset" );
		}
	}
};


/*!
 * jQuery UI Legacy jQuery Core patches 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 *
 */

//>>label: Legacy jQuery Core patches
//>>group: Core
//>>description: Backport `.even()`, `.odd()` and `$.escapeSelector` to older jQuery Core versions (deprecated)


// Support: jQuery 2.2.x or older.
// This method has been defined in jQuery 3.0.0.
// Code from https://github.com/jquery/jquery/blob/e539bac79e666bba95bba86d690b4e609dca2286/src/selector/escapeSelector.js
if ( !$.escapeSelector ) {
	$.escapeSelector = function( id ) {
		return CSS.escape( id + "" );
	};
}

// Support: jQuery 3.4.x or older
// These methods have been defined in jQuery 3.5.0.
if ( !$.fn.even || !$.fn.odd ) {
	$.fn.extend( {
		even: function() {
			return this.filter( function( i ) {
				return i % 2 === 0;
			} );
		},
		odd: function() {
			return this.filter( function( i ) {
				return i % 2 === 1;
			} );
		}
	} );
}

;
/*!
 * jQuery UI Keycode 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: https://api.jqueryui.com/jQuery.ui.keyCode/


var keycode = $.ui.keyCode = {
	BACKSPACE: 8,
	COMMA: 188,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	LEFT: 37,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SPACE: 32,
	TAB: 9,
	UP: 38
};


/*!
 * jQuery UI Labels 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: labels
//>>group: Core
//>>description: Find all the labels associated with a given input
//>>docs: https://api.jqueryui.com/labels/


var labels = $.fn.labels = function() {
	var ancestor, selector, id, labels, ancestors;

	if ( !this.length ) {
		return this.pushStack( [] );
	}

	// Check control.labels first
	if ( this[ 0 ].labels && this[ 0 ].labels.length ) {
		return this.pushStack( this[ 0 ].labels );
	}

	// If `control.labels` is empty - e.g. inside of document fragments - find
	// the labels manually
	labels = this.eq( 0 ).parents( "label" );

	// Look for the label based on the id
	id = this.attr( "id" );
	if ( id ) {

		// We don't search against the document in case the element
		// is disconnected from the DOM
		ancestor = this.eq( 0 ).parents().last();

		// Get a full set of top level ancestors
		ancestors = ancestor.add( ancestor.length ? ancestor.siblings() : this.siblings() );

		// Create a selector for the label based on the id
		selector = "label[for='" + CSS.escape( id ) + "']";

		labels = labels.add( ancestors.find( selector ).addBack( selector ) );

	}

	// Return whatever we have found for labels
	return this.pushStack( labels );
};


/*!
 * jQuery UI Scroll Parent 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: https://api.jqueryui.com/scrollParent/


var scrollParent = $.fn.scrollParent = function( includeHidden ) {
	var position = this.css( "position" ),
		excludeStaticParent = position === "absolute",
		overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
		scrollParent = this.parents().filter( function() {
			var parent = $( this );
			if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
				return false;
			}
			return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
				parent.css( "overflow-x" ) );
		} ).eq( 0 );

	return position === "fixed" || !scrollParent.length ?
		$( this[ 0 ].ownerDocument || document ) :
		scrollParent;
};


/*!
 * jQuery UI Tabbable 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: :tabbable Selector
//>>group: Core
//>>description: Selects elements which can be tabbed to.
//>>docs: https://api.jqueryui.com/tabbable-selector/


var tabbable = $.extend( $.expr.pseudos, {
	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			hasTabindex = tabIndex != null;
		return ( !hasTabindex || tabIndex >= 0 ) && $.ui.focusable( element, hasTabindex );
	}
} );


/*!
 * jQuery UI Unique ID 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: https://api.jqueryui.com/uniqueId/


var uniqueId = $.fn.extend( {
	uniqueId: ( function() {
		var uuid = 0;

		return function() {
			return this.each( function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			} );
		};
	} )(),

	removeUniqueId: function() {
		return this.each( function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		} );
	}
} );


/*!
 * jQuery UI Accordion 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Accordion
//>>group: Widgets
/* eslint-disable max-len */
//>>description: Displays collapsible content panels for presenting information in a limited amount of space.
/* eslint-enable max-len */
//>>docs: https://api.jqueryui.com/accordion/
//>>demos: https://jqueryui.com/accordion/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/accordion.css
//>>css.theme: ../../themes/base/theme.css


var widgetsAccordion = $.widget( "ui.accordion", {
	version: "1.14.0",
	options: {
		active: 0,
		animate: {},
		classes: {
			"ui-accordion-header": "ui-corner-top",
			"ui-accordion-header-collapsed": "ui-corner-all",
			"ui-accordion-content": "ui-corner-bottom"
		},
		collapsible: false,
		event: "click",
		header: function( elem ) {
			return elem
				.find( "> li > :first-child" )
				.add(
					elem.find( "> :not(li)" )

						// Support: jQuery <3.5 only
						// We could use `.even()` but that's unavailable in older jQuery.
						.filter( function( i ) {
							return i % 2 === 0;
						} )
				);
		},
		heightStyle: "auto",
		icons: {
			activeHeader: "ui-icon-triangle-1-s",
			header: "ui-icon-triangle-1-e"
		},

		// Callbacks
		activate: null,
		beforeActivate: null
	},

	hideProps: {
		borderTopWidth: "hide",
		borderBottomWidth: "hide",
		paddingTop: "hide",
		paddingBottom: "hide",
		height: "hide"
	},

	showProps: {
		borderTopWidth: "show",
		borderBottomWidth: "show",
		paddingTop: "show",
		paddingBottom: "show",
		height: "show"
	},

	_create: function() {
		var options = this.options;

		this.prevShow = this.prevHide = $();
		this._addClass( "ui-accordion", "ui-widget ui-helper-reset" );
		this.element.attr( "role", "tablist" );

		// Don't allow collapsible: false and active: false / null
		if ( !options.collapsible && ( options.active === false || options.active == null ) ) {
			options.active = 0;
		}

		this._processPanels();

		// handle negative values
		if ( options.active < 0 ) {
			options.active += this.headers.length;
		}
		this._refresh();
	},

	_getCreateEventData: function() {
		return {
			header: this.active,
			panel: !this.active.length ? $() : this.active.next()
		};
	},

	_createIcons: function() {
		var icon, children,
			icons = this.options.icons;

		if ( icons ) {
			icon = $( "<span>" );
			this._addClass( icon, "ui-accordion-header-icon", "ui-icon " + icons.header );
			icon.prependTo( this.headers );
			children = this.active.children( ".ui-accordion-header-icon" );
			this._removeClass( children, icons.header )
				._addClass( children, null, icons.activeHeader )
				._addClass( this.headers, "ui-accordion-icons" );
		}
	},

	_destroyIcons: function() {
		this._removeClass( this.headers, "ui-accordion-icons" );
		this.headers.children( ".ui-accordion-header-icon" ).remove();
	},

	_destroy: function() {
		var contents;

		// Clean up main element
		this.element.removeAttr( "role" );

		// Clean up headers
		this.headers
			.removeAttr( "role aria-expanded aria-selected aria-controls tabIndex" )
			.removeUniqueId();

		this._destroyIcons();

		// Clean up content panels
		contents = this.headers.next()
			.css( "display", "" )
			.removeAttr( "role aria-hidden aria-labelledby" )
			.removeUniqueId();

		if ( this.options.heightStyle !== "content" ) {
			contents.css( "height", "" );
		}
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {

			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "event" ) {
			if ( this.options.event ) {
				this._off( this.headers, this.options.event );
			}
			this._setupEvents( value );
		}

		this._super( key, value );

		// Setting collapsible: false while collapsed; open first panel
		if ( key === "collapsible" && !value && this.options.active === false ) {
			this._activate( 0 );
		}

		if ( key === "icons" ) {
			this._destroyIcons();
			if ( value ) {
				this._createIcons();
			}
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", value );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	_keydown: function( event ) {
		if ( event.altKey || event.ctrlKey ) {
			return;
		}

		var keyCode = $.ui.keyCode,
			length = this.headers.length,
			currentIndex = this.headers.index( event.target ),
			toFocus = false;

		switch ( event.keyCode ) {
		case keyCode.RIGHT:
		case keyCode.DOWN:
			toFocus = this.headers[ ( currentIndex + 1 ) % length ];
			break;
		case keyCode.LEFT:
		case keyCode.UP:
			toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
			break;
		case keyCode.SPACE:
		case keyCode.ENTER:
			this._eventHandler( event );
			break;
		case keyCode.HOME:
			toFocus = this.headers[ 0 ];
			break;
		case keyCode.END:
			toFocus = this.headers[ length - 1 ];
			break;
		}

		if ( toFocus ) {
			$( event.target ).attr( "tabIndex", -1 );
			$( toFocus ).attr( "tabIndex", 0 );
			$( toFocus ).trigger( "focus" );
			event.preventDefault();
		}
	},

	_panelKeyDown: function( event ) {
		if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
			$( event.currentTarget ).prev().trigger( "focus" );
		}
	},

	refresh: function() {
		var options = this.options;
		this._processPanels();

		// Was collapsed or no panel
		if ( ( options.active === false && options.collapsible === true ) ||
				!this.headers.length ) {
			options.active = false;
			this.active = $();

		// active false only when collapsible is true
		} else if ( options.active === false ) {
			this._activate( 0 );

		// was active, but active panel is gone
		} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {

			// all remaining panel are disabled
			if ( this.headers.length === this.headers.find( ".ui-state-disabled" ).length ) {
				options.active = false;
				this.active = $();

			// activate previous panel
			} else {
				this._activate( Math.max( 0, options.active - 1 ) );
			}

		// was active, active panel still exists
		} else {

			// make sure active index is correct
			options.active = this.headers.index( this.active );
		}

		this._destroyIcons();

		this._refresh();
	},

	_processPanels: function() {
		var prevHeaders = this.headers,
			prevPanels = this.panels;

		if ( typeof this.options.header === "function" ) {
			this.headers = this.options.header( this.element );
		} else {
			this.headers = this.element.find( this.options.header );
		}
		this._addClass( this.headers, "ui-accordion-header ui-accordion-header-collapsed",
			"ui-state-default" );

		this.panels = this.headers.next().filter( ":not(.ui-accordion-content-active)" ).hide();
		this._addClass( this.panels, "ui-accordion-content", "ui-helper-reset ui-widget-content" );

		// Avoid memory leaks (#10056)
		if ( prevPanels ) {
			this._off( prevHeaders.not( this.headers ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	_refresh: function() {
		var maxHeight,
			options = this.options,
			heightStyle = options.heightStyle,
			parent = this.element.parent();

		this.active = this._findActive( options.active );
		this._addClass( this.active, "ui-accordion-header-active", "ui-state-active" )
			._removeClass( this.active, "ui-accordion-header-collapsed" );
		this._addClass( this.active.next(), "ui-accordion-content-active" );
		this.active.next().show();

		this.headers
			.attr( "role", "tab" )
			.each( function() {
				var header = $( this ),
					headerId = header.uniqueId().attr( "id" ),
					panel = header.next(),
					panelId = panel.uniqueId().attr( "id" );
				header.attr( "aria-controls", panelId );
				panel.attr( "aria-labelledby", headerId );
			} )
			.next()
				.attr( "role", "tabpanel" );

		this.headers
			.not( this.active )
				.attr( {
					"aria-selected": "false",
					"aria-expanded": "false",
					tabIndex: -1
				} )
				.next()
					.attr( {
						"aria-hidden": "true"
					} )
					.hide();

		// Make sure at least one header is in the tab order
		if ( !this.active.length ) {
			this.headers.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active.attr( {
				"aria-selected": "true",
				"aria-expanded": "true",
				tabIndex: 0
			} )
				.next()
					.attr( {
						"aria-hidden": "false"
					} );
		}

		this._createIcons();

		this._setupEvents( options.event );

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			this.element.siblings( ":visible" ).each( function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			} );

			this.headers.each( function() {
				maxHeight -= $( this ).outerHeight( true );
			} );

			this.headers.next()
				.each( function() {
					$( this ).height( Math.max( 0, maxHeight -
						$( this ).innerHeight() + $( this ).height() ) );
				} )
				.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.headers.next()
				.each( function() {
					var isVisible = $( this ).is( ":visible" );
					if ( !isVisible ) {
						$( this ).show();
					}
					maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
					if ( !isVisible ) {
						$( this ).hide();
					}
				} )
				.height( maxHeight );
		}
	},

	_activate: function( index ) {
		var active = this._findActive( index )[ 0 ];

		// Trying to activate the already active panel
		if ( active === this.active[ 0 ] ) {
			return;
		}

		// Trying to collapse, simulate a click on the currently active header
		active = active || this.active[ 0 ];

		this._eventHandler( {
			target: active,
			currentTarget: active,
			preventDefault: $.noop
		} );
	},

	_findActive: function( selector ) {
		return typeof selector === "number" ? this.headers.eq( selector ) : $();
	},

	_setupEvents: function( event ) {
		var events = {
			keydown: "_keydown"
		};
		if ( event ) {
			$.each( event.split( " " ), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			} );
		}

		this._off( this.headers.add( this.headers.next() ) );
		this._on( this.headers, events );
		this._on( this.headers.next(), { keydown: "_panelKeyDown" } );
		this._hoverable( this.headers );
		this._focusable( this.headers );
	},

	_eventHandler: function( event ) {
		var activeChildren, clickedChildren,
			options = this.options,
			active = this.active,
			clicked = $( event.currentTarget ),
			clickedIsActive = clicked[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : clicked.next(),
			toHide = active.next(),
			eventData = {
				oldHeader: active,
				oldPanel: toHide,
				newHeader: collapsing ? $() : clicked,
				newPanel: toShow
			};

		event.preventDefault();

		if (

				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||

				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.headers.index( clicked );

		// When the call to ._toggle() comes after the class changes
		// it causes a very odd bug in IE 8 (see #6720)
		this.active = clickedIsActive ? $() : clicked;
		this._toggle( eventData );

		// Switch classes
		// corner classes on the previously active header stay after the animation
		this._removeClass( active, "ui-accordion-header-active", "ui-state-active" );
		if ( options.icons ) {
			activeChildren = active.children( ".ui-accordion-header-icon" );
			this._removeClass( activeChildren, null, options.icons.activeHeader )
				._addClass( activeChildren, null, options.icons.header );
		}

		if ( !clickedIsActive ) {
			this._removeClass( clicked, "ui-accordion-header-collapsed" )
				._addClass( clicked, "ui-accordion-header-active", "ui-state-active" );
			if ( options.icons ) {
				clickedChildren = clicked.children( ".ui-accordion-header-icon" );
				this._removeClass( clickedChildren, null, options.icons.header )
					._addClass( clickedChildren, null, options.icons.activeHeader );
			}

			this._addClass( clicked.next(), "ui-accordion-content-active" );
		}
	},

	_toggle: function( data ) {
		var toShow = data.newPanel,
			toHide = this.prevShow.length ? this.prevShow : data.oldPanel;

		// Handle activating a panel during the animation for another activation
		this.prevShow.add( this.prevHide ).stop( true, true );
		this.prevShow = toShow;
		this.prevHide = toHide;

		if ( this.options.animate ) {
			this._animate( toShow, toHide, data );
		} else {
			toHide.hide();
			toShow.show();
			this._toggleComplete( data );
		}

		toHide.attr( {
			"aria-hidden": "true"
		} );
		toHide.prev().attr( {
			"aria-selected": "false",
			"aria-expanded": "false"
		} );

		// if we're switching panels, remove the old header from the tab order
		// if we're opening from collapsed state, remove the previous header from the tab order
		// if we're collapsing, then keep the collapsing header in the tab order
		if ( toShow.length && toHide.length ) {
			toHide.prev().attr( {
				"tabIndex": -1,
				"aria-expanded": "false"
			} );
		} else if ( toShow.length ) {
			this.headers.filter( function() {
				return parseInt( $( this ).attr( "tabIndex" ), 10 ) === 0;
			} )
				.attr( "tabIndex", -1 );
		}

		toShow
			.attr( "aria-hidden", "false" )
			.prev()
				.attr( {
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				} );
	},

	_animate: function( toShow, toHide, data ) {
		var total, easing, duration,
			that = this,
			adjust = 0,
			boxSizing = toShow.css( "box-sizing" ),
			down = toShow.length &&
				( !toHide.length || ( toShow.index() < toHide.index() ) ),
			animate = this.options.animate || {},
			options = down && animate.down || animate,
			complete = function() {
				that._toggleComplete( data );
			};

		if ( typeof options === "number" ) {
			duration = options;
		}
		if ( typeof options === "string" ) {
			easing = options;
		}

		// fall back from options to animation in case of partial down settings
		easing = easing || options.easing || animate.easing;
		duration = duration || options.duration || animate.duration;

		if ( !toHide.length ) {
			return toShow.animate( this.showProps, duration, easing, complete );
		}
		if ( !toShow.length ) {
			return toHide.animate( this.hideProps, duration, easing, complete );
		}

		total = toShow.show().outerHeight();
		toHide.animate( this.hideProps, {
			duration: duration,
			easing: easing,
			step: function( now, fx ) {
				fx.now = Math.round( now );
			}
		} );
		toShow
			.hide()
			.animate( this.showProps, {
				duration: duration,
				easing: easing,
				complete: complete,
				step: function( now, fx ) {
					fx.now = Math.round( now );
					if ( fx.prop !== "height" ) {
						if ( boxSizing === "content-box" ) {
							adjust += fx.now;
						}
					} else if ( that.options.heightStyle !== "content" ) {
						fx.now = Math.round( total - toHide.outerHeight() - adjust );
						adjust = 0;
					}
				}
			} );
	},

	_toggleComplete: function( data ) {
		var toHide = data.oldPanel,
			prev = toHide.prev();

		this._removeClass( toHide, "ui-accordion-content-active" );
		this._removeClass( prev, "ui-accordion-header-active" )
			._addClass( prev, "ui-accordion-header-collapsed" );

		this._trigger( "activate", null, data );
	}
} );


/*!
 * jQuery UI Menu 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Menu
//>>group: Widgets
//>>description: Creates nestable menus.
//>>docs: https://api.jqueryui.com/menu/
//>>demos: https://jqueryui.com/menu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/menu.css
//>>css.theme: ../../themes/base/theme.css


var widgetsMenu = $.widget( "ui.menu", {
	version: "1.14.0",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-caret-1-e"
		},
		items: "> *",
		menus: "ul",
		position: {
			my: "left top",
			at: "right top"
		},
		role: "menu",

		// Callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.lastMousePosition = { x: null, y: null };
		this.element
			.uniqueId()
			.attr( {
				role: this.options.role,
				tabIndex: 0
			} );

		this._addClass( "ui-menu", "ui-widget ui-widget-content" );
		this._on( {

			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .ui-menu-item": function( event ) {
				event.preventDefault();

				this._activateItem( event );
			},
			"click .ui-menu-item": function( event ) {
				var target = $( event.target );
				var active = $( this.document[ 0 ].activeElement );
				if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) &&
							active.closest( ".ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": "_activateItem",
			"mousemove .ui-menu-item": "_activateItem",
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {

				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this._menuItems().first();

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay( function() {
					var notContained = !$.contains(
						this.element[ 0 ],
						this.document[ 0 ].activeElement
					);
					if ( notContained ) {
						this.collapseAll( event );
					}
				} );
			},
			keydown: "_keydown"
		} );

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event, true );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		} );
	},

	_activateItem: function( event ) {

		// Ignore mouse events while typeahead is active, see #10458.
		// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
		// is over an item in the menu
		if ( this.previousFilter ) {
			return;
		}

		// If the mouse didn't actually move, but the page was scrolled, ignore the event (#9356)
		if ( event.clientX === this.lastMousePosition.x &&
				event.clientY === this.lastMousePosition.y ) {
			return;
		}

		this.lastMousePosition = {
			x: event.clientX,
			y: event.clientY
		};

		var actualTarget = $( event.target ).closest( ".ui-menu-item" ),
			target = $( event.currentTarget );

		// Ignore bubbled events on parent items, see #11641
		if ( actualTarget[ 0 ] !== target[ 0 ] ) {
			return;
		}

		// If the item is already active, there's nothing to do
		if ( target.is( ".ui-state-active" ) ) {
			return;
		}

		// Remove ui-state-active class from siblings of the newly focused menu item
		// to avoid a jump caused by adjacent elements both having a class with a border
		this._removeClass( target.siblings().children( ".ui-state-active" ),
			null, "ui-state-active" );
		this.focus( event, target );
	},

	_destroy: function() {
		var items = this.element.find( ".ui-menu-item" )
				.removeAttr( "role aria-disabled" ),
			submenus = items.children( ".ui-menu-item-wrapper" )
				.removeUniqueId()
				.removeAttr( "tabIndex role aria-haspopup" );

		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " +
					"tabIndex" )
				.removeUniqueId()
				.show();

		submenus.children().each( function() {
			var elem = $( this );
			if ( elem.data( "ui-menu-submenu-caret" ) ) {
				elem.remove();
			}
		} );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			skip = false;

			// Support number pad values
			character = event.keyCode >= 96 && event.keyCode <= 105 ?
				( event.keyCode - 96 ).toString() : String.fromCharCode( event.keyCode );

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip && match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay( function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.children( "[aria-haspopup='true']" ).length ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items, newSubmenus, newItems, newWrappers,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this._toggleClass( "ui-menu-icons", null, !!this.element.find( ".ui-icon" ).length );

		// Initialize nested menus
		newSubmenus = submenus.filter( ":not(.ui-menu)" )
			.hide()
			.attr( {
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			} )
			.each( function() {
				var menu = $( this ),
					item = menu.prev(),
					submenuCaret = $( "<span>" ).data( "ui-menu-submenu-caret", true );

				that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon );
				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCaret );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			} );

		this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" );

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".ui-menu-item" ).each( function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				that._addClass( item, "ui-menu-divider", "ui-widget-content" );
			}
		} );

		// Don't refresh list items that are already adapted
		newItems = items.not( ".ui-menu-item, .ui-menu-divider" );
		newWrappers = newItems.children()
			.not( ".ui-menu" )
				.uniqueId()
				.attr( {
					tabIndex: -1,
					role: this._itemRole()
				} );
		this._addClass( newItems, "ui-menu-item" )
			._addClass( newWrappers, "ui-menu-item-wrapper" );

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icons = this.element.find( ".ui-menu-icon" );
			this._removeClass( icons, null, this.options.icons.submenu )
				._addClass( icons, null, value.submenu );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", String( value ) );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	focus: function( event, item ) {
		var nested, focused, activeParent;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();

		focused = this.active.children( ".ui-menu-item-wrapper" );
		this._addClass( focused, null, "ui-state-active" );

		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		activeParent = this.active
			.parent()
				.closest( ".ui-menu-item" )
					.children( ".ui-menu-item-wrapper" );
		this._addClass( activeParent, null, "ui-state-active" );

		if ( event && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay( function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
			this._startOpening( nested );
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this._removeClass( this.active.children( ".ui-menu-item-wrapper" ),
			null, "ui-state-active" );

		this._trigger( "blur", event, { item: this.active } );
		this.active = null;
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the caret icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay( function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend( {
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay( function() {

			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event && event.target ).closest( this.element.find( ".ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all
			// sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );

			// Work around active item staying active after menu is blurred
			this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" );

			this.activeMenu = currentMenu;
		}, all ? 0 : this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu.find( ".ui-menu" )
			.hide()
			.attr( "aria-hidden", "true" )
			.attr( "aria-expanded", "false" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active && this._menuItems( this.active.children( ".ui-menu" ) ).first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay( function() {
				this.focus( event, newItem );
			} );
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_menuItems: function( menu ) {
		return ( menu || this.element )
			.find( this.options.items )
			.filter( ".ui-menu-item" );
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.last();
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.first();
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this._menuItems( this.activeMenu )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.innerHeight();

			// jQuery 3.2 doesn't include scrollbars in innerHeight, add it back.
			if ( $.fn.jquery.indexOf( "3.2." ) === 0 ) {
				height += this.element[ 0 ].offsetHeight - this.element.outerHeight();
			}

			this.active.nextAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this._menuItems( this.activeMenu )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.innerHeight();

			// jQuery 3.2 doesn't include scrollbars in innerHeight, add it back.
			if ( $.fn.jquery.indexOf( "3.2." ) === 0 ) {
				height += this.element[ 0 ].offsetHeight - this.element.outerHeight();
			}

			this.active.prevAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this._menuItems( this.activeMenu ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
	},

	select: function( event ) {

		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function( character ) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

				// Only match on items, not dividers or other content (#10571)
				.filter( ".ui-menu-item" )
					.filter( function() {
						return regex.test(
							String.prototype.trim.call(
								$( this ).children( ".ui-menu-item-wrapper" ).text() ) );
					} );
	}
} );


/*!
 * jQuery UI Autocomplete 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Autocomplete
//>>group: Widgets
//>>description: Lists suggested words as the user is typing.
//>>docs: https://api.jqueryui.com/autocomplete/
//>>demos: https://jqueryui.com/autocomplete/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/autocomplete.css
//>>css.theme: ../../themes/base/theme.css


$.widget( "ui.autocomplete", {
	version: "1.14.0",
	defaultElement: "<input>",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,
	liveRegionTimer: null,

	_create: function() {

		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		// Textareas are always multi-line
		// Inputs are always single-line, even if inside a contentEditable element
		// All other element types are determined by whether they're contentEditable
		this.isMultiLine = isTextarea ||
			!isInput && this.element.prop( "contentEditable" ) === "true";

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this._addClass( "ui-autocomplete-input" );
		this.element.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:

					// when menu is open and has focus
					if ( this.menu.active ) {

						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );

						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;

					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// Replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		} );

		this._initSource();
		this.menu = $( "<ul>" )
			.appendTo( this._appendTo() )
			.menu( {

				// disable ARIA support, the live region takes care of that
				role: null
			} )
			.hide()
			.menu( "instance" );

		this._addClass( this.menu.element, "ui-autocomplete", "ui-front" );
		this._on( this.menu.element, {
			mousedown: function( event ) {

				// Prevent moving focus out of the text field
				event.preventDefault();
			},
			menufocus: function( event, ui ) {
				var label, item;

				// Support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						} );

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {

					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label && String.prototype.trim.call( label ).length ) {
					clearTimeout( this.liveRegionTimer );
					this.liveRegionTimer = this._delay( function() {
						this.liveRegion.html( $( "<div>" ).text( label ) );
					}, 100 );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "ui-autocomplete-item" ),
					previous = this.previous;

				// Only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) {
					this.element.trigger( "focus" );
					this.previous = previous;
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}

				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		} );

		this.liveRegion = $( "<div>", {
			role: "status",
			"aria-live": "assertive",
			"aria-relevant": "additions"
		} )
			.appendTo( this.document[ 0 ].body );

		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		// Turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		} );
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_isEventTargetInWidget: function( event ) {
		var menuElement = this.menu.element[ 0 ];

		return event.target === this.element[ 0 ] ||
			event.target === menuElement ||
			$.contains( menuElement, event.target );
	},

	_closeOnClickOutside: function( event ) {
		if ( !this._isEventTargetInWidget( event ) ) {
			this.close();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front, dialog" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( Array.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax( {
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response( [] );
					}
				} );
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay( function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// Always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this._addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this._removeClass( "ui-autocomplete-loading" );
			}
		}.bind( this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {

			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {

		// Remove the handler that closes the menu on outside clicks
		this._off( this.document, "mousedown" );

		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {

		// assume all items have the right format when the first item is complete
		if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			} );
		} );
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// Size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend( {
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}

		// Listen for interactions outside of the widget (#6642)
		this._on( this.document, {
			mousedown: "_closeOnClickOutside"
		} );
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(

			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "<li>" )
			.append( $( "<div>" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
				this.menu.isLastItem() && /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// Prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	}
} );

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		} );
	}
} );

// Live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
	options: {
		messages: {
			noResults: "No search results.",
			results: function( amount ) {
				return amount + ( amount > 1 ? " results are" : " result is" ) +
					" available, use up and down arrow keys to navigate.";
			}
		}
	},

	__response: function( content ) {
		var message;
		this._superApply( arguments );
		if ( this.options.disabled || this.cancelSearch ) {
			return;
		}
		if ( content && content.length ) {
			message = this.options.messages.results( content.length );
		} else {
			message = this.options.messages.noResults;
		}
		clearTimeout( this.liveRegionTimer );
		this.liveRegionTimer = this._delay( function() {
			this.liveRegion.html( $( "<div>" ).text( message ) );
		}, 100 );
	}
} );

var widgetsAutocomplete = $.ui.autocomplete;


/*!
 * jQuery UI Controlgroup 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Controlgroup
//>>group: Widgets
//>>description: Visually groups form control widgets
//>>docs: https://api.jqueryui.com/controlgroup/
//>>demos: https://jqueryui.com/controlgroup/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/controlgroup.css
//>>css.theme: ../../themes/base/theme.css


var controlgroupCornerRegex = /ui-corner-([a-z]){2,6}/g;

var widgetsControlgroup = $.widget( "ui.controlgroup", {
	version: "1.14.0",
	defaultElement: "<div>",
	options: {
		direction: "horizontal",
		disabled: null,
		onlyVisible: true,
		items: {
			"button": "input[type=button], input[type=submit], input[type=reset], button, a",
			"controlgroupLabel": ".ui-controlgroup-label",
			"checkboxradio": "input[type='checkbox'], input[type='radio']",
			"selectmenu": "select",
			"spinner": ".ui-spinner-input"
		}
	},

	_create: function() {
		this._enhance();
	},

	// To support the enhanced option in jQuery Mobile, we isolate DOM manipulation
	_enhance: function() {
		this.element.attr( "role", "toolbar" );
		this.refresh();
	},

	_destroy: function() {
		this._callChildMethod( "destroy" );
		this.childWidgets.removeData( "ui-controlgroup-data" );
		this.element.removeAttr( "role" );
		if ( this.options.items.controlgroupLabel ) {
			this.element
				.find( this.options.items.controlgroupLabel )
				.find( ".ui-controlgroup-label-contents" )
				.contents().unwrap();
		}
	},

	_initWidgets: function() {
		var that = this,
			childWidgets = [];

		// First we iterate over each of the items options
		$.each( this.options.items, function( widget, selector ) {
			var labels;
			var options = {};

			// Make sure the widget has a selector set
			if ( !selector ) {
				return;
			}

			if ( widget === "controlgroupLabel" ) {
				labels = that.element.find( selector );
				labels.each( function() {
					var element = $( this );

					if ( element.children( ".ui-controlgroup-label-contents" ).length ) {
						return;
					}
					element.contents()
						.wrapAll( "<span class='ui-controlgroup-label-contents'></span>" );
				} );
				that._addClass( labels, null, "ui-widget ui-widget-content ui-state-default" );
				childWidgets = childWidgets.concat( labels.get() );
				return;
			}

			// Make sure the widget actually exists
			if ( !$.fn[ widget ] ) {
				return;
			}

			// We assume everything is in the middle to start because we can't determine
			// first / last elements until all enhancments are done.
			if ( that[ "_" + widget + "Options" ] ) {
				options = that[ "_" + widget + "Options" ]( "middle" );
			} else {
				options = { classes: {} };
			}

			// Find instances of this widget inside controlgroup and init them
			that.element
				.find( selector )
				.each( function() {
					var element = $( this );
					var instance = element[ widget ]( "instance" );

					// We need to clone the default options for this type of widget to avoid
					// polluting the variable options which has a wider scope than a single widget.
					var instanceOptions = $.widget.extend( {}, options );

					// If the button is the child of a spinner ignore it
					// TODO: Find a more generic solution
					if ( widget === "button" && element.parent( ".ui-spinner" ).length ) {
						return;
					}

					// Create the widget if it doesn't exist
					if ( !instance ) {
						instance = element[ widget ]()[ widget ]( "instance" );
					}
					if ( instance ) {
						instanceOptions.classes =
							that._resolveClassesValues( instanceOptions.classes, instance );
					}
					element[ widget ]( instanceOptions );

					// Store an instance of the controlgroup to be able to reference
					// from the outermost element for changing options and refresh
					var widgetElement = element[ widget ]( "widget" );
					$.data( widgetElement[ 0 ], "ui-controlgroup-data",
						instance ? instance : element[ widget ]( "instance" ) );

					childWidgets.push( widgetElement[ 0 ] );
				} );
		} );

		this.childWidgets = $( $.uniqueSort( childWidgets ) );
		this._addClass( this.childWidgets, "ui-controlgroup-item" );
	},

	_callChildMethod: function( method ) {
		this.childWidgets.each( function() {
			var element = $( this ),
				data = element.data( "ui-controlgroup-data" );
			if ( data && data[ method ] ) {
				data[ method ]();
			}
		} );
	},

	_updateCornerClass: function( element, position ) {
		var remove = "ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";
		var add = this._buildSimpleOptions( position, "label" ).classes.label;

		this._removeClass( element, null, remove );
		this._addClass( element, null, add );
	},

	_buildSimpleOptions: function( position, key ) {
		var direction = this.options.direction === "vertical";
		var result = {
			classes: {}
		};
		result.classes[ key ] = {
			"middle": "",
			"first": "ui-corner-" + ( direction ? "top" : "left" ),
			"last": "ui-corner-" + ( direction ? "bottom" : "right" ),
			"only": "ui-corner-all"
		}[ position ];

		return result;
	},

	_spinnerOptions: function( position ) {
		var options = this._buildSimpleOptions( position, "ui-spinner" );

		options.classes[ "ui-spinner-up" ] = "";
		options.classes[ "ui-spinner-down" ] = "";

		return options;
	},

	_buttonOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-button" );
	},

	_checkboxradioOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-checkboxradio-label" );
	},

	_selectmenuOptions: function( position ) {
		var direction = this.options.direction === "vertical";
		return {
			width: direction ? "auto" : false,
			classes: {
				middle: {
					"ui-selectmenu-button-open": "",
					"ui-selectmenu-button-closed": ""
				},
				first: {
					"ui-selectmenu-button-open": "ui-corner-" + ( direction ? "top" : "tl" ),
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "top" : "left" )
				},
				last: {
					"ui-selectmenu-button-open": direction ? "" : "ui-corner-tr",
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "bottom" : "right" )
				},
				only: {
					"ui-selectmenu-button-open": "ui-corner-top",
					"ui-selectmenu-button-closed": "ui-corner-all"
				}

			}[ position ]
		};
	},

	_resolveClassesValues: function( classes, instance ) {
		var result = {};
		$.each( classes, function( key ) {
			var current = instance.options.classes[ key ] || "";
			current = String.prototype.trim.call( current.replace( controlgroupCornerRegex, "" ) );
			result[ key ] = ( current + " " + classes[ key ] ).replace( /\s+/g, " " );
		} );
		return result;
	},

	_setOption: function( key, value ) {
		if ( key === "direction" ) {
			this._removeClass( "ui-controlgroup-" + this.options.direction );
		}

		this._super( key, value );
		if ( key === "disabled" ) {
			this._callChildMethod( value ? "disable" : "enable" );
			return;
		}

		this.refresh();
	},

	refresh: function() {
		var children,
			that = this;

		this._addClass( "ui-controlgroup ui-controlgroup-" + this.options.direction );

		if ( this.options.direction === "horizontal" ) {
			this._addClass( null, "ui-helper-clearfix" );
		}
		this._initWidgets();

		children = this.childWidgets;

		// We filter here because we need to track all childWidgets not just the visible ones
		if ( this.options.onlyVisible ) {
			children = children.filter( ":visible" );
		}

		if ( children.length ) {

			// We do this last because we need to make sure all enhancment is done
			// before determining first and last
			$.each( [ "first", "last" ], function( index, value ) {
				var instance = children[ value ]().data( "ui-controlgroup-data" );

				if ( instance && that[ "_" + instance.widgetName + "Options" ] ) {
					var options = that[ "_" + instance.widgetName + "Options" ](
						children.length === 1 ? "only" : value
					);
					options.classes = that._resolveClassesValues( options.classes, instance );
					instance.element[ instance.widgetName ]( options );
				} else {
					that._updateCornerClass( children[ value ](), value );
				}
			} );

			// Finally call the refresh method on each of the child widgets.
			this._callChildMethod( "refresh" );
		}
	}
} );

/*!
 * jQuery UI Checkboxradio 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Checkboxradio
//>>group: Widgets
//>>description: Enhances a form with multiple themeable checkboxes or radio buttons.
//>>docs: https://api.jqueryui.com/checkboxradio/
//>>demos: https://jqueryui.com/checkboxradio/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.structure: ../../themes/base/checkboxradio.css
//>>css.theme: ../../themes/base/theme.css


$.widget( "ui.checkboxradio", [ $.ui.formResetMixin, {
	version: "1.14.0",
	options: {
		disabled: null,
		label: null,
		icon: true,
		classes: {
			"ui-checkboxradio-label": "ui-corner-all",
			"ui-checkboxradio-icon": "ui-corner-all"
		}
	},

	_getCreateOptions: function() {
		var disabled, labels, labelContents;
		var options = this._super() || {};

		// We read the type here, because it makes more sense to throw a element type error first,
		// rather then the error for lack of a label. Often if its the wrong type, it
		// won't have a label (e.g. calling on a div, btn, etc)
		this._readType();

		labels = this.element.labels();

		// If there are multiple labels, use the last one
		this.label = $( labels[ labels.length - 1 ] );
		if ( !this.label.length ) {
			$.error( "No label found for checkboxradio widget" );
		}

		this.originalLabel = "";

		// We need to get the label text but this may also need to make sure it does not contain the
		// input itself.
		// The label contents could be text, html, or a mix. We wrap all elements
		// and read the wrapper's `innerHTML` to get a string representation of
		// the label, without the input as part of it.
		labelContents = this.label.contents().not( this.element[ 0 ] );

		if ( labelContents.length ) {
			this.originalLabel += labelContents
				.clone()
				.wrapAll( "<div></div>" )
				.parent()
				.html();
		}

		// Set the label option if we found label text
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}
		return options;
	},

	_create: function() {
		var checked = this.element[ 0 ].checked;

		this._bindFormResetHandler();

		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled;
		}

		this._setOption( "disabled", this.options.disabled );
		this._addClass( "ui-checkboxradio", "ui-helper-hidden-accessible" );
		this._addClass( this.label, "ui-checkboxradio-label", "ui-button ui-widget" );

		if ( this.type === "radio" ) {
			this._addClass( this.label, "ui-checkboxradio-radio-label" );
		}

		if ( this.options.label && this.options.label !== this.originalLabel ) {
			this._updateLabel();
		} else if ( this.originalLabel ) {
			this.options.label = this.originalLabel;
		}

		this._enhance();

		if ( checked ) {
			this._addClass( this.label, "ui-checkboxradio-checked", "ui-state-active" );
		}

		this._on( {
			change: "_toggleClasses",
			focus: function() {
				this._addClass( this.label, null, "ui-state-focus ui-visual-focus" );
			},
			blur: function() {
				this._removeClass( this.label, null, "ui-state-focus ui-visual-focus" );
			}
		} );
	},

	_readType: function() {
		var nodeName = this.element[ 0 ].nodeName.toLowerCase();
		this.type = this.element[ 0 ].type;
		if ( nodeName !== "input" || !/radio|checkbox/.test( this.type ) ) {
			$.error( "Can't create checkboxradio on element.nodeName=" + nodeName +
				" and element.type=" + this.type );
		}
	},

	// Support jQuery Mobile enhanced option
	_enhance: function() {
		this._updateIcon( this.element[ 0 ].checked );
	},

	widget: function() {
		return this.label;
	},

	_getRadioGroup: function() {
		var group;
		var name = this.element[ 0 ].name;
		var nameSelector = "input[name='" + CSS.escape( name ) + "']";

		if ( !name ) {
			return $( [] );
		}

		if ( this.form.length ) {
			group = $( this.form[ 0 ].elements ).filter( nameSelector );
		} else {

			// Not inside a form, check all inputs that also are not inside a form
			group = $( nameSelector ).filter( function() {
				return $( $( this ).prop( "form" ) ).length === 0;
			} );
		}

		return group.not( this.element );
	},

	_toggleClasses: function() {
		var checked = this.element[ 0 ].checked;
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );

		if ( this.options.icon && this.type === "checkbox" ) {
			this._toggleClass( this.icon, null, "ui-icon-check ui-state-checked", checked )
				._toggleClass( this.icon, null, "ui-icon-blank", !checked );
		}

		if ( this.type === "radio" ) {
			this._getRadioGroup()
				.each( function() {
					var instance = $( this ).checkboxradio( "instance" );

					if ( instance ) {
						instance._removeClass( instance.label,
							"ui-checkboxradio-checked", "ui-state-active" );
					}
				} );
		}
	},

	_destroy: function() {
		this._unbindFormResetHandler();

		if ( this.icon ) {
			this.icon.remove();
			this.iconSpace.remove();
		}
	},

	_setOption: function( key, value ) {

		// We don't allow the value to be set to nothing
		if ( key === "label" && !value ) {
			return;
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( this.label, null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;

			// Don't refresh when setting disabled
			return;
		}
		this.refresh();
	},

	_updateIcon: function( checked ) {
		var toAdd = "ui-icon ui-icon-background ";

		if ( this.options.icon ) {
			if ( !this.icon ) {
				this.icon = $( "<span>" );
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-checkboxradio-icon-space" );
			}

			if ( this.type === "checkbox" ) {
				toAdd += checked ? "ui-icon-check ui-state-checked" : "ui-icon-blank";
				this._removeClass( this.icon, null, checked ? "ui-icon-blank" : "ui-icon-check" );
			} else {
				toAdd += "ui-icon-blank";
			}
			this._addClass( this.icon, "ui-checkboxradio-icon", toAdd );
			if ( !checked ) {
				this._removeClass( this.icon, null, "ui-icon-check ui-state-checked" );
			}
			this.icon.prependTo( this.label ).after( this.iconSpace );
		} else if ( this.icon !== undefined ) {
			this.icon.remove();
			this.iconSpace.remove();
			delete this.icon;
		}
	},

	_updateLabel: function() {

		// Remove the contents of the label ( minus the icon, icon space, and input )
		var contents = this.label.contents().not( this.element[ 0 ] );
		if ( this.icon ) {
			contents = contents.not( this.icon[ 0 ] );
		}
		if ( this.iconSpace ) {
			contents = contents.not( this.iconSpace[ 0 ] );
		}
		contents.remove();

		this.label.append( this.options.label );
	},

	refresh: function() {
		var checked = this.element[ 0 ].checked,
			isDisabled = this.element[ 0 ].disabled;

		this._updateIcon( checked );
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );
		if ( this.options.label !== null ) {
			this._updateLabel();
		}

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { "disabled": isDisabled } );
		}
	}

} ] );

var widgetsCheckboxradio = $.ui.checkboxradio;


/*!
 * jQuery UI Button 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Button
//>>group: Widgets
//>>description: Enhances a form with themeable buttons.
//>>docs: https://api.jqueryui.com/button/
//>>demos: https://jqueryui.com/button/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.theme: ../../themes/base/theme.css


$.widget( "ui.button", {
	version: "1.14.0",
	defaultElement: "<button>",
	options: {
		classes: {
			"ui-button": "ui-corner-all"
		},
		disabled: null,
		icon: null,
		iconPosition: "beginning",
		label: null,
		showLabel: true
	},

	_getCreateOptions: function() {
		var disabled,

			// This is to support cases like in jQuery Mobile where the base widget does have
			// an implementation of _getCreateOptions
			options = this._super() || {};

		this.isInput = this.element.is( "input" );

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}

		this.originalLabel = this.isInput ? this.element.val() : this.element.html();
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		return options;
	},

	_create: function() {
		if ( !this.option.showLabel & !this.options.icon ) {
			this.options.showLabel = true;
		}

		// We have to check the option again here even though we did in _getCreateOptions,
		// because null may have been passed on init which would override what was set in
		// _getCreateOptions
		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled || false;
		}

		this.hasTitle = !!this.element.attr( "title" );

		// Check to see if the label needs to be set or if its already correct
		if ( this.options.label && this.options.label !== this.originalLabel ) {
			if ( this.isInput ) {
				this.element.val( this.options.label );
			} else {
				this.element.html( this.options.label );
			}
		}
		this._addClass( "ui-button", "ui-widget" );
		this._setOption( "disabled", this.options.disabled );
		this._enhance();

		if ( this.element.is( "a" ) ) {
			this._on( {
				"keyup": function( event ) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						event.preventDefault();

						// If a native click is available use it, so we
						// actually cause navigation. Otherwise, just trigger
						// a click event.
						if ( this.element[ 0 ].click ) {
							this.element[ 0 ].click();
						} else {
							this.element.trigger( "click" );
						}
					}
				}
			} );
		}
	},

	_enhance: function() {
		if ( !this.element.is( "button" ) ) {
			this.element.attr( "role", "button" );
		}

		if ( this.options.icon ) {
			this._updateIcon( "icon", this.options.icon );
			this._updateTooltip();
		}
	},

	_updateTooltip: function() {
		this.title = this.element.attr( "title" );

		if ( !this.options.showLabel && !this.title ) {
			this.element.attr( "title", this.options.label );
		}
	},

	_updateIcon: function( option, value ) {
		var icon = option !== "iconPosition",
			position = icon ? this.options.iconPosition : value,
			displayBlock = position === "top" || position === "bottom";

		// Create icon
		if ( !this.icon ) {
			this.icon = $( "<span>" );

			this._addClass( this.icon, "ui-button-icon", "ui-icon" );

			if ( !this.options.showLabel ) {
				this._addClass( "ui-button-icon-only" );
			}
		} else if ( icon ) {

			// If we are updating the icon remove the old icon class
			this._removeClass( this.icon, null, this.options.icon );
		}

		// If we are updating the icon add the new icon class
		if ( icon ) {
			this._addClass( this.icon, null, value );
		}

		this._attachIcon( position );

		// If the icon is on top or bottom we need to add the ui-widget-icon-block class and remove
		// the iconSpace if there is one.
		if ( displayBlock ) {
			this._addClass( this.icon, null, "ui-widget-icon-block" );
			if ( this.iconSpace ) {
				this.iconSpace.remove();
			}
		} else {

			// Position is beginning or end so remove the ui-widget-icon-block class and add the
			// space if it does not exist
			if ( !this.iconSpace ) {
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-button-icon-space" );
			}
			this._removeClass( this.icon, null, "ui-wiget-icon-block" );
			this._attachIconSpace( position );
		}
	},

	_destroy: function() {
		this.element.removeAttr( "role" );

		if ( this.icon ) {
			this.icon.remove();
		}
		if ( this.iconSpace ) {
			this.iconSpace.remove();
		}
		if ( !this.hasTitle ) {
			this.element.removeAttr( "title" );
		}
	},

	_attachIconSpace: function( iconPosition ) {
		this.icon[ /^(?:end|bottom)/.test( iconPosition ) ? "before" : "after" ]( this.iconSpace );
	},

	_attachIcon: function( iconPosition ) {
		this.element[ /^(?:end|bottom)/.test( iconPosition ) ? "append" : "prepend" ]( this.icon );
	},

	_setOptions: function( options ) {
		var newShowLabel = options.showLabel === undefined ?
				this.options.showLabel :
				options.showLabel,
			newIcon = options.icon === undefined ? this.options.icon : options.icon;

		if ( !newShowLabel && !newIcon ) {
			options.showLabel = true;
		}
		this._super( options );
	},

	_setOption: function( key, value ) {
		if ( key === "icon" ) {
			if ( value ) {
				this._updateIcon( key, value );
			} else if ( this.icon ) {
				this.icon.remove();
				if ( this.iconSpace ) {
					this.iconSpace.remove();
				}
			}
		}

		if ( key === "iconPosition" ) {
			this._updateIcon( key, value );
		}

		// Make sure we can't end up with a button that has neither text nor icon
		if ( key === "showLabel" ) {
				this._toggleClass( "ui-button-icon-only", null, !value );
				this._updateTooltip();
		}

		if ( key === "label" ) {
			if ( this.isInput ) {
				this.element.val( value );
			} else {

				// If there is an icon, append it, else nothing then append the value
				// this avoids removal of the icon when setting label text
				this.element.html( value );
				if ( this.icon ) {
					this._attachIcon( this.options.iconPosition );
					this._attachIconSpace( this.options.iconPosition );
				}
			}
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;
			if ( value ) {
				this.element.trigger( "blur" );
			}
		}
	},

	refresh: function() {

		// Make sure to only check disabled if its an element that supports this otherwise
		// check for the disabled class to determine state
		var isDisabled = this.element.is( "input, button" ) ?
			this.element[ 0 ].disabled : this.element.hasClass( "ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { disabled: isDisabled } );
		}

		this._updateTooltip();
	}
} );

// DEPRECATED
if ( $.uiBackCompat === true ) {

	// Text and Icons options
	$.widget( "ui.button", $.ui.button, {
		options: {
			text: true,
			icons: {
				primary: null,
				secondary: null
			}
		},

		_create: function() {
			if ( this.options.showLabel && !this.options.text ) {
				this.options.showLabel = this.options.text;
			}
			if ( !this.options.showLabel && this.options.text ) {
				this.options.text = this.options.showLabel;
			}
			if ( !this.options.icon && ( this.options.icons.primary ||
					this.options.icons.secondary ) ) {
				if ( this.options.icons.primary ) {
					this.options.icon = this.options.icons.primary;
				} else {
					this.options.icon = this.options.icons.secondary;
					this.options.iconPosition = "end";
				}
			} else if ( this.options.icon ) {
				this.options.icons.primary = this.options.icon;
			}
			this._super();
		},

		_setOption: function( key, value ) {
			if ( key === "text" ) {
				this._super( "showLabel", value );
				return;
			}
			if ( key === "showLabel" ) {
				this.options.text = value;
			}
			if ( key === "icon" ) {
				this.options.icons.primary = value;
			}
			if ( key === "icons" ) {
				if ( value.primary ) {
					this._super( "icon", value.primary );
					this._super( "iconPosition", "beginning" );
				} else if ( value.secondary ) {
					this._super( "icon", value.secondary );
					this._super( "iconPosition", "end" );
				}
			}
			this._superApply( arguments );
		}
	} );

	$.fn.button = ( function( orig ) {
		return function( options ) {
			var isMethodCall = typeof options === "string";
			var args = Array.prototype.slice.call( arguments, 1 );
			var returnValue = this;

			if ( isMethodCall ) {

				// If this is an empty collection, we need to have the instance method
				// return undefined instead of the jQuery instance
				if ( !this.length && options === "instance" ) {
					returnValue = undefined;
				} else {
					this.each( function() {
						var methodValue;
						var type = $( this ).attr( "type" );
						var name = type !== "checkbox" && type !== "radio" ?
							"button" :
							"checkboxradio";
						var instance = $.data( this, "ui-" + name );

						if ( options === "instance" ) {
							returnValue = instance;
							return false;
						}

						if ( !instance ) {
							return $.error( "cannot call methods on button" +
								" prior to initialization; " +
								"attempted to call method '" + options + "'" );
						}

						if ( typeof instance[ options ] !== "function" ||
							options.charAt( 0 ) === "_" ) {
							return $.error( "no such method '" + options + "' for button" +
								" widget instance" );
						}

						methodValue = instance[ options ].apply( instance, args );

						if ( methodValue !== instance && methodValue !== undefined ) {
							returnValue = methodValue && methodValue.jquery ?
								returnValue.pushStack( methodValue.get() ) :
								methodValue;
							return false;
						}
					} );
				}
			} else {

				// Allow multiple hashes to be passed on init
				if ( args.length ) {
					options = $.widget.extend.apply( null, [ options ].concat( args ) );
				}

				this.each( function() {
					var type = $( this ).attr( "type" );
					var name = type !== "checkbox" && type !== "radio" ? "button" : "checkboxradio";
					var instance = $.data( this, "ui-" + name );

					if ( instance ) {
						instance.option( options || {} );
						if ( instance._init ) {
							instance._init();
						}
					} else {
						if ( name === "button" ) {
							orig.call( $( this ), options );
							return;
						}

						$( this ).checkboxradio( $.extend( { icon: false }, options ) );
					}
				} );
			}

			return returnValue;
		};
	} )( $.fn.button );

	$.fn.buttonset = function() {
		if ( !$.ui.controlgroup ) {
			$.error( "Controlgroup widget missing" );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" && arguments[ 2 ] ) {
			return this.controlgroup.apply( this,
				[ arguments[ 0 ], "items.button", arguments[ 2 ] ] );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" ) {
			return this.controlgroup.apply( this, [ arguments[ 0 ], "items.button" ] );
		}
		if ( typeof arguments[ 0 ] === "object" && arguments[ 0 ].items ) {
			arguments[ 0 ].items = {
				button: arguments[ 0 ].items
			};
		}
		return this.controlgroup.apply( this, arguments );
	};
}

var widgetsButton = $.ui.button;


/* eslint-disable max-len, camelcase */
/*!
 * jQuery UI Datepicker 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Datepicker
//>>group: Widgets
//>>description: Displays a calendar from an input or inline for selecting dates.
//>>docs: https://api.jqueryui.com/datepicker/
//>>demos: https://jqueryui.com/datepicker/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/datepicker.css
//>>css.theme: ../../themes/base/theme.css


$.extend( $.ui, { datepicker: { version: "1.14.0" } } );

var datepicker_instActive;

function datepicker_getZindex( elem ) {
	var position, value;
	while ( elem.length && elem[ 0 ] !== document ) {

		// Ignore z-index if position is set to a value where z-index is ignored by the browser
		// This makes behavior of this function consistent across browsers
		// WebKit always returns auto if the element is positioned
		position = elem.css( "position" );
		if ( position === "absolute" || position === "relative" || position === "fixed" ) {

			// IE returns 0 when zIndex is not specified
			// other browsers return a string
			// we ignore the case of nested elements with an explicit value of 0
			// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
			value = parseInt( elem.css( "zIndex" ), 10 );
			if ( !isNaN( value ) && value !== 0 ) {
				return value;
			}
		}
		elem = elem.parent();
	}

	return 0;
}

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
	this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
	this._appendClass = "ui-datepicker-append"; // The name of the append marker class
	this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
	this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
	this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
	this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
	this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
	this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[ "" ] = { // Default regional settings
		closeText: "Done", // Display text for close link
		prevText: "Prev", // Display text for previous month link
		nextText: "Next", // Display text for next month link
		currentText: "Today", // Display text for current month link
		monthNames: [ "January", "February", "March", "April", "May", "June",
			"July", "August", "September", "October", "November", "December" ], // Names of months for drop-down and formatting
		monthNamesShort: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // For formatting
		dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // For formatting
		dayNamesShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // For formatting
		dayNamesMin: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ], // Column headings for days starting at Sunday
		weekHeader: "Wk", // Column header for week of the year
		dateFormat: "mm/dd/yy", // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: "", // Additional text to append to the year in the month headers,
		selectMonthLabel: "Select month", // Invisible label for month selector
		selectYearLabel: "Select year" // Invisible label for year selector
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: "focus", // "focus" for popup on focus,
			// "button" for trigger button, or "both" for either
		showAnim: "fadeIn", // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: "", // Display text following the input box, e.g. showing the format
		buttonText: "...", // Text for trigger button
		buttonImage: "", // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: "c-10:c+10", // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: "+10", // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with "+" for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: "fast", // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		onUpdateDatepicker: null, // Define a callback function when the datepicker is updated
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: "", // Selector for an alternate field to store selected dates into
		altFormat: "", // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false, // True to size the input for the date format, false to leave as is
		disabled: false // The initial disabled state
	};
	$.extend( this._defaults, this.regional[ "" ] );
	this.regional.en = $.extend( true, {}, this.regional[ "" ] );
	this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
	this.dpDiv = datepicker_bindHover( $( "<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) );
}

$.extend( Datepicker.prototype, {

	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: "hasDatepicker",

	//Keep track of the maximum number of rows displayed (see #7043)
	maxRows: 4,

	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	 * @param  settings  object - the new settings to use as defaults (anonymous object)
	 * @return the manager object
	 */
	setDefaults: function( settings ) {
		datepicker_extendRemove( this._defaults, settings || {} );
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
	 */
	_attachDatepicker: function( target, settings ) {
		var nodeName, inline, inst;
		nodeName = target.nodeName.toLowerCase();
		inline = ( nodeName === "div" || nodeName === "span" );
		if ( !target.id ) {
			this.uuid += 1;
			target.id = "dp" + this.uuid;
		}
		inst = this._newInst( $( target ), inline );
		inst.settings = $.extend( {}, settings || {} );
		if ( nodeName === "input" ) {
			this._connectDatepicker( target, inst );
		} else if ( inline ) {
			this._inlineDatepicker( target, inst );
		}
	},

	/* Create a new instance object. */
	_newInst: function( target, inline ) {
		var id = target[ 0 ].id.replace( /([^A-Za-z0-9_\-])/g, "\\\\$1" ); // escape jQuery meta chars
		return { id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: ( !inline ? this.dpDiv : // presentation div
			datepicker_bindHover( $( "<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) ) ) };
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function( target, inst ) {
		var input = $( target );
		inst.append = $( [] );
		inst.trigger = $( [] );
		if ( input.hasClass( this.markerClassName ) ) {
			return;
		}
		this._attachments( input, inst );
		input.addClass( this.markerClassName ).on( "keydown", this._doKeyDown ).
			on( "keypress", this._doKeyPress ).on( "keyup", this._doKeyUp );
		this._autoSize( inst );
		$.data( target, "datepicker", inst );

		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
	},

	/* Make attachments based on settings. */
	_attachments: function( input, inst ) {
		var showOn, buttonText, buttonImage,
			appendText = this._get( inst, "appendText" ),
			isRTL = this._get( inst, "isRTL" );

		if ( inst.append ) {
			inst.append.remove();
		}
		if ( appendText ) {
			inst.append = $( "<span>" )
				.addClass( this._appendClass )
				.text( appendText );
			input[ isRTL ? "before" : "after" ]( inst.append );
		}

		input.off( "focus", this._showDatepicker );

		if ( inst.trigger ) {
			inst.trigger.remove();
		}

		showOn = this._get( inst, "showOn" );
		if ( showOn === "focus" || showOn === "both" ) { // pop-up date picker when in the marked field
			input.on( "focus", this._showDatepicker );
		}
		if ( showOn === "button" || showOn === "both" ) { // pop-up date picker when button clicked
			buttonText = this._get( inst, "buttonText" );
			buttonImage = this._get( inst, "buttonImage" );

			if ( this._get( inst, "buttonImageOnly" ) ) {
				inst.trigger = $( "<img>" )
					.addClass( this._triggerClass )
					.attr( {
						src: buttonImage,
						alt: buttonText,
						title: buttonText
					} );
			} else {
				inst.trigger = $( "<button type='button'>" )
					.addClass( this._triggerClass );
				if ( buttonImage ) {
					inst.trigger.html(
						$( "<img>" )
							.attr( {
								src: buttonImage,
								alt: buttonText,
								title: buttonText
							} )
					);
				} else {
					inst.trigger.text( buttonText );
				}
			}

			input[ isRTL ? "before" : "after" ]( inst.trigger );
			inst.trigger.on( "click", function() {
				if ( $.datepicker._datepickerShowing && $.datepicker._lastInput === input[ 0 ] ) {
					$.datepicker._hideDatepicker();
				} else if ( $.datepicker._datepickerShowing && $.datepicker._lastInput !== input[ 0 ] ) {
					$.datepicker._hideDatepicker();
					$.datepicker._showDatepicker( input[ 0 ] );
				} else {
					$.datepicker._showDatepicker( input[ 0 ] );
				}
				return false;
			} );
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function( inst ) {
		if ( this._get( inst, "autoSize" ) && !inst.inline ) {
			var findMax, max, maxI, i,
				date = new Date( 2009, 12 - 1, 20 ), // Ensure double digits
				dateFormat = this._get( inst, "dateFormat" );

			if ( dateFormat.match( /[DM]/ ) ) {
				findMax = function( names ) {
					max = 0;
					maxI = 0;
					for ( i = 0; i < names.length; i++ ) {
						if ( names[ i ].length > max ) {
							max = names[ i ].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth( findMax( this._get( inst, ( dateFormat.match( /MM/ ) ?
					"monthNames" : "monthNamesShort" ) ) ) );
				date.setDate( findMax( this._get( inst, ( dateFormat.match( /DD/ ) ?
					"dayNames" : "dayNamesShort" ) ) ) + 20 - date.getDay() );
			}
			inst.input.attr( "size", this._formatDate( inst, date ).length );
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function( target, inst ) {
		var divSpan = $( target );
		if ( divSpan.hasClass( this.markerClassName ) ) {
			return;
		}
		divSpan.addClass( this.markerClassName ).append( inst.dpDiv );
		$.data( target, "datepicker", inst );
		this._setDate( inst, this._getDefaultDate( inst ), true );
		this._updateDatepicker( inst );
		this._updateAlternate( inst );

		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}

		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
		// https://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
		inst.dpDiv.css( "display", "block" );
	},

	/* Pop-up the date picker in a "dialog" box.
	 * @param  input element - ignored
	 * @param  date	string or Date - the initial date to display
	 * @param  onSelect  function - the function to call when a date is selected
	 * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	 * @param  pos int[2] - coordinates for the dialog's position within the screen or
	 *					event - with x/y coordinates or
	 *					leave empty for default (screen centre)
	 * @return the manager object
	 */
	_dialogDatepicker: function( input, date, onSelect, settings, pos ) {
		var id, browserWidth, browserHeight, scrollX, scrollY,
			inst = this._dialogInst; // internal instance

		if ( !inst ) {
			this.uuid += 1;
			id = "dp" + this.uuid;
			this._dialogInput = $( "<input type='text' id='" + id +
				"' style='position: absolute; top: -100px; width: 0px;'/>" );
			this._dialogInput.on( "keydown", this._doKeyDown );
			$( "body" ).append( this._dialogInput );
			inst = this._dialogInst = this._newInst( this._dialogInput, false );
			inst.settings = {};
			$.data( this._dialogInput[ 0 ], "datepicker", inst );
		}
		datepicker_extendRemove( inst.settings, settings || {} );
		date = ( date && date.constructor === Date ? this._formatDate( inst, date ) : date );
		this._dialogInput.val( date );

		this._pos = ( pos ? ( pos.length ? pos : [ pos.pageX, pos.pageY ] ) : null );
		if ( !this._pos ) {
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[ ( browserWidth / 2 ) - 100 + scrollX, ( browserHeight / 2 ) - 150 + scrollY ];
		}

		// Move input on screen for focus, but hidden behind dialog
		this._dialogInput.css( "left", ( this._pos[ 0 ] + 20 ) + "px" ).css( "top", this._pos[ 1 ] + "px" );
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass( this._dialogClass );
		this._showDatepicker( this._dialogInput[ 0 ] );
		if ( $.blockUI ) {
			$.blockUI( this.dpDiv );
		}
		$.data( this._dialogInput[ 0 ], "datepicker", inst );
		return this;
	},

	/* Detach a datepicker from its control.
	 * @param  target	element - the target input field or division or span
	 */
	_destroyDatepicker: function( target ) {
		var nodeName,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData( target, "datepicker" );
		if ( nodeName === "input" ) {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass( this.markerClassName ).
				off( "focus", this._showDatepicker ).
				off( "keydown", this._doKeyDown ).
				off( "keypress", this._doKeyPress ).
				off( "keyup", this._doKeyUp );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			$target.removeClass( this.markerClassName ).empty();
		}

		$.datepicker._hideDatepicker();
		if ( datepicker_instActive === inst ) {
			datepicker_instActive = null;
			this._curInst = null;
		}
	},

	/* Enable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_enableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = false;
			inst.trigger.filter( "button" ).
				each( function() {
					this.disabled = false;
				} ).end().
				filter( "img" ).css( { opacity: "1.0", cursor: "" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().removeClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", false );
		}
		this._disabledInputs = $.map( this._disabledInputs,

			// Delete entry
			function( value ) {
				return ( value === target ? null : value );
			} );
	},

	/* Disable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_disableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = true;
			inst.trigger.filter( "button" ).
				each( function() {
					this.disabled = true;
				} ).end().
				filter( "img" ).css( { opacity: "0.5", cursor: "default" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().addClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", true );
		}
		this._disabledInputs = $.map( this._disabledInputs,

			// Delete entry
			function( value ) {
				return ( value === target ? null : value );
			} );
		this._disabledInputs[ this._disabledInputs.length ] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	 * @param  target	element - the target input field or division or span
	 * @return boolean - true if disabled, false if enabled
	 */
	_isDisabledDatepicker: function( target ) {
		if ( !target ) {
			return false;
		}
		for ( var i = 0; i < this._disabledInputs.length; i++ ) {
			if ( this._disabledInputs[ i ] === target ) {
				return true;
			}
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	 * @param  target  element - the target input field or division or span
	 * @return  object - the associated instance data
	 * @throws  error if a jQuery problem getting data
	 */
	_getInst: function( target ) {
		try {
			return $.data( target, "datepicker" );
		} catch ( err ) {
			throw "Missing instance data for this datepicker";
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 * @param  name	object - the new settings to update or
	 *				string - the name of the setting to change or retrieve,
	 *				when retrieving also "all" for all instance settings or
	 *				"defaults" for all global defaults
	 * @param  value   any - the new value for the setting
	 *				(omit if above is an object or to retrieve a value)
	 */
	_optionDatepicker: function( target, name, value ) {
		var settings, date, minDate, maxDate,
			inst = this._getInst( target );

		if ( arguments.length === 2 && typeof name === "string" ) {
			return ( name === "defaults" ? $.extend( {}, $.datepicker._defaults ) :
				( inst ? ( name === "all" ? $.extend( {}, inst.settings ) :
				this._get( inst, name ) ) : null ) );
		}

		settings = name || {};
		if ( typeof name === "string" ) {
			settings = {};
			settings[ name ] = value;
		}

		if ( inst ) {
			if ( this._curInst === inst ) {
				this._hideDatepicker();
			}

			date = this._getDateDatepicker( target, true );
			minDate = this._getMinMaxDate( inst, "min" );
			maxDate = this._getMinMaxDate( inst, "max" );
			datepicker_extendRemove( inst.settings, settings );

			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if ( minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined ) {
				inst.settings.minDate = this._formatDate( inst, minDate );
			}
			if ( maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined ) {
				inst.settings.maxDate = this._formatDate( inst, maxDate );
			}
			if ( "disabled" in settings ) {
				if ( settings.disabled ) {
					this._disableDatepicker( target );
				} else {
					this._enableDatepicker( target );
				}
			}
			this._attachments( $( target ), inst );
			this._autoSize( inst );
			this._setDate( inst, date );
			this._updateAlternate( inst );
			this._updateDatepicker( inst );
		}
	},

	// Change method deprecated
	_changeDatepicker: function( target, name, value ) {
		this._optionDatepicker( target, name, value );
	},

	/* Redraw the date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 */
	_refreshDatepicker: function( target ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._updateDatepicker( inst );
		}
	},

	/* Set the dates for a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  date	Date - the new date
	 */
	_setDateDatepicker: function( target, date ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._setDate( inst, date );
			this._updateDatepicker( inst );
			this._updateAlternate( inst );
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  noDefault boolean - true if no default date is to be used
	 * @return Date - the current date
	 */
	_getDateDatepicker: function( target, noDefault ) {
		var inst = this._getInst( target );
		if ( inst && !inst.inline ) {
			this._setDateFromField( inst, noDefault );
		}
		return ( inst ? this._getDate( inst ) : null );
	},

	/* Handle keystrokes. */
	_doKeyDown: function( event ) {
		var onSelect, dateStr, sel,
			inst = $.datepicker._getInst( event.target ),
			handled = true,
			isRTL = inst.dpDiv.is( ".ui-datepicker-rtl" );

		inst._keyEvent = true;
		if ( $.datepicker._datepickerShowing ) {
			switch ( event.keyCode ) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: sel = $( "td." + $.datepicker._dayOverClass + ":not(." +
									$.datepicker._currentClass + ")", inst.dpDiv );
						if ( sel[ 0 ] ) {
							$.datepicker._selectDay( event.target, inst.selectedMonth, inst.selectedYear, sel[ 0 ] );
						}

						onSelect = $.datepicker._get( inst, "onSelect" );
						if ( onSelect ) {
							dateStr = $.datepicker._formatDate( inst );

							// Trigger custom callback
							onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );
						} else {
							$.datepicker._hideDatepicker();
						}

						return false; // don't submit the form
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							-$.datepicker._get( inst, "stepBigMonths" ) :
							-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							+$.datepicker._get( inst, "stepBigMonths" ) :
							+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // next month/year on page down/+ ctrl
				case 35: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._clearDate( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._gotoToday( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? +1 : -1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// -1 day on ctrl or command +left
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								-$.datepicker._get( inst, "stepBigMonths" ) :
								-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +left on Mac
						break;
				case 38: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, -7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? -1 : +1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// +1 day on ctrl or command +right
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								+$.datepicker._get( inst, "stepBigMonths" ) :
								+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +right
						break;
				case 40: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, +7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		} else if ( event.keyCode === 36 && event.ctrlKey ) { // display the date picker on ctrl+home
			$.datepicker._showDatepicker( this );
		} else {
			handled = false;
		}

		if ( handled ) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function( event ) {
		var chars, chr,
			inst = $.datepicker._getInst( event.target );

		if ( $.datepicker._get( inst, "constrainInput" ) ) {
			chars = $.datepicker._possibleChars( $.datepicker._get( inst, "dateFormat" ) );
			chr = String.fromCharCode( event.charCode == null ? event.keyCode : event.charCode );
			return event.ctrlKey || event.metaKey || ( chr < " " || !chars || chars.indexOf( chr ) > -1 );
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function( event ) {
		var date,
			inst = $.datepicker._getInst( event.target );

		if ( inst.input.val() !== inst.lastVal ) {
			try {
				date = $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
					( inst.input ? inst.input.val() : null ),
					$.datepicker._getFormatConfig( inst ) );

				if ( date ) { // only if valid
					$.datepicker._setDateFromField( inst );
					$.datepicker._updateAlternate( inst );
					$.datepicker._updateDatepicker( inst );
				}
			} catch ( err ) {
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	 * If false returned from beforeShow event handler do not show.
	 * @param  input  element - the input field attached to the date picker or
	 *					event - if triggered by focus
	 */
	_showDatepicker: function( input ) {
		input = input.target || input;
		if ( input.nodeName.toLowerCase() !== "input" ) { // find from button/image trigger
			input = $( "input", input.parentNode )[ 0 ];
		}

		if ( $.datepicker._isDisabledDatepicker( input ) || $.datepicker._lastInput === input ) { // already here
			return;
		}

		var inst, beforeShow, beforeShowSettings, isFixed,
			offset, showAnim, duration;

		inst = $.datepicker._getInst( input );
		if ( $.datepicker._curInst && $.datepicker._curInst !== inst ) {
			$.datepicker._curInst.dpDiv.stop( true, true );
			if ( inst && $.datepicker._datepickerShowing ) {
				$.datepicker._hideDatepicker( $.datepicker._curInst.input[ 0 ] );
			}
		}

		beforeShow = $.datepicker._get( inst, "beforeShow" );
		beforeShowSettings = beforeShow ? beforeShow.apply( input, [ input, inst ] ) : {};
		if ( beforeShowSettings === false ) {
			return;
		}
		datepicker_extendRemove( inst.settings, beforeShowSettings );

		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField( inst );

		if ( $.datepicker._inDialog ) { // hide cursor
			input.value = "";
		}
		if ( !$.datepicker._pos ) { // position below input
			$.datepicker._pos = $.datepicker._findPos( input );
			$.datepicker._pos[ 1 ] += input.offsetHeight; // add the height
		}

		isFixed = false;
		$( input ).parents().each( function() {
			isFixed |= $( this ).css( "position" ) === "fixed";
			return !isFixed;
		} );

		offset = { left: $.datepicker._pos[ 0 ], top: $.datepicker._pos[ 1 ] };
		$.datepicker._pos = null;

		//to avoid flashes on Firefox
		inst.dpDiv.empty();

		// determine sizing offscreen
		inst.dpDiv.css( { position: "absolute", display: "block", top: "-1000px" } );
		$.datepicker._updateDatepicker( inst );

		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset( inst, offset, isFixed );
		inst.dpDiv.css( { position: ( $.datepicker._inDialog && $.blockUI ?
			"static" : ( isFixed ? "fixed" : "absolute" ) ), display: "none",
			left: offset.left + "px", top: offset.top + "px" } );

		if ( !inst.inline ) {
			showAnim = $.datepicker._get( inst, "showAnim" );
			duration = $.datepicker._get( inst, "duration" );
			inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
			$.datepicker._datepickerShowing = true;

			if ( $.effects && $.effects.effect[ showAnim ] ) {
				inst.dpDiv.show( showAnim, $.datepicker._get( inst, "showOptions" ), duration );
			} else {
				inst.dpDiv[ showAnim || "show" ]( showAnim ? duration : null );
			}

			if ( $.datepicker._shouldFocusInput( inst ) ) {
				inst.input.trigger( "focus" );
			}

			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function( inst ) {
		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
		datepicker_instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append( this._generateHTML( inst ) );
		this._attachHandlers( inst );

		var origyearshtml,
			numMonths = this._getNumberOfMonths( inst ),
			cols = numMonths[ 1 ],
			width = 17,
			activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" ),
			onUpdateDatepicker = $.datepicker._get( inst, "onUpdateDatepicker" );

		if ( activeCell.length > 0 ) {
			datepicker_handleMouseover.apply( activeCell.get( 0 ) );
		}

		inst.dpDiv.removeClass( "ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4" ).width( "" );
		if ( cols > 1 ) {
			inst.dpDiv.addClass( "ui-datepicker-multi-" + cols ).css( "width", ( width * cols ) + "em" );
		}
		inst.dpDiv[ ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-multi" );
		inst.dpDiv[ ( this._get( inst, "isRTL" ) ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-rtl" );

		if ( inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
			inst.input.trigger( "focus" );
		}

		// Deffered render of the years select (to avoid flashes on Firefox)
		if ( inst.yearshtml ) {
			origyearshtml = inst.yearshtml;
			setTimeout( function() {

				//assure that inst.yearshtml didn't change.
				if ( origyearshtml === inst.yearshtml && inst.yearshtml ) {
					inst.dpDiv.find( "select.ui-datepicker-year" ).first().replaceWith( inst.yearshtml );
				}
				origyearshtml = inst.yearshtml = null;
			}, 0 );
		}

		if ( onUpdateDatepicker ) {
			onUpdateDatepicker.apply( ( inst.input ? inst.input[ 0 ] : null ), [ inst ] );
		}
	},

	_shouldFocusInput: function( inst ) {
		return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" );
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function( inst, offset, isFixed ) {
		var dpWidth = inst.dpDiv.outerWidth(),
			dpHeight = inst.dpDiv.outerHeight(),
			inputWidth = inst.input ? inst.input.outerWidth() : 0,
			inputHeight = inst.input ? inst.input.outerHeight() : 0,
			viewWidth = document.documentElement.clientWidth + ( isFixed ? 0 : $( document ).scrollLeft() ),
			viewHeight = document.documentElement.clientHeight + ( isFixed ? 0 : $( document ).scrollTop() );

		offset.left -= ( this._get( inst, "isRTL" ) ? ( dpWidth - inputWidth ) : 0 );
		offset.left -= ( isFixed && offset.left === inst.input.offset().left ) ? $( document ).scrollLeft() : 0;
		offset.top -= ( isFixed && offset.top === ( inst.input.offset().top + inputHeight ) ) ? $( document ).scrollTop() : 0;

		// Now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= Math.min( offset.left, ( offset.left + dpWidth > viewWidth && viewWidth > dpWidth ) ?
			Math.abs( offset.left + dpWidth - viewWidth ) : 0 );
		offset.top -= Math.min( offset.top, ( offset.top + dpHeight > viewHeight && viewHeight > dpHeight ) ?
			Math.abs( dpHeight + inputHeight ) : 0 );

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function( obj ) {
		var position,
			inst = this._getInst( obj ),
			isRTL = this._get( inst, "isRTL" );

		while ( obj && ( obj.type === "hidden" || obj.nodeType !== 1 || $.expr.pseudos.hidden( obj ) ) ) {
			obj = obj[ isRTL ? "previousSibling" : "nextSibling" ];
		}

		position = $( obj ).offset();
		return [ position.left, position.top ];
	},

	/* Hide the date picker from view.
	 * @param  input  element - the input field attached to the date picker
	 */
	_hideDatepicker: function( input ) {
		var showAnim, duration, postProcess, onClose,
			inst = this._curInst;

		if ( !inst || ( input && inst !== $.data( input, "datepicker" ) ) ) {
			return;
		}

		if ( this._datepickerShowing ) {
			showAnim = this._get( inst, "showAnim" );
			duration = this._get( inst, "duration" );
			postProcess = function() {
				$.datepicker._tidyDialog( inst );
			};

			if ( $.effects && ( $.effects.effect[ showAnim ] ) ) {
				inst.dpDiv.hide( showAnim, $.datepicker._get( inst, "showOptions" ), duration, postProcess );
			} else {
				inst.dpDiv[ ( showAnim === "slideDown" ? "slideUp" :
					( showAnim === "fadeIn" ? "fadeOut" : "hide" ) ) ]( ( showAnim ? duration : null ), postProcess );
			}

			if ( !showAnim ) {
				postProcess();
			}
			this._datepickerShowing = false;

			onClose = this._get( inst, "onClose" );
			if ( onClose ) {
				onClose.apply( ( inst.input ? inst.input[ 0 ] : null ), [ ( inst.input ? inst.input.val() : "" ), inst ] );
			}

			this._lastInput = null;
			if ( this._inDialog ) {
				this._dialogInput.css( { position: "absolute", left: "0", top: "-100px" } );
				if ( $.blockUI ) {
					$.unblockUI();
					$( "body" ).append( this.dpDiv );
				}
			}
			this._inDialog = false;
		}
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function( inst ) {
		inst.dpDiv.removeClass( this._dialogClass ).off( ".ui-datepicker-calendar" );
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function( event ) {
		if ( !$.datepicker._curInst ) {
			return;
		}

		var $target = $( event.target ),
			inst = $.datepicker._getInst( $target[ 0 ] );

		if ( ( ( $target[ 0 ].id !== $.datepicker._mainDivId &&
				$target.parents( "#" + $.datepicker._mainDivId ).length === 0 &&
				!$target.hasClass( $.datepicker.markerClassName ) &&
				!$target.closest( "." + $.datepicker._triggerClass ).length &&
				$.datepicker._datepickerShowing && !( $.datepicker._inDialog && $.blockUI ) ) ) ||
			( $target.hasClass( $.datepicker.markerClassName ) && $.datepicker._curInst !== inst ) ) {
				$.datepicker._hideDatepicker();
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function( id, offset, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}
		this._adjustInstDate( inst, offset, period );
		this._updateDatepicker( inst );
	},

	/* Action for current link. */
	_gotoToday: function( id ) {
		var date,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._get( inst, "gotoCurrent" ) && inst.currentDay ) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function( id, select, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		inst[ "selected" + ( period === "M" ? "Month" : "Year" ) ] =
		inst[ "draw" + ( period === "M" ? "Month" : "Year" ) ] =
			parseInt( select.options[ select.selectedIndex ].value, 10 );

		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a day. */
	_selectDay: function( id, month, year, td ) {
		var inst,
			target = $( id );

		if ( $( td ).hasClass( this._unselectableClass ) || this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}

		inst = this._getInst( target[ 0 ] );
		inst.selectedDay = inst.currentDay = parseInt( $( "a", td ).attr( "data-date" ) );
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate( id, this._formatDate( inst,
			inst.currentDay, inst.currentMonth, inst.currentYear ) );
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function( id ) {
		var target = $( id );
		this._selectDate( target, "" );
	},

	/* Update the input field with the selected date. */
	_selectDate: function( id, dateStr ) {
		var onSelect,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		dateStr = ( dateStr != null ? dateStr : this._formatDate( inst ) );
		if ( inst.input ) {
			inst.input.val( dateStr );
		}
		this._updateAlternate( inst );

		onSelect = this._get( inst, "onSelect" );
		if ( onSelect ) {
			onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );  // trigger custom callback
		} else if ( inst.input ) {
			inst.input.trigger( "change" ); // fire the change event
		}

		if ( inst.inline ) {
			this._updateDatepicker( inst );
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[ 0 ];
			if ( typeof( inst.input[ 0 ] ) !== "object" ) {
				inst.input.trigger( "focus" ); // restore focus
			}
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function( inst ) {
		var altFormat, date, dateStr,
			altField = this._get( inst, "altField" );

		if ( altField ) { // update alternate field too
			altFormat = this._get( inst, "altFormat" ) || this._get( inst, "dateFormat" );
			date = this._getDate( inst );
			dateStr = this.formatDate( altFormat, date, this._getFormatConfig( inst ) );
			$( document ).find( altField ).val( dateStr );
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	 * @param  date  Date - the date to customise
	 * @return [boolean, string] - is this date selectable?, what is its CSS class?
	 */
	noWeekends: function( date ) {
		var day = date.getDay();
		return [ ( day > 0 && day < 6 ), "" ];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	 * @param  date  Date - the date to get the week for
	 * @return  number - the number of the week within the year that contains this date
	 */
	iso8601Week: function( date ) {
		var time,
			checkDate = new Date( date.getTime() );

		// Find Thursday of this week starting on Monday
		checkDate.setDate( checkDate.getDate() + 4 - ( checkDate.getDay() || 7 ) );

		time = checkDate.getTime();
		checkDate.setMonth( 0 ); // Compare with Jan 1
		checkDate.setDate( 1 );
		return Math.floor( Math.round( ( time - checkDate ) / 86400000 ) / 7 ) + 1;
	},

	/* Parse a string value into a date object.
	 * See formatDate below for the possible formats.
	 *
	 * @param  format string - the expected format of the date
	 * @param  value string - the date in the above format
	 * @param  settings Object - attributes include:
	 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  Date - the extracted date value or null if value is blank
	 */
	parseDate: function( format, value, settings ) {
		if ( format == null || value == null ) {
			throw "Invalid arguments";
		}

		value = ( typeof value === "object" ? value.toString() : value + "" );
		if ( value === "" ) {
			return null;
		}

		var iFormat, dim, extra,
			iValue = 0,
			shortYearCutoffTemp = ( settings ? settings.shortYearCutoff : null ) || this._defaults.shortYearCutoff,
			shortYearCutoff = ( typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
				new Date().getFullYear() % 100 + parseInt( shortYearCutoffTemp, 10 ) ),
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,
			year = -1,
			month = -1,
			day = -1,
			doy = -1,
			literal = false,
			date,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Extract a number from the string value
			getNumber = function( match ) {
				var isDoubled = lookAhead( match ),
					size = ( match === "@" ? 14 : ( match === "!" ? 20 :
					( match === "y" && isDoubled ? 4 : ( match === "o" ? 3 : 2 ) ) ) ),
					minSize = ( match === "y" ? size : 1 ),
					digits = new RegExp( "^\\d{" + minSize + "," + size + "}" ),
					num = value.substring( iValue ).match( digits );
				if ( !num ) {
					throw "Missing number at position " + iValue;
				}
				iValue += num[ 0 ].length;
				return parseInt( num[ 0 ], 10 );
			},

			// Extract a name from the string value and convert to an index
			getName = function( match, shortNames, longNames ) {
				var index = -1,
					names = $.map( lookAhead( match ) ? longNames : shortNames, function( v, k ) {
						return [ [ k, v ] ];
					} ).sort( function( a, b ) {
						return -( a[ 1 ].length - b[ 1 ].length );
					} );

				$.each( names, function( i, pair ) {
					var name = pair[ 1 ];
					if ( value.substr( iValue, name.length ).toLowerCase() === name.toLowerCase() ) {
						index = pair[ 0 ];
						iValue += name.length;
						return false;
					}
				} );
				if ( index !== -1 ) {
					return index + 1;
				} else {
					throw "Unknown name at position " + iValue;
				}
			},

			// Confirm that a literal character matches the string value
			checkLiteral = function() {
				if ( value.charAt( iValue ) !== format.charAt( iFormat ) ) {
					throw "Unexpected literal at position " + iValue;
				}
				iValue++;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					checkLiteral();
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d":
						day = getNumber( "d" );
						break;
					case "D":
						getName( "D", dayNamesShort, dayNames );
						break;
					case "o":
						doy = getNumber( "o" );
						break;
					case "m":
						month = getNumber( "m" );
						break;
					case "M":
						month = getName( "M", monthNamesShort, monthNames );
						break;
					case "y":
						year = getNumber( "y" );
						break;
					case "@":
						date = new Date( getNumber( "@" ) );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "!":
						date = new Date( ( getNumber( "!" ) - this._ticksTo1970 ) / 10000 );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if ( lookAhead( "'" ) ) {
							checkLiteral();
						} else {
							literal = true;
						}
						break;
					default:
						checkLiteral();
				}
			}
		}

		if ( iValue < value.length ) {
			extra = value.substr( iValue );
			if ( !/^\s+/.test( extra ) ) {
				throw "Extra/unparsed characters found in date: " + extra;
			}
		}

		if ( year === -1 ) {
			year = new Date().getFullYear();
		} else if ( year < 100 ) {
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				( year <= shortYearCutoff ? 0 : -100 );
		}

		if ( doy > -1 ) {
			month = 1;
			day = doy;
			do {
				dim = this._getDaysInMonth( year, month - 1 );
				if ( day <= dim ) {
					break;
				}
				month++;
				day -= dim;
			} while ( true );
		}

		date = this._daylightSavingAdjust( new Date( year, month - 1, day ) );
		if ( date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day ) {
			throw "Invalid date"; // E.g. 31/02/00
		}
		return date;
	},

	/* Standard date formats. */
	ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
	COOKIE: "D, dd M yy",
	ISO_8601: "yy-mm-dd",
	RFC_822: "D, d M y",
	RFC_850: "DD, dd-M-y",
	RFC_1036: "D, d M y",
	RFC_1123: "D, d M yy",
	RFC_2822: "D, d M yy",
	RSS: "D, d M y", // RFC 822
	TICKS: "!",
	TIMESTAMP: "@",
	W3C: "yy-mm-dd", // ISO 8601

	_ticksTo1970: ( ( ( 1970 - 1 ) * 365 + Math.floor( 1970 / 4 ) - Math.floor( 1970 / 100 ) +
		Math.floor( 1970 / 400 ) ) * 24 * 60 * 60 * 10000000 ),

	/* Format a date object into a string value.
	 * The format can be combinations of the following:
	 * d  - day of month (no leading zero)
	 * dd - day of month (two digit)
	 * o  - day of year (no leading zeros)
	 * oo - day of year (three digit)
	 * D  - day name short
	 * DD - day name long
	 * m  - month of year (no leading zero)
	 * mm - month of year (two digit)
	 * M  - month name short
	 * MM - month name long
	 * y  - year (two digit)
	 * yy - year (four digit)
	 * @ - Unix timestamp (ms since 01/01/1970)
	 * ! - Windows ticks (100ns since 01/01/0001)
	 * "..." - literal text
	 * '' - single quote
	 *
	 * @param  format string - the desired format of the date
	 * @param  date Date - the date value to format
	 * @param  settings Object - attributes include:
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  string - the date in the above format
	 */
	formatDate: function( format, date, settings ) {
		if ( !date ) {
			return "";
		}

		var iFormat,
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Format a number, with leading zero if necessary
			formatNumber = function( match, value, len ) {
				var num = "" + value;
				if ( lookAhead( match ) ) {
					while ( num.length < len ) {
						num = "0" + num;
					}
				}
				return num;
			},

			// Format a name, short or long as requested
			formatName = function( match, value, shortNames, longNames ) {
				return ( lookAhead( match ) ? longNames[ value ] : shortNames[ value ] );
			},
			output = "",
			literal = false;

		if ( date ) {
			for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
				if ( literal ) {
					if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
						literal = false;
					} else {
						output += format.charAt( iFormat );
					}
				} else {
					switch ( format.charAt( iFormat ) ) {
						case "d":
							output += formatNumber( "d", date.getDate(), 2 );
							break;
						case "D":
							output += formatName( "D", date.getDay(), dayNamesShort, dayNames );
							break;
						case "o":
							output += formatNumber( "o",
								Math.round( ( new Date( date.getFullYear(), date.getMonth(), date.getDate() ).getTime() - new Date( date.getFullYear(), 0, 0 ).getTime() ) / 86400000 ), 3 );
							break;
						case "m":
							output += formatNumber( "m", date.getMonth() + 1, 2 );
							break;
						case "M":
							output += formatName( "M", date.getMonth(), monthNamesShort, monthNames );
							break;
						case "y":
							output += ( lookAhead( "y" ) ? date.getFullYear() :
								( date.getFullYear() % 100 < 10 ? "0" : "" ) + date.getFullYear() % 100 );
							break;
						case "@":
							output += date.getTime();
							break;
						case "!":
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if ( lookAhead( "'" ) ) {
								output += "'";
							} else {
								literal = true;
							}
							break;
						default:
							output += format.charAt( iFormat );
					}
				}
			}
		}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function( format ) {
		var iFormat,
			chars = "",
			literal = false,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					chars += format.charAt( iFormat );
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d": case "m": case "y": case "@":
						chars += "0123456789";
						break;
					case "D": case "M":
						return null; // Accept anything
					case "'":
						if ( lookAhead( "'" ) ) {
							chars += "'";
						} else {
							literal = true;
						}
						break;
					default:
						chars += format.charAt( iFormat );
				}
			}
		}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function( inst, name ) {
		return inst.settings[ name ] !== undefined ?
			inst.settings[ name ] : this._defaults[ name ];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function( inst, noDefault ) {
		if ( inst.input.val() === inst.lastVal ) {
			return;
		}

		var dateFormat = this._get( inst, "dateFormat" ),
			dates = inst.lastVal = inst.input ? inst.input.val() : null,
			defaultDate = this._getDefaultDate( inst ),
			date = defaultDate,
			settings = this._getFormatConfig( inst );

		try {
			date = this.parseDate( dateFormat, dates, settings ) || defaultDate;
		} catch ( event ) {
			dates = ( noDefault ? "" : dates );
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = ( dates ? date.getDate() : 0 );
		inst.currentMonth = ( dates ? date.getMonth() : 0 );
		inst.currentYear = ( dates ? date.getFullYear() : 0 );
		this._adjustInstDate( inst );
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function( inst ) {
		return this._restrictMinMax( inst,
			this._determineDate( inst, this._get( inst, "defaultDate" ), new Date() ) );
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function( inst, date, defaultDate ) {
		var offsetNumeric = function( offset ) {
				var date = new Date();
				date.setDate( date.getDate() + offset );
				return date;
			},
			offsetString = function( offset ) {
				try {
					return $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
						offset, $.datepicker._getFormatConfig( inst ) );
				} catch ( e ) {

					// Ignore
				}

				var date = ( offset.toLowerCase().match( /^c/ ) ?
					$.datepicker._getDate( inst ) : null ) || new Date(),
					year = date.getFullYear(),
					month = date.getMonth(),
					day = date.getDate(),
					pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
					matches = pattern.exec( offset );

				while ( matches ) {
					switch ( matches[ 2 ] || "d" ) {
						case "d" : case "D" :
							day += parseInt( matches[ 1 ], 10 ); break;
						case "w" : case "W" :
							day += parseInt( matches[ 1 ], 10 ) * 7; break;
						case "m" : case "M" :
							month += parseInt( matches[ 1 ], 10 );
							day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
							break;
						case "y": case "Y" :
							year += parseInt( matches[ 1 ], 10 );
							day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
							break;
					}
					matches = pattern.exec( offset );
				}
				return new Date( year, month, day );
			},
			newDate = ( date == null || date === "" ? defaultDate : ( typeof date === "string" ? offsetString( date ) :
				( typeof date === "number" ? ( isNaN( date ) ? defaultDate : offsetNumeric( date ) ) : new Date( date.getTime() ) ) ) );

		newDate = ( newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate );
		if ( newDate ) {
			newDate.setHours( 0 );
			newDate.setMinutes( 0 );
			newDate.setSeconds( 0 );
			newDate.setMilliseconds( 0 );
		}
		return this._daylightSavingAdjust( newDate );
	},

	/* Handle switch to/from daylight saving.
	 * Hours may be non-zero on daylight saving cut-over:
	 * > 12 when midnight changeover, but then cannot generate
	 * midnight datetime, so jump to 1AM, otherwise reset.
	 * @param  date  (Date) the date to check
	 * @return  (Date) the corrected date
	 */
	_daylightSavingAdjust: function( date ) {
		if ( !date ) {
			return null;
		}
		date.setHours( date.getHours() > 12 ? date.getHours() + 2 : 0 );
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function( inst, date, noChange ) {
		var clear = !date,
			origMonth = inst.selectedMonth,
			origYear = inst.selectedYear,
			newDate = this._restrictMinMax( inst, this._determineDate( inst, date, new Date() ) );

		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ( ( origMonth !== inst.selectedMonth || origYear !== inst.selectedYear ) && !noChange ) {
			this._notifyChange( inst );
		}
		this._adjustInstDate( inst );
		if ( inst.input ) {
			inst.input.val( clear ? "" : this._formatDate( inst ) );
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function( inst ) {
		var startDate = ( !inst.currentYear || ( inst.input && inst.input.val() === "" ) ? null :
			this._daylightSavingAdjust( new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
			return startDate;
	},

	/* Attach the onxxx handlers.  These are declared statically so
	 * they work with static code transformers like Caja.
	 */
	_attachHandlers: function( inst ) {
		var stepMonths = this._get( inst, "stepMonths" ),
			id = "#" + inst.id.replace( /\\\\/g, "\\" );
		inst.dpDiv.find( "[data-handler]" ).map( function() {
			var handler = {
				prev: function() {
					$.datepicker._adjustDate( id, -stepMonths, "M" );
				},
				next: function() {
					$.datepicker._adjustDate( id, +stepMonths, "M" );
				},
				hide: function() {
					$.datepicker._hideDatepicker();
				},
				today: function() {
					$.datepicker._gotoToday( id );
				},
				selectDay: function() {
					$.datepicker._selectDay( id, +this.getAttribute( "data-month" ), +this.getAttribute( "data-year" ), this );
					return false;
				},
				selectMonth: function() {
					$.datepicker._selectMonthYear( id, this, "M" );
					return false;
				},
				selectYear: function() {
					$.datepicker._selectMonthYear( id, this, "Y" );
					return false;
				}
			};
			$( this ).on( this.getAttribute( "data-event" ), handler[ this.getAttribute( "data-handler" ) ] );
		} );
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function( inst ) {
		var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
			controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
			monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
			selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
			cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
			printDate, dRow, tbody, daySettings, otherMonth, unselectable,
			tempDate = new Date(),
			today = this._daylightSavingAdjust(
				new Date( tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate() ) ), // clear time
			isRTL = this._get( inst, "isRTL" ),
			showButtonPanel = this._get( inst, "showButtonPanel" ),
			hideIfNoPrevNext = this._get( inst, "hideIfNoPrevNext" ),
			navigationAsDateFormat = this._get( inst, "navigationAsDateFormat" ),
			numMonths = this._getNumberOfMonths( inst ),
			showCurrentAtPos = this._get( inst, "showCurrentAtPos" ),
			stepMonths = this._get( inst, "stepMonths" ),
			isMultiMonth = ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ),
			currentDate = this._daylightSavingAdjust( ( !inst.currentDay ? new Date( 9999, 9, 9 ) :
				new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) ),
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			drawMonth = inst.drawMonth - showCurrentAtPos,
			drawYear = inst.drawYear;

		if ( drawMonth < 0 ) {
			drawMonth += 12;
			drawYear--;
		}
		if ( maxDate ) {
			maxDraw = this._daylightSavingAdjust( new Date( maxDate.getFullYear(),
				maxDate.getMonth() - ( numMonths[ 0 ] * numMonths[ 1 ] ) + 1, maxDate.getDate() ) );
			maxDraw = ( minDate && maxDraw < minDate ? minDate : maxDraw );
			while ( this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 ) ) > maxDraw ) {
				drawMonth--;
				if ( drawMonth < 0 ) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;

		prevText = this._get( inst, "prevText" );
		prevText = ( !navigationAsDateFormat ? prevText : this.formatDate( prevText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth - stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		if ( this._canAdjustMonth( inst, -1, drawYear, drawMonth ) ) {
			prev = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-prev ui-corner-all",
					"data-handler": "prev",
					"data-event": "click",
					title: prevText
				} )
				.append(
					$( "<span>" )
						.addClass( "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "e" : "w" ) )
						.text( prevText )
				)[ 0 ].outerHTML;
		} else if ( hideIfNoPrevNext ) {
			prev = "";
		} else {
			prev = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-prev ui-corner-all ui-state-disabled",
					title: prevText
				} )
				.append(
					$( "<span>" )
						.addClass( "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "e" : "w" ) )
						.text( prevText )
				)[ 0 ].outerHTML;
		}

		nextText = this._get( inst, "nextText" );
		nextText = ( !navigationAsDateFormat ? nextText : this.formatDate( nextText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth + stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		if ( this._canAdjustMonth( inst, +1, drawYear, drawMonth ) ) {
			next = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-next ui-corner-all",
					"data-handler": "next",
					"data-event": "click",
					title: nextText
				} )
				.append(
					$( "<span>" )
						.addClass( "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "w" : "e" ) )
						.text( nextText )
				)[ 0 ].outerHTML;
		} else if ( hideIfNoPrevNext ) {
			next = "";
		} else {
			next = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-next ui-corner-all ui-state-disabled",
					title: nextText
				} )
				.append(
					$( "<span>" )
						.attr( "class", "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "w" : "e" ) )
						.text( nextText )
				)[ 0 ].outerHTML;
		}

		currentText = this._get( inst, "currentText" );
		gotoDate = ( this._get( inst, "gotoCurrent" ) && inst.currentDay ? currentDate : today );
		currentText = ( !navigationAsDateFormat ? currentText :
			this.formatDate( currentText, gotoDate, this._getFormatConfig( inst ) ) );

		controls = "";
		if ( !inst.inline ) {
			controls = $( "<button>" )
				.attr( {
					type: "button",
					"class": "ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all",
					"data-handler": "hide",
					"data-event": "click"
				} )
				.text( this._get( inst, "closeText" ) )[ 0 ].outerHTML;
		}

		buttonPanel = "";
		if ( showButtonPanel ) {
			buttonPanel = $( "<div class='ui-datepicker-buttonpane ui-widget-content'>" )
				.append( isRTL ? controls : "" )
				.append( this._isInRange( inst, gotoDate ) ?
					$( "<button>" )
						.attr( {
							type: "button",
							"class": "ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all",
							"data-handler": "today",
							"data-event": "click"
						} )
						.text( currentText ) :
					"" )
				.append( isRTL ? "" : controls )[ 0 ].outerHTML;
		}

		firstDay = parseInt( this._get( inst, "firstDay" ), 10 );
		firstDay = ( isNaN( firstDay ) ? 0 : firstDay );

		showWeek = this._get( inst, "showWeek" );
		dayNames = this._get( inst, "dayNames" );
		dayNamesMin = this._get( inst, "dayNamesMin" );
		monthNames = this._get( inst, "monthNames" );
		monthNamesShort = this._get( inst, "monthNamesShort" );
		beforeShowDay = this._get( inst, "beforeShowDay" );
		showOtherMonths = this._get( inst, "showOtherMonths" );
		selectOtherMonths = this._get( inst, "selectOtherMonths" );
		defaultDate = this._getDefaultDate( inst );
		html = "";

		for ( row = 0; row < numMonths[ 0 ]; row++ ) {
			group = "";
			this.maxRows = 4;
			for ( col = 0; col < numMonths[ 1 ]; col++ ) {
				selectedDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, inst.selectedDay ) );
				cornerClass = " ui-corner-all";
				calender = "";
				if ( isMultiMonth ) {
					calender += "<div class='ui-datepicker-group";
					if ( numMonths[ 1 ] > 1 ) {
						switch ( col ) {
							case 0: calender += " ui-datepicker-group-first";
								cornerClass = " ui-corner-" + ( isRTL ? "right" : "left" ); break;
							case numMonths[ 1 ] - 1: calender += " ui-datepicker-group-last";
								cornerClass = " ui-corner-" + ( isRTL ? "left" : "right" ); break;
							default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
						}
					}
					calender += "'>";
				}
				calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
					( /all|left/.test( cornerClass ) && row === 0 ? ( isRTL ? next : prev ) : "" ) +
					( /all|right/.test( cornerClass ) && row === 0 ? ( isRTL ? prev : next ) : "" ) +
					this._generateMonthYearHeader( inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort ) + // draw month headers
					"</div><table class='ui-datepicker-calendar'><thead>" +
					"<tr>";
				thead = ( showWeek ? "<th class='ui-datepicker-week-col'>" + this._get( inst, "weekHeader" ) + "</th>" : "" );
				for ( dow = 0; dow < 7; dow++ ) { // days of the week
					day = ( dow + firstDay ) % 7;
					thead += "<th scope='col'" + ( ( dow + firstDay + 6 ) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "" ) + ">" +
						"<span title='" + dayNames[ day ] + "'>" + dayNamesMin[ day ] + "</span></th>";
				}
				calender += thead + "</tr></thead><tbody>";
				daysInMonth = this._getDaysInMonth( drawYear, drawMonth );
				if ( drawYear === inst.selectedYear && drawMonth === inst.selectedMonth ) {
					inst.selectedDay = Math.min( inst.selectedDay, daysInMonth );
				}
				leadDays = ( this._getFirstDayOfMonth( drawYear, drawMonth ) - firstDay + 7 ) % 7;
				curRows = Math.ceil( ( leadDays + daysInMonth ) / 7 ); // calculate the number of rows to generate
				numRows = ( isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows ); //If multiple months, use the higher number of rows (see #7043)
				this.maxRows = numRows;
				printDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 - leadDays ) );
				for ( dRow = 0; dRow < numRows; dRow++ ) { // create date picker rows
					calender += "<tr>";
					tbody = ( !showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
						this._get( inst, "calculateWeek" )( printDate ) + "</td>" );
					for ( dow = 0; dow < 7; dow++ ) { // create date picker days
						daySettings = ( beforeShowDay ?
							beforeShowDay.apply( ( inst.input ? inst.input[ 0 ] : null ), [ printDate ] ) : [ true, "" ] );
						otherMonth = ( printDate.getMonth() !== drawMonth );
						unselectable = ( otherMonth && !selectOtherMonths ) || !daySettings[ 0 ] ||
							( minDate && printDate < minDate ) || ( maxDate && printDate > maxDate );
						tbody += "<td class='" +
							( ( dow + firstDay + 6 ) % 7 >= 5 ? " ui-datepicker-week-end" : "" ) + // highlight weekends
							( otherMonth ? " ui-datepicker-other-month" : "" ) + // highlight days from other months
							( ( printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent ) || // user pressed key
							( defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime() ) ?

							// or defaultDate is current printedDate and defaultDate is selectedDate
							" " + this._dayOverClass : "" ) + // highlight selected day
							( unselectable ? " " + this._unselectableClass + " ui-state-disabled" : "" ) +  // highlight unselectable days
							( otherMonth && !showOtherMonths ? "" : " " + daySettings[ 1 ] + // highlight custom dates
							( printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "" ) + // highlight selected day
							( printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "" ) ) + "'" + // highlight today (if different)
							( ( !otherMonth || showOtherMonths ) && daySettings[ 2 ] ? " title='" + daySettings[ 2 ].replace( /'/g, "&#39;" ) + "'" : "" ) + // cell title
							( unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'" ) + ">" + // actions
							( otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
							( unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
							( printDate.getTime() === today.getTime() ? " ui-state-highlight" : "" ) +
							( printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "" ) + // highlight selected day
							( otherMonth ? " ui-priority-secondary" : "" ) + // distinguish dates from other months
							"' href='#' aria-current='" + ( printDate.getTime() === currentDate.getTime() ? "true" : "false" ) + // mark date as selected for screen reader
							"' data-date='" + printDate.getDate() + // store date as data
							"'>" + printDate.getDate() + "</a>" ) ) + "</td>"; // display selectable date
						printDate.setDate( printDate.getDate() + 1 );
						printDate = this._daylightSavingAdjust( printDate );
					}
					calender += tbody + "</tr>";
				}
				drawMonth++;
				if ( drawMonth > 11 ) {
					drawMonth = 0;
					drawYear++;
				}
				calender += "</tbody></table>" + ( isMultiMonth ? "</div>" +
							( ( numMonths[ 0 ] > 0 && col === numMonths[ 1 ] - 1 ) ? "<div class='ui-datepicker-row-break'></div>" : "" ) : "" );
				group += calender;
			}
			html += group;
		}
		html += buttonPanel;
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function( inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort ) {

		var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
			changeMonth = this._get( inst, "changeMonth" ),
			changeYear = this._get( inst, "changeYear" ),
			showMonthAfterYear = this._get( inst, "showMonthAfterYear" ),
			selectMonthLabel = this._get( inst, "selectMonthLabel" ),
			selectYearLabel = this._get( inst, "selectYearLabel" ),
			html = "<div class='ui-datepicker-title'>",
			monthHtml = "";

		// Month selection
		if ( secondary || !changeMonth ) {
			monthHtml += "<span class='ui-datepicker-month'>" + monthNames[ drawMonth ] + "</span>";
		} else {
			inMinYear = ( minDate && minDate.getFullYear() === drawYear );
			inMaxYear = ( maxDate && maxDate.getFullYear() === drawYear );
			monthHtml += "<select class='ui-datepicker-month' aria-label='" + selectMonthLabel + "' data-handler='selectMonth' data-event='change'>";
			for ( month = 0; month < 12; month++ ) {
				if ( ( !inMinYear || month >= minDate.getMonth() ) && ( !inMaxYear || month <= maxDate.getMonth() ) ) {
					monthHtml += "<option value='" + month + "'" +
						( month === drawMonth ? " selected='selected'" : "" ) +
						">" + monthNamesShort[ month ] + "</option>";
				}
			}
			monthHtml += "</select>";
		}

		if ( !showMonthAfterYear ) {
			html += monthHtml + ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" );
		}

		// Year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = "";
			if ( secondary || !changeYear ) {
				html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
			} else {

				// determine range of years to display
				years = this._get( inst, "yearRange" ).split( ":" );
				thisYear = new Date().getFullYear();
				determineYear = function( value ) {
					var year = ( value.match( /c[+\-].*/ ) ? drawYear + parseInt( value.substring( 1 ), 10 ) :
						( value.match( /[+\-].*/ ) ? thisYear + parseInt( value, 10 ) :
						parseInt( value, 10 ) ) );
					return ( isNaN( year ) ? thisYear : year );
				};
				year = determineYear( years[ 0 ] );
				endYear = Math.max( year, determineYear( years[ 1 ] || "" ) );
				year = ( minDate ? Math.max( year, minDate.getFullYear() ) : year );
				endYear = ( maxDate ? Math.min( endYear, maxDate.getFullYear() ) : endYear );
				inst.yearshtml += "<select class='ui-datepicker-year' aria-label='" + selectYearLabel + "' data-handler='selectYear' data-event='change'>";
				for ( ; year <= endYear; year++ ) {
					inst.yearshtml += "<option value='" + year + "'" +
						( year === drawYear ? " selected='selected'" : "" ) +
						">" + year + "</option>";
				}
				inst.yearshtml += "</select>";

				html += inst.yearshtml;
				inst.yearshtml = null;
			}
		}

		html += this._get( inst, "yearSuffix" );
		if ( showMonthAfterYear ) {
			html += ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" ) + monthHtml;
		}
		html += "</div>"; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function( inst, offset, period ) {
		var year = inst.selectedYear + ( period === "Y" ? offset : 0 ),
			month = inst.selectedMonth + ( period === "M" ? offset : 0 ),
			day = Math.min( inst.selectedDay, this._getDaysInMonth( year, month ) ) + ( period === "D" ? offset : 0 ),
			date = this._restrictMinMax( inst, this._daylightSavingAdjust( new Date( year, month, day ) ) );

		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if ( period === "M" || period === "Y" ) {
			this._notifyChange( inst );
		}
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function( inst, date ) {
		var minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			newDate = ( minDate && date < minDate ? minDate : date );
		return ( maxDate && newDate > maxDate ? maxDate : newDate );
	},

	/* Notify change of month/year. */
	_notifyChange: function( inst ) {
		var onChange = this._get( inst, "onChangeMonthYear" );
		if ( onChange ) {
			onChange.apply( ( inst.input ? inst.input[ 0 ] : null ),
				[ inst.selectedYear, inst.selectedMonth + 1, inst ] );
		}
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function( inst ) {
		var numMonths = this._get( inst, "numberOfMonths" );
		return ( numMonths == null ? [ 1, 1 ] : ( typeof numMonths === "number" ? [ 1, numMonths ] : numMonths ) );
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function( inst, minMax ) {
		return this._determineDate( inst, this._get( inst, minMax + "Date" ), null );
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function( year, month ) {
		return 32 - this._daylightSavingAdjust( new Date( year, month, 32 ) ).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function( year, month ) {
		return new Date( year, month, 1 ).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function( inst, offset, curYear, curMonth ) {
		var numMonths = this._getNumberOfMonths( inst ),
			date = this._daylightSavingAdjust( new Date( curYear,
			curMonth + ( offset < 0 ? offset : numMonths[ 0 ] * numMonths[ 1 ] ), 1 ) );

		if ( offset < 0 ) {
			date.setDate( this._getDaysInMonth( date.getFullYear(), date.getMonth() ) );
		}
		return this._isInRange( inst, date );
	},

	/* Is the given date in the accepted range? */
	_isInRange: function( inst, date ) {
		var yearSplit, currentYear,
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			minYear = null,
			maxYear = null,
			years = this._get( inst, "yearRange" );
			if ( years ) {
				yearSplit = years.split( ":" );
				currentYear = new Date().getFullYear();
				minYear = parseInt( yearSplit[ 0 ], 10 );
				maxYear = parseInt( yearSplit[ 1 ], 10 );
				if ( yearSplit[ 0 ].match( /[+\-].*/ ) ) {
					minYear += currentYear;
				}
				if ( yearSplit[ 1 ].match( /[+\-].*/ ) ) {
					maxYear += currentYear;
				}
			}

		return ( ( !minDate || date.getTime() >= minDate.getTime() ) &&
			( !maxDate || date.getTime() <= maxDate.getTime() ) &&
			( !minYear || date.getFullYear() >= minYear ) &&
			( !maxYear || date.getFullYear() <= maxYear ) );
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function( inst ) {
		var shortYearCutoff = this._get( inst, "shortYearCutoff" );
		shortYearCutoff = ( typeof shortYearCutoff !== "string" ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt( shortYearCutoff, 10 ) );
		return { shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get( inst, "dayNamesShort" ), dayNames: this._get( inst, "dayNames" ),
			monthNamesShort: this._get( inst, "monthNamesShort" ), monthNames: this._get( inst, "monthNames" ) };
	},

	/* Format the given date for display. */
	_formatDate: function( inst, day, month, year ) {
		if ( !day ) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = ( day ? ( typeof day === "object" ? day :
			this._daylightSavingAdjust( new Date( year, month, day ) ) ) :
			this._daylightSavingAdjust( new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
		return this.formatDate( this._get( inst, "dateFormat" ), date, this._getFormatConfig( inst ) );
	}
} );

/*
 * Bind hover events for datepicker elements.
 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function datepicker_bindHover( dpDiv ) {
	var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
	return dpDiv.on( "mouseout", selector, function() {
			$( this ).removeClass( "ui-state-hover" );
			if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-prev-hover" );
			}
			if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-next-hover" );
			}
		} )
		.on( "mouseover", selector, datepicker_handleMouseover );
}

function datepicker_handleMouseover() {
	if ( !$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? datepicker_instActive.dpDiv.parent()[ 0 ] : datepicker_instActive.input[ 0 ] ) ) {
		$( this ).parents( ".ui-datepicker-calendar" ).find( "a" ).removeClass( "ui-state-hover" );
		$( this ).addClass( "ui-state-hover" );
		if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-prev-hover" );
		}
		if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-next-hover" );
		}
	}
}

/* jQuery extend now ignores nulls! */
function datepicker_extendRemove( target, props ) {
	$.extend( target, props );
	for ( var name in props ) {
		if ( props[ name ] == null ) {
			target[ name ] = props[ name ];
		}
	}
	return target;
}

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
					Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function( options ) {

	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}

	/* Initialise the date picker. */
	if ( !$.datepicker.initialized ) {
		$( document ).on( "mousedown", $.datepicker._checkExternalClick );
		$.datepicker.initialized = true;
	}

	/* Append datepicker main container to body if not exist. */
	if ( $( "#" + $.datepicker._mainDivId ).length === 0 ) {
		$( "body" ).append( $.datepicker.dpDiv );
	}

	var otherArgs = Array.prototype.slice.call( arguments, 1 );
	if ( typeof options === "string" && ( options === "isDisabled" || options === "getDate" || options === "widget" ) ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	if ( options === "option" && arguments.length === 2 && typeof arguments[ 1 ] === "string" ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	return this.each( function() {
		if ( typeof options === "string" ) {
			$.datepicker[ "_" + options + "Datepicker" ]
				.apply( $.datepicker, [ this ].concat( otherArgs ) );
		} else {
			$.datepicker._attachDatepicker( this, options );
		}
	} );
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.14.0";

var widgetsDatepicker = $.datepicker;


/*!
 * jQuery UI Mouse 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: https://api.jqueryui.com/mouse/


var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
} );

var widgetsMouse = $.widget( "ui.mouse", {
	version: "1.14.0",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on( "mousedown." + this.widgetName, function( event ) {
				return that._mouseDown( event );
			} )
			.on( "click." + this.widgetName, function( event ) {
				if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
					$.removeData( event.target, that.widgetName + ".preventClickEvent" );
					event.stopImmediatePropagation();
					return false;
				}
			} );

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off( "." + this.widgetName );
		if ( this._mouseMoveDelegate ) {
			this.document
				.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
				.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
		}
	},

	_mouseDown: function( event ) {

		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		if ( this._mouseStarted ) {
			this._mouseUp( event );
		}

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = event.which === 1,
			elIsCancel = typeof this.options.cancel === "string" ?
				$( event.target ).closest( this.options.cancel ).length :
				false;
		if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if ( !this.mouseDelayMet ) {
			this._mouseDelayTimer = setTimeout( function() {
				that.mouseDelayMet = true;
			}, this.options.delay );
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted = ( this._mouseStart( event ) !== false );
			if ( !this._mouseStarted ) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
			$.removeData( event.target, this.widgetName + ".preventClickEvent" );
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function( event ) {
			return that._mouseMove( event );
		};
		this._mouseUpDelegate = function( event ) {
			return that._mouseUp( event );
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once.
		if ( this._mouseMoved && !event.which ) {

			// Support: Safari <=8 - 9
			// Safari sets which to 0 if you press any of the following keys
			// during a drag (#14461)
			if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
					event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
				this.ignoreMissingWhich = true;
			} else if ( !this.ignoreMissingWhich ) {
				return this._mouseUp( event );
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if ( this._mouseStarted ) {
			this._mouseDrag( event );
			return event.preventDefault();
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted =
				( this._mouseStart( this._mouseDownEvent, event ) !== false );
			if ( this._mouseStarted ) {
				this._mouseDrag( event );
			} else {
				this._mouseUp( event );
			}
		}

		return !this._mouseStarted;
	},

	_mouseUp: function( event ) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if ( this._mouseStarted ) {
			this._mouseStarted = false;

			if ( event.target === this._mouseDownEvent.target ) {
				$.data( event.target, this.widgetName + ".preventClickEvent", true );
			}

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

	_mouseDistanceMet: function( event ) {
		return ( Math.max(
				Math.abs( this._mouseDownEvent.pageX - event.pageX ),
				Math.abs( this._mouseDownEvent.pageY - event.pageY )
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function( /* event */ ) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function( /* event */ ) {},
	_mouseDrag: function( /* event */ ) {},
	_mouseStop: function( /* event */ ) {},
	_mouseCapture: function( /* event */ ) {
		return true;
	}
} );



// $.ui.plugin is deprecated. Use $.widget() extensions instead.
var plugin = $.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode ||
				instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};


/*!
 * jQuery UI Draggable 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Draggable
//>>group: Interactions
//>>description: Enables dragging functionality for any element.
//>>docs: https://api.jqueryui.com/draggable/
//>>demos: https://jqueryui.com/draggable/
//>>css.structure: ../../themes/base/draggable.css


$.widget( "ui.draggable", $.ui.mouse, {
	version: "1.14.0",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// Callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if ( this.options.addClasses ) {
			this._addClass( "ui-draggable" );
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var o = this.options;

		// Among others, prevent a drag on a resizable-handle
		if ( this.helper || o.disabled ||
				$( event.target ).closest( ".ui-resizable-handle" ).length > 0 ) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle( event );
		if ( !this.handle ) {
			return false;
		}

		this._blurActiveElement( event );

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var activeElement = this.document[ 0 ].activeElement,
			target = $( event.target );

		// Don't blur if the event occurred on an element that is within
		// the currently focused element
		// See #10527, #12472
		if ( target.closest( activeElement ).length ) {
			return;
		}

		// Blur any element that currently has focus, see #4261
		$( activeElement ).trigger( "blur" );
	},

	_mouseStart: function( event ) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		this._addClass( this.helper, "ui-draggable-dragging" );

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter( function() {
				return $( this ).css( "position" ) === "fixed";
			} ).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		if ( o.cursorAt ) {
			this._adjustOffsetFromHelper( o.cursorAt );
		}

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if ( this._trigger( "start", event ) === false ) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		// Execute the drag once - this causes the helper not to be visible before getting its
		// correct position
		this._mouseDrag( event, true );

		// If the ddmanager is used for droppables, inform the manager that dragging has started
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart( this, event );
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function( event, noPropagation ) {

		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Call plugins and callbacks and use the resulting position if something is returned
		if ( !noPropagation ) {
			var ui = this._uiHash();
			if ( this._trigger( "drag", event, ui ) === false ) {
				this._mouseUp( new $.Event( "mouseup", event ) );
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		return false;
	},

	_mouseStop: function( event ) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			dropped = $.ui.ddmanager.drop( this, event );
		}

		//if a drop comes from outside (a sortable)
		if ( this.dropped ) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ( ( this.options.revert === "invalid" && !dropped ) ||
				( this.options.revert === "valid" && dropped ) ||
				this.options.revert === true || ( typeof this.options.revert === "function" &&
				this.options.revert.call( this.element, dropped ) )
		) {
			$( this.helper ).animate(
				this.originalPosition,
				parseInt( this.options.revertDuration, 10 ),
				function() {
					if ( that._trigger( "stop", event ) !== false ) {
						that._clear();
					}
				}
			);
		} else {
			if ( this._trigger( "stop", event ) !== false ) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		// If the ddmanager is used for droppables, inform the manager that dragging has stopped
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop( this, event );
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {

			// The interaction is over; whether or not the click resulted in a drag,
			// focus the element
			this.element.trigger( "focus" );
		}

		return $.ui.mouse.prototype._mouseUp.call( this, event );
	},

	cancel: function() {

		if ( this.helper.is( ".ui-draggable-dragging" ) ) {
			this._mouseUp( new $.Event( "mouseup", { target: this.element[ 0 ] } ) );
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function( event ) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this._addClass( this.handleElement, "ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this._removeClass( this.handleElement, "ui-draggable-handle" );
	},

	_createHelper: function( event ) {

		var o = this.options,
			helperIsFunction = typeof o.helper === "function",
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if ( !helper.parents( "body" ).length ) {
			helper.appendTo( ( o.appendTo === "parent" ?
				this.element[ 0 ].parentNode :
				o.appendTo ) );
		}

		// https://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if ( helper[ 0 ] !== this.element[ 0 ] &&
				!( /(fixed|absolute)/ ).test( helper.css( "position" ) ) ) {
			helper.css( "position", "absolute" );
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( Array.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== document &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
			left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: ( parseInt( this.element.css( "marginLeft" ), 10 ) || 0 ),
			top: ( parseInt( this.element.css( "marginTop" ), 10 ) || 0 ),
			right: ( parseInt( this.element.css( "marginRight" ), 10 ) || 0 ),
			bottom: ( parseInt( this.element.css( "marginBottom" ), 10 ) || 0 )
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() -
					this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() +
					( $( window ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document" ) {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod )
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ) {
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if ( event.pageX - this.offset.click.left < containment[ 0 ] ) {
					pageX = containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < containment[ 1 ] ) {
					pageY = containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > containment[ 2 ] ) {
					pageX = containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > containment[ 3 ] ) {
					pageY = containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {

				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
				// argument errors in IE (see ticket #6950)
				top = o.grid[ 1 ] ? this.originalPageY + Math.round( ( pageY -
					this.originalPageY ) / o.grid[ 1 ] ) * o.grid[ 1 ] : this.originalPageY;
				pageY = containment ? ( ( top - this.offset.click.top >= containment[ 1 ] ||
					top - this.offset.click.top > containment[ 3 ] ) ?
						top :
						( ( top - this.offset.click.top >= containment[ 1 ] ) ?
							top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) : top;

				left = o.grid[ 0 ] ? this.originalPageX +
					Math.round( ( pageX - this.originalPageX ) / o.grid[ 0 ] ) * o.grid[ 0 ] :
					this.originalPageX;
				pageX = containment ? ( ( left - this.offset.click.left >= containment[ 0 ] ||
					left - this.offset.click.left > containment[ 2 ] ) ?
						left :
						( ( left - this.offset.click.left >= containment[ 0 ] ) ?
							left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this._removeClass( this.helper, "ui-draggable-dragging" );
		if ( this.helper[ 0 ] !== this.element[ 0 ] && !this.cancelHelperRemoval ) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

} );

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each( function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// RefreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger( "activate", event, uiSortable );
			}
		} );
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop( event );

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {

				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		} );
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {

					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				} );
			}

			if ( innermostIntersecting ) {

				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					// Store draggable's parent in case we need to reappend to it later.
					draggable._parent = ui.helper.parent();

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );

					// Hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );

					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {

				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// Restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Restore and recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways. (#8809, #10669)
					ui.helper.appendTo( draggable._parent );
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );
				}
			}
		} );
	}
} );

$.ui.plugin.add( "draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if ( t.css( "cursor" ) ) {
			o._cursor = t.css( "cursor" );
		}
		t.css( "cursor", o.cursor );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._cursor ) {
			$( "body" ).css( "cursor", o._cursor );
		}
	}
} );

$.ui.plugin.add( "draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if ( t.css( "opacity" ) ) {
			o._opacity = t.css( "opacity" );
		}
		t.css( "opacity", o.opacity );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._opacity ) {
			$( ui.helper ).css( "opacity", o._opacity );
		}
	}
} );

$.ui.plugin.add( "draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] &&
				i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY <
						o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX <
						o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if ( !o.axis || o.axis !== "x" ) {
				if ( event.pageY - $( document ).scrollTop() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() - o.scrollSpeed );
				} else if ( $( window ).height() - ( event.pageY - $( document ).scrollTop() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() + o.scrollSpeed );
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( event.pageX - $( document ).scrollLeft() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() - o.scrollSpeed
					);
				} else if ( $( window ).width() - ( event.pageX - $( document ).scrollLeft() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() + o.scrollSpeed
					);
				}
			}

		}

		if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( i, event );
		}

	}
} );

$.ui.plugin.add( "draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$( o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap )
			.each( function() {
				var $t = $( this ),
					$o = $t.offset();
				if ( this !== i.element[ 0 ] ) {
					i.snapElements.push( {
						item: this,
						width: $t.outerWidth(), height: $t.outerHeight(),
						top: $o.top, left: $o.left
					} );
				}
			} );

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for ( i = inst.snapElements.length - 1; i >= 0; i-- ) {

			l = inst.snapElements[ i ].left - inst.margins.left;
			r = l + inst.snapElements[ i ].width;
			t = inst.snapElements[ i ].top - inst.margins.top;
			b = t + inst.snapElements[ i ].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
					!$.contains( inst.snapElements[ i ].item.ownerDocument,
					inst.snapElements[ i ].item ) ) {
				if ( inst.snapElements[ i ].snapping ) {
					if ( inst.options.snap.release ) {
						inst.options.snap.release.call(
							inst.element,
							event,
							$.extend( inst._uiHash(), { snapItem: inst.snapElements[ i ].item } )
						);
					}
				}
				inst.snapElements[ i ].snapping = false;
				continue;
			}

			if ( o.snapMode !== "inner" ) {
				ts = Math.abs( t - y2 ) <= d;
				bs = Math.abs( b - y1 ) <= d;
				ls = Math.abs( l - x2 ) <= d;
				rs = Math.abs( r - x1 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l - inst.helperProportions.width
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r
					} ).left;
				}
			}

			first = ( ts || bs || ls || rs );

			if ( o.snapMode !== "outer" ) {
				ts = Math.abs( t - y1 ) <= d;
				bs = Math.abs( b - y2 ) <= d;
				ls = Math.abs( l - x1 ) <= d;
				rs = Math.abs( r - x2 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r - inst.helperProportions.width
					} ).left;
				}
			}

			if ( !inst.snapElements[ i ].snapping && ( ts || bs || ls || rs || first ) ) {
				if ( inst.options.snap.snap ) {
					inst.options.snap.snap.call(
						inst.element,
						event,
						$.extend( inst._uiHash(), {
							snapItem: inst.snapElements[ i ].item
						} ) );
				}
			}
			inst.snapElements[ i ].snapping = ( ts || bs || ls || rs || first );

		}

	}
} );

$.ui.plugin.add( "draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray( $( o.stack ) ).sort( function( a, b ) {
				return ( parseInt( $( a ).css( "zIndex" ), 10 ) || 0 ) -
					( parseInt( $( b ).css( "zIndex" ), 10 ) || 0 );
			} );

		if ( !group.length ) {
			return;
		}

		min = parseInt( $( group[ 0 ] ).css( "zIndex" ), 10 ) || 0;
		$( group ).each( function( i ) {
			$( this ).css( "zIndex", min + i );
		} );
		this.css( "zIndex", ( min + group.length ) );
	}
} );

$.ui.plugin.add( "draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if ( t.css( "zIndex" ) ) {
			o._zIndex = t.css( "zIndex" );
		}
		t.css( "zIndex", o.zIndex );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if ( o._zIndex ) {
			$( ui.helper ).css( "zIndex", o._zIndex );
		}
	}
} );

var widgetsDraggable = $.ui.draggable;


/*!
 * jQuery UI Resizable 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Resizable
//>>group: Interactions
//>>description: Enables resize functionality for any element.
//>>docs: https://api.jqueryui.com/resizable/
//>>demos: https://jqueryui.com/resizable/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/resizable.css
//>>css.theme: ../../themes/base/theme.css


$.widget( "ui.resizable", $.ui.mouse, {
	version: "1.14.0",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		classes: {
			"ui-resizable-se": "ui-icon ui-icon-gripsmall-diagonal-se"
		},
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,

		// See #7960
		zIndex: 90,

		// Callbacks
		resize: null,
		start: null,
		stop: null
	},

	_num: function( value ) {
		return parseFloat( value ) || 0;
	},

	_isNumber: function( value ) {
		return !isNaN( parseFloat( value ) );
	},

	_hasScroll: function( el, a ) {

		if ( $( el ).css( "overflow" ) === "hidden" ) {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		try {
			el[ scroll ] = 1;
			has = ( el[ scroll ] > 0 );
			el[ scroll ] = 0;
		} catch ( e ) {

			// `el` might be a string, then setting `scroll` will throw
			// an error in strict mode; ignore it.
		}
		return has;
	},

	_create: function() {

		var margins,
			o = this.options,
			that = this;
		this._addClass( "ui-resizable" );

		$.extend( this, {
			_aspectRatio: !!( o.aspectRatio ),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
		} );

		// Wrap the element if it cannot hold child nodes
		if ( this.element[ 0 ].nodeName.match( /^(canvas|textarea|input|select|button|img)$/i ) ) {

			this.element.wrap(
				$( "<div class='ui-wrapper'></div>" ).css( {
					overflow: "hidden",
					position: this.element.css( "position" ),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css( "top" ),
					left: this.element.css( "left" )
				} )
			);

			this.element = this.element.parent().data(
				"ui-resizable", this.element.resizable( "instance" )
			);

			this.elementIsWrapper = true;

			margins = {
				marginTop: this.originalElement.css( "marginTop" ),
				marginRight: this.originalElement.css( "marginRight" ),
				marginBottom: this.originalElement.css( "marginBottom" ),
				marginLeft: this.originalElement.css( "marginLeft" )
			};

			this.element.css( margins );

			// Support: Safari
			// Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css( "resize" );
			this.originalElement.css( "resize", "none" );

			this._proportionallyResizeElements.push( this.originalElement.css( {
				position: "static",
				zoom: 1,
				display: "block"
			} ) );

			this._proportionallyResize();
		}

		this._setupHandles();

		if ( o.autoHide ) {
			$( this.element )
				.on( "mouseenter", function() {
					if ( o.disabled ) {
						return;
					}
					that._removeClass( "ui-resizable-autohide" );
					that._handles.show();
				} )
				.on( "mouseleave", function() {
					if ( o.disabled ) {
						return;
					}
					if ( !that.resizing ) {
						that._addClass( "ui-resizable-autohide" );
						that._handles.hide();
					}
				} );
		}

		this._mouseInit();
	},

	_destroy: function() {

		this._mouseDestroy();
		this._addedHandles.remove();

		var wrapper,
			_destroy = function( exp ) {
				$( exp )
					.removeData( "resizable" )
					.removeData( "ui-resizable" )
					.off( ".resizable" );
			};

		// TODO: Unwrap at same DOM position
		if ( this.elementIsWrapper ) {
			_destroy( this.element );
			wrapper = this.element;
			this.originalElement.css( {
				position: wrapper.css( "position" ),
				width: wrapper.outerWidth(),
				height: wrapper.outerHeight(),
				top: wrapper.css( "top" ),
				left: wrapper.css( "left" )
			} ).insertAfter( wrapper );
			wrapper.remove();
		}

		this.originalElement.css( "resize", this.originalResizeStyle );
		_destroy( this.originalElement );

		return this;
	},

	_setOption: function( key, value ) {
		this._super( key, value );

		switch ( key ) {
		case "handles":
			this._removeHandles();
			this._setupHandles();
			break;
		case "aspectRatio":
			this._aspectRatio = !!value;
			break;
		default:
			break;
		}
	},

	_setupHandles: function() {
		var o = this.options, handle, i, n, hname, axis, that = this;
		this.handles = o.handles ||
			( !$( ".ui-resizable-handle", this.element ).length ?
				"e,s,se" : {
					n: ".ui-resizable-n",
					e: ".ui-resizable-e",
					s: ".ui-resizable-s",
					w: ".ui-resizable-w",
					se: ".ui-resizable-se",
					sw: ".ui-resizable-sw",
					ne: ".ui-resizable-ne",
					nw: ".ui-resizable-nw"
				} );

		this._handles = $();
		this._addedHandles = $();
		if ( this.handles.constructor === String ) {

			if ( this.handles === "all" ) {
				this.handles = "n,e,s,w,se,sw,ne,nw";
			}

			n = this.handles.split( "," );
			this.handles = {};

			for ( i = 0; i < n.length; i++ ) {

				handle = String.prototype.trim.call( n[ i ] );
				hname = "ui-resizable-" + handle;
				axis = $( "<div>" );
				this._addClass( axis, "ui-resizable-handle " + hname );

				axis.css( { zIndex: o.zIndex } );

				this.handles[ handle ] = ".ui-resizable-" + handle;
				if ( !this.element.children( this.handles[ handle ] ).length ) {
					this.element.append( axis );
					this._addedHandles = this._addedHandles.add( axis );
				}
			}

		}

		this._renderAxis = function( target ) {

			var i, axis, padPos, padWrapper;

			target = target || this.element;

			for ( i in this.handles ) {

				if ( this.handles[ i ].constructor === String ) {
					this.handles[ i ] = this.element.children( this.handles[ i ] ).first().show();
				} else if ( this.handles[ i ].jquery || this.handles[ i ].nodeType ) {
					this.handles[ i ] = $( this.handles[ i ] );
					this._on( this.handles[ i ], { "mousedown": that._mouseDown } );
				}

				if ( this.elementIsWrapper &&
						this.originalElement[ 0 ]
							.nodeName
							.match( /^(textarea|input|select|button)$/i ) ) {
					axis = $( this.handles[ i ], this.element );

					padWrapper = /sw|ne|nw|se|n|s/.test( i ) ?
						axis.outerHeight() :
						axis.outerWidth();

					padPos = [ "padding",
						/ne|nw|n/.test( i ) ? "Top" :
						/se|sw|s/.test( i ) ? "Bottom" :
						/^e$/.test( i ) ? "Right" : "Left" ].join( "" );

					target.css( padPos, padWrapper );

					this._proportionallyResize();
				}

				this._handles = this._handles.add( this.handles[ i ] );
			}
		};

		// TODO: make renderAxis a prototype function
		this._renderAxis( this.element );

		this._handles = this._handles.add( this.element.find( ".ui-resizable-handle" ) );
		this._handles.disableSelection();

		this._handles.on( "mouseover", function() {
			if ( !that.resizing ) {
				if ( this.className ) {
					axis = this.className.match( /ui-resizable-(se|sw|ne|nw|n|e|s|w)/i );
				}
				that.axis = axis && axis[ 1 ] ? axis[ 1 ] : "se";
			}
		} );

		if ( o.autoHide ) {
			this._handles.hide();
			this._addClass( "ui-resizable-autohide" );
		}
	},

	_removeHandles: function() {
		this._addedHandles.remove();
	},

	_mouseCapture: function( event ) {
		var i, handle,
			capture = false;

		for ( i in this.handles ) {
			handle = $( this.handles[ i ] )[ 0 ];
			if ( handle === event.target || $.contains( handle, event.target ) ) {
				capture = true;
			}
		}

		return !this.options.disabled && capture;
	},

	_mouseStart: function( event ) {

		var curleft, curtop, cursor,
			o = this.options,
			el = this.element;

		this.resizing = true;

		this._renderProxy();

		curleft = this._num( this.helper.css( "left" ) );
		curtop = this._num( this.helper.css( "top" ) );

		if ( o.containment ) {
			curleft += $( o.containment ).scrollLeft() || 0;
			curtop += $( o.containment ).scrollTop() || 0;
		}

		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };

		this.size = this._helper ? {
				width: this.helper.width(),
				height: this.helper.height()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.originalSize = this._helper ? {
				width: el.outerWidth(),
				height: el.outerHeight()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.sizeDiff = {
			width: el.outerWidth() - el.width(),
			height: el.outerHeight() - el.height()
		};

		this.originalPosition = { left: curleft, top: curtop };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		this.aspectRatio = ( typeof o.aspectRatio === "number" ) ?
			o.aspectRatio :
			( ( this.originalSize.width / this.originalSize.height ) || 1 );

		cursor = $( ".ui-resizable-" + this.axis ).css( "cursor" );
		$( "body" ).css( "cursor", cursor === "auto" ? this.axis + "-resize" : cursor );

		this._addClass( "ui-resizable-resizing" );
		this._propagate( "start", event );
		return true;
	},

	_mouseDrag: function( event ) {

		var data, props,
			smp = this.originalMousePosition,
			a = this.axis,
			dx = ( event.pageX - smp.left ) || 0,
			dy = ( event.pageY - smp.top ) || 0,
			trigger = this._change[ a ];

		this._updatePrevProperties();

		if ( !trigger ) {
			return false;
		}

		data = trigger.apply( this, [ event, dx, dy ] );

		this._updateVirtualBoundaries( event.shiftKey );
		if ( this._aspectRatio || event.shiftKey ) {
			data = this._updateRatio( data, event );
		}

		data = this._respectSize( data, event );

		this._updateCache( data );

		this._propagate( "resize", event );

		props = this._applyChanges();

		if ( !this._helper && this._proportionallyResizeElements.length ) {
			this._proportionallyResize();
		}

		if ( !$.isEmptyObject( props ) ) {
			this._updatePrevProperties();
			this._trigger( "resize", event, this.ui() );
			this._applyChanges();
		}

		return false;
	},

	_mouseStop: function( event ) {

		this.resizing = false;
		var pr, ista, soffseth, soffsetw, s, left, top,
			o = this.options, that = this;

		if ( this._helper ) {

			pr = this._proportionallyResizeElements;
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName );
			soffseth = ista && this._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = {
				width: ( that.helper.width()  - soffsetw ),
				height: ( that.helper.height() - soffseth )
			};
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null;
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

			if ( !o.animate ) {
				this.element.css( $.extend( s, { top: top, left: left } ) );
			}

			that.helper.height( that.size.height );
			that.helper.width( that.size.width );

			if ( this._helper && !o.animate ) {
				this._proportionallyResize();
			}
		}

		$( "body" ).css( "cursor", "auto" );

		this._removeClass( "ui-resizable-resizing" );

		this._propagate( "stop", event );

		if ( this._helper ) {
			this.helper.remove();
		}

		return false;

	},

	_updatePrevProperties: function() {
		this.prevPosition = {
			top: this.position.top,
			left: this.position.left
		};
		this.prevSize = {
			width: this.size.width,
			height: this.size.height
		};
	},

	_applyChanges: function() {
		var props = {};

		if ( this.position.top !== this.prevPosition.top ) {
			props.top = this.position.top + "px";
		}
		if ( this.position.left !== this.prevPosition.left ) {
			props.left = this.position.left + "px";
		}

		this.helper.css( props );

		if ( this.size.width !== this.prevSize.width ) {
			props.width = this.size.width + "px";
			this.helper.width( props.width );
		}
		if ( this.size.height !== this.prevSize.height ) {
			props.height = this.size.height + "px";
			this.helper.height( props.height );
		}

		return props;
	},

	_updateVirtualBoundaries: function( forceAspectRatio ) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: this._isNumber( o.minWidth ) ? o.minWidth : 0,
			maxWidth: this._isNumber( o.maxWidth ) ? o.maxWidth : Infinity,
			minHeight: this._isNumber( o.minHeight ) ? o.minHeight : 0,
			maxHeight: this._isNumber( o.maxHeight ) ? o.maxHeight : Infinity
		};

		if ( this._aspectRatio || forceAspectRatio ) {
			pMinWidth = b.minHeight * this.aspectRatio;
			pMinHeight = b.minWidth / this.aspectRatio;
			pMaxWidth = b.maxHeight * this.aspectRatio;
			pMaxHeight = b.maxWidth / this.aspectRatio;

			if ( pMinWidth > b.minWidth ) {
				b.minWidth = pMinWidth;
			}
			if ( pMinHeight > b.minHeight ) {
				b.minHeight = pMinHeight;
			}
			if ( pMaxWidth < b.maxWidth ) {
				b.maxWidth = pMaxWidth;
			}
			if ( pMaxHeight < b.maxHeight ) {
				b.maxHeight = pMaxHeight;
			}
		}
		this._vBoundaries = b;
	},

	_updateCache: function( data ) {
		this.offset = this.helper.offset();
		if ( this._isNumber( data.left ) ) {
			this.position.left = data.left;
		}
		if ( this._isNumber( data.top ) ) {
			this.position.top = data.top;
		}
		if ( this._isNumber( data.height ) ) {
			this.size.height = data.height;
		}
		if ( this._isNumber( data.width ) ) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if ( this._isNumber( data.height ) ) {
			data.width = ( data.height * this.aspectRatio );
		} else if ( this._isNumber( data.width ) ) {
			data.height = ( data.width / this.aspectRatio );
		}

		if ( a === "sw" ) {
			data.left = cpos.left + ( csize.width - data.width );
			data.top = null;
		}
		if ( a === "nw" ) {
			data.top = cpos.top + ( csize.height - data.height );
			data.left = cpos.left + ( csize.width - data.width );
		}

		return data;
	},

	_respectSize: function( data ) {

		var o = this._vBoundaries,
			a = this.axis,
			ismaxw = this._isNumber( data.width ) && o.maxWidth && ( o.maxWidth < data.width ),
			ismaxh = this._isNumber( data.height ) && o.maxHeight && ( o.maxHeight < data.height ),
			isminw = this._isNumber( data.width ) && o.minWidth && ( o.minWidth > data.width ),
			isminh = this._isNumber( data.height ) && o.minHeight && ( o.minHeight > data.height ),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.originalPosition.top + this.originalSize.height,
			cw = /sw|nw|w/.test( a ), ch = /nw|ne|n/.test( a );
		if ( isminw ) {
			data.width = o.minWidth;
		}
		if ( isminh ) {
			data.height = o.minHeight;
		}
		if ( ismaxw ) {
			data.width = o.maxWidth;
		}
		if ( ismaxh ) {
			data.height = o.maxHeight;
		}

		if ( isminw && cw ) {
			data.left = dw - o.minWidth;
		}
		if ( ismaxw && cw ) {
			data.left = dw - o.maxWidth;
		}
		if ( isminh && ch ) {
			data.top = dh - o.minHeight;
		}
		if ( ismaxh && ch ) {
			data.top = dh - o.maxHeight;
		}

		// Fixing jump error on top/left - bug #2330
		if ( !data.width && !data.height && !data.left && data.top ) {
			data.top = null;
		} else if ( !data.width && !data.height && !data.top && data.left ) {
			data.left = null;
		}

		return data;
	},

	_getPaddingPlusBorderDimensions: function( element ) {
		var i = 0,
			widths = [],
			borders = [
				element.css( "borderTopWidth" ),
				element.css( "borderRightWidth" ),
				element.css( "borderBottomWidth" ),
				element.css( "borderLeftWidth" )
			],
			paddings = [
				element.css( "paddingTop" ),
				element.css( "paddingRight" ),
				element.css( "paddingBottom" ),
				element.css( "paddingLeft" )
			];

		for ( ; i < 4; i++ ) {
			widths[ i ] = ( parseFloat( borders[ i ] ) || 0 );
			widths[ i ] += ( parseFloat( paddings[ i ] ) || 0 );
		}

		return {
			height: widths[ 0 ] + widths[ 2 ],
			width: widths[ 1 ] + widths[ 3 ]
		};
	},

	_proportionallyResize: function() {

		if ( !this._proportionallyResizeElements.length ) {
			return;
		}

		var prel,
			i = 0,
			element = this.helper || this.element;

		for ( ; i < this._proportionallyResizeElements.length; i++ ) {

			prel = this._proportionallyResizeElements[ i ];

			// TODO: Seems like a bug to cache this.outerDimensions
			// considering that we are in a loop.
			if ( !this.outerDimensions ) {
				this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
			}

			prel.css( {
				height: ( element.height() - this.outerDimensions.height ) || 0,
				width: ( element.width() - this.outerDimensions.width ) || 0
			} );

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if ( this._helper ) {

			this.helper = this.helper || $( "<div></div>" ).css( { overflow: "hidden" } );

			this._addClass( this.helper, this._helper );
			this.helper.css( {
				width: this.element.outerWidth(),
				height: this.element.outerHeight(),
				position: "absolute",
				left: this.elementOffset.left + "px",
				top: this.elementOffset.top + "px",
				zIndex: ++o.zIndex //TODO: Don't modify option
			} );

			this.helper
				.appendTo( "body" )
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function( event, dx ) {
			return { width: this.originalSize.width + dx };
		},
		w: function( event, dx ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function( event, dx, dy ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function( event, dx, dy ) {
			return { height: this.originalSize.height + dy };
		},
		se: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		sw: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		},
		ne: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		nw: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		}
	},

	_propagate: function( n, event ) {
		$.ui.plugin.call( this, n, [ event, this.ui() ] );
		if ( n !== "resize" ) {
			this._trigger( n, event, this.ui() );
		}
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

} );

/*
 * Resizable Extensions
 */

$.ui.plugin.add( "resizable", "animate", {

	stop: function( event ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName ),
			soffseth = ista && that._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = {
				width: ( that.size.width - soffsetw ),
				height: ( that.size.height - soffseth )
			},
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null,
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

		that.element.animate(
			$.extend( style, top && left ? { top: top, left: left } : {} ), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseFloat( that.element.css( "width" ) ),
						height: parseFloat( that.element.css( "height" ) ),
						top: parseFloat( that.element.css( "top" ) ),
						left: parseFloat( that.element.css( "left" ) )
					};

					if ( pr && pr.length ) {
						$( pr[ 0 ] ).css( { width: data.width, height: data.height } );
					}

					// Propagating resize, and updating values for each animation step
					that._updateCache( data );
					that._propagate( "resize", event );

				}
			}
		);
	}

} );

$.ui.plugin.add( "resizable", "containment", {

	start: function() {
		var element, p, co, ch, cw, width, height,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			el = that.element,
			oc = o.containment,
			ce = ( oc instanceof $ ) ?
				oc.get( 0 ) :
				( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;

		if ( !ce ) {
			return;
		}

		that.containerElement = $( ce );

		if ( /document/.test( oc ) || oc === document ) {
			that.containerOffset = {
				left: 0,
				top: 0
			};
			that.containerPosition = {
				left: 0,
				top: 0
			};

			that.parentData = {
				element: $( document ),
				left: 0,
				top: 0,
				width: $( document ).width(),
				height: $( document ).height() || document.body.parentNode.scrollHeight
			};
		} else {
			element = $( ce );
			p = [];
			$( [ "Top", "Right", "Left", "Bottom" ] ).each( function( i, name ) {
				p[ i ] = that._num( element.css( "padding" + name ) );
			} );

			that.containerOffset = element.offset();
			that.containerPosition = element.position();
			that.containerSize = {
				height: ( element.innerHeight() - p[ 3 ] ),
				width: ( element.innerWidth() - p[ 1 ] )
			};

			co = that.containerOffset;
			ch = that.containerSize.height;
			cw = that.containerSize.width;
			width = ( that._hasScroll( ce, "left" ) ? ce.scrollWidth : cw );
			height = ( that._hasScroll( ce ) ? ce.scrollHeight : ch );

			that.parentData = {
				element: ce,
				left: co.left,
				top: co.top,
				width: width,
				height: height
			};
		}
	},

	resize: function( event ) {
		var woset, hoset, isParent, isOffsetRelative,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = {
				top: 0,
				left: 0
			},
			ce = that.containerElement,
			continueResize = true;

		if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
			cop = co;
		}

		if ( cp.left < ( that._helper ? co.left : 0 ) ) {
			that.size.width = that.size.width +
				( that._helper ?
					( that.position.left - co.left ) :
					( that.position.left - cop.left ) );

			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
			that.position.left = o.helper ? co.left : 0;
		}

		if ( cp.top < ( that._helper ? co.top : 0 ) ) {
			that.size.height = that.size.height +
				( that._helper ?
					( that.position.top - co.top ) :
					that.position.top );

			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
		isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );

		if ( isParent && isOffsetRelative ) {
			that.offset.left = that.parentData.left + that.position.left;
			that.offset.top = that.parentData.top + that.position.top;
		} else {
			that.offset.left = that.element.offset().left;
			that.offset.top = that.element.offset().top;
		}

		woset = Math.abs( that.sizeDiff.width +
			( that._helper ?
				that.offset.left - cop.left :
				( that.offset.left - co.left ) ) );

		hoset = Math.abs( that.sizeDiff.height +
			( that._helper ?
				that.offset.top - cop.top :
				( that.offset.top - co.top ) ) );

		if ( woset + that.size.width >= that.parentData.width ) {
			that.size.width = that.parentData.width - woset;
			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
		}

		if ( hoset + that.size.height >= that.parentData.height ) {
			that.size.height = that.parentData.height - hoset;
			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
		}

		if ( !continueResize ) {
			that.position.left = that.prevPosition.left;
			that.position.top = that.prevPosition.top;
			that.size.width = that.prevSize.width;
			that.size.height = that.prevSize.height;
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cop = that.containerPosition,
			ce = that.containerElement,
			helper = $( that.helper ),
			ho = helper.offset(),
			w = helper.outerWidth() - that.sizeDiff.width,
			h = helper.outerHeight() - that.sizeDiff.height;

		if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}

		if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}
	}
} );

$.ui.plugin.add( "resizable", "alsoResize", {

	start: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options;

		$( o.alsoResize ).each( function() {
			var el = $( this );
			el.data( "ui-resizable-alsoresize", {
				width: parseFloat( el.css( "width" ) ), height: parseFloat( el.css( "height" ) ),
				left: parseFloat( el.css( "left" ) ), top: parseFloat( el.css( "top" ) )
			} );
		} );
	},

	resize: function( event, ui ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			os = that.originalSize,
			op = that.originalPosition,
			delta = {
				height: ( that.size.height - os.height ) || 0,
				width: ( that.size.width - os.width ) || 0,
				top: ( that.position.top - op.top ) || 0,
				left: ( that.position.left - op.left ) || 0
			};

			$( o.alsoResize ).each( function() {
				var el = $( this ), start = $( this ).data( "ui-resizable-alsoresize" ), style = {},
					css = el.parents( ui.originalElement[ 0 ] ).length ?
							[ "width", "height" ] :
							[ "width", "height", "top", "left" ];

				$.each( css, function( i, prop ) {
					var sum = ( start[ prop ] || 0 ) + ( delta[ prop ] || 0 );
					if ( sum && sum >= 0 ) {
						style[ prop ] = sum || null;
					}
				} );

				el.css( style );
			} );
	},

	stop: function() {
		$( this ).removeData( "ui-resizable-alsoresize" );
	}
} );

$.ui.plugin.add( "resizable", "ghost", {

	start: function() {

		var that = $( this ).resizable( "instance" ), cs = that.size;

		that.ghost = that.originalElement.clone();
		that.ghost.css( {
			opacity: 0.25,
			display: "block",
			position: "relative",
			height: cs.height,
			width: cs.width,
			margin: 0,
			left: 0,
			top: 0
		} );

		that._addClass( that.ghost, "ui-resizable-ghost" );

		// DEPRECATED
		// TODO: remove after 1.12
		if ( $.uiBackCompat === true && typeof that.options.ghost === "string" ) {

			// Ghost option
			that.ghost.addClass( this.options.ghost );
		}

		that.ghost.appendTo( that.helper );

	},

	resize: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost ) {
			that.ghost.css( {
				position: "relative",
				height: that.size.height,
				width: that.size.width
			} );
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost && that.helper ) {
			that.helper.get( 0 ).removeChild( that.ghost.get( 0 ) );
		}
	}

} );

$.ui.plugin.add( "resizable", "grid", {

	resize: function() {
		var outerDimensions,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			cs = that.size,
			os = that.originalSize,
			op = that.originalPosition,
			a = that.axis,
			grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
			gridX = ( grid[ 0 ] || 1 ),
			gridY = ( grid[ 1 ] || 1 ),
			ox = Math.round( ( cs.width - os.width ) / gridX ) * gridX,
			oy = Math.round( ( cs.height - os.height ) / gridY ) * gridY,
			newWidth = os.width + ox,
			newHeight = os.height + oy,
			isMaxWidth = o.maxWidth && ( o.maxWidth < newWidth ),
			isMaxHeight = o.maxHeight && ( o.maxHeight < newHeight ),
			isMinWidth = o.minWidth && ( o.minWidth > newWidth ),
			isMinHeight = o.minHeight && ( o.minHeight > newHeight );

		o.grid = grid;

		if ( isMinWidth ) {
			newWidth += gridX;
		}
		if ( isMinHeight ) {
			newHeight += gridY;
		}
		if ( isMaxWidth ) {
			newWidth -= gridX;
		}
		if ( isMaxHeight ) {
			newHeight -= gridY;
		}

		if ( /^(se|s|e)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
		} else if ( /^(ne)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
		} else if ( /^(sw)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.left = op.left - ox;
		} else {
			if ( newHeight - gridY <= 0 || newWidth - gridX <= 0 ) {
				outerDimensions = that._getPaddingPlusBorderDimensions( this );
			}

			if ( newHeight - gridY > 0 ) {
				that.size.height = newHeight;
				that.position.top = op.top - oy;
			} else {
				newHeight = gridY - outerDimensions.height;
				that.size.height = newHeight;
				that.position.top = op.top + os.height - newHeight;
			}
			if ( newWidth - gridX > 0 ) {
				that.size.width = newWidth;
				that.position.left = op.left - ox;
			} else {
				newWidth = gridX - outerDimensions.width;
				that.size.width = newWidth;
				that.position.left = op.left + os.width - newWidth;
			}
		}
	}

} );

var widgetsResizable = $.ui.resizable;


/*!
 * jQuery UI Dialog 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Dialog
//>>group: Widgets
//>>description: Displays customizable dialog windows.
//>>docs: https://api.jqueryui.com/dialog/
//>>demos: https://jqueryui.com/dialog/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/dialog.css
//>>css.theme: ../../themes/base/theme.css


$.widget( "ui.dialog", {
	version: "1.14.0",
	options: {
		appendTo: "body",
		autoOpen: true,
		buttons: [],
		classes: {
			"ui-dialog": "ui-corner-all",
			"ui-dialog-titlebar": "ui-corner-all"
		},
		closeOnEscape: true,
		closeText: "Close",
		draggable: true,
		hide: null,
		height: "auto",
		maxHeight: null,
		maxWidth: null,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: {
			my: "center",
			at: "center",
			of: window,
			collision: "fit",

			// Ensure the titlebar is always visible
			using: function( pos ) {
				var topOffset = $( this ).css( pos ).offset().top;
				if ( topOffset < 0 ) {
					$( this ).css( "top", pos.top - topOffset );
				}
			}
		},
		resizable: true,
		show: null,
		title: null,
		width: 300,

		// Callbacks
		beforeClose: null,
		close: null,
		drag: null,
		dragStart: null,
		dragStop: null,
		focus: null,
		open: null,
		resize: null,
		resizeStart: null,
		resizeStop: null
	},

	sizeRelatedOptions: {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},

	resizableRelatedOptions: {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	},

	_create: function() {
		this.originalCss = {
			display: this.element[ 0 ].style.display,
			width: this.element[ 0 ].style.width,
			minHeight: this.element[ 0 ].style.minHeight,
			maxHeight: this.element[ 0 ].style.maxHeight,
			height: this.element[ 0 ].style.height
		};
		this.originalPosition = {
			parent: this.element.parent(),
			index: this.element.parent().children().index( this.element )
		};
		this.originalTitle = this.element.attr( "title" );
		if ( this.options.title == null && this.originalTitle != null ) {
			this.options.title = this.originalTitle;
		}

		// Dialogs can't be disabled
		if ( this.options.disabled ) {
			this.options.disabled = false;
		}

		this._createWrapper();

		this.element
			.show()
			.removeAttr( "title" )
			.appendTo( this.uiDialog );

		this._addClass( "ui-dialog-content", "ui-widget-content" );

		this._createTitlebar();
		this._createButtonPane();

		if ( this.options.draggable && $.fn.draggable ) {
			this._makeDraggable();
		}
		if ( this.options.resizable && $.fn.resizable ) {
			this._makeResizable();
		}

		this._isOpen = false;

		this._trackFocus();
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;
		if ( element && ( element.jquery || element.nodeType ) ) {
			return $( element );
		}
		return this.document.find( element || "body" ).eq( 0 );
	},

	_destroy: function() {
		var next,
			originalPosition = this.originalPosition;

		this._untrackInstance();
		this._destroyOverlay();

		this.element
			.removeUniqueId()
			.css( this.originalCss )

			// Without detaching first, the following becomes really slow
			.detach();

		this.uiDialog.remove();

		if ( this.originalTitle ) {
			this.element.attr( "title", this.originalTitle );
		}

		next = originalPosition.parent.children().eq( originalPosition.index );

		// Don't try to place the dialog next to itself (#8613)
		if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
			next.before( this.element );
		} else {
			originalPosition.parent.append( this.element );
		}
	},

	widget: function() {
		return this.uiDialog;
	},

	disable: $.noop,
	enable: $.noop,

	close: function( event ) {
		var that = this;

		if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
			return;
		}

		this._isOpen = false;
		this._focusedElement = null;
		this._destroyOverlay();
		this._untrackInstance();

		if ( !this.opener.filter( ":focusable" ).trigger( "focus" ).length ) {

			// Hiding a focused element doesn't trigger blur in WebKit
			// so in case we have nothing to focus on, explicitly blur the active element
			// https://bugs.webkit.org/show_bug.cgi?id=47182
			$( this.document[ 0 ].activeElement ).trigger( "blur" );
		}

		this._hide( this.uiDialog, this.options.hide, function() {
			that._trigger( "close", event );
		} );
	},

	isOpen: function() {
		return this._isOpen;
	},

	moveToTop: function() {
		this._moveToTop();
	},

	_moveToTop: function( event, silent ) {
		var moved = false,
			zIndices = this.uiDialog.siblings( ".ui-front:visible" ).map( function() {
				return +$( this ).css( "z-index" );
			} ).get(),
			zIndexMax = Math.max.apply( null, zIndices );

		if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) {
			this.uiDialog.css( "z-index", zIndexMax + 1 );
			moved = true;
		}

		if ( moved && !silent ) {
			this._trigger( "focus", event );
		}
		return moved;
	},

	open: function() {
		var that = this;
		if ( this._isOpen ) {
			if ( this._moveToTop() ) {
				this._focusTabbable();
			}
			return;
		}

		this._isOpen = true;
		this.opener = $( this.document[ 0 ].activeElement );

		this._size();
		this._position();
		this._createOverlay();
		this._moveToTop( null, true );

		// Ensure the overlay is moved to the top with the dialog, but only when
		// opening. The overlay shouldn't move after the dialog is open so that
		// modeless dialogs opened after the modal dialog stack properly.
		if ( this.overlay ) {
			this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 );
		}

		this._show( this.uiDialog, this.options.show, function() {
			that._focusTabbable();
			that._trigger( "focus" );
		} );

		// Track the dialog immediately upon opening in case a focus event
		// somehow occurs outside of the dialog before an element inside the
		// dialog is focused (#10152)
		this._makeFocusTarget();

		this._trigger( "open" );
	},

	_focusTabbable: function() {

		// Set focus to the first match:
		// 1. An element that was focused previously
		// 2. First element inside the dialog matching [autofocus]
		// 3. Tabbable element inside the content element
		// 4. Tabbable element inside the buttonpane
		// 5. The close button
		// 6. The dialog itself
		var hasFocus = this._focusedElement;
		if ( !hasFocus ) {
			hasFocus = this.element.find( "[autofocus]" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.element.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialog;
		}
		hasFocus.eq( 0 ).trigger( "focus" );
	},

	_restoreTabbableFocus: function() {
		var activeElement = this.document[ 0 ].activeElement,
			isActive = this.uiDialog[ 0 ] === activeElement ||
				$.contains( this.uiDialog[ 0 ], activeElement );
		if ( !isActive ) {
			this._focusTabbable();
		}
	},

	_keepFocus: function( event ) {
		event.preventDefault();
		this._restoreTabbableFocus();
	},

	_createWrapper: function() {
		this.uiDialog = $( "<div>" )
			.hide()
			.attr( {

				// Setting tabIndex makes the div focusable
				tabIndex: -1,
				role: "dialog",
				"aria-modal": this.options.modal ? "true" : null
			} )
			.appendTo( this._appendTo() );

		this._addClass( this.uiDialog, "ui-dialog", "ui-widget ui-widget-content ui-front" );
		this._on( this.uiDialog, {
			keydown: function( event ) {
				if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE ) {
					event.preventDefault();
					this.close( event );
					return;
				}

				// Prevent tabbing out of dialogs
				if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) {
					return;
				}
				var tabbables = this.uiDialog.find( ":tabbable" ),
					first = tabbables.first(),
					last = tabbables.last();

				if ( ( event.target === last[ 0 ] || event.target === this.uiDialog[ 0 ] ) &&
						!event.shiftKey ) {
					this._delay( function() {
						first.trigger( "focus" );
					} );
					event.preventDefault();
				} else if ( ( event.target === first[ 0 ] ||
						event.target === this.uiDialog[ 0 ] ) && event.shiftKey ) {
					this._delay( function() {
						last.trigger( "focus" );
					} );
					event.preventDefault();
				}
			},
			mousedown: function( event ) {
				if ( this._moveToTop( event ) ) {
					this._focusTabbable();
				}
			}
		} );

		// We assume that any existing aria-describedby attribute means
		// that the dialog content is marked up properly
		// otherwise we brute force the content as the description
		if ( !this.element.find( "[aria-describedby]" ).length ) {
			this.uiDialog.attr( {
				"aria-describedby": this.element.uniqueId().attr( "id" )
			} );
		}
	},

	_createTitlebar: function() {
		var uiDialogTitle;

		this.uiDialogTitlebar = $( "<div>" );
		this._addClass( this.uiDialogTitlebar,
			"ui-dialog-titlebar", "ui-widget-header ui-helper-clearfix" );
		this._on( this.uiDialogTitlebar, {
			mousedown: function( event ) {

				// Don't prevent click on close button (#8838)
				// Focusing a dialog that is partially scrolled out of view
				// causes the browser to scroll it into view, preventing the click event
				if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) {

					// Dialog isn't getting focus when dragging (#8063)
					this.uiDialog.trigger( "focus" );
				}
			}
		} );

		this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
			.button( {
				label: $( "<a>" ).text( this.options.closeText ).html(),
				icon: "ui-icon-closethick",
				showLabel: false
			} )
			.appendTo( this.uiDialogTitlebar );

		this._addClass( this.uiDialogTitlebarClose, "ui-dialog-titlebar-close" );
		this._on( this.uiDialogTitlebarClose, {
			click: function( event ) {
				event.preventDefault();
				this.close( event );
			}
		} );

		uiDialogTitle = $( "<span>" ).uniqueId().prependTo( this.uiDialogTitlebar );
		this._addClass( uiDialogTitle, "ui-dialog-title" );
		this._title( uiDialogTitle );

		this.uiDialogTitlebar.prependTo( this.uiDialog );

		this.uiDialog.attr( {
			"aria-labelledby": uiDialogTitle.attr( "id" )
		} );
	},

	_title: function( title ) {
		if ( this.options.title ) {
			title.text( this.options.title );
		} else {
			title.html( "&#160;" );
		}
	},

	_createButtonPane: function() {
		this.uiDialogButtonPane = $( "<div>" );
		this._addClass( this.uiDialogButtonPane, "ui-dialog-buttonpane",
			"ui-widget-content ui-helper-clearfix" );

		this.uiButtonSet = $( "<div>" )
			.appendTo( this.uiDialogButtonPane );
		this._addClass( this.uiButtonSet, "ui-dialog-buttonset" );

		this._createButtons();
	},

	_createButtons: function() {
		var that = this,
			buttons = this.options.buttons;

		// If we already have a button pane, remove it
		this.uiDialogButtonPane.remove();
		this.uiButtonSet.empty();

		if ( $.isEmptyObject( buttons ) || ( Array.isArray( buttons ) && !buttons.length ) ) {
			this._removeClass( this.uiDialog, "ui-dialog-buttons" );
			return;
		}

		$.each( buttons, function( name, props ) {
			var click, buttonOptions;
			props = typeof props === "function" ?
				{ click: props, text: name } :
				props;

			// Default to a non-submitting button
			props = $.extend( { type: "button" }, props );

			// Change the context for the click callback to be the main element
			click = props.click;
			buttonOptions = {
				icon: props.icon,
				iconPosition: props.iconPosition,
				showLabel: props.showLabel,

				// Deprecated options
				icons: props.icons,
				text: props.text
			};

			delete props.click;
			delete props.icon;
			delete props.iconPosition;
			delete props.showLabel;

			// Deprecated options
			delete props.icons;
			if ( typeof props.text === "boolean" ) {
				delete props.text;
			}

			$( "<button></button>", props )
				.button( buttonOptions )
				.appendTo( that.uiButtonSet )
				.on( "click", function() {
					click.apply( that.element[ 0 ], arguments );
				} );
		} );
		this._addClass( this.uiDialog, "ui-dialog-buttons" );
		this.uiDialogButtonPane.appendTo( this.uiDialog );
	},

	_makeDraggable: function() {
		var that = this,
			options = this.options;

		function filteredUi( ui ) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		this.uiDialog.draggable( {
			cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
			handle: ".ui-dialog-titlebar",
			containment: "document",
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-dragging" );
				that._blockFrames();
				that._trigger( "dragStart", event, filteredUi( ui ) );
			},
			drag: function( event, ui ) {
				that._trigger( "drag", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var left = ui.offset.left - that.document.scrollLeft(),
					top = ui.offset.top - that.document.scrollTop();

				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-dragging" );
				that._unblockFrames();
				that._trigger( "dragStop", event, filteredUi( ui ) );
			}
		} );
	},

	_makeResizable: function() {
		var that = this,
			options = this.options,
			handles = options.resizable,

			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = this.uiDialog.css( "position" ),
			resizeHandles = typeof handles === "string" ?
				handles :
				"n,e,s,w,se,sw,ne,nw";

		function filteredUi( ui ) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		this.uiDialog.resizable( {
			cancel: ".ui-dialog-content",
			containment: "document",
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: this._minHeight(),
			handles: resizeHandles,
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-resizing" );
				that._blockFrames();
				that._trigger( "resizeStart", event, filteredUi( ui ) );
			},
			resize: function( event, ui ) {
				that._trigger( "resize", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var offset = that.uiDialog.offset(),
					left = offset.left - that.document.scrollLeft(),
					top = offset.top - that.document.scrollTop();

				options.height = that.uiDialog.height();
				options.width = that.uiDialog.width();
				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-resizing" );
				that._unblockFrames();
				that._trigger( "resizeStop", event, filteredUi( ui ) );
			}
		} )
			.css( "position", position );
	},

	_trackFocus: function() {
		this._on( this.widget(), {
			focusin: function( event ) {
				this._makeFocusTarget();
				this._focusedElement = $( event.target );
			}
		} );
	},

	_makeFocusTarget: function() {
		this._untrackInstance();
		this._trackingInstances().unshift( this );
	},

	_untrackInstance: function() {
		var instances = this._trackingInstances(),
			exists = $.inArray( this, instances );
		if ( exists !== -1 ) {
			instances.splice( exists, 1 );
		}
	},

	_trackingInstances: function() {
		var instances = this.document.data( "ui-dialog-instances" );
		if ( !instances ) {
			instances = [];
			this.document.data( "ui-dialog-instances", instances );
		}
		return instances;
	},

	_minHeight: function() {
		var options = this.options;

		return options.height === "auto" ?
			options.minHeight :
			Math.min( options.minHeight, options.height );
	},

	_position: function() {

		// Need to show the dialog to get the actual offset in the position plugin
		var isVisible = this.uiDialog.is( ":visible" );
		if ( !isVisible ) {
			this.uiDialog.show();
		}
		this.uiDialog.position( this.options.position );
		if ( !isVisible ) {
			this.uiDialog.hide();
		}
	},

	_setOptions: function( options ) {
		var that = this,
			resize = false,
			resizableOptions = {};

		$.each( options, function( key, value ) {
			that._setOption( key, value );

			if ( key in that.sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in that.resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		} );

		if ( resize ) {
			this._size();
			this._position();
		}
		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function( key, value ) {
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "disabled" ) {
			return;
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.uiDialog.appendTo( this._appendTo() );
		}

		if ( key === "buttons" ) {
			this._createButtons();
		}

		if ( key === "closeText" ) {
			this.uiDialogTitlebarClose.button( {

				// Ensure that we always pass a string
				label: $( "<a>" ).text( "" + this.options.closeText ).html()
			} );
		}

		if ( key === "draggable" ) {
			isDraggable = uiDialog.is( ":data(ui-draggable)" );
			if ( isDraggable && !value ) {
				uiDialog.draggable( "destroy" );
			}

			if ( !isDraggable && value ) {
				this._makeDraggable();
			}
		}

		if ( key === "position" ) {
			this._position();
		}

		if ( key === "resizable" ) {

			// currently resizable, becoming non-resizable
			isResizable = uiDialog.is( ":data(ui-resizable)" );
			if ( isResizable && !value ) {
				uiDialog.resizable( "destroy" );
			}

			// Currently resizable, changing handles
			if ( isResizable && typeof value === "string" ) {
				uiDialog.resizable( "option", "handles", value );
			}

			// Currently non-resizable, becoming resizable
			if ( !isResizable && value !== false ) {
				this._makeResizable();
			}
		}

		if ( key === "title" ) {
			this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
		}

		if ( key === "modal" ) {
			uiDialog.attr( "aria-modal", value ? "true" : null );
		}
	},

	_size: function() {

		// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		// divs will both have width and height set, so we need to reset them
		var nonContentHeight, minContentHeight, maxContentHeight,
			options = this.options;

		// Reset content sizing
		this.element.show().css( {
			width: "auto",
			minHeight: 0,
			maxHeight: "none",
			height: 0
		} );

		if ( options.minWidth > options.width ) {
			options.width = options.minWidth;
		}

		// Reset wrapper sizing
		// determine the height of all the non-content elements
		nonContentHeight = this.uiDialog.css( {
			height: "auto",
			width: options.width
		} )
			.outerHeight();
		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
		maxContentHeight = typeof options.maxHeight === "number" ?
			Math.max( 0, options.maxHeight - nonContentHeight ) :
			"none";

		if ( options.height === "auto" ) {
			this.element.css( {
				minHeight: minContentHeight,
				maxHeight: maxContentHeight,
				height: "auto"
			} );
		} else {
			this.element.height( Math.max( 0, options.height - nonContentHeight ) );
		}

		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
		}
	},

	_blockFrames: function() {
		this.iframeBlocks = this.document.find( "iframe" ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( {
					position: "absolute",
					width: iframe.outerWidth(),
					height: iframe.outerHeight()
				} )
				.appendTo( iframe.parent() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_allowInteraction: function( event ) {
		if ( $( event.target ).closest( ".ui-dialog" ).length ) {
			return true;
		}

		// TODO: Remove hack when datepicker implements
		// the .ui-front logic (#8989)
		return !!$( event.target ).closest( ".ui-datepicker" ).length;
	},

	_createOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		// We use a delay in case the overlay is created from an
		// event that we're going to be cancelling (#2804)
		var isOpening = true;
		this._delay( function() {
			isOpening = false;
		} );

		if ( !this.document.data( "ui-dialog-overlays" ) ) {

			// Prevent use of anchors and inputs
			// This doesn't use `_on()` because it is a shared event handler
			// across all open modal dialogs.
			this.document.on( "focusin.ui-dialog", function( event ) {
				if ( isOpening ) {
					return;
				}

				var instance = this._trackingInstances()[ 0 ];
				if ( !instance._allowInteraction( event ) ) {
					event.preventDefault();
					instance._focusTabbable();
				}
			}.bind( this ) );
		}

		this.overlay = $( "<div>" )
			.appendTo( this._appendTo() );

		this._addClass( this.overlay, null, "ui-widget-overlay ui-front" );
		this._on( this.overlay, {
			mousedown: "_keepFocus"
		} );
		this.document.data( "ui-dialog-overlays",
			( this.document.data( "ui-dialog-overlays" ) || 0 ) + 1 );
	},

	_destroyOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		if ( this.overlay ) {
			var overlays = this.document.data( "ui-dialog-overlays" ) - 1;

			if ( !overlays ) {
				this.document.off( "focusin.ui-dialog" );
				this.document.removeData( "ui-dialog-overlays" );
			} else {
				this.document.data( "ui-dialog-overlays", overlays );
			}

			this.overlay.remove();
			this.overlay = null;
		}
	}
} );

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat === true ) {

	// Backcompat for dialogClass option
	$.widget( "ui.dialog", $.ui.dialog, {
		options: {
			dialogClass: ""
		},
		_createWrapper: function() {
			this._super();
			this.uiDialog.addClass( this.options.dialogClass );
		},
		_setOption: function( key, value ) {
			if ( key === "dialogClass" ) {
				this.uiDialog
					.removeClass( this.options.dialogClass )
					.addClass( value );
			}
			this._superApply( arguments );
		}
	} );
}

var widgetsDialog = $.ui.dialog;


/*!
 * jQuery UI Droppable 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Droppable
//>>group: Interactions
//>>description: Enables drop targets for draggable elements.
//>>docs: https://api.jqueryui.com/droppable/
//>>demos: https://jqueryui.com/droppable/


$.widget( "ui.droppable", {
	version: "1.14.0",
	widgetEventPrefix: "drop",
	options: {
		accept: "*",
		addClasses: true,
		greedy: false,
		scope: "default",
		tolerance: "intersect",

		// Callbacks
		activate: null,
		deactivate: null,
		drop: null,
		out: null,
		over: null
	},
	_create: function() {

		var proportions,
			o = this.options,
			accept = o.accept;

		this.isover = false;
		this.isout = true;

		this.accept = typeof accept === "function" ? accept : function( d ) {
			return d.is( accept );
		};

		this.proportions = function( /* valueToWrite */ ) {
			if ( arguments.length ) {

				// Store the droppable's proportions
				proportions = arguments[ 0 ];
			} else {

				// Retrieve or derive the droppable's proportions
				return proportions ?
					proportions :
					proportions = {
						width: this.element[ 0 ].offsetWidth,
						height: this.element[ 0 ].offsetHeight
					};
			}
		};

		this._addToManager( o.scope );

		if ( o.addClasses ) {
			this._addClass( "ui-droppable" );
		}

	},

	_addToManager: function( scope ) {

		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || [];
		$.ui.ddmanager.droppables[ scope ].push( this );
	},

	_splice: function( drop ) {
		var i = 0;
		for ( ; i < drop.length; i++ ) {
			if ( drop[ i ] === this ) {
				drop.splice( i, 1 );
			}
		}
	},

	_destroy: function() {
		var drop = $.ui.ddmanager.droppables[ this.options.scope ];

		this._splice( drop );
	},

	_setOption: function( key, value ) {

		if ( key === "accept" ) {
			this.accept = typeof value === "function" ? value : function( d ) {
				return d.is( value );
			};
		} else if ( key === "scope" ) {
			var drop = $.ui.ddmanager.droppables[ this.options.scope ];

			this._splice( drop );
			this._addToManager( value );
		}

		this._super( key, value );
	},

	_activate: function( event ) {
		var draggable = $.ui.ddmanager.current;

		this._addActiveClass();
		if ( draggable ) {
			this._trigger( "activate", event, this.ui( draggable ) );
		}
	},

	_deactivate: function( event ) {
		var draggable = $.ui.ddmanager.current;

		this._removeActiveClass();
		if ( draggable ) {
			this._trigger( "deactivate", event, this.ui( draggable ) );
		}
	},

	_over: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem ||
				draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem ||
				draggable.element ) ) ) {
			this._addHoverClass();
			this._trigger( "over", event, this.ui( draggable ) );
		}

	},

	_out: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem ||
				draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem ||
				draggable.element ) ) ) {
			this._removeHoverClass();
			this._trigger( "out", event, this.ui( draggable ) );
		}

	},

	_drop: function( event, custom ) {

		var draggable = custom || $.ui.ddmanager.current,
			childrenIntersection = false;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem ||
				draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return false;
		}

		this.element
			.find( ":data(ui-droppable)" )
			.not( ".ui-draggable-dragging" )
			.each( function() {
				var inst = $( this ).droppable( "instance" );
				if (
					inst.options.greedy &&
					!inst.options.disabled &&
					inst.options.scope === draggable.options.scope &&
					inst.accept.call(
						inst.element[ 0 ], ( draggable.currentItem || draggable.element )
					) &&
					$.ui.intersect(
						draggable,
						$.extend( inst, { offset: inst.element.offset() } ),
						inst.options.tolerance, event
					)
				) {
					childrenIntersection = true;
					return false;
				}
			} );
		if ( childrenIntersection ) {
			return false;
		}

		if ( this.accept.call( this.element[ 0 ],
				( draggable.currentItem || draggable.element ) ) ) {
			this._removeActiveClass();
			this._removeHoverClass();

			this._trigger( "drop", event, this.ui( draggable ) );
			return this.element;
		}

		return false;

	},

	ui: function( c ) {
		return {
			draggable: ( c.currentItem || c.element ),
			helper: c.helper,
			position: c.position,
			offset: c.positionAbs
		};
	},

	// Extension points just to make backcompat sane and avoid duplicating logic
	// TODO: Remove in 1.14 along with call to it below
	_addHoverClass: function() {
		this._addClass( "ui-droppable-hover" );
	},

	_removeHoverClass: function() {
		this._removeClass( "ui-droppable-hover" );
	},

	_addActiveClass: function() {
		this._addClass( "ui-droppable-active" );
	},

	_removeActiveClass: function() {
		this._removeClass( "ui-droppable-active" );
	}
} );

$.ui.intersect = ( function() {
	function isOverAxis( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	}

	return function( draggable, droppable, toleranceMode, event ) {

		if ( !droppable.offset ) {
			return false;
		}

		var x1 = ( draggable.positionAbs ||
				draggable.position.absolute ).left + draggable.margins.left,
			y1 = ( draggable.positionAbs ||
				draggable.position.absolute ).top + draggable.margins.top,
			x2 = x1 + draggable.helperProportions.width,
			y2 = y1 + draggable.helperProportions.height,
			l = droppable.offset.left,
			t = droppable.offset.top,
			r = l + droppable.proportions().width,
			b = t + droppable.proportions().height;

		switch ( toleranceMode ) {
		case "fit":
			return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b );
		case "intersect":
			return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half
				x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half
		case "pointer":
			return isOverAxis( event.pageY, t, droppable.proportions().height ) &&
				isOverAxis( event.pageX, l, droppable.proportions().width );
		case "touch":
			return (
				( y1 >= t && y1 <= b ) || // Top edge touching
				( y2 >= t && y2 <= b ) || // Bottom edge touching
				( y1 < t && y2 > b ) // Surrounded vertically
			) && (
				( x1 >= l && x1 <= r ) || // Left edge touching
				( x2 >= l && x2 <= r ) || // Right edge touching
				( x1 < l && x2 > r ) // Surrounded horizontally
			);
		default:
			return false;
		}
	};
} )();

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { "default": [] },
	prepareOffsets: function( t, event ) {

		var i, j,
			m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
			type = event ? event.type : null, // workaround for #2317
			list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack();

		droppablesLoop: for ( i = 0; i < m.length; i++ ) {

			// No disabled and non-accepted
			if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ],
					( t.currentItem || t.element ) ) ) ) {
				continue;
			}

			// Filter out elements in the current dragged item
			for ( j = 0; j < list.length; j++ ) {
				if ( list[ j ] === m[ i ].element[ 0 ] ) {
					m[ i ].proportions().height = 0;
					continue droppablesLoop;
				}
			}

			m[ i ].visible = m[ i ].element.css( "display" ) !== "none";
			if ( !m[ i ].visible ) {
				continue;
			}

			// Activate the droppable if used directly from draggables
			if ( type === "mousedown" ) {
				m[ i ]._activate.call( m[ i ], event );
			}

			m[ i ].offset = m[ i ].element.offset();
			m[ i ].proportions( {
				width: m[ i ].element[ 0 ].offsetWidth,
				height: m[ i ].element[ 0 ].offsetHeight
			} );

		}

	},
	drop: function( draggable, event ) {

		var dropped = false;

		// Create a copy of the droppables in case the list changes during the drop (#9116)
		$.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() {

			if ( !this.options ) {
				return;
			}
			if ( !this.options.disabled && this.visible &&
					$.ui.intersect( draggable, this, this.options.tolerance, event ) ) {
				dropped = this._drop.call( this, event ) || dropped;
			}

			if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ],
					( draggable.currentItem || draggable.element ) ) ) {
				this.isout = true;
				this.isover = false;
				this._deactivate.call( this, event );
			}

		} );
		return dropped;

	},
	dragStart: function( draggable, event ) {

		// Listen for scrolling so that if the dragging causes scrolling the position of the
		// droppables can be recalculated (see #5003)
		draggable.element.parentsUntil( "body" ).on( "scroll.droppable", function() {
			if ( !draggable.options.refreshPositions ) {
				$.ui.ddmanager.prepareOffsets( draggable, event );
			}
		} );
	},
	drag: function( draggable, event ) {

		// If you have a highly dynamic page, you might try this option. It renders positions
		// every time you move the mouse.
		if ( draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}

		// Run through all droppables and check their positions based on specific tolerance options
		$.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() {

			if ( this.options.disabled || this.greedyChild || !this.visible ) {
				return;
			}

			var parentInstance, scope, parent,
				intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ),
				c = !intersects && this.isover ?
					"isout" :
					( intersects && !this.isover ? "isover" : null );
			if ( !c ) {
				return;
			}

			if ( this.options.greedy ) {

				// find droppable parents with same scope
				scope = this.options.scope;
				parent = this.element.parents( ":data(ui-droppable)" ).filter( function() {
					return $( this ).droppable( "instance" ).options.scope === scope;
				} );

				if ( parent.length ) {
					parentInstance = $( parent[ 0 ] ).droppable( "instance" );
					parentInstance.greedyChild = ( c === "isover" );
				}
			}

			// We just moved into a greedy child
			if ( parentInstance && c === "isover" ) {
				parentInstance.isover = false;
				parentInstance.isout = true;
				parentInstance._out.call( parentInstance, event );
			}

			this[ c ] = true;
			this[ c === "isout" ? "isover" : "isout" ] = false;
			this[ c === "isover" ? "_over" : "_out" ].call( this, event );

			// We just moved out of a greedy child
			if ( parentInstance && c === "isout" ) {
				parentInstance.isout = false;
				parentInstance.isover = true;
				parentInstance._over.call( parentInstance, event );
			}
		} );

	},
	dragStop: function( draggable, event ) {
		draggable.element.parentsUntil( "body" ).off( "scroll.droppable" );

		// Call prepareOffsets one final time since IE does not fire return scroll events when
		// overflow was caused by drag (see #5003)
		if ( !draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}
	}
};

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat === true ) {

	// Backcompat for activeClass and hoverClass options
	$.widget( "ui.droppable", $.ui.droppable, {
		options: {
			hoverClass: false,
			activeClass: false
		},
		_addActiveClass: function() {
			this._super();
			if ( this.options.activeClass ) {
				this.element.addClass( this.options.activeClass );
			}
		},
		_removeActiveClass: function() {
			this._super();
			if ( this.options.activeClass ) {
				this.element.removeClass( this.options.activeClass );
			}
		},
		_addHoverClass: function() {
			this._super();
			if ( this.options.hoverClass ) {
				this.element.addClass( this.options.hoverClass );
			}
		},
		_removeHoverClass: function() {
			this._super();
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
		}
	} );
}

var widgetsDroppable = $.ui.droppable;


/*!
 * jQuery UI Progressbar 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Progressbar
//>>group: Widgets
/* eslint-disable max-len */
//>>description: Displays a status indicator for loading state, standard percentage, and other progress indicators.
/* eslint-enable max-len */
//>>docs: https://api.jqueryui.com/progressbar/
//>>demos: https://jqueryui.com/progressbar/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/progressbar.css
//>>css.theme: ../../themes/base/theme.css


var widgetsProgressbar = $.widget( "ui.progressbar", {
	version: "1.14.0",
	options: {
		classes: {
			"ui-progressbar": "ui-corner-all",
			"ui-progressbar-value": "ui-corner-left",
			"ui-progressbar-complete": "ui-corner-right"
		},
		max: 100,
		value: 0,

		change: null,
		complete: null
	},

	min: 0,

	_create: function() {

		// Constrain initial value
		this.oldValue = this.options.value = this._constrainedValue();

		this.element.attr( {

			// Only set static values; aria-valuenow and aria-valuemax are
			// set inside _refreshValue()
			role: "progressbar",
			"aria-valuemin": this.min
		} );
		this._addClass( "ui-progressbar", "ui-widget ui-widget-content" );

		this.valueDiv = $( "<div>" ).appendTo( this.element );
		this._addClass( this.valueDiv, "ui-progressbar-value", "ui-widget-header" );
		this._refreshValue();
	},

	_destroy: function() {
		this.element.removeAttr( "role aria-valuemin aria-valuemax aria-valuenow" );

		this.valueDiv.remove();
	},

	value: function( newValue ) {
		if ( newValue === undefined ) {
			return this.options.value;
		}

		this.options.value = this._constrainedValue( newValue );
		this._refreshValue();
	},

	_constrainedValue: function( newValue ) {
		if ( newValue === undefined ) {
			newValue = this.options.value;
		}

		this.indeterminate = newValue === false;

		// Sanitize value
		if ( typeof newValue !== "number" ) {
			newValue = 0;
		}

		return this.indeterminate ? false :
			Math.min( this.options.max, Math.max( this.min, newValue ) );
	},

	_setOptions: function( options ) {

		// Ensure "value" option is set after other values (like max)
		var value = options.value;
		delete options.value;

		this._super( options );

		this.options.value = this._constrainedValue( value );
		this._refreshValue();
	},

	_setOption: function( key, value ) {
		if ( key === "max" ) {

			// Don't allow a max less than min
			value = Math.max( this.min, value );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", value );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	_percentage: function() {
		return this.indeterminate ?
			100 :
			100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
	},

	_refreshValue: function() {
		var value = this.options.value,
			percentage = this._percentage();

		this.valueDiv
			.toggle( this.indeterminate || value > this.min )
			.width( percentage.toFixed( 0 ) + "%" );

		this
			._toggleClass( this.valueDiv, "ui-progressbar-complete", null,
				value === this.options.max )
			._toggleClass( "ui-progressbar-indeterminate", null, this.indeterminate );

		if ( this.indeterminate ) {
			this.element.removeAttr( "aria-valuenow" );
			if ( !this.overlayDiv ) {
				this.overlayDiv = $( "<div>" ).appendTo( this.valueDiv );
				this._addClass( this.overlayDiv, "ui-progressbar-overlay" );
			}
		} else {
			this.element.attr( {
				"aria-valuemax": this.options.max,
				"aria-valuenow": value
			} );
			if ( this.overlayDiv ) {
				this.overlayDiv.remove();
				this.overlayDiv = null;
			}
		}

		if ( this.oldValue !== value ) {
			this.oldValue = value;
			this._trigger( "change" );
		}
		if ( value === this.options.max ) {
			this._trigger( "complete" );
		}
	}
} );


/*!
 * jQuery UI Selectable 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Selectable
//>>group: Interactions
//>>description: Allows groups of elements to be selected with the mouse.
//>>docs: https://api.jqueryui.com/selectable/
//>>demos: https://jqueryui.com/selectable/
//>>css.structure: ../../themes/base/selectable.css


var widgetsSelectable = $.widget( "ui.selectable", $.ui.mouse, {
	version: "1.14.0",
	options: {
		appendTo: "body",
		autoRefresh: true,
		distance: 0,
		filter: "*",
		tolerance: "touch",

		// Callbacks
		selected: null,
		selecting: null,
		start: null,
		stop: null,
		unselected: null,
		unselecting: null
	},
	_create: function() {
		var that = this;

		this._addClass( "ui-selectable" );

		this.dragged = false;

		// Cache selectee children based on filter
		this.refresh = function() {
			that.elementPos = $( that.element[ 0 ] ).offset();
			that.selectees = $( that.options.filter, that.element[ 0 ] );
			that._addClass( that.selectees, "ui-selectee" );
			that.selectees.each( function() {
				var $this = $( this ),
					selecteeOffset = $this.offset(),
					pos = {
						left: selecteeOffset.left - that.elementPos.left,
						top: selecteeOffset.top - that.elementPos.top
					};
				$.data( this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.outerWidth(),
					bottom: pos.top + $this.outerHeight(),
					startselected: false,
					selected: $this.hasClass( "ui-selected" ),
					selecting: $this.hasClass( "ui-selecting" ),
					unselecting: $this.hasClass( "ui-unselecting" )
				} );
			} );
		};
		this.refresh();

		this._mouseInit();

		this.helper = $( "<div>" );
		this._addClass( this.helper, "ui-selectable-helper" );
	},

	_destroy: function() {
		this.selectees.removeData( "selectable-item" );
		this._mouseDestroy();
	},

	_mouseStart: function( event ) {
		var that = this,
			options = this.options;

		this.opos = [ event.pageX, event.pageY ];
		this.elementPos = $( this.element[ 0 ] ).offset();

		if ( this.options.disabled ) {
			return;
		}

		this.selectees = $( options.filter, this.element[ 0 ] );

		this._trigger( "start", event );

		$( options.appendTo ).append( this.helper );

		// position helper (lasso)
		this.helper.css( {
			"left": event.pageX,
			"top": event.pageY,
			"width": 0,
			"height": 0
		} );

		if ( options.autoRefresh ) {
			this.refresh();
		}

		this.selectees.filter( ".ui-selected" ).each( function() {
			var selectee = $.data( this, "selectable-item" );
			selectee.startselected = true;
			if ( !event.metaKey && !event.ctrlKey ) {
				that._removeClass( selectee.$element, "ui-selected" );
				selectee.selected = false;
				that._addClass( selectee.$element, "ui-unselecting" );
				selectee.unselecting = true;

				// selectable UNSELECTING callback
				that._trigger( "unselecting", event, {
					unselecting: selectee.element
				} );
			}
		} );

		$( event.target ).parents().addBack().each( function() {
			var doSelect,
				selectee = $.data( this, "selectable-item" );
			if ( selectee ) {
				doSelect = ( !event.metaKey && !event.ctrlKey ) ||
					!selectee.$element.hasClass( "ui-selected" );
				that._removeClass( selectee.$element, doSelect ? "ui-unselecting" : "ui-selected" )
					._addClass( selectee.$element, doSelect ? "ui-selecting" : "ui-unselecting" );
				selectee.unselecting = !doSelect;
				selectee.selecting = doSelect;
				selectee.selected = doSelect;

				// selectable (UN)SELECTING callback
				if ( doSelect ) {
					that._trigger( "selecting", event, {
						selecting: selectee.element
					} );
				} else {
					that._trigger( "unselecting", event, {
						unselecting: selectee.element
					} );
				}
				return false;
			}
		} );

	},

	_mouseDrag: function( event ) {

		this.dragged = true;

		if ( this.options.disabled ) {
			return;
		}

		var tmp,
			that = this,
			options = this.options,
			x1 = this.opos[ 0 ],
			y1 = this.opos[ 1 ],
			x2 = event.pageX,
			y2 = event.pageY;

		if ( x1 > x2 ) {
			tmp = x2; x2 = x1; x1 = tmp;
		}
		if ( y1 > y2 ) {
			tmp = y2; y2 = y1; y1 = tmp;
		}
		this.helper.css( { left: x1, top: y1, width: x2 - x1, height: y2 - y1 } );

		this.selectees.each( function() {
			var selectee = $.data( this, "selectable-item" ),
				hit = false,
				offset = {};

			//prevent helper from being selected if appendTo: selectable
			if ( !selectee || selectee.element === that.element[ 0 ] ) {
				return;
			}

			offset.left   = selectee.left   + that.elementPos.left;
			offset.right  = selectee.right  + that.elementPos.left;
			offset.top    = selectee.top    + that.elementPos.top;
			offset.bottom = selectee.bottom + that.elementPos.top;

			if ( options.tolerance === "touch" ) {
				hit = ( !( offset.left > x2 || offset.right < x1 || offset.top > y2 ||
                    offset.bottom < y1 ) );
			} else if ( options.tolerance === "fit" ) {
				hit = ( offset.left > x1 && offset.right < x2 && offset.top > y1 &&
                    offset.bottom < y2 );
			}

			if ( hit ) {

				// SELECT
				if ( selectee.selected ) {
					that._removeClass( selectee.$element, "ui-selected" );
					selectee.selected = false;
				}
				if ( selectee.unselecting ) {
					that._removeClass( selectee.$element, "ui-unselecting" );
					selectee.unselecting = false;
				}
				if ( !selectee.selecting ) {
					that._addClass( selectee.$element, "ui-selecting" );
					selectee.selecting = true;

					// selectable SELECTING callback
					that._trigger( "selecting", event, {
						selecting: selectee.element
					} );
				}
			} else {

				// UNSELECT
				if ( selectee.selecting ) {
					if ( ( event.metaKey || event.ctrlKey ) && selectee.startselected ) {
						that._removeClass( selectee.$element, "ui-selecting" );
						selectee.selecting = false;
						that._addClass( selectee.$element, "ui-selected" );
						selectee.selected = true;
					} else {
						that._removeClass( selectee.$element, "ui-selecting" );
						selectee.selecting = false;
						if ( selectee.startselected ) {
							that._addClass( selectee.$element, "ui-unselecting" );
							selectee.unselecting = true;
						}

						// selectable UNSELECTING callback
						that._trigger( "unselecting", event, {
							unselecting: selectee.element
						} );
					}
				}
				if ( selectee.selected ) {
					if ( !event.metaKey && !event.ctrlKey && !selectee.startselected ) {
						that._removeClass( selectee.$element, "ui-selected" );
						selectee.selected = false;

						that._addClass( selectee.$element, "ui-unselecting" );
						selectee.unselecting = true;

						// selectable UNSELECTING callback
						that._trigger( "unselecting", event, {
							unselecting: selectee.element
						} );
					}
				}
			}
		} );

		return false;
	},

	_mouseStop: function( event ) {
		var that = this;

		this.dragged = false;

		$( ".ui-unselecting", this.element[ 0 ] ).each( function() {
			var selectee = $.data( this, "selectable-item" );
			that._removeClass( selectee.$element, "ui-unselecting" );
			selectee.unselecting = false;
			selectee.startselected = false;
			that._trigger( "unselected", event, {
				unselected: selectee.element
			} );
		} );
		$( ".ui-selecting", this.element[ 0 ] ).each( function() {
			var selectee = $.data( this, "selectable-item" );
			that._removeClass( selectee.$element, "ui-selecting" )
				._addClass( selectee.$element, "ui-selected" );
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			that._trigger( "selected", event, {
				selected: selectee.element
			} );
		} );
		this._trigger( "stop", event );

		this.helper.remove();

		return false;
	}

} );


/*!
 * jQuery UI Selectmenu 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Selectmenu
//>>group: Widgets
/* eslint-disable max-len */
//>>description: Duplicates and extends the functionality of a native HTML select element, allowing it to be customizable in behavior and appearance far beyond the limitations of a native select.
/* eslint-enable max-len */
//>>docs: https://api.jqueryui.com/selectmenu/
//>>demos: https://jqueryui.com/selectmenu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/selectmenu.css, ../../themes/base/button.css
//>>css.theme: ../../themes/base/theme.css


var widgetsSelectmenu = $.widget( "ui.selectmenu", [ $.ui.formResetMixin, {
	version: "1.14.0",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		classes: {
			"ui-selectmenu-button-open": "ui-corner-top",
			"ui-selectmenu-button-closed": "ui-corner-all"
		},
		disabled: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		width: false,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();
		this._bindFormResetHandler();

		this._rendered = false;
		this.menuItems = $();
	},

	_drawButton: function() {
		var icon,
			that = this,
			item = this._parseOption(
				this.element.find( "option:selected" ),
				this.element[ 0 ].selectedIndex
			);

		// Associate existing label with the new button
		this.labels = this.element.labels().attr( "for", this.ids.button );
		this._on( this.labels, {
			click: function( event ) {
				this.button.trigger( "focus" );
				event.preventDefault();
			}
		} );

		// Hide original select element
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			tabindex: this.options.disabled ? -1 : 0,
			id: this.ids.button,
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true",
			title: this.element.attr( "title" )
		} )
			.insertAfter( this.element );

		this._addClass( this.button, "ui-selectmenu-button ui-selectmenu-button-closed",
			"ui-button ui-widget" );

		icon = $( "<span>" ).appendTo( this.button );
		this._addClass( icon, "ui-selectmenu-icon", "ui-icon " + this.options.icons.button );
		this.buttonItem = this._renderButtonItem( item )
			.appendTo( this.button );

		if ( this.options.width !== false ) {
			this._resizeButton();
		}

		this._on( this.button, this._buttonEvents );
		this.button.one( "focusin", function() {

			// Delay rendering the menu items until the button receives focus.
			// The menu may have already been rendered via a programmatic open.
			if ( !that._rendered ) {
				that._refreshMenu();
			}
		} );
	},

	_drawMenu: function() {
		var that = this;

		// Create menu
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		} );

		// Wrap menu
		this.menuWrap = $( "<div>" ).append( this.menu );
		this._addClass( this.menuWrap, "ui-selectmenu-menu", "ui-front" );
		this.menuWrap.appendTo( this._appendTo() );

		// Initialize menu widget
		this.menuInstance = this.menu
			.menu( {
				classes: {
					"ui-menu": "ui-corner-bottom"
				},
				role: "listbox",
				select: function( event, ui ) {
					event.preventDefault();
					that._select( ui.item.data( "ui-selectmenu-item" ), event );
				},
				focus: function( event, ui ) {
					var item = ui.item.data( "ui-selectmenu-item" );

					// Prevent inital focus from firing and check if its a newly focused item
					if ( that.focusIndex != null && item.index !== that.focusIndex ) {
						that._trigger( "focus", event, { item: item } );
						if ( !that.isOpen ) {
							that._select( item, event );
						}
					}
					that.focusIndex = item.index;

					that.button.attr( "aria-activedescendant",
						that.menuItems.eq( item.index ).attr( "id" ) );
				}
			} )
			.menu( "instance" );

		// Don't close the menu on mouseleave
		this.menuInstance._off( this.menu, "mouseleave" );

		// Cancel the menu's collapseAll on document click
		this.menuInstance._closeOnDocumentClick = function() {
			return false;
		};

		// Selects often contain empty items, but never contain dividers
		this.menuInstance._isDivider = function() {
			return false;
		};
	},

	refresh: function() {
		this._refreshMenu();
		this.buttonItem.replaceWith(
			this.buttonItem = this._renderButtonItem(

				// Fall back to an empty object in case there are no options
				this._getSelectedItem().data( "ui-selectmenu-item" ) || {}
			)
		);
		if ( this.options.width === null ) {
			this._resizeButton();
		}
	},

	_refreshMenu: function() {
		var item,
			options = this.element.find( "option" );

		this.menu.empty();

		this._parseOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menuInstance.refresh();
		this.menuItems = this.menu.find( "li" )
			.not( ".ui-selectmenu-optgroup" )
				.find( ".ui-menu-item-wrapper" );

		this._rendered = true;

		if ( !options.length ) {
			return;
		}

		item = this._getSelectedItem();

		// Update the menu to have the correct item focused
		this.menuInstance.focus( null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", this.element.prop( "disabled" ) );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}

		// If this is the first time the menu is being opened, render the items
		if ( !this._rendered ) {
			this._refreshMenu();
		} else {

			// Menu clears focus on close, reset focus to selected item
			this._removeClass( this.menu.find( ".ui-state-active" ), null, "ui-state-active" );
			this.menuInstance.focus( null, this._getSelectedItem() );
		}

		// If there are no options, don't open the menu
		if ( !this.menuItems.length ) {
			return;
		}

		this.isOpen = true;
		this._toggleAttr();
		this._resizeMenu();
		this._position();

		this._on( this.document, this._documentClick );

		this._trigger( "open", event );
	},

	_position: function() {
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		this.range = null;
		this._off( this.document );

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderButtonItem: function( item ) {
		var buttonItem = $( "<span>" );

		this._setText( buttonItem, item.label );
		this._addClass( buttonItem, "ui-selectmenu-text" );

		return buttonItem;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			var li;

			if ( item.optgroup !== currentOptgroup ) {
				li = $( "<li>", {
					text: item.optgroup
				} );
				that._addClass( li, "ui-selectmenu-optgroup", "ui-menu-divider" +
					( item.element.parent( "optgroup" ).prop( "disabled" ) ?
						" ui-state-disabled" :
						"" ) );

				li.appendTo( ul );

				currentOptgroup = item.optgroup;
			}

			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" ),
			wrapper = $( "<div>", {
				title: item.element.attr( "title" )
			} );

		if ( item.disabled ) {
			this._addClass( li, null, "ui-state-disabled" );
		}

		if ( item.hidden ) {
			li.prop( "hidden", true );
		} else {
			this._setText( wrapper, item.label );
		}

		return li.append( wrapper ).appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( "&#160;" );
		}
	},

	_move: function( direction, event ) {
		var item, next,
			filter = ".ui-menu-item";

		if ( this.isOpen ) {
			item = this.menuItems.eq( this.focusIndex ).parent( "li" );
		} else {
			item = this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
			filter += ":not(.ui-state-disabled)";
		}

		if ( direction === "first" || direction === "last" ) {
			next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 );
		} else {
			next = item[ direction + "All" ]( filter ).eq( 0 );
		}

		if ( next.length ) {
			this.menuInstance.focus( event, next );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
	},

	_toggle: function( event ) {
		this[ this.isOpen ? "close" : "open" ]( event );
	},

	_setSelection: function() {
		var selection;

		if ( !this.range ) {
			return;
		}

		selection = window.getSelection();
		selection.removeAllRanges();
		selection.addRange( this.range );
	},

	_documentClick: {
		mousedown: function( event ) {
			if ( !this.isOpen ) {
				return;
			}

			if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" +
				CSS.escape( this.ids.button ) ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {

		// Prevent text selection from being reset when interacting with the selectmenu (#10144)
		mousedown: function() {
			var selection = window.getSelection();
			if ( selection.rangeCount ) {
				this.range = selection.getRangeAt( 0 );
			}
		},

		click: function( event ) {
			this._setSelection();
			this._toggle( event );
		},

		keydown: function( event ) {
			var preventDefault = true;
			switch ( event.keyCode ) {
			case $.ui.keyCode.TAB:
			case $.ui.keyCode.ESCAPE:
				this.close( event );
				preventDefault = false;
				break;
			case $.ui.keyCode.ENTER:
				if ( this.isOpen ) {
					this._selectFocusedItem( event );
				}
				break;
			case $.ui.keyCode.UP:
				if ( event.altKey ) {
					this._toggle( event );
				} else {
					this._move( "prev", event );
				}
				break;
			case $.ui.keyCode.DOWN:
				if ( event.altKey ) {
					this._toggle( event );
				} else {
					this._move( "next", event );
				}
				break;
			case $.ui.keyCode.SPACE:
				if ( this.isOpen ) {
					this._selectFocusedItem( event );
				} else {
					this._toggle( event );
				}
				break;
			case $.ui.keyCode.LEFT:
				this._move( "prev", event );
				break;
			case $.ui.keyCode.RIGHT:
				this._move( "next", event );
				break;
			case $.ui.keyCode.HOME:
			case $.ui.keyCode.PAGE_UP:
				this._move( "first", event );
				break;
			case $.ui.keyCode.END:
			case $.ui.keyCode.PAGE_DOWN:
				this._move( "last", event );
				break;
			default:
				this.menu.trigger( event );
				preventDefault = false;
			}

			if ( preventDefault ) {
				event.preventDefault();
			}
		}
	},

	_selectFocusedItem: function( event ) {
		var item = this.menuItems.eq( this.focusIndex ).parent( "li" );
		if ( !item.hasClass( "ui-state-disabled" ) ) {
			this._select( item.data( "ui-selectmenu-item" ), event );
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;

		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this.buttonItem.replaceWith( this.buttonItem = this._renderButtonItem( item ) );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}

		this.close( event );
	},

	_setAria: function( item ) {
		var id = this.menuItems.eq( item.index ).attr( "id" );

		this.button.attr( {
			"aria-labelledby": id,
			"aria-activedescendant": id
		} );
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icon = this.button.find( "span.ui-icon" );
			this._removeClass( icon, null, this.options.icons.button )
				._addClass( icon, null, value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}

		if ( key === "width" ) {
			this._resizeButton();
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.menuInstance.option( "disabled", value );
		this.button.attr( "aria-disabled", value );
		this._toggleClass( this.button, null, "ui-state-disabled", value );

		this.element.prop( "disabled", value );
		if ( value ) {
			this.button.attr( "tabindex", -1 );
			this.close();
		} else {
			this.button.attr( "tabindex", 0 );
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front, dialog" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_toggleAttr: function() {
		this.button.attr( "aria-expanded", this.isOpen );

		// We can't use two _toggleClass() calls here, because we need to make sure
		// we always remove classes first and add them second, otherwise if both classes have the
		// same theme class, it will be removed after we add it.
		this._removeClass( this.button, "ui-selectmenu-button-" +
			( this.isOpen ? "closed" : "open" ) )
			._addClass( this.button, "ui-selectmenu-button-" +
				( this.isOpen ? "open" : "closed" ) )
			._toggleClass( this.menuWrap, "ui-selectmenu-open", null, this.isOpen );

		this.menu.attr( "aria-hidden", !this.isOpen );
	},

	_resizeButton: function() {
		var width = this.options.width;

		// For `width: false`, just remove inline style and stop
		if ( width === false ) {
			this.button.css( "width", "" );
			return;
		}

		// For `width: null`, match the width of the original element
		if ( width === null ) {
			width = this.element.show().outerWidth();
			this.element.hide();
		}

		this.button.outerWidth( width );
	},

	_resizeMenu: function() {
		this.menu.outerWidth( Math.max(
			this.button.outerWidth(),
			this.menu.width( "" ).outerWidth()
		) );
	},

	_getCreateOptions: function() {
		var options = this._super();

		options.disabled = this.element.prop( "disabled" );

		return options;
	},

	_parseOptions: function( options ) {
		var that = this,
			data = [];
		options.each( function( index, item ) {
			data.push( that._parseOption( $( item ), index ) );
		} );
		this.items = data;
	},

	_parseOption: function( option, index ) {
		var optgroup = option.parent( "optgroup" );

		return {
			element: option,
			index: index,
			value: option.val(),
			label: option.text(),
			hidden: optgroup.prop( "hidden" ) || option.prop( "hidden" ),
			optgroup: optgroup.attr( "label" ) || "",
			disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" )
		};
	},

	_destroy: function() {
		this._unbindFormResetHandler();
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.labels.attr( "for", this.ids.element );
	}
} ] );


/*!
 * jQuery UI Slider 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Slider
//>>group: Widgets
//>>description: Displays a flexible slider with ranges and accessibility via keyboard.
//>>docs: https://api.jqueryui.com/slider/
//>>demos: https://jqueryui.com/slider/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/slider.css
//>>css.theme: ../../themes/base/theme.css


var widgetsSlider = $.widget( "ui.slider", $.ui.mouse, {
	version: "1.14.0",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		classes: {
			"ui-slider": "ui-corner-all",
			"ui-slider-handle": "ui-corner-all",

			// Note: ui-widget-header isn't the most fittingly semantic framework class for this
			// element, but worked best visually with a variety of themes
			"ui-slider-range": "ui-corner-all ui-widget-header"
		},
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// Callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// Number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this._addClass( "ui-slider ui-slider-" + this.orientation,
			"ui-widget ui-widget-content" );

		this._refresh();

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ),
			handle = "<span tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this._addClass( this.handles, "ui-slider-handle", "ui-state-default" );

		this.handle = this.handles.eq( 0 );

		this.handles.each( function( i ) {
			$( this )
				.data( "ui-slider-handle-index", i )
				.attr( "tabIndex", 0 );
		} );
	},

	_createRange: function() {
		var options = this.options;

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[ 0 ], options.values[ 0 ] ];
				} else if ( Array.isArray( options.values ) ) {
					options.values = options.values.slice( 0 );
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div>" )
					.appendTo( this.element );

				this._addClass( this.range, "ui-slider-range" );
			} else {
				this._removeClass( this.range, "ui-slider-range-min ui-slider-range-max" );

				// Handle range switching from true to min/max
				this.range.css( {
					"left": "",
					"bottom": ""
				} );
			}
			if ( options.range === "min" || options.range === "max" ) {
				this._addClass( this.range, "ui-slider-range-" + options.range );
			}
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each( function( i ) {
			var thisDistance = Math.abs( normValue - that.values( i ) );
			if ( ( distance > thisDistance ) ||
				( distance === thisDistance &&
					( i === that._lastChangedValue || that.values( i ) === o.min ) ) ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		} );

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		this._addClass( closestHandle, null, "ui-state-active" );
		closestHandle.trigger( "focus" );

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css( "borderTopWidth" ), 10 ) || 0 ) -
				( parseInt( closestHandle.css( "borderBottomWidth" ), 10 ) || 0 ) +
				( parseInt( closestHandle.css( "marginTop" ), 10 ) || 0 )
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this._removeClass( this.handles, null, "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left -
				( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top -
				( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_uiHash: function( index, value, values ) {
		var uiHash = {
			handle: this.handles[ index ],
			handleIndex: index,
			value: value !== undefined ? value : this.value()
		};

		if ( this._hasMultipleValues() ) {
			uiHash.value = value !== undefined ? value : this.values( index );
			uiHash.values = values || this.values();
		}

		return uiHash;
	},

	_hasMultipleValues: function() {
		return this.options.values && this.options.values.length;
	},

	_start: function( event, index ) {
		return this._trigger( "start", event, this._uiHash( index ) );
	},

	_slide: function( event, index, newVal ) {
		var allowed, otherVal,
			currentValue = this.value(),
			newValues = this.values();

		if ( this._hasMultipleValues() ) {
			otherVal = this.values( index ? 0 : 1 );
			currentValue = this.values( index );

			if ( this.options.values.length === 2 && this.options.range === true ) {
				newVal =  index === 0 ? Math.min( otherVal, newVal ) : Math.max( otherVal, newVal );
			}

			newValues[ index ] = newVal;
		}

		if ( newVal === currentValue ) {
			return;
		}

		allowed = this._trigger( "slide", event, this._uiHash( index, newVal, newValues ) );

		// A slide can be canceled by returning false from the slide callback
		if ( allowed === false ) {
			return;
		}

		if ( this._hasMultipleValues() ) {
			this.values( index, newVal );
		} else {
			this.value( newVal );
		}
	},

	_stop: function( event, index ) {
		this._trigger( "stop", event, this._uiHash( index ) );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;
			this._trigger( "change", event, this._uiHash( index ) );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( Array.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this._hasMultipleValues() ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( Array.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this._removeClass( "ui-slider-horizontal ui-slider-vertical" )
					._addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				if ( this.options.range ) {
					this._refreshRange( value );
				}

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();

				// Start from the last handle to prevent unreachable handles (#9046)
				for ( i = valsLength - 1; i >= 0; i-- ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this._hasMultipleValues() ) {

			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1 ) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// Returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = ( val - this._valueMin() ) % step,
			alignValue = val - valModStep;

		if ( Math.abs( valModStep ) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed( 5 ) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.round( ( max - min ) / step ) * step;
		max = aboveMin + min;
		if ( max > this.options.max ) {

			//If max is not divisible by step, rounding off may increase its value
			max -= step;
		}
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshRange: function( orientation ) {
		if ( orientation === "vertical" ) {
			this.range.css( { "width": "", "left": "" } );
		}
		if ( orientation === "horizontal" ) {
			this.range.css( { "height": "", "bottom": "" } );
		}
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this._hasMultipleValues() ) {
			this.handles.each( function( i ) {
				valPercent = ( that.values( i ) - that._valueMin() ) / ( that._valueMax() -
					that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								left: valPercent + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								width: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								bottom: ( valPercent ) + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								height: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					}
				}
				lastValPercent = valPercent;
			} );
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						this._addClass( $( event.target ), null, "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this._hasMultipleValues() ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( ( this._valueMax() - this._valueMin() ) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				this._removeClass( $( event.target ), null, "ui-state-active" );
			}
		}
	}
} );


/*!
 * jQuery UI Sortable 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Sortable
//>>group: Interactions
//>>description: Enables items in a list to be sorted using the mouse.
//>>docs: https://api.jqueryui.com/sortable/
//>>demos: https://jqueryui.com/sortable/
//>>css.structure: ../../themes/base/sortable.css


var widgetsSortable = $.widget( "ui.sortable", $.ui.mouse, {
	version: "1.14.0",
	widgetEventPrefix: "sort",
	ready: false,
	options: {
		appendTo: "parent",
		axis: false,
		connectWith: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: "> *",
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000,

		// Callbacks
		activate: null,
		beforeStop: null,
		change: null,
		deactivate: null,
		out: null,
		over: null,
		receive: null,
		remove: null,
		sort: null,
		start: null,
		stop: null,
		update: null
	},

	_isOverAxis: function( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	},

	_isFloating: function( item ) {
		return ( /left|right/ ).test( item.css( "float" ) ) ||
			( /inline|table-cell/ ).test( item.css( "display" ) );
	},

	_create: function() {
		this.containerCache = {};
		this._addClass( "ui-sortable" );

		//Get the items
		this.refresh();

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

		this._setHandleClassName();

		//We're ready to go
		this.ready = true;

	},

	_setOption: function( key, value ) {
		this._super( key, value );

		if ( key === "handle" ) {
			this._setHandleClassName();
		}
	},

	_setHandleClassName: function() {
		var that = this;
		this._removeClass( this.element.find( ".ui-sortable-handle" ), "ui-sortable-handle" );
		$.each( this.items, function() {
			that._addClass(
				this.instance.options.handle ?
					this.item.find( this.instance.options.handle ) :
					this.item,
				"ui-sortable-handle"
			);
		} );
	},

	_destroy: function() {
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- ) {
			this.items[ i ].item.removeData( this.widgetName + "-item" );
		}

		return this;
	},

	_mouseCapture: function( event, overrideHandle ) {
		var currentItem = null,
			validHandle = false,
			that = this;

		if ( this.reverting ) {
			return false;
		}

		if ( this.options.disabled || this.options.type === "static" ) {
			return false;
		}

		//We have to refresh the items data once first
		this._refreshItems( event );

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		$( event.target ).parents().each( function() {
			if ( $.data( this, that.widgetName + "-item" ) === that ) {
				currentItem = $( this );
				return false;
			}
		} );
		if ( $.data( event.target, that.widgetName + "-item" ) === that ) {
			currentItem = $( event.target );
		}

		if ( !currentItem ) {
			return false;
		}
		if ( this.options.handle && !overrideHandle ) {
			$( this.options.handle, currentItem ).find( "*" ).addBack().each( function() {
				if ( this === event.target ) {
					validHandle = true;
				}
			} );
			if ( !validHandle ) {
				return false;
			}
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function( event, overrideHandle, noActivation ) {

		var i, body,
			o = this.options;

		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to
		// mouseCapture
		this.refreshPositions();

		//Prepare the dragged items parent
		this.appendTo = $( o.appendTo !== "parent" ?
				o.appendTo :
				this.currentItem.parent() );

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend( this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},

			// This is a relative to absolute position minus the actual position calculation -
			// only used for relative positioned helper
			relative: this._getRelativeOffset()
		} );

		// After we get the helper offset, but before we get the parent offset we can
		// change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css( "position", "absolute" );
		this.cssPosition = this.helper.css( "position" );

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		if ( o.cursorAt ) {
			this._adjustOffsetFromHelper( o.cursorAt );
		}

		//Cache the former DOM position
		this.domPosition = {
			prev: this.currentItem.prev()[ 0 ],
			parent: this.currentItem.parent()[ 0 ]
		};

		// If the helper is not the original, hide the original so it's not playing any role during
		// the drag, won't cause anything bad this way
		if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Get the next scrolling parent
		this.scrollParent = this.placeholder.scrollParent();

		$.extend( this.offset, {
			parent: this._getParentOffset()
		} );

		//Set a containment if given in the options
		if ( o.containment ) {
			this._setContainment();
		}

		if ( o.cursor && o.cursor !== "auto" ) { // cursor option
			body = this.document.find( "body" );

			this._storedStylesheet =
				$( "<style>*{ cursor: " + o.cursor + " !important; }</style>" ).appendTo( body );
		}

		// We need to make sure to grab the zIndex before setting the
		// opacity, because setting the opacity to anything lower than 1
		// causes the zIndex to change from "auto" to 0.
		if ( o.zIndex ) { // zIndex option
			if ( this.helper.css( "zIndex" ) ) {
				this._storedZIndex = this.helper.css( "zIndex" );
			}
			this.helper.css( "zIndex", o.zIndex );
		}

		if ( o.opacity ) { // opacity option
			if ( this.helper.css( "opacity" ) ) {
				this._storedOpacity = this.helper.css( "opacity" );
			}
			this.helper.css( "opacity", o.opacity );
		}

		//Prepare scrolling
		if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ].tagName !== "HTML" ) {
			this.overflowOffset = this.scrollParent.offset();
		}

		//Call callbacks
		this._trigger( "start", event, this._uiHash() );

		//Recache the helper size
		if ( !this._preserveHelperProportions ) {
			this._cacheHelperProportions();
		}

		//Post "activate" events to possible containers
		if ( !noActivation ) {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
			}
		}

		//Prepare possible droppables
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		this.dragging = true;

		this._addClass( this.helper, "ui-sortable-helper" );

		//Move the helper, if needed
		if ( !this.helper.parent().is( this.appendTo ) ) {
			this.helper.detach().appendTo( this.appendTo );

			//Update position
			this.offset.parent = this._getParentOffset();
		}

		//Generate the original position
		this.position = this.originalPosition = this._generatePosition( event );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;
		this.lastPositionAbs = this.positionAbs = this._convertPositionTo( "absolute" );

		this._mouseDrag( event );

		return true;

	},

	_scroll: function( event ) {
		var o = this.options,
			scrolled = false;

		if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ].tagName !== "HTML" ) {

			if ( ( this.overflowOffset.top + this.scrollParent[ 0 ].offsetHeight ) -
					event.pageY < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollTop =
					scrolled = this.scrollParent[ 0 ].scrollTop + o.scrollSpeed;
			} else if ( event.pageY - this.overflowOffset.top < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollTop =
					scrolled = this.scrollParent[ 0 ].scrollTop - o.scrollSpeed;
			}

			if ( ( this.overflowOffset.left + this.scrollParent[ 0 ].offsetWidth ) -
					event.pageX < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollLeft = scrolled =
					this.scrollParent[ 0 ].scrollLeft + o.scrollSpeed;
			} else if ( event.pageX - this.overflowOffset.left < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollLeft = scrolled =
					this.scrollParent[ 0 ].scrollLeft - o.scrollSpeed;
			}

		} else {

			if ( event.pageY - this.document.scrollTop() < o.scrollSensitivity ) {
				scrolled = this.document.scrollTop( this.document.scrollTop() - o.scrollSpeed );
			} else if ( this.window.height() - ( event.pageY - this.document.scrollTop() ) <
					o.scrollSensitivity ) {
				scrolled = this.document.scrollTop( this.document.scrollTop() + o.scrollSpeed );
			}

			if ( event.pageX - this.document.scrollLeft() < o.scrollSensitivity ) {
				scrolled = this.document.scrollLeft(
					this.document.scrollLeft() - o.scrollSpeed
				);
			} else if ( this.window.width() - ( event.pageX - this.document.scrollLeft() ) <
					o.scrollSensitivity ) {
				scrolled = this.document.scrollLeft(
					this.document.scrollLeft() + o.scrollSpeed
				);
			}

		}

		return scrolled;
	},

	_mouseDrag: function( event ) {
		var i, item, itemElement, intersection,
			o = this.options;

		//Compute the helpers position
		this.position = this._generatePosition( event );
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Set the helper position
		if ( !this.options.axis || this.options.axis !== "y" ) {
			this.helper[ 0 ].style.left = this.position.left + "px";
		}
		if ( !this.options.axis || this.options.axis !== "x" ) {
			this.helper[ 0 ].style.top = this.position.top + "px";
		}

		//Do scrolling
		if ( o.scroll ) {
			if ( this._scroll( event ) !== false ) {

				//Update item positions used in position checks
				this._refreshItemPositions( true );

				if ( $.ui.ddmanager && !o.dropBehaviour ) {
					$.ui.ddmanager.prepareOffsets( this, event );
				}
			}
		}

		this.dragDirection = {
			vertical: this._getDragVerticalDirection(),
			horizontal: this._getDragHorizontalDirection()
		};

		//Rearrange
		for ( i = this.items.length - 1; i >= 0; i-- ) {

			//Cache variables and intersection, continue if no intersection
			item = this.items[ i ];
			itemElement = item.item[ 0 ];
			intersection = this._intersectsWithPointer( item );
			if ( !intersection ) {
				continue;
			}

			// Only put the placeholder inside the current Container, skip all
			// items from other containers. This works because when moving
			// an item from one container to another the
			// currentContainer is switched before the placeholder is moved.
			//
			// Without this, moving items in "sub-sortables" can cause
			// the placeholder to jitter between the outer and inner container.
			if ( item.instance !== this.currentContainer ) {
				continue;
			}

			// Cannot intersect with itself
			// no useless actions that have been done before
			// no action if the item moved is the parent of the item checked
			if ( itemElement !== this.currentItem[ 0 ] &&
				this.placeholder[ intersection === 1 ?
				"next" : "prev" ]()[ 0 ] !== itemElement &&
				!$.contains( this.placeholder[ 0 ], itemElement ) &&
				( this.options.type === "semi-dynamic" ?
					!$.contains( this.element[ 0 ], itemElement ) :
					true
				)
			) {

				this.direction = intersection === 1 ? "down" : "up";

				if ( this.options.tolerance === "pointer" ||
						this._intersectsWithSides( item ) ) {
					this._rearrange( event, item );
				} else {
					break;
				}

				this._trigger( "change", event, this._uiHash() );
				break;
			}
		}

		//Post events to containers
		this._contactContainers( event );

		//Interconnect with droppables
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		//Call callbacks
		this._trigger( "sort", event, this._uiHash() );

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function( event, noPropagation ) {

		if ( !event ) {
			return;
		}

		//If we are using droppables, inform the manager about the drop
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			$.ui.ddmanager.drop( this, event );
		}

		if ( this.options.revert ) {
			var that = this,
				cur = this.placeholder.offset(),
				axis = this.options.axis,
				animation = {};

			if ( !axis || axis === "x" ) {
				animation.left = cur.left - this.offset.parent.left - this.margins.left +
					( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
						0 :
						this.offsetParent[ 0 ].scrollLeft
					);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top +
					( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
						0 :
						this.offsetParent[ 0 ].scrollTop
					);
			}
			this.reverting = true;
			$( this.helper ).animate(
				animation,
				parseInt( this.options.revert, 10 ) || 500,
				function() {
					that._clear( event );
				}
			);
		} else {
			this._clear( event, noPropagation );
		}

		return false;

	},

	cancel: function() {

		if ( this.dragging ) {

			this._mouseUp( new $.Event( "mouseup", { target: null } ) );

			if ( this.options.helper === "original" ) {
				this.currentItem.css( this._storedCSS );
				this._removeClass( this.currentItem, "ui-sortable-helper" );
			} else {
				this.currentItem.show();
			}

			//Post deactivating events to containers
			for ( var i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "deactivate", null, this._uiHash( this ) );
				if ( this.containers[ i ].containerCache.over ) {
					this.containers[ i ]._trigger( "out", null, this._uiHash( this ) );
					this.containers[ i ].containerCache.over = 0;
				}
			}

		}

		if ( this.placeholder ) {

			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
			// it unbinds ALL events from the original node!
			if ( this.placeholder[ 0 ].parentNode ) {
				this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );
			}
			if ( this.options.helper !== "original" && this.helper &&
					this.helper[ 0 ].parentNode ) {
				this.helper.remove();
			}

			$.extend( this, {
				helper: null,
				dragging: false,
				reverting: false,
				_noFinalSort: null
			} );

			if ( this.domPosition.prev ) {
				$( this.domPosition.prev ).after( this.currentItem );
			} else {
				$( this.domPosition.parent ).prepend( this.currentItem );
			}
		}

		return this;

	},

	serialize: function( o ) {

		var items = this._getItemsAsjQuery( o && o.connected ),
			str = [];
		o = o || {};

		$( items ).each( function() {
			var res = ( $( o.item || this ).attr( o.attribute || "id" ) || "" )
				.match( o.expression || ( /(.+)[\-=_](.+)/ ) );
			if ( res ) {
				str.push(
					( o.key || res[ 1 ] + "[]" ) +
					"=" + ( o.key && o.expression ? res[ 1 ] : res[ 2 ] ) );
			}
		} );

		if ( !str.length && o.key ) {
			str.push( o.key + "=" );
		}

		return str.join( "&" );

	},

	toArray: function( o ) {

		var items = this._getItemsAsjQuery( o && o.connected ),
			ret = [];

		o = o || {};

		items.each( function() {
			ret.push( $( o.item || this ).attr( o.attribute || "id" ) || "" );
		} );
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function( item ) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height,
			l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height,
			dyClick = this.offset.click.top,
			dxClick = this.offset.click.left,
			isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t &&
				( y1 + dyClick ) < b ),
			isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l &&
				( x1 + dxClick ) < r ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( this.options.tolerance === "pointer" ||
			this.options.forcePointerForContainers ||
			( this.options.tolerance !== "pointer" &&
				this.helperProportions[ this.floating ? "width" : "height" ] >
				item[ this.floating ? "width" : "height" ] )
		) {
			return isOverElement;
		} else {

			return ( l < x1 + ( this.helperProportions.width / 2 ) && // Right Half
				x2 - ( this.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( this.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( this.helperProportions.height / 2 ) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function( item ) {
		var verticalDirection, horizontalDirection,
			isOverElementHeight = ( this.options.axis === "x" ) ||
				this._isOverAxis(
					this.positionAbs.top + this.offset.click.top, item.top, item.height ),
			isOverElementWidth = ( this.options.axis === "y" ) ||
				this._isOverAxis(
					this.positionAbs.left + this.offset.click.left, item.left, item.width ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( !isOverElement ) {
			return false;
		}

		verticalDirection = this.dragDirection.vertical;
		horizontalDirection = this.dragDirection.horizontal;

		return this.floating ?
			( ( horizontalDirection === "right" || verticalDirection === "down" ) ? 2 : 1 ) :
			( verticalDirection && ( verticalDirection === "down" ? 2 : 1 ) );

	},

	_intersectsWithSides: function( item ) {

		var isOverBottomHalf = this._isOverAxis( this.positionAbs.top +
				this.offset.click.top, item.top + ( item.height / 2 ), item.height ),
			isOverRightHalf = this._isOverAxis( this.positionAbs.left +
				this.offset.click.left, item.left + ( item.width / 2 ), item.width ),
			verticalDirection = this.dragDirection.vertical,
			horizontalDirection = this.dragDirection.horizontal;

		if ( this.floating && horizontalDirection ) {
			return ( ( horizontalDirection === "right" && isOverRightHalf ) ||
				( horizontalDirection === "left" && !isOverRightHalf ) );
		} else {
			return verticalDirection && ( ( verticalDirection === "down" && isOverBottomHalf ) ||
				( verticalDirection === "up" && !isOverBottomHalf ) );
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta !== 0 && ( delta > 0 ? "down" : "up" );
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta !== 0 && ( delta > 0 ? "right" : "left" );
	},

	refresh: function( event ) {
		this._refreshItems( event );
		this._setHandleClassName();
		this.refreshPositions();
		return this;
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor === String ?
			[ options.connectWith ] :
			options.connectWith;
	},

	_getItemsAsjQuery: function( connected ) {

		var i, j, cur, inst,
			items = [],
			queries = [],
			connectWith = this._connectWith();

		if ( connectWith && connected ) {
			for ( i = connectWith.length - 1; i >= 0; i-- ) {
				cur = $( connectWith[ i ], this.document[ 0 ] );
				for ( j = cur.length - 1; j >= 0; j-- ) {
					inst = $.data( cur[ j ], this.widgetFullName );
					if ( inst && inst !== this && !inst.options.disabled ) {
						queries.push( [ typeof inst.options.items === "function" ?
							inst.options.items.call( inst.element ) :
							$( inst.options.items, inst.element )
								.not( ".ui-sortable-helper" )
								.not( ".ui-sortable-placeholder" ), inst ] );
					}
				}
			}
		}

		queries.push( [ typeof this.options.items === "function" ?
			this.options.items
				.call( this.element, null, { options: this.options, item: this.currentItem } ) :
			$( this.options.items, this.element )
				.not( ".ui-sortable-helper" )
				.not( ".ui-sortable-placeholder" ), this ] );

		function addItems() {
			items.push( this );
		}
		for ( i = queries.length - 1; i >= 0; i-- ) {
			queries[ i ][ 0 ].each( addItems );
		}

		return $( items );

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find( ":data(" + this.widgetName + "-item)" );

		this.items = $.grep( this.items, function( item ) {
			for ( var j = 0; j < list.length; j++ ) {
				if ( list[ j ] === item.item[ 0 ] ) {
					return false;
				}
			}
			return true;
		} );

	},

	_refreshItems: function( event ) {

		this.items = [];
		this.containers = [ this ];

		var i, j, cur, inst, targetData, _queries, item, queriesLength,
			items = this.items,
			queries = [ [ typeof this.options.items === "function" ?
				this.options.items.call( this.element[ 0 ], event, { item: this.currentItem } ) :
				$( this.options.items, this.element ), this ] ],
			connectWith = this._connectWith();

		//Shouldn't be run the first time through due to massive slow-down
		if ( connectWith && this.ready ) {
			for ( i = connectWith.length - 1; i >= 0; i-- ) {
				cur = $( connectWith[ i ], this.document[ 0 ] );
				for ( j = cur.length - 1; j >= 0; j-- ) {
					inst = $.data( cur[ j ], this.widgetFullName );
					if ( inst && inst !== this && !inst.options.disabled ) {
						queries.push( [ typeof inst.options.items === "function" ?
							inst.options.items
								.call( inst.element[ 0 ], event, { item: this.currentItem } ) :
							$( inst.options.items, inst.element ), inst ] );
						this.containers.push( inst );
					}
				}
			}
		}

		for ( i = queries.length - 1; i >= 0; i-- ) {
			targetData = queries[ i ][ 1 ];
			_queries = queries[ i ][ 0 ];

			for ( j = 0, queriesLength = _queries.length; j < queriesLength; j++ ) {
				item = $( _queries[ j ] );

				// Data for target checking (mouse manager)
				item.data( this.widgetName + "-item", targetData );

				items.push( {
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				} );
			}
		}

	},

	_refreshItemPositions: function( fast ) {
		var i, item, t, p;

		for ( i = this.items.length - 1; i >= 0; i-- ) {
			item = this.items[ i ];

			//We ignore calculating positions of all connected containers when we're not over them
			if ( this.currentContainer && item.instance !== this.currentContainer &&
					item.item[ 0 ] !== this.currentItem[ 0 ] ) {
				continue;
			}

			t = this.options.toleranceElement ?
				$( this.options.toleranceElement, item.item ) :
				item.item;

			if ( !fast ) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			p = t.offset();
			item.left = p.left;
			item.top = p.top;
		}
	},

	refreshPositions: function( fast ) {

		// Determine whether items are being displayed horizontally
		this.floating = this.items.length ?
			this.options.axis === "x" || this._isFloating( this.items[ 0 ].item ) :
			false;

		// This has to be redone because due to the item being moved out/into the offsetParent,
		// the offsetParent's position will change
		if ( this.offsetParent && this.helper ) {
			this.offset.parent = this._getParentOffset();
		}

		this._refreshItemPositions( fast );

		var i, p;

		if ( this.options.custom && this.options.custom.refreshContainers ) {
			this.options.custom.refreshContainers.call( this );
		} else {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				p = this.containers[ i ].element.offset();
				this.containers[ i ].containerCache.left = p.left;
				this.containers[ i ].containerCache.top = p.top;
				this.containers[ i ].containerCache.width =
					this.containers[ i ].element.outerWidth();
				this.containers[ i ].containerCache.height =
					this.containers[ i ].element.outerHeight();
			}
		}

		return this;
	},

	_createPlaceholder: function( that ) {
		that = that || this;
		var className, nodeName,
			o = that.options;

		if ( !o.placeholder || o.placeholder.constructor === String ) {
			className = o.placeholder;
			nodeName = that.currentItem[ 0 ].nodeName.toLowerCase();
			o.placeholder = {
				element: function() {

					var element = $( "<" + nodeName + ">", that.document[ 0 ] );

					that._addClass( element, "ui-sortable-placeholder",
							className || that.currentItem[ 0 ].className )
						._removeClass( element, "ui-sortable-helper" );

					if ( nodeName === "tbody" ) {
						that._createTrPlaceholder(
							that.currentItem.find( "tr" ).eq( 0 ),
							$( "<tr>", that.document[ 0 ] ).appendTo( element )
						);
					} else if ( nodeName === "tr" ) {
						that._createTrPlaceholder( that.currentItem, element );
					} else if ( nodeName === "img" ) {
						element.attr( "src", that.currentItem.attr( "src" ) );
					}

					if ( !className ) {
						element.css( "visibility", "hidden" );
					}

					return element;
				},
				update: function( container, p ) {

					// 1. If a className is set as 'placeholder option, we don't force sizes -
					// the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a
					// class name is specified
					if ( className && !o.forcePlaceholderSize ) {
						return;
					}

					// If the element doesn't have a actual height or width by itself (without
					// styles coming from a stylesheet), it receives the inline height and width
					// from the dragged item. Or, if it's a tbody or tr, it's going to have a height
					// anyway since we're populating them with <td>s above, but they're unlikely to
					// be the correct height on their own if the row heights are dynamic, so we'll
					// always assign the height of the dragged item given forcePlaceholderSize
					// is true.
					if ( !p.height() || ( o.forcePlaceholderSize &&
							( nodeName === "tbody" || nodeName === "tr" ) ) ) {
						p.height(
							that.currentItem.innerHeight() -
							parseInt( that.currentItem.css( "paddingTop" ) || 0, 10 ) -
							parseInt( that.currentItem.css( "paddingBottom" ) || 0, 10 ) );
					}
					if ( !p.width() ) {
						p.width(
							that.currentItem.innerWidth() -
							parseInt( that.currentItem.css( "paddingLeft" ) || 0, 10 ) -
							parseInt( that.currentItem.css( "paddingRight" ) || 0, 10 ) );
					}
				}
			};
		}

		//Create the placeholder
		that.placeholder = $( o.placeholder.element.call( that.element, that.currentItem ) );

		//Append it after the actual current item
		that.currentItem.after( that.placeholder );

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update( that, that.placeholder );

	},

	_createTrPlaceholder: function( sourceTr, targetTr ) {
		var that = this;

		sourceTr.children().each( function() {
			$( "<td>&#160;</td>", that.document[ 0 ] )
				.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
				.appendTo( targetTr );
		} );
	},

	_contactContainers: function( event ) {
		var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom,
			floating, axis,
			innermostContainer = null,
			innermostIndex = null;

		// Get innermost container that intersects with item
		for ( i = this.containers.length - 1; i >= 0; i-- ) {

			// Never consider a container that's located within the item itself
			if ( $.contains( this.currentItem[ 0 ], this.containers[ i ].element[ 0 ] ) ) {
				continue;
			}

			if ( this._intersectsWith( this.containers[ i ].containerCache ) ) {

				// If we've already found a container and it's more "inner" than this, then continue
				if ( innermostContainer &&
						$.contains(
							this.containers[ i ].element[ 0 ],
							innermostContainer.element[ 0 ] ) ) {
					continue;
				}

				innermostContainer = this.containers[ i ];
				innermostIndex = i;

			} else {

				// container doesn't intersect. trigger "out" event if necessary
				if ( this.containers[ i ].containerCache.over ) {
					this.containers[ i ]._trigger( "out", event, this._uiHash( this ) );
					this.containers[ i ].containerCache.over = 0;
				}
			}

		}

		// If no intersecting containers found, return
		if ( !innermostContainer ) {
			return;
		}

		// Move the item into the container if it's not there already
		if ( this.containers.length === 1 ) {
			if ( !this.containers[ innermostIndex ].containerCache.over ) {
				this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
				this.containers[ innermostIndex ].containerCache.over = 1;
			}
		} else {

			// When entering a new container, we will find the item with the least distance and
			// append our item near it
			dist = 10000;
			itemWithLeastDistance = null;
			floating = innermostContainer.floating || this._isFloating( this.currentItem );
			posProperty = floating ? "left" : "top";
			sizeProperty = floating ? "width" : "height";
			axis = floating ? "pageX" : "pageY";

			for ( j = this.items.length - 1; j >= 0; j-- ) {
				if ( !$.contains(
						this.containers[ innermostIndex ].element[ 0 ], this.items[ j ].item[ 0 ] )
				) {
					continue;
				}
				if ( this.items[ j ].item[ 0 ] === this.currentItem[ 0 ] ) {
					continue;
				}

				cur = this.items[ j ].item.offset()[ posProperty ];
				nearBottom = false;
				if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
					nearBottom = true;
				}

				if ( Math.abs( event[ axis ] - cur ) < dist ) {
					dist = Math.abs( event[ axis ] - cur );
					itemWithLeastDistance = this.items[ j ];
					this.direction = nearBottom ? "up" : "down";
				}
			}

			//Check if dropOnEmpty is enabled
			if ( !itemWithLeastDistance && !this.options.dropOnEmpty ) {
				return;
			}

			if ( this.currentContainer === this.containers[ innermostIndex ] ) {
				if ( !this.currentContainer.containerCache.over ) {
					this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
					this.currentContainer.containerCache.over = 1;
				}
				return;
			}

			if ( itemWithLeastDistance ) {
				this._rearrange( event, itemWithLeastDistance, null, true );
			} else {
				this._rearrange( event, null, this.containers[ innermostIndex ].element, true );
			}
			this._trigger( "change", event, this._uiHash() );
			this.containers[ innermostIndex ]._trigger( "change", event, this._uiHash( this ) );
			this.currentContainer = this.containers[ innermostIndex ];

			//Update the placeholder
			this.options.placeholder.update( this.currentContainer, this.placeholder );

			//Update scrollParent
			this.scrollParent = this.placeholder.scrollParent();

			//Update overflowOffset
			if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
					this.scrollParent[ 0 ].tagName !== "HTML" ) {
				this.overflowOffset = this.scrollParent.offset();
			}

			this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
			this.containers[ innermostIndex ].containerCache.over = 1;
		}

	},

	_createHelper: function( event ) {

		var o = this.options,
			helper = typeof o.helper === "function" ?
				$( o.helper.apply( this.element[ 0 ], [ event, this.currentItem ] ) ) :
				( o.helper === "clone" ? this.currentItem.clone() : this.currentItem );

		//Add the helper to the DOM if that didn't happen already
		if ( !helper.parents( "body" ).length ) {
			this.appendTo[ 0 ].appendChild( helper[ 0 ] );
		}

		if ( helper[ 0 ] === this.currentItem[ 0 ] ) {
			this._storedCSS = {
				width: this.currentItem[ 0 ].style.width,
				height: this.currentItem[ 0 ].style.height,
				position: this.currentItem.css( "position" ),
				top: this.currentItem.css( "top" ),
				left: this.currentItem.css( "left" )
			};
		}

		if ( !helper[ 0 ].style.width || o.forceHelperSize ) {
			helper.width( this.currentItem.width() );
		}
		if ( !helper[ 0 ].style.height || o.forceHelperSize ) {
			helper.height( this.currentItem.height() );
		}

		return helper;

	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( Array.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		// This needs to be actually done for all browsers, since pageX/pageY includes
		// this information.
		if ( this.offsetParent[ 0 ] === this.document[ 0 ].body ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
			left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
		};

	},

	_getRelativeOffset: function() {

		if ( this.cssPosition === "relative" ) {
			var p = this.currentItem.position();
			return {
				top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
					this.scrollParent.scrollTop(),
				left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
					this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: ( parseInt( this.currentItem.css( "marginLeft" ), 10 ) || 0 ),
			top: ( parseInt( this.currentItem.css( "marginTop" ), 10 ) || 0 )
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var ce, co, over,
			o = this.options;
		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}
		if ( o.containment === "document" || o.containment === "window" ) {
			this.containment = [
				0 - this.offset.relative.left - this.offset.parent.left,
				0 - this.offset.relative.top - this.offset.parent.top,
				o.containment === "document" ?
					this.document.width() :
					this.window.width() - this.helperProportions.width - this.margins.left,
				( o.containment === "document" ?
					( this.document.height() || document.body.parentNode.scrollHeight ) :
					this.window.height() || this.document[ 0 ].body.parentNode.scrollHeight
				) - this.helperProportions.height - this.margins.top
			];
		}

		if ( !( /^(document|window|parent)$/ ).test( o.containment ) ) {
			ce = $( o.containment )[ 0 ];
			co = $( o.containment ).offset();
			over = ( $( ce ).css( "overflow" ) !== "hidden" );

			this.containment = [
				co.left + ( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) +
					( parseInt( $( ce ).css( "paddingLeft" ), 10 ) || 0 ) - this.margins.left,
				co.top + ( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) +
					( parseInt( $( ce ).css( "paddingTop" ), 10 ) || 0 ) - this.margins.top,
				co.left + ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
					( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) -
					( parseInt( $( ce ).css( "paddingRight" ), 10 ) || 0 ) -
					this.helperProportions.width - this.margins.left,
				co.top + ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
					( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) -
					( parseInt( $( ce ).css( "paddingBottom" ), 10 ) || 0 ) -
					this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}
		var mod = d === "absolute" ? 1 : -1,
			scroll = this.cssPosition === "absolute" &&
				!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
					this.offsetParent :
					this.scrollParent,
			scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollTop() :
					( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 :
					scroll.scrollLeft() ) * mod )
			)
		};

	},

	_generatePosition: function( event ) {

		var top, left,
			o = this.options,
			pageX = event.pageX,
			pageY = event.pageY,
			scroll = this.cssPosition === "absolute" &&
				!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
					this.offsetParent :
					this.scrollParent,
				scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if ( this.cssPosition === "relative" && !( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ] !== this.offsetParent[ 0 ] ) ) {
			this.offset.relative = this._getRelativeOffset();
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if ( this.originalPosition ) { //If we are not dragging yet, we won't check for options

			if ( this.containment ) {
				if ( event.pageX - this.offset.click.left < this.containment[ 0 ] ) {
					pageX = this.containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < this.containment[ 1 ] ) {
					pageY = this.containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > this.containment[ 2 ] ) {
					pageX = this.containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > this.containment[ 3 ] ) {
					pageY = this.containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {
				top = this.originalPageY + Math.round( ( pageY - this.originalPageY ) /
					o.grid[ 1 ] ) * o.grid[ 1 ];
				pageY = this.containment ?
					( ( top - this.offset.click.top >= this.containment[ 1 ] &&
						top - this.offset.click.top <= this.containment[ 3 ] ) ?
							top :
							( ( top - this.offset.click.top >= this.containment[ 1 ] ) ?
								top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) :
								top;

				left = this.originalPageX + Math.round( ( pageX - this.originalPageX ) /
					o.grid[ 0 ] ) * o.grid[ 0 ];
				pageX = this.containment ?
					( ( left - this.offset.click.left >= this.containment[ 0 ] &&
						left - this.offset.click.left <= this.containment[ 2 ] ) ?
							left :
							( ( left - this.offset.click.left >= this.containment[ 0 ] ) ?
								left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) :
								left;
			}

		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollTop() :
					( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollLeft() :
					scrollIsRootNode ? 0 : scroll.scrollLeft() ) )
			)
		};

	},

	_rearrange: function( event, i, a, hardRefresh ) {

		if ( a ) {
			a[ 0 ].appendChild( this.placeholder[ 0 ] );
		} else {
			i.item[ 0 ].parentNode.insertBefore( this.placeholder[ 0 ],
				( this.direction === "down" ? i.item[ 0 ] : i.item[ 0 ].nextSibling ) );
		}

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout,
		// if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var counter = this.counter;

		this._delay( function() {
			if ( counter === this.counter ) {

				//Precompute after each DOM insertion, NOT on mousemove
				this.refreshPositions( !hardRefresh );
			}
		} );

	},

	_clear: function( event, noPropagation ) {

		this.reverting = false;

		// We delay all events that have to be triggered to after the point where the placeholder
		// has been removed and everything else normalized again
		var i,
			delayedTriggers = [];

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets
		// reappended (see #4088)
		if ( !this._noFinalSort && this.currentItem.parent().length ) {
			this.placeholder.before( this.currentItem );
		}
		this._noFinalSort = null;

		if ( this.helper[ 0 ] === this.currentItem[ 0 ] ) {
			for ( i in this._storedCSS ) {
				if ( this._storedCSS[ i ] === "auto" || this._storedCSS[ i ] === "static" ) {
					this._storedCSS[ i ] = "";
				}
			}
			this.currentItem.css( this._storedCSS );
			this._removeClass( this.currentItem, "ui-sortable-helper" );
		} else {
			this.currentItem.show();
		}

		if ( this.fromOutside && !noPropagation ) {
			delayedTriggers.push( function( event ) {
				this._trigger( "receive", event, this._uiHash( this.fromOutside ) );
			} );
		}
		if ( ( this.fromOutside ||
				this.domPosition.prev !==
				this.currentItem.prev().not( ".ui-sortable-helper" )[ 0 ] ||
				this.domPosition.parent !== this.currentItem.parent()[ 0 ] ) && !noPropagation ) {

			// Trigger update callback if the DOM position has changed
			delayedTriggers.push( function( event ) {
				this._trigger( "update", event, this._uiHash() );
			} );
		}

		// Check if the items Container has Changed and trigger appropriate
		// events.
		if ( this !== this.currentContainer ) {
			if ( !noPropagation ) {
				delayedTriggers.push( function( event ) {
					this._trigger( "remove", event, this._uiHash() );
				} );
				delayedTriggers.push( ( function( c ) {
					return function( event ) {
						c._trigger( "receive", event, this._uiHash( this ) );
					};
				} ).call( this, this.currentContainer ) );
				delayedTriggers.push( ( function( c ) {
					return function( event ) {
						c._trigger( "update", event, this._uiHash( this ) );
					};
				} ).call( this, this.currentContainer ) );
			}
		}

		//Post events to containers
		function delayEvent( type, instance, container ) {
			return function( event ) {
				container._trigger( type, event, instance._uiHash( instance ) );
			};
		}
		for ( i = this.containers.length - 1; i >= 0; i-- ) {
			if ( !noPropagation ) {
				delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
			}
			if ( this.containers[ i ].containerCache.over ) {
				delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
				this.containers[ i ].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if ( this._storedStylesheet ) {
			this._storedStylesheet.remove();
			this._storedStylesheet = null;
		}
		if ( this._storedOpacity ) {
			this.helper.css( "opacity", this._storedOpacity );
		}
		if ( this._storedZIndex ) {
			this.helper.css( "zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex );
		}

		this.dragging = false;

		if ( !noPropagation ) {
			this._trigger( "beforeStop", event, this._uiHash() );
		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
		// it unbinds ALL events from the original node!
		this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );

		if ( !this.cancelHelperRemoval ) {
			if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
				this.helper.remove();
			}
			this.helper = null;
		}

		if ( !noPropagation ) {
			for ( i = 0; i < delayedTriggers.length; i++ ) {

				// Trigger all delayed events
				delayedTriggers[ i ].call( this, event );
			}
			this._trigger( "stop", event, this._uiHash() );
		}

		this.fromOutside = false;
		return !this.cancelHelperRemoval;

	},

	_trigger: function() {
		if ( $.Widget.prototype._trigger.apply( this, arguments ) === false ) {
			this.cancel();
		}
	},

	_uiHash: function( _inst ) {
		var inst = _inst || this;
		return {
			helper: inst.helper,
			placeholder: inst.placeholder || $( [] ),
			position: inst.position,
			originalPosition: inst.originalPosition,
			offset: inst.positionAbs,
			item: inst.currentItem,
			sender: _inst ? _inst.element : null
		};
	}

} );


/*!
 * jQuery UI Spinner 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Spinner
//>>group: Widgets
//>>description: Displays buttons to easily input numbers via the keyboard or mouse.
//>>docs: https://api.jqueryui.com/spinner/
//>>demos: https://jqueryui.com/spinner/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/spinner.css
//>>css.theme: ../../themes/base/theme.css


function spinnerModifier( fn ) {
	return function() {
		var previous = this.element.val();
		fn.apply( this, arguments );
		this._refresh();
		if ( previous !== this.element.val() ) {
			this._trigger( "change" );
		}
	};
}

$.widget( "ui.spinner", {
	version: "1.14.0",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		classes: {
			"ui-spinner": "ui-corner-all",
			"ui-spinner-down": "ui-corner-br",
			"ui-spinner-up": "ui-corner-tr"
		},
		culture: null,
		icons: {
			down: "ui-icon-triangle-1-s",
			up: "ui-icon-triangle-1-n"
		},
		incremental: true,
		max: null,
		min: null,
		numberFormat: null,
		page: 10,
		step: 1,

		change: null,
		spin: null,
		start: null,
		stop: null
	},

	_create: function() {

		// handle string values that need to be parsed
		this._setOption( "max", this.options.max );
		this._setOption( "min", this.options.min );
		this._setOption( "step", this.options.step );

		// Only format if there is a value, prevents the field from being marked
		// as invalid in Firefox, see #9573.
		if ( this.value() !== "" ) {

			// Format the value, but don't constrain.
			this._value( this.element.val(), true );
		}

		this._draw();
		this._on( this._events );
		this._refresh();

		// Turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		} );
	},

	_getCreateOptions: function() {
		var options = this._super();
		var element = this.element;

		$.each( [ "min", "max", "step" ], function( i, option ) {
			var value = element.attr( option );
			if ( value != null && value.length ) {
				options[ option ] = value;
			}
		} );

		return options;
	},

	_events: {
		keydown: function( event ) {
			if ( this._start( event ) && this._keydown( event ) ) {
				event.preventDefault();
			}
		},
		keyup: "_stop",
		focus: function() {
			this.previous = this.element.val();
		},
		blur: function( event ) {
			this._stop();
			this._refresh();
			if ( this.previous !== this.element.val() ) {
				this._trigger( "change", event );
			}
		},
		mousewheel: function( event, delta ) {
			var activeElement = this.document[ 0 ].activeElement;
			var isActive = this.element[ 0 ] === activeElement;

			if ( !isActive || !delta ) {
				return;
			}

			if ( !this.spinning && !this._start( event ) ) {
				return false;
			}

			this._spin( ( delta > 0 ? 1 : -1 ) * this.options.step, event );
			clearTimeout( this.mousewheelTimer );
			this.mousewheelTimer = this._delay( function() {
				if ( this.spinning ) {
					this._stop( event );
				}
			}, 100 );
			event.preventDefault();
		},
		"mousedown .ui-spinner-button": function( event ) {
			var previous;

			// We never want the buttons to have focus; whenever the user is
			// interacting with the spinner, the focus should be on the input.
			// If the input is focused then this.previous is properly set from
			// when the input first received focus. If the input is not focused
			// then we need to set this.previous based on the value before spinning.
			previous = this.element[ 0 ] === this.document[ 0 ].activeElement ?
				this.previous : this.element.val();
			function checkFocus() {
				var isActive = this.element[ 0 ] === this.document[ 0 ].activeElement;
				if ( !isActive ) {
					this.element.trigger( "focus" );
					this.previous = previous;
				}
			}

			// Ensure focus is on (or stays on) the text field
			event.preventDefault();
			checkFocus.call( this );

			if ( this._start( event ) === false ) {
				return;
			}

			this._repeat( null, $( event.currentTarget )
				.hasClass( "ui-spinner-up" ) ? 1 : -1, event );
		},
		"mouseup .ui-spinner-button": "_stop",
		"mouseenter .ui-spinner-button": function( event ) {

			// button will add ui-state-active if mouse was down while mouseleave and kept down
			if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
				return;
			}

			if ( this._start( event ) === false ) {
				return false;
			}
			this._repeat( null, $( event.currentTarget )
				.hasClass( "ui-spinner-up" ) ? 1 : -1, event );
		},

		// TODO: do we really want to consider this a stop?
		// shouldn't we just stop the repeater and wait until mouseup before
		// we trigger the stop event?
		"mouseleave .ui-spinner-button": "_stop"
	},

	// Support mobile enhanced option and make backcompat more sane
	_enhance: function() {
		this.uiSpinner = this.element
			.attr( "autocomplete", "off" )
			.wrap( "<span>" )
			.parent()

				// Add buttons
				.append(
					"<a></a><a></a>"
				);
	},

	_draw: function() {
		this._enhance();

		this._addClass( this.uiSpinner, "ui-spinner", "ui-widget ui-widget-content" );
		this._addClass( "ui-spinner-input" );

		this.element.attr( "role", "spinbutton" );

		// Button bindings
		this.buttons = this.uiSpinner.children( "a" )
			.attr( "tabIndex", -1 )
			.attr( "aria-hidden", true )
			.button( {
				classes: {
					"ui-button": ""
				}
			} );

		// TODO: Right now button does not support classes this is already updated in button PR
		this._removeClass( this.buttons, "ui-corner-all" );

		this._addClass( this.buttons.first(), "ui-spinner-button ui-spinner-up" );
		this._addClass( this.buttons.last(), "ui-spinner-button ui-spinner-down" );
		this.buttons.first().button( {
			"icon": this.options.icons.up,
			"showLabel": false
		} );
		this.buttons.last().button( {
			"icon": this.options.icons.down,
			"showLabel": false
		} );

		// IE 6 doesn't understand height: 50% for the buttons
		// unless the wrapper has an explicit height
		if ( this.buttons.height() > Math.ceil( this.uiSpinner.height() * 0.5 ) &&
				this.uiSpinner.height() > 0 ) {
			this.uiSpinner.height( this.uiSpinner.height() );
		}
	},

	_keydown: function( event ) {
		var options = this.options,
			keyCode = $.ui.keyCode;

		switch ( event.keyCode ) {
		case keyCode.UP:
			this._repeat( null, 1, event );
			return true;
		case keyCode.DOWN:
			this._repeat( null, -1, event );
			return true;
		case keyCode.PAGE_UP:
			this._repeat( null, options.page, event );
			return true;
		case keyCode.PAGE_DOWN:
			this._repeat( null, -options.page, event );
			return true;
		}

		return false;
	},

	_start: function( event ) {
		if ( !this.spinning && this._trigger( "start", event ) === false ) {
			return false;
		}

		if ( !this.counter ) {
			this.counter = 1;
		}
		this.spinning = true;
		return true;
	},

	_repeat: function( i, steps, event ) {
		i = i || 500;

		clearTimeout( this.timer );
		this.timer = this._delay( function() {
			this._repeat( 40, steps, event );
		}, i );

		this._spin( steps * this.options.step, event );
	},

	_spin: function( step, event ) {
		var value = this.value() || 0;

		if ( !this.counter ) {
			this.counter = 1;
		}

		value = this._adjustValue( value + step * this._increment( this.counter ) );

		if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false ) {
			this._value( value );
			this.counter++;
		}
	},

	_increment: function( i ) {
		var incremental = this.options.incremental;

		if ( incremental ) {
			return typeof incremental === "function" ?
				incremental( i ) :
				Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 );
		}

		return 1;
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_adjustValue: function( value ) {
		var base, aboveMin,
			options = this.options;

		// Make sure we're at a valid step
		// - find out where we are relative to the base (min or 0)
		base = options.min !== null ? options.min : 0;
		aboveMin = value - base;

		// - round to the nearest step
		aboveMin = Math.round( aboveMin / options.step ) * options.step;

		// - rounding is based on 0, so adjust back to our base
		value = base + aboveMin;

		// Fix precision from bad JS floating point math
		value = parseFloat( value.toFixed( this._precision() ) );

		// Clamp the value
		if ( options.max !== null && value > options.max ) {
			return options.max;
		}
		if ( options.min !== null && value < options.min ) {
			return options.min;
		}

		return value;
	},

	_stop: function( event ) {
		if ( !this.spinning ) {
			return;
		}

		clearTimeout( this.timer );
		clearTimeout( this.mousewheelTimer );
		this.counter = 0;
		this.spinning = false;
		this._trigger( "stop", event );
	},

	_setOption: function( key, value ) {
		var prevValue, first, last;

		if ( key === "culture" || key === "numberFormat" ) {
			prevValue = this._parse( this.element.val() );
			this.options[ key ] = value;
			this.element.val( this._format( prevValue ) );
			return;
		}

		if ( key === "max" || key === "min" || key === "step" ) {
			if ( typeof value === "string" ) {
				value = this._parse( value );
			}
		}
		if ( key === "icons" ) {
			first = this.buttons.first().find( ".ui-icon" );
			this._removeClass( first, null, this.options.icons.up );
			this._addClass( first, null, value.up );
			last = this.buttons.last().find( ".ui-icon" );
			this._removeClass( last, null, this.options.icons.down );
			this._addClass( last, null, value.down );
		}

		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( this.uiSpinner, null, "ui-state-disabled", !!value );
		this.element.prop( "disabled", !!value );
		this.buttons.button( value ? "disable" : "enable" );
	},

	_setOptions: spinnerModifier( function( options ) {
		this._super( options );
	} ),

	_parse: function( val ) {
		if ( typeof val === "string" && val !== "" ) {
			val = window.Globalize && this.options.numberFormat ?
				Globalize.parseFloat( val, 10, this.options.culture ) : +val;
		}
		return val === "" || isNaN( val ) ? null : val;
	},

	_format: function( value ) {
		if ( value === "" ) {
			return "";
		}
		return window.Globalize && this.options.numberFormat ?
			Globalize.format( value, this.options.numberFormat, this.options.culture ) :
			value;
	},

	_refresh: function() {
		this.element.attr( {
			"aria-valuemin": this.options.min,
			"aria-valuemax": this.options.max,

			// TODO: what should we do with values that can't be parsed?
			"aria-valuenow": this._parse( this.element.val() )
		} );
	},

	isValid: function() {
		var value = this.value();

		// Null is invalid
		if ( value === null ) {
			return false;
		}

		// If value gets adjusted, it's invalid
		return value === this._adjustValue( value );
	},

	// Update the value without triggering change
	_value: function( value, allowAny ) {
		var parsed;
		if ( value !== "" ) {
			parsed = this._parse( value );
			if ( parsed !== null ) {
				if ( !allowAny ) {
					parsed = this._adjustValue( parsed );
				}
				value = this._format( parsed );
			}
		}
		this.element.val( value );
		this._refresh();
	},

	_destroy: function() {
		this.element
			.prop( "disabled", false )
			.removeAttr( "autocomplete role aria-valuemin aria-valuemax aria-valuenow" );

		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: spinnerModifier( function( steps ) {
		this._stepUp( steps );
	} ),
	_stepUp: function( steps ) {
		if ( this._start() ) {
			this._spin( ( steps || 1 ) * this.options.step );
			this._stop();
		}
	},

	stepDown: spinnerModifier( function( steps ) {
		this._stepDown( steps );
	} ),
	_stepDown: function( steps ) {
		if ( this._start() ) {
			this._spin( ( steps || 1 ) * -this.options.step );
			this._stop();
		}
	},

	pageUp: spinnerModifier( function( pages ) {
		this._stepUp( ( pages || 1 ) * this.options.page );
	} ),

	pageDown: spinnerModifier( function( pages ) {
		this._stepDown( ( pages || 1 ) * this.options.page );
	} ),

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		spinnerModifier( this._value ).call( this, newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
} );

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat === true ) {

	// Backcompat for spinner html extension points
	$.widget( "ui.spinner", $.ui.spinner, {
		_enhance: function() {
			this.uiSpinner = this.element
				.attr( "autocomplete", "off" )
				.wrap( this._uiSpinnerHtml() )
				.parent()

					// Add buttons
					.append( this._buttonHtml() );
		},
		_uiSpinnerHtml: function() {
			return "<span>";
		},

		_buttonHtml: function() {
			return "<a></a><a></a>";
		}
	} );
}

var widgetsSpinner = $.ui.spinner;


/*!
 * jQuery UI Tabs 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Tabs
//>>group: Widgets
//>>description: Transforms a set of container elements into a tab structure.
//>>docs: https://api.jqueryui.com/tabs/
//>>demos: https://jqueryui.com/tabs/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/tabs.css
//>>css.theme: ../../themes/base/theme.css


$.widget( "ui.tabs", {
	version: "1.14.0",
	delay: 300,
	options: {
		active: null,
		classes: {
			"ui-tabs": "ui-corner-all",
			"ui-tabs-nav": "ui-corner-all",
			"ui-tabs-panel": "ui-corner-bottom",
			"ui-tabs-tab": "ui-corner-top"
		},
		collapsible: false,
		event: "click",
		heightStyle: "content",
		hide: null,
		show: null,

		// Callbacks
		activate: null,
		beforeActivate: null,
		beforeLoad: null,
		load: null
	},

	_isLocal: ( function() {
		var rhash = /#.*$/;

		return function( anchor ) {
			var anchorUrl, locationUrl;

			anchorUrl = anchor.href.replace( rhash, "" );
			locationUrl = location.href.replace( rhash, "" );

			// Decoding may throw an error if the URL isn't UTF-8 (#9518)
			try {
				anchorUrl = decodeURIComponent( anchorUrl );
			} catch ( error ) {}
			try {
				locationUrl = decodeURIComponent( locationUrl );
			} catch ( error ) {}

			return anchor.hash.length > 1 && anchorUrl === locationUrl;
		};
	} )(),

	_create: function() {
		var that = this,
			options = this.options;

		this.running = false;

		this._addClass( "ui-tabs", "ui-widget ui-widget-content" );
		this._toggleClass( "ui-tabs-collapsible", null, options.collapsible );

		this._processTabs();
		options.active = this._initialActive();

		// Take disabling tabs via class attribute from HTML
		// into account and update option properly.
		if ( Array.isArray( options.disabled ) ) {
			options.disabled = $.uniqueSort( options.disabled.concat(
				$.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
					return that.tabs.index( li );
				} )
			) ).sort();
		}

		// Check for length avoids error when initializing empty list
		if ( this.options.active !== false && this.anchors.length ) {
			this.active = this._findActive( options.active );
		} else {
			this.active = $();
		}

		this._refresh();

		if ( this.active.length ) {
			this.load( options.active );
		}
	},

	_initialActive: function() {
		var active = this.options.active,
			collapsible = this.options.collapsible,
			locationHash = location.hash.substring( 1 );

		if ( active === null ) {

			// check the fragment identifier in the URL
			if ( locationHash ) {
				this.tabs.each( function( i, tab ) {
					if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
						active = i;
						return false;
					}
				} );
			}

			// Check for a tab marked active via a class
			if ( active === null ) {
				active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
			}

			// No active tab, set to false
			if ( active === null || active === -1 ) {
				active = this.tabs.length ? 0 : false;
			}
		}

		// Handle numbers: negative, out of range
		if ( active !== false ) {
			active = this.tabs.index( this.tabs.eq( active ) );
			if ( active === -1 ) {
				active = collapsible ? false : 0;
			}
		}

		// Don't allow collapsible: false and active: false
		if ( !collapsible && active === false && this.anchors.length ) {
			active = 0;
		}

		return active;
	},

	_getCreateEventData: function() {
		return {
			tab: this.active,
			panel: !this.active.length ? $() : this._getPanelForTab( this.active )
		};
	},

	_tabKeydown: function( event ) {
		var focusedTab = $( this.document[ 0 ].activeElement ).closest( "li" ),
			selectedIndex = this.tabs.index( focusedTab ),
			goingForward = true;

		if ( this._handlePageNav( event ) ) {
			return;
		}

		switch ( event.keyCode ) {
		case $.ui.keyCode.RIGHT:
		case $.ui.keyCode.DOWN:
			selectedIndex++;
			break;
		case $.ui.keyCode.UP:
		case $.ui.keyCode.LEFT:
			goingForward = false;
			selectedIndex--;
			break;
		case $.ui.keyCode.END:
			selectedIndex = this.anchors.length - 1;
			break;
		case $.ui.keyCode.HOME:
			selectedIndex = 0;
			break;
		case $.ui.keyCode.SPACE:

			// Activate only, no collapsing
			event.preventDefault();
			clearTimeout( this.activating );
			this._activate( selectedIndex );
			return;
		case $.ui.keyCode.ENTER:

			// Toggle (cancel delayed activation, allow collapsing)
			event.preventDefault();
			clearTimeout( this.activating );

			// Determine if we should collapse or activate
			this._activate( selectedIndex === this.options.active ? false : selectedIndex );
			return;
		default:
			return;
		}

		// Focus the appropriate tab, based on which key was pressed
		event.preventDefault();
		clearTimeout( this.activating );
		selectedIndex = this._focusNextTab( selectedIndex, goingForward );

		// Navigating with control/command key will prevent automatic activation
		if ( !event.ctrlKey && !event.metaKey ) {

			// Update aria-selected immediately so that AT think the tab is already selected.
			// Otherwise AT may confuse the user by stating that they need to activate the tab,
			// but the tab will already be activated by the time the announcement finishes.
			focusedTab.attr( "aria-selected", "false" );
			this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );

			this.activating = this._delay( function() {
				this.option( "active", selectedIndex );
			}, this.delay );
		}
	},

	_panelKeydown: function( event ) {
		if ( this._handlePageNav( event ) ) {
			return;
		}

		// Ctrl+up moves focus to the current tab
		if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
			event.preventDefault();
			this.active.trigger( "focus" );
		}
	},

	// Alt+page up/down moves focus to the previous/next tab (and activates)
	_handlePageNav: function( event ) {
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
			this._activate( this._focusNextTab( this.options.active - 1, false ) );
			return true;
		}
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
			this._activate( this._focusNextTab( this.options.active + 1, true ) );
			return true;
		}
	},

	_findNextTab: function( index, goingForward ) {
		var lastTabIndex = this.tabs.length - 1;

		function constrain() {
			if ( index > lastTabIndex ) {
				index = 0;
			}
			if ( index < 0 ) {
				index = lastTabIndex;
			}
			return index;
		}

		while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
			index = goingForward ? index + 1 : index - 1;
		}

		return index;
	},

	_focusNextTab: function( index, goingForward ) {
		index = this._findNextTab( index, goingForward );
		this.tabs.eq( index ).trigger( "focus" );
		return index;
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {

			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		this._super( key, value );

		if ( key === "collapsible" ) {
			this._toggleClass( "ui-tabs-collapsible", null, value );

			// Setting collapsible: false while collapsed; open first panel
			if ( !value && this.options.active === false ) {
				this._activate( 0 );
			}
		}

		if ( key === "event" ) {
			this._setupEvents( value );
		}

		if ( key === "heightStyle" ) {
			this._setupHeightStyle( value );
		}
	},

	_sanitizeSelector: function( hash ) {
		return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
	},

	refresh: function() {
		var options = this.options,
			lis = this.tablist.children( ":has(a[href])" );

		// Get disabled tabs from class attribute from HTML
		// this will get converted to a boolean if needed in _refresh()
		options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
			return lis.index( tab );
		} );

		this._processTabs();

		// Was collapsed or no tabs
		if ( options.active === false || !this.anchors.length ) {
			options.active = false;
			this.active = $();

		// was active, but active tab is gone
		} else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {

			// all remaining tabs are disabled
			if ( this.tabs.length === options.disabled.length ) {
				options.active = false;
				this.active = $();

			// activate previous tab
			} else {
				this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
			}

		// was active, active tab still exists
		} else {

			// make sure active index is correct
			options.active = this.tabs.index( this.active );
		}

		this._refresh();
	},

	_refresh: function() {
		this._setOptionDisabled( this.options.disabled );
		this._setupEvents( this.options.event );
		this._setupHeightStyle( this.options.heightStyle );

		this.tabs.not( this.active ).attr( {
			"aria-selected": "false",
			"aria-expanded": "false",
			tabIndex: -1
		} );
		this.panels.not( this._getPanelForTab( this.active ) )
			.hide()
			.attr( {
				"aria-hidden": "true"
			} );

		// Make sure one tab is in the tab order
		if ( !this.active.length ) {
			this.tabs.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active
				.attr( {
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				} );
			this._addClass( this.active, "ui-tabs-active", "ui-state-active" );
			this._getPanelForTab( this.active )
				.show()
				.attr( {
					"aria-hidden": "false"
				} );
		}
	},

	_processTabs: function() {
		var that = this,
			prevTabs = this.tabs,
			prevAnchors = this.anchors,
			prevPanels = this.panels;

		this.tablist = this._getList().attr( "role", "tablist" );
		this._addClass( this.tablist, "ui-tabs-nav",
			"ui-helper-reset ui-helper-clearfix ui-widget-header" );

		// Prevent users from focusing disabled tabs via click
		this.tablist
			.on( "mousedown" + this.eventNamespace, "> li", function( event ) {
				if ( $( this ).is( ".ui-state-disabled" ) ) {
					event.preventDefault();
				}
			} );

		this.tabs = this.tablist.find( "> li:has(a[href])" )
			.attr( {
				role: "tab",
				tabIndex: -1
			} );
		this._addClass( this.tabs, "ui-tabs-tab", "ui-state-default" );

		this.anchors = this.tabs.map( function() {
			return $( "a", this )[ 0 ];
		} )
			.attr( {
				tabIndex: -1
			} );
		this._addClass( this.anchors, "ui-tabs-anchor" );

		this.panels = $();

		this.anchors.each( function( i, anchor ) {
			var selector, panel, panelId,
				anchorId = $( anchor ).uniqueId().attr( "id" ),
				tab = $( anchor ).closest( "li" ),
				originalAriaControls = tab.attr( "aria-controls" );

			// Inline tab
			if ( that._isLocal( anchor ) ) {
				selector = anchor.hash;
				panelId = selector.substring( 1 );
				panel = that.element.find( that._sanitizeSelector( selector ) );

			// remote tab
			} else {

				// If the tab doesn't already have aria-controls,
				// generate an id by using a throw-away element
				panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id;
				selector = "#" + panelId;
				panel = that.element.find( selector );
				if ( !panel.length ) {
					panel = that._createPanel( panelId );
					panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
				}
				panel.attr( "aria-live", "polite" );
			}

			if ( panel.length ) {
				that.panels = that.panels.add( panel );
			}
			if ( originalAriaControls ) {
				tab.data( "ui-tabs-aria-controls", originalAriaControls );
			}
			tab.attr( {
				"aria-controls": panelId,
				"aria-labelledby": anchorId
			} );
			panel.attr( "aria-labelledby", anchorId );
		} );

		this.panels.attr( "role", "tabpanel" );
		this._addClass( this.panels, "ui-tabs-panel", "ui-widget-content" );

		// Avoid memory leaks (#10056)
		if ( prevTabs ) {
			this._off( prevTabs.not( this.tabs ) );
			this._off( prevAnchors.not( this.anchors ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	// Allow overriding how to find the list for rare usage scenarios (#7715)
	_getList: function() {
		return this.tablist || this.element.find( "ol, ul" ).eq( 0 );
	},

	_createPanel: function( id ) {
		return $( "<div>" )
			.attr( "id", id )
			.data( "ui-tabs-destroy", true );
	},

	_setOptionDisabled: function( disabled ) {
		var currentItem, li, i;

		if ( Array.isArray( disabled ) ) {
			if ( !disabled.length ) {
				disabled = false;
			} else if ( disabled.length === this.anchors.length ) {
				disabled = true;
			}
		}

		// Disable tabs
		for ( i = 0; ( li = this.tabs[ i ] ); i++ ) {
			currentItem = $( li );
			if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
				currentItem.attr( "aria-disabled", "true" );
				this._addClass( currentItem, null, "ui-state-disabled" );
			} else {
				currentItem.removeAttr( "aria-disabled" );
				this._removeClass( currentItem, null, "ui-state-disabled" );
			}
		}

		this.options.disabled = disabled;

		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null,
			disabled === true );
	},

	_setupEvents: function( event ) {
		var events = {};
		if ( event ) {
			$.each( event.split( " " ), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			} );
		}

		this._off( this.anchors.add( this.tabs ).add( this.panels ) );

		// Always prevent the default action, even when disabled
		this._on( true, this.anchors, {
			click: function( event ) {
				event.preventDefault();
			}
		} );
		this._on( this.anchors, events );
		this._on( this.tabs, { keydown: "_tabKeydown" } );
		this._on( this.panels, { keydown: "_panelKeydown" } );

		this._focusable( this.tabs );
		this._hoverable( this.tabs );
	},

	_setupHeightStyle: function( heightStyle ) {
		var maxHeight,
			parent = this.element.parent();

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			maxHeight -= this.element.outerHeight() - this.element.height();

			this.element.siblings( ":visible" ).each( function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			} );

			this.element.children().not( this.panels ).each( function() {
				maxHeight -= $( this ).outerHeight( true );
			} );

			this.panels.each( function() {
				$( this ).height( Math.max( 0, maxHeight -
					$( this ).innerHeight() + $( this ).height() ) );
			} )
				.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.panels.each( function() {
				maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
			} ).height( maxHeight );
		}
	},

	_eventHandler: function( event ) {
		var options = this.options,
			active = this.active,
			anchor = $( event.currentTarget ),
			tab = anchor.closest( "li" ),
			clickedIsActive = tab[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : this._getPanelForTab( tab ),
			toHide = !active.length ? $() : this._getPanelForTab( active ),
			eventData = {
				oldTab: active,
				oldPanel: toHide,
				newTab: collapsing ? $() : tab,
				newPanel: toShow
			};

		event.preventDefault();

		if ( tab.hasClass( "ui-state-disabled" ) ||

				// tab is already loading
				tab.hasClass( "ui-tabs-loading" ) ||

				// can't switch durning an animation
				this.running ||

				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||

				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.tabs.index( tab );

		this.active = clickedIsActive ? $() : tab;
		if ( this.xhr ) {
			this.xhr.abort();
		}

		if ( !toHide.length && !toShow.length ) {
			$.error( "jQuery UI Tabs: Mismatching fragment identifier." );
		}

		if ( toShow.length ) {
			this.load( this.tabs.index( tab ), event );
		}
		this._toggle( event, eventData );
	},

	// Handles show/hide for selecting tabs
	_toggle: function( event, eventData ) {
		var that = this,
			toShow = eventData.newPanel,
			toHide = eventData.oldPanel;

		this.running = true;

		function complete() {
			that.running = false;
			that._trigger( "activate", event, eventData );
		}

		function show() {
			that._addClass( eventData.newTab.closest( "li" ), "ui-tabs-active", "ui-state-active" );

			if ( toShow.length && that.options.show ) {
				that._show( toShow, that.options.show, complete );
			} else {
				toShow.show();
				complete();
			}
		}

		// Start out by hiding, then showing, then completing
		if ( toHide.length && this.options.hide ) {
			this._hide( toHide, this.options.hide, function() {
				that._removeClass( eventData.oldTab.closest( "li" ),
					"ui-tabs-active", "ui-state-active" );
				show();
			} );
		} else {
			this._removeClass( eventData.oldTab.closest( "li" ),
				"ui-tabs-active", "ui-state-active" );
			toHide.hide();
			show();
		}

		toHide.attr( "aria-hidden", "true" );
		eventData.oldTab.attr( {
			"aria-selected": "false",
			"aria-expanded": "false"
		} );

		// If we're switching tabs, remove the old tab from the tab order.
		// If we're opening from collapsed state, remove the previous tab from the tab order.
		// If we're collapsing, then keep the collapsing tab in the tab order.
		if ( toShow.length && toHide.length ) {
			eventData.oldTab.attr( "tabIndex", -1 );
		} else if ( toShow.length ) {
			this.tabs.filter( function() {
				return $( this ).attr( "tabIndex" ) === 0;
			} )
				.attr( "tabIndex", -1 );
		}

		toShow.attr( "aria-hidden", "false" );
		eventData.newTab.attr( {
			"aria-selected": "true",
			"aria-expanded": "true",
			tabIndex: 0
		} );
	},

	_activate: function( index ) {
		var anchor,
			active = this._findActive( index );

		// Trying to activate the already active panel
		if ( active[ 0 ] === this.active[ 0 ] ) {
			return;
		}

		// Trying to collapse, simulate a click on the current active header
		if ( !active.length ) {
			active = this.active;
		}

		anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
		this._eventHandler( {
			target: anchor,
			currentTarget: anchor,
			preventDefault: $.noop
		} );
	},

	_findActive: function( index ) {
		return index === false ? $() : this.tabs.eq( index );
	},

	_getIndex: function( index ) {

		// meta-function to give users option to provide a href string instead of a numerical index.
		if ( typeof index === "string" ) {
			index = this.anchors.index( this.anchors.filter( "[href$='" +
				CSS.escape( index ) + "']" ) );
		}

		return index;
	},

	_destroy: function() {
		if ( this.xhr ) {
			this.xhr.abort();
		}

		this.tablist
			.removeAttr( "role" )
			.off( this.eventNamespace );

		this.anchors
			.removeAttr( "role tabIndex" )
			.removeUniqueId();

		this.tabs.add( this.panels ).each( function() {
			if ( $.data( this, "ui-tabs-destroy" ) ) {
				$( this ).remove();
			} else {
				$( this ).removeAttr( "role tabIndex " +
					"aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded" );
			}
		} );

		this.tabs.each( function() {
			var li = $( this ),
				prev = li.data( "ui-tabs-aria-controls" );
			if ( prev ) {
				li
					.attr( "aria-controls", prev )
					.removeData( "ui-tabs-aria-controls" );
			} else {
				li.removeAttr( "aria-controls" );
			}
		} );

		this.panels.show();

		if ( this.options.heightStyle !== "content" ) {
			this.panels.css( "height", "" );
		}
	},

	enable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === false ) {
			return;
		}

		if ( index === undefined ) {
			disabled = false;
		} else {
			index = this._getIndex( index );
			if ( Array.isArray( disabled ) ) {
				disabled = $.map( disabled, function( num ) {
					return num !== index ? num : null;
				} );
			} else {
				disabled = $.map( this.tabs, function( li, num ) {
					return num !== index ? num : null;
				} );
			}
		}
		this._setOptionDisabled( disabled );
	},

	disable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === true ) {
			return;
		}

		if ( index === undefined ) {
			disabled = true;
		} else {
			index = this._getIndex( index );
			if ( $.inArray( index, disabled ) !== -1 ) {
				return;
			}
			if ( Array.isArray( disabled ) ) {
				disabled = $.merge( [ index ], disabled ).sort();
			} else {
				disabled = [ index ];
			}
		}
		this._setOptionDisabled( disabled );
	},

	load: function( index, event ) {
		index = this._getIndex( index );
		var that = this,
			tab = this.tabs.eq( index ),
			anchor = tab.find( ".ui-tabs-anchor" ),
			panel = this._getPanelForTab( tab ),
			eventData = {
				tab: tab,
				panel: panel
			},
			complete = function( jqXHR, status ) {
				if ( status === "abort" ) {
					that.panels.stop( false, true );
				}

				that._removeClass( tab, "ui-tabs-loading" );
				panel.removeAttr( "aria-busy" );

				if ( jqXHR === that.xhr ) {
					delete that.xhr;
				}
			};

		// Not remote
		if ( this._isLocal( anchor[ 0 ] ) ) {
			return;
		}

		this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );

		if ( this.xhr.statusText !== "canceled" ) {
			this._addClass( tab, "ui-tabs-loading" );
			panel.attr( "aria-busy", "true" );

			this.xhr
				.done( function( response, status, jqXHR ) {
					panel.html( response );
					that._trigger( "load", event, eventData );

					complete( jqXHR, status );
				} )
				.fail( function( jqXHR, status ) {
					complete( jqXHR, status );
				} );
		}
	},

	_ajaxSettings: function( anchor, event, eventData ) {
		var that = this;
		return {
			url: anchor.attr( "href" ),
			beforeSend: function( jqXHR, settings ) {
				return that._trigger( "beforeLoad", event,
					$.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) );
			}
		};
	},

	_getPanelForTab: function( tab ) {
		var id = $( tab ).attr( "aria-controls" );
		return this.element.find( this._sanitizeSelector( "#" + id ) );
	}
} );

// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat === true ) {

	// Backcompat for ui-tab class (now ui-tabs-tab)
	$.widget( "ui.tabs", $.ui.tabs, {
		_processTabs: function() {
			this._superApply( arguments );
			this._addClass( this.tabs, "ui-tab" );
		}
	} );
}

var widgetsTabs = $.ui.tabs;


/*!
 * jQuery UI Tooltip 1.14.0
 * https://jqueryui.com
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * https://jquery.org/license
 */

//>>label: Tooltip
//>>group: Widgets
//>>description: Shows additional information for any element on hover or focus.
//>>docs: https://api.jqueryui.com/tooltip/
//>>demos: https://jqueryui.com/tooltip/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/tooltip.css
//>>css.theme: ../../themes/base/theme.css


$.widget( "ui.tooltip", {
	version: "1.14.0",
	options: {
		classes: {
			"ui-tooltip": "ui-corner-all ui-widget-shadow"
		},
		content: function() {
			var title = $( this ).attr( "title" );

			// Escape title, since we're going from an attribute to raw HTML
			return $( "<a>" ).text( title ).html();
		},
		hide: true,

		// Disabled elements have inconsistent behavior across browsers (#8661)
		items: "[title]:not([disabled])",
		position: {
			my: "left top+15",
			at: "left bottom",
			collision: "flipfit flip"
		},
		show: true,
		track: false,

		// Callbacks
		close: null,
		open: null
	},

	_addDescribedBy: function( elem, id ) {
		var describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ );
		describedby.push( id );
		elem
			.data( "ui-tooltip-id", id )
			.attr( "aria-describedby", String.prototype.trim.call( describedby.join( " " ) ) );
	},

	_removeDescribedBy: function( elem ) {
		var id = elem.data( "ui-tooltip-id" ),
			describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ ),
			index = $.inArray( id, describedby );

		if ( index !== -1 ) {
			describedby.splice( index, 1 );
		}

		elem.removeData( "ui-tooltip-id" );
		describedby = String.prototype.trim.call( describedby.join( " " ) );
		if ( describedby ) {
			elem.attr( "aria-describedby", describedby );
		} else {
			elem.removeAttr( "aria-describedby" );
		}
	},

	_create: function() {
		this._on( {
			mouseover: "open",
			focusin: "open"
		} );

		// IDs of generated tooltips, needed for destroy
		this.tooltips = {};

		// IDs of parent tooltips where we removed the title attribute
		this.parents = {};

		// Append the aria-live region so tooltips announce correctly
		this.liveRegion = $( "<div>" )
			.attr( {
				role: "log",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			} )
			.appendTo( this.document[ 0 ].body );
		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		this.disabledTitles = $( [] );
	},

	_setOption: function( key, value ) {
		var that = this;

		this._super( key, value );

		if ( key === "content" ) {
			$.each( this.tooltips, function( id, tooltipData ) {
				that._updateContent( tooltipData.element );
			} );
		}
	},

	_setOptionDisabled: function( value ) {
		this[ value ? "_disable" : "_enable" ]();
	},

	_disable: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			var event = $.Event( "blur" );
			event.target = event.currentTarget = tooltipData.element[ 0 ];
			that.close( event, true );
		} );

		// Remove title attributes to prevent native tooltips
		this.disabledTitles = this.disabledTitles.add(
			this.element.find( this.options.items ).addBack()
				.filter( function() {
					var element = $( this );
					if ( element.is( "[title]" ) ) {
						return element
							.data( "ui-tooltip-title", element.attr( "title" ) )
							.removeAttr( "title" );
					}
				} )
		);
	},

	_enable: function() {

		// restore title attributes
		this.disabledTitles.each( function() {
			var element = $( this );
			if ( element.data( "ui-tooltip-title" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
			}
		} );
		this.disabledTitles = $( [] );
	},

	open: function( event ) {
		var that = this,
			target = $( event ? event.target : this.element )

				// we need closest here due to mouseover bubbling,
				// but always pointing at the same event target
				.closest( this.options.items );

		// No element to show a tooltip for or the tooltip is already open
		if ( !target.length || target.data( "ui-tooltip-id" ) ) {
			return;
		}

		if ( target.attr( "title" ) ) {
			target.data( "ui-tooltip-title", target.attr( "title" ) );
		}

		target.data( "ui-tooltip-open", true );

		// Kill parent tooltips, custom or native, for hover
		if ( event && event.type === "mouseover" ) {
			target.parents().each( function() {
				var parent = $( this ),
					blurEvent;
				if ( parent.data( "ui-tooltip-open" ) ) {
					blurEvent = $.Event( "blur" );
					blurEvent.target = blurEvent.currentTarget = this;
					that.close( blurEvent, true );
				}
				if ( parent.attr( "title" ) ) {
					parent.uniqueId();
					that.parents[ this.id ] = {
						element: this,
						title: parent.attr( "title" )
					};
					parent.attr( "title", "" );
				}
			} );
		}

		this._registerCloseHandlers( event, target );
		this._updateContent( target, event );
	},

	_updateContent: function( target, event ) {
		var content,
			contentOption = this.options.content,
			that = this,
			eventType = event ? event.type : null;

		if ( typeof contentOption === "string" || contentOption.nodeType ||
				contentOption.jquery ) {
			return this._open( event, target, contentOption );
		}

		content = contentOption.call( target[ 0 ], function( response ) {

			// Ignore async response if tooltip was closed already
			if ( !target.data( "ui-tooltip-open" ) ) {
				return;
			}

			// JQuery creates a special event for focusin when it doesn't
			// exist natively. To improve performance, the native event
			// object is reused and the type is changed. Therefore, we can't
			// rely on the type being correct after the event finished
			// bubbling, so we set it back to the previous value. (#8740)
			if ( event ) {
				event.type = eventType;
			}
			that._open( event, target, response );
		} );
		if ( content ) {
			this._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		var tooltipData, tooltip, delayedShow, a11yContent,
			positionOption = $.extend( {}, this.options.position );

		if ( !content ) {
			return;
		}

		// Content can be updated multiple times. If the tooltip already
		// exists, then just update the content and bail.
		tooltipData = this._find( target );
		if ( tooltipData ) {
			tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
			return;
		}

		// If we have a title, clear it to prevent the native tooltip
		// we have to check first to avoid defining a title if none exists
		// (we don't want to cause an element to start matching [title])
		//
		// We use removeAttr only for key events, to allow IE to export the correct
		// accessible attributes. For mouse events, set to empty string to avoid
		// native tooltip showing up (happens only when removing inside mouseover).
		if ( target.is( "[title]" ) ) {
			if ( event && event.type === "mouseover" ) {
				target.attr( "title", "" );
			} else {
				target.removeAttr( "title" );
			}
		}

		tooltipData = this._tooltip( target );
		tooltip = tooltipData.tooltip;
		this._addDescribedBy( target, tooltip.attr( "id" ) );
		tooltip.find( ".ui-tooltip-content" ).html( content );

		// Support: Voiceover on OS X, JAWS on IE <= 9
		// JAWS announces deletions even when aria-relevant="additions"
		// Voiceover will sometimes re-read the entire log region's contents from the beginning
		this.liveRegion.children().hide();
		a11yContent = $( "<div>" ).html( tooltip.find( ".ui-tooltip-content" ).html() );
		a11yContent.removeAttr( "name" ).find( "[name]" ).removeAttr( "name" );
		a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
		a11yContent.appendTo( this.liveRegion );

		function position( event ) {
			positionOption.of = event;
			if ( tooltip.is( ":hidden" ) ) {
				return;
			}
			tooltip.position( positionOption );
		}
		if ( this.options.track && event && /^mouse/.test( event.type ) ) {
			this._on( this.document, {
				mousemove: position
			} );

			// trigger once to override element-relative positioning
			position( event );
		} else {
			tooltip.position( $.extend( {
				of: target
			}, this.options.position ) );
		}

		tooltip.hide();

		this._show( tooltip, this.options.show );

		// Handle tracking tooltips that are shown with a delay (#8644). As soon
		// as the tooltip is visible, position the tooltip using the most recent
		// event.
		// Adds the check to add the timers only when both delay and track options are set (#14682)
		if ( this.options.track && this.options.show && this.options.show.delay ) {
			delayedShow = this.delayedShow = setInterval( function() {
				if ( tooltip.is( ":visible" ) ) {
					position( positionOption.of );
					clearInterval( delayedShow );
				}
			}, 13 );
		}

		this._trigger( "open", event, { tooltip: tooltip } );
	},

	_registerCloseHandlers: function( event, target ) {
		var events = {
			keyup: function( event ) {
				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
					var fakeEvent = $.Event( event );
					fakeEvent.currentTarget = target[ 0 ];
					this.close( fakeEvent, true );
				}
			}
		};

		// Only bind remove handler for delegated targets. Non-delegated
		// tooltips will handle this in destroy.
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			events.remove = function() {
				var targetElement = this._find( target );
				if ( targetElement ) {
					this._removeTooltip( targetElement.tooltip );
				}
			};
		}

		if ( !event || event.type === "mouseover" ) {
			events.mouseleave = "close";
		}
		if ( !event || event.type === "focusin" ) {
			events.focusout = "close";
		}
		this._on( true, target, events );
	},

	close: function( event ) {
		var tooltip,
			that = this,
			target = $( event ? event.currentTarget : this.element ),
			tooltipData = this._find( target );

		// The tooltip may already be closed
		if ( !tooltipData ) {

			// We set ui-tooltip-open immediately upon open (in open()), but only set the
			// additional data once there's actually content to show (in _open()). So even if the
			// tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
			// the period between open() and _open().
			target.removeData( "ui-tooltip-open" );
			return;
		}

		tooltip = tooltipData.tooltip;

		// Disabling closes the tooltip, so we need to track when we're closing
		// to avoid an infinite loop in case the tooltip becomes disabled on close
		if ( tooltipData.closing ) {
			return;
		}

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		// Only set title if we had one before (see comment in _open())
		// If the title attribute has changed since open(), don't restore
		if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
			target.attr( "title", target.data( "ui-tooltip-title" ) );
		}

		this._removeDescribedBy( target );

		tooltipData.hiding = true;
		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			that._removeTooltip( $( this ) );
		} );

		target.removeData( "ui-tooltip-open" );
		this._off( target, "mouseleave focusout keyup" );

		// Remove 'remove' binding only on delegated targets
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			this._off( target, "remove" );
		}
		this._off( this.document, "mousemove" );

		if ( event && event.type === "mouseleave" ) {
			$.each( this.parents, function( id, parent ) {
				$( parent.element ).attr( "title", parent.title );
				delete that.parents[ id ];
			} );
		}

		tooltipData.closing = true;
		this._trigger( "close", event, { tooltip: tooltip } );
		if ( !tooltipData.hiding ) {
			tooltipData.closing = false;
		}
	},

	_tooltip: function( element ) {
		var tooltip = $( "<div>" ).attr( "role", "tooltip" ),
			content = $( "<div>" ).appendTo( tooltip ),
			id = tooltip.uniqueId().attr( "id" );

		this._addClass( content, "ui-tooltip-content" );
		this._addClass( tooltip, "ui-tooltip", "ui-widget ui-widget-content" );

		tooltip.appendTo( this._appendTo( element ) );

		return this.tooltips[ id ] = {
			element: element,
			tooltip: tooltip
		};
	},

	_find: function( target ) {
		var id = target.data( "ui-tooltip-id" );
		return id ? this.tooltips[ id ] : null;
	},

	_removeTooltip: function( tooltip ) {

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		tooltip.remove();
		delete this.tooltips[ tooltip.attr( "id" ) ];
	},

	_appendTo: function( target ) {
		var element = target.closest( ".ui-front, dialog" );

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_destroy: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {

			// Delegate to close method to handle common cleanup
			var event = $.Event( "blur" ),
				element = tooltipData.element;
			event.target = event.currentTarget = element[ 0 ];
			that.close( event, true );

			// Remove immediately; destroying an open tooltip doesn't use the
			// hide animation
			$( "#" + id ).remove();

			// Restore the title
			if ( element.data( "ui-tooltip-title" ) ) {

				// If the title attribute has changed since open(), don't restore
				if ( !element.attr( "title" ) ) {
					element.attr( "title", element.data( "ui-tooltip-title" ) );
				}
				element.removeData( "ui-tooltip-title" );
			}
		} );
		this.liveRegion.remove();
	}
} );

// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat === true ) {

	// Backcompat for tooltipClass option
	$.widget( "ui.tooltip", $.ui.tooltip, {
		options: {
			tooltipClass: null
		},
		_tooltip: function() {
			var tooltipData = this._superApply( arguments );
			if ( this.options.tooltipClass ) {
				tooltipData.tooltip.addClass( this.options.tooltipClass );
			}
			return tooltipData;
		}
	} );
}

var widgetsTooltip = $.ui.tooltip;




} );

/* ========================================
 FILE: /includes/js/jquery/jquery-ui-1.14.0/jquery-ui-i18n.js
 ==================== */

/*! jQuery UI - v1.8.24 - 2012-09-28
* https://github.com/jquery/jquery-ui
* Includes: jquery.ui.datepicker-af.js, jquery.ui.datepicker-ar-DZ.js, jquery.ui.datepicker-ar.js, jquery.ui.datepicker-az.js, jquery.ui.datepicker-bg.js, jquery.ui.datepicker-bs.js, jquery.ui.datepicker-ca.js, jquery.ui.datepicker-cs.js, jquery.ui.datepicker-cy-GB.js, jquery.ui.datepicker-da.js, jquery.ui.datepicker-de.js, jquery.ui.datepicker-el.js, jquery.ui.datepicker-en-AU.js, jquery.ui.datepicker-en-GB.js, jquery.ui.datepicker-en-NZ.js, jquery.ui.datepicker-eo.js, jquery.ui.datepicker-es.js, jquery.ui.datepicker-et.js, jquery.ui.datepicker-eu.js, jquery.ui.datepicker-fa.js, jquery.ui.datepicker-fi.js, jquery.ui.datepicker-fo.js, jquery.ui.datepicker-fr-CH.js, jquery.ui.datepicker-fr.js, jquery.ui.datepicker-gl.js, jquery.ui.datepicker-he.js, jquery.ui.datepicker-hi.js, jquery.ui.datepicker-hr.js, jquery.ui.datepicker-hu.js, jquery.ui.datepicker-hy.js, jquery.ui.datepicker-id.js, jquery.ui.datepicker-is.js, jquery.ui.datepicker-it.js, jquery.ui.datepicker-ja.js, jquery.ui.datepicker-ka.js, jquery.ui.datepicker-kk.js, jquery.ui.datepicker-km.js, jquery.ui.datepicker-ko.js, jquery.ui.datepicker-lb.js, jquery.ui.datepicker-lt.js, jquery.ui.datepicker-lv.js, jquery.ui.datepicker-mk.js, jquery.ui.datepicker-ml.js, jquery.ui.datepicker-ms.js, jquery.ui.datepicker-nl-BE.js, jquery.ui.datepicker-nl.js, jquery.ui.datepicker-no.js, jquery.ui.datepicker-pl.js, jquery.ui.datepicker-pt-BR.js, jquery.ui.datepicker-pt.js, jquery.ui.datepicker-rm.js, jquery.ui.datepicker-ro.js, jquery.ui.datepicker-ru.js, jquery.ui.datepicker-sk.js, jquery.ui.datepicker-sl.js, jquery.ui.datepicker-sq.js, jquery.ui.datepicker-sr-SR.js, jquery.ui.datepicker-sr.js, jquery.ui.datepicker-sv.js, jquery.ui.datepicker-ta.js, jquery.ui.datepicker-th.js, jquery.ui.datepicker-tj.js, jquery.ui.datepicker-tr.js, jquery.ui.datepicker-uk.js, jquery.ui.datepicker-vi.js, jquery.ui.datepicker-zh-CN.js, jquery.ui.datepicker-zh-HK.js, jquery.ui.datepicker-zh-TW.js
* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */

/* Afrikaans initialisation for the jQuery UI date picker plugin. */
/* Written by Renier Pretorius. */
jQuery(function($){
	$.datepicker.regional['af'] = {
		closeText: 'Selekteer',
		prevText: 'Vorige',
		nextText: 'Volgende',
		currentText: 'Vandag',
		monthNames: ['Januarie','Februarie','Maart','April','Mei','Junie',
		'Julie','Augustus','September','Oktober','November','Desember'],
		monthNamesShort: ['Jan', 'Feb', 'Mrt', 'Apr', 'Mei', 'Jun',
		'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'],
		dayNames: ['Sondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrydag', 'Saterdag'],
		dayNamesShort: ['Son', 'Maa', 'Din', 'Woe', 'Don', 'Vry', 'Sat'],
		dayNamesMin: ['So','Ma','Di','Wo','Do','Vr','Sa'],
		weekHeader: 'Wk',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['af']);
});

/* Algerian Arabic Translation for jQuery UI date picker plugin. (can be used for Tunisia)*/
/* Mohamed Cherif BOUCHELAGHEM -- cherifbouchelaghem@yahoo.fr */

jQuery(function($){
	$.datepicker.regional['ar-DZ'] = {
		closeText: 'إغلاق',
		prevText: '&#x3c;السابق',
		nextText: 'التالي&#x3e;',
		currentText: 'اليوم',
		monthNames: ['جانفي', 'فيفري', 'مارس', 'أفريل', 'ماي', 'جوان',
		'جويلية', 'أوت', 'سبتمبر','أكتوبر', 'نوفمبر', 'ديسمبر'],
		monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
		dayNames: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
		dayNamesShort: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
		dayNamesMin: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
		weekHeader: 'أسبوع',
		dateFormat: 'dd/mm/yy',
		firstDay: 6,
  		isRTL: true,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ar-DZ']);
});

/* Arabic Translation for jQuery UI date picker plugin. */
/* Khaled Alhourani -- me@khaledalhourani.com */
/* NOTE: monthNames are the original months names and they are the Arabic names, not the new months name فبراير - يناير and there isn't any Arabic roots for these months */
jQuery(function($){
	$.datepicker.regional['ar'] = {
		closeText: 'إغلاق',
		prevText: '&#x3c;السابق',
		nextText: 'التالي&#x3e;',
		currentText: 'اليوم',
		monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'مايو', 'حزيران',
		'تموز', 'آب', 'أيلول',	'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
		monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
		dayNames: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
		dayNamesShort: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'],
		dayNamesMin: ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
		weekHeader: 'أسبوع',
		dateFormat: 'dd/mm/yy',
		firstDay: 6,
  		isRTL: true,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ar']);
});
/* Azerbaijani (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Jamil Najafov (necefov33@gmail.com). */
jQuery(function($) {
	$.datepicker.regional['az'] = {
		closeText: 'Bağla',
		prevText: '&#x3c;Geri',
		nextText: 'İrəli&#x3e;',
		currentText: 'Bugün',
		monthNames: ['Yanvar','Fevral','Mart','Aprel','May','İyun',
		'İyul','Avqust','Sentyabr','Oktyabr','Noyabr','Dekabr'],
		monthNamesShort: ['Yan','Fev','Mar','Apr','May','İyun',
		'İyul','Avq','Sen','Okt','Noy','Dek'],
		dayNames: ['Bazar','Bazar ertəsi','Çərşənbə axşamı','Çərşənbə','Cümə axşamı','Cümə','Şənbə'],
		dayNamesShort: ['B','Be','Ça','Ç','Ca','C','Ş'],
		dayNamesMin: ['B','B','Ç','С','Ç','C','Ş'],
		weekHeader: 'Hf',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['az']);
});
/* Bulgarian initialisation for the jQuery UI date picker plugin. */
/* Written by Stoyan Kyosev (http://svest.org). */
jQuery(function($){
    $.datepicker.regional['bg'] = {
        closeText: 'затвори',
        prevText: '&#x3c;назад',
        nextText: 'напред&#x3e;',
		nextBigText: '&#x3e;&#x3e;',
        currentText: 'днес',
        monthNames: ['Януари','Февруари','Март','Април','Май','Юни',
        'Юли','Август','Септември','Октомври','Ноември','Декември'],
        monthNamesShort: ['Яну','Фев','Мар','Апр','Май','Юни',
        'Юли','Авг','Сеп','Окт','Нов','Дек'],
        dayNames: ['Неделя','Понеделник','Вторник','Сряда','Четвъртък','Петък','Събота'],
        dayNamesShort: ['Нед','Пон','Вто','Сря','Чет','Пет','Съб'],
        dayNamesMin: ['Не','По','Вт','Ср','Че','Пе','Съ'],
		weekHeader: 'Wk',
        dateFormat: 'dd.mm.yy',
		firstDay: 1,
        isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['bg']);
});

/* Bosnian i18n for the jQuery UI date picker plugin. */
/* Written by Kenan Konjo. */
jQuery(function($){
	$.datepicker.regional['bs'] = {
		closeText: 'Zatvori', 
		prevText: '&#x3c;', 
		nextText: '&#x3e;', 
		currentText: 'Danas', 
		monthNames: ['Januar','Februar','Mart','April','Maj','Juni',
		'Juli','August','Septembar','Oktobar','Novembar','Decembar'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
		'Jul','Aug','Sep','Okt','Nov','Dec'],
		dayNames: ['Nedelja','Ponedeljak','Utorak','Srijeda','Četvrtak','Petak','Subota'],
		dayNamesShort: ['Ned','Pon','Uto','Sri','Čet','Pet','Sub'],
		dayNamesMin: ['Ne','Po','Ut','Sr','Če','Pe','Su'],
		weekHeader: 'Wk',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['bs']);
});
/* Inicialització en català per a l'extenció 'calendar' per jQuery. */
/* Writers: (joan.leon@gmail.com). */
jQuery(function($){
	$.datepicker.regional['ca'] = {
		closeText: 'Tancar',
		prevText: '&#x3c;Ant',
		nextText: 'Seg&#x3e;',
		currentText: 'Avui',
		monthNames: ['Gener','Febrer','Mar&ccedil;','Abril','Maig','Juny',
		'Juliol','Agost','Setembre','Octubre','Novembre','Desembre'],
		monthNamesShort: ['Gen','Feb','Mar','Abr','Mai','Jun',
		'Jul','Ago','Set','Oct','Nov','Des'],
		dayNames: ['Diumenge','Dilluns','Dimarts','Dimecres','Dijous','Divendres','Dissabte'],
		dayNamesShort: ['Dug','Dln','Dmt','Dmc','Djs','Dvn','Dsb'],
		dayNamesMin: ['Dg','Dl','Dt','Dc','Dj','Dv','Ds'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ca']);
});
/* Czech initialisation for the jQuery UI date picker plugin. */
/* Written by Tomas Muller (tomas@tomas-muller.net). */
jQuery(function($){
	$.datepicker.regional['cs'] = {
		closeText: 'Zavřít',
		prevText: '&#x3c;Dříve',
		nextText: 'Později&#x3e;',
		currentText: 'Nyní',
		monthNames: ['leden','únor','březen','duben','květen','červen',
        'červenec','srpen','září','říjen','listopad','prosinec'],
		monthNamesShort: ['led','úno','bře','dub','kvě','čer',
		'čvc','srp','zář','říj','lis','pro'],
		dayNames: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
		dayNamesShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
		dayNamesMin: ['ne','po','út','st','čt','pá','so'],
		weekHeader: 'Týd',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['cs']);
});

/* Welsh/UK initialisation for the jQuery UI date picker plugin. */
/* Written by William Griffiths. */
jQuery(function($){
	$.datepicker.regional['cy-GB'] = {
		closeText: 'Done',
		prevText: 'Prev',
		nextText: 'Next',
		currentText: 'Today',
		monthNames: ['Ionawr','Chwefror','Mawrth','Ebrill','Mai','Mehefin',
		'Gorffennaf','Awst','Medi','Hydref','Tachwedd','Rhagfyr'],
		monthNamesShort: ['Ion', 'Chw', 'Maw', 'Ebr', 'Mai', 'Meh',
		'Gor', 'Aws', 'Med', 'Hyd', 'Tac', 'Rha'],
		dayNames: ['Dydd Sul', 'Dydd Llun', 'Dydd Mawrth', 'Dydd Mercher', 'Dydd Iau', 'Dydd Gwener', 'Dydd Sadwrn'],
		dayNamesShort: ['Sul', 'Llu', 'Maw', 'Mer', 'Iau', 'Gwe', 'Sad'],
		dayNamesMin: ['Su','Ll','Ma','Me','Ia','Gw','Sa'],
		weekHeader: 'Wy',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['cy-GB']);
});
/* Danish initialisation for the jQuery UI date picker plugin. */
/* Written by Jan Christensen ( deletestuff@gmail.com). */
jQuery(function($){
    $.datepicker.regional['da'] = {
		closeText: 'Luk',
        prevText: '&#x3c;Forrige',
		nextText: 'Næste&#x3e;',
		currentText: 'Idag',
        monthNames: ['Januar','Februar','Marts','April','Maj','Juni',
        'Juli','August','September','Oktober','November','December'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
        'Jul','Aug','Sep','Okt','Nov','Dec'],
		dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
		dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
		dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
		weekHeader: 'Uge',
        dateFormat: 'dd-mm-yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['da']);
});

/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
	$.datepicker.regional['de'] = {
		closeText: 'schließen',
		prevText: '&#x3c;zurück',
		nextText: 'Vor&#x3e;',
		currentText: 'heute',
		monthNames: ['Januar','Februar','März','April','Mai','Juni',
		'Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
		'Jul','Aug','Sep','Okt','Nov','Dez'],
		dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
		dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		weekHeader: 'KW',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['de']);
});

/* Greek (el) initialisation for the jQuery UI date picker plugin. */
/* Written by Alex Cicovic (http://www.alexcicovic.com) */
jQuery(function($){
	$.datepicker.regional['el'] = {
		closeText: 'Κλείσιμο',
		prevText: 'Προηγούμενος',
		nextText: 'Επόμενος',
		currentText: 'Τρέχων Μήνας',
		monthNames: ['Ιανουάριος','Φεβρουάριος','Μάρτιος','Απρίλιος','Μάιος','Ιούνιος',
		'Ιούλιος','Αύγουστος','Σεπτέμβριος','Οκτώβριος','Νοέμβριος','Δεκέμβριος'],
		monthNamesShort: ['Ιαν','Φεβ','Μαρ','Απρ','Μαι','Ιουν',
		'Ιουλ','Αυγ','Σεπ','Οκτ','Νοε','Δεκ'],
		dayNames: ['Κυριακή','Δευτέρα','Τρίτη','Τετάρτη','Πέμπτη','Παρασκευή','Σάββατο'],
		dayNamesShort: ['Κυρ','Δευ','Τρι','Τετ','Πεμ','Παρ','Σαβ'],
		dayNamesMin: ['Κυ','Δε','Τρ','Τε','Πε','Πα','Σα'],
		weekHeader: 'Εβδ',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['el']);
});
/* English/Australia initialisation for the jQuery UI date picker plugin. */
/* Based on the en-GB initialisation. */
jQuery(function($){
	$.datepicker.regional['en-AU'] = {
		closeText: 'Done',
		prevText: 'Prev',
		nextText: 'Next',
		currentText: 'Today',
		monthNames: ['January','February','March','April','May','June',
		'July','August','September','October','November','December'],
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
		'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
		weekHeader: 'Wk',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['en-AU']);
});

/* English/UK initialisation for the jQuery UI date picker plugin. */
/* Written by Stuart. */
jQuery(function($){
	$.datepicker.regional['en-GB'] = {
		closeText: 'Done',
		prevText: 'Prev',
		nextText: 'Next',
		currentText: 'Today',
		monthNames: ['January','February','March','April','May','June',
		'July','August','September','October','November','December'],
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
		'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
		weekHeader: 'Wk',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['en-GB']);
});

/* English/New Zealand initialisation for the jQuery UI date picker plugin. */
/* Based on the en-GB initialisation. */
jQuery(function($){
	$.datepicker.regional['en-NZ'] = {
		closeText: 'Done',
		prevText: 'Prev',
		nextText: 'Next',
		currentText: 'Today',
		monthNames: ['January','February','March','April','May','June',
		'July','August','September','October','November','December'],
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
		'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
		weekHeader: 'Wk',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['en-NZ']);
});

/* Esperanto initialisation for the jQuery UI date picker plugin. */
/* Written by Olivier M. (olivierweb@ifrance.com). */
jQuery(function($){
	$.datepicker.regional['eo'] = {
		closeText: 'Fermi',
		prevText: '&lt;Anta',
		nextText: 'Sekv&gt;',
		currentText: 'Nuna',
		monthNames: ['Januaro','Februaro','Marto','Aprilo','Majo','Junio',
		'Julio','Aŭgusto','Septembro','Oktobro','Novembro','Decembro'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
		'Jul','Aŭg','Sep','Okt','Nov','Dec'],
		dayNames: ['Dimanĉo','Lundo','Mardo','Merkredo','Ĵaŭdo','Vendredo','Sabato'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Ĵaŭ','Ven','Sab'],
		dayNamesMin: ['Di','Lu','Ma','Me','Ĵa','Ve','Sa'],
		weekHeader: 'Sb',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['eo']);
});

/* Inicialización en español para la extensión 'UI date picker' para jQuery. */
/* Traducido por Vester (xvester@gmail.com). */
jQuery(function($){
	$.datepicker.regional['es'] = {
		closeText: 'Cerrar',
		prevText: '&#x3c;Ant',
		nextText: 'Sig&#x3e;',
		currentText: 'Hoy',
		monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
		'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
		monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
		'Jul','Ago','Sep','Oct','Nov','Dic'],
		dayNames: ['Domingo','Lunes','Martes','Mi&eacute;rcoles','Jueves','Viernes','S&aacute;bado'],
		dayNamesShort: ['Dom','Lun','Mar','Mi&eacute;','Juv','Vie','S&aacute;b'],
		dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','S&aacute;'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['es']);
});
/* Estonian initialisation for the jQuery UI date picker plugin. */
/* Written by Mart Sõmermaa (mrts.pydev at gmail com). */
jQuery(function($){
	$.datepicker.regional['et'] = {
		closeText: 'Sulge',
		prevText: 'Eelnev',
		nextText: 'Järgnev',
		currentText: 'Täna',
		monthNames: ['Jaanuar','Veebruar','Märts','Aprill','Mai','Juuni',
		'Juuli','August','September','Oktoober','November','Detsember'],
		monthNamesShort: ['Jaan', 'Veebr', 'Märts', 'Apr', 'Mai', 'Juuni',
		'Juuli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dets'],
		dayNames: ['Pühapäev', 'Esmaspäev', 'Teisipäev', 'Kolmapäev', 'Neljapäev', 'Reede', 'Laupäev'],
		dayNamesShort: ['Pühap', 'Esmasp', 'Teisip', 'Kolmap', 'Neljap', 'Reede', 'Laup'],
		dayNamesMin: ['P','E','T','K','N','R','L'],
		weekHeader: 'näd',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['et']);
}); 
/* Euskarako oinarria 'UI date picker' jquery-ko extentsioarentzat */
/* Karrikas-ek itzulia (karrikas@karrikas.com) */
jQuery(function($){
	$.datepicker.regional['eu'] = {
		closeText: 'Egina',
		prevText: '&#x3c;Aur',
		nextText: 'Hur&#x3e;',
		currentText: 'Gaur',
		monthNames: ['urtarrila','otsaila','martxoa','apirila','maiatza','ekaina',
			'uztaila','abuztua','iraila','urria','azaroa','abendua'],
		monthNamesShort: ['urt.','ots.','mar.','api.','mai.','eka.',
			'uzt.','abu.','ira.','urr.','aza.','abe.'],
		dayNames: ['igandea','astelehena','asteartea','asteazkena','osteguna','ostirala','larunbata'],
		dayNamesShort: ['ig.','al.','ar.','az.','og.','ol.','lr.'],
		dayNamesMin: ['ig','al','ar','az','og','ol','lr'],
		weekHeader: 'As',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['eu']);
});
/* Persian (Farsi) Translation for the jQuery UI date picker plugin. */
/* Javad Mowlanezhad -- jmowla@gmail.com */
/* Jalali calendar should supported soon! (Its implemented but I have to test it) */
jQuery(function($) {
	$.datepicker.regional['fa'] = {
		closeText: 'بستن',
		prevText: '&#x3C;قبلی',
		nextText: 'بعدی&#x3E;',
		currentText: 'امروز',
		monthNames: [
			'فروردين',
			'ارديبهشت',
			'خرداد',
			'تير',
			'مرداد',
			'شهريور',
			'مهر',
			'آبان',
			'آذر',
			'دی',
			'بهمن',
			'اسفند'
		],
		monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
		dayNames: [
			'يکشنبه',
			'دوشنبه',
			'سه‌شنبه',
			'چهارشنبه',
			'پنجشنبه',
			'جمعه',
			'شنبه'
		],
		dayNamesShort: [
			'ی',
			'د',
			'س',
			'چ',
			'پ',
			'ج', 
			'ش'
		],
		dayNamesMin: [
			'ی',
			'د',
			'س',
			'چ',
			'پ',
			'ج', 
			'ش'
		],
		weekHeader: 'هف',
		dateFormat: 'yy/mm/dd',
		firstDay: 6,
		isRTL: true,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['fa']);
});
/* Finnish initialisation for the jQuery UI date picker plugin. */
/* Written by Harri Kilpiö (harrikilpio@gmail.com). */
jQuery(function($){
	$.datepicker.regional['fi'] = {
		closeText: 'Sulje',
		prevText: '&#xAB;Edellinen',
		nextText: 'Seuraava&#xBB;',
		currentText: 'T&#xE4;n&#xE4;&#xE4;n',
		monthNames: ['Tammikuu','Helmikuu','Maaliskuu','Huhtikuu','Toukokuu','Kes&#xE4;kuu',
		'Hein&#xE4;kuu','Elokuu','Syyskuu','Lokakuu','Marraskuu','Joulukuu'],
		monthNamesShort: ['Tammi','Helmi','Maalis','Huhti','Touko','Kes&#xE4;',
		'Hein&#xE4;','Elo','Syys','Loka','Marras','Joulu'],
		dayNamesShort: ['Su','Ma','Ti','Ke','To','Pe','La'],
		dayNames: ['Sunnuntai','Maanantai','Tiistai','Keskiviikko','Torstai','Perjantai','Lauantai'],
		dayNamesMin: ['Su','Ma','Ti','Ke','To','Pe','La'],
		weekHeader: 'Vk',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['fi']);
});

/* Faroese initialisation for the jQuery UI date picker plugin */
/* Written by Sverri Mohr Olsen, sverrimo@gmail.com */
jQuery(function($){
	$.datepicker.regional['fo'] = {
		closeText: 'Lat aftur',
		prevText: '&#x3c;Fyrra',
		nextText: 'Næsta&#x3e;',
		currentText: 'Í dag',
		monthNames: ['Januar','Februar','Mars','Apríl','Mei','Juni',
		'Juli','August','September','Oktober','November','Desember'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Mei','Jun',
		'Jul','Aug','Sep','Okt','Nov','Des'],
		dayNames: ['Sunnudagur','Mánadagur','Týsdagur','Mikudagur','Hósdagur','Fríggjadagur','Leyardagur'],
		dayNamesShort: ['Sun','Mán','Týs','Mik','Hós','Frí','Ley'],
		dayNamesMin: ['Su','Má','Tý','Mi','Hó','Fr','Le'],
		weekHeader: 'Vk',
		dateFormat: 'dd-mm-yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['fo']);
});

/* Swiss-French initialisation for the jQuery UI date picker plugin. */
/* Written Martin Voelkle (martin.voelkle@e-tc.ch). */
jQuery(function($){
	$.datepicker.regional['fr-CH'] = {
		closeText: 'Fermer',
		prevText: '&#x3c;Préc',
		nextText: 'Suiv&#x3e;',
		currentText: 'Courant',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		weekHeader: 'Sm',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['fr-CH']);
});
/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood{at}iinet.com.au),
              Stéphane Nahmani (sholby@sholby.net),
              Stéphane Raimbault <stephane.raimbault@gmail.com> */
jQuery(function($){
	$.datepicker.regional['fr'] = {
		closeText: 'Fermer',
		prevText: 'Précédent',
		nextText: 'Suivant',
		currentText: 'Aujourd\'hui',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Janv.','Févr.','Mars','Avril','Mai','Juin',
		'Juil.','Août','Sept.','Oct.','Nov.','Déc.'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim.','Lun.','Mar.','Mer.','Jeu.','Ven.','Sam.'],
		dayNamesMin: ['D','L','M','M','J','V','S'],
		weekHeader: 'Sem.',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
});

/* Galician localization for 'UI date picker' jQuery extension. */
/* Translated by Jorge Barreiro <yortx.barry@gmail.com>. */
jQuery(function($){
	$.datepicker.regional['gl'] = {
		closeText: 'Pechar',
		prevText: '&#x3c;Ant',
		nextText: 'Seg&#x3e;',
		currentText: 'Hoxe',
		monthNames: ['Xaneiro','Febreiro','Marzo','Abril','Maio','Xuño',
		'Xullo','Agosto','Setembro','Outubro','Novembro','Decembro'],
		monthNamesShort: ['Xan','Feb','Mar','Abr','Mai','Xuñ',
		'Xul','Ago','Set','Out','Nov','Dec'],
		dayNames: ['Domingo','Luns','Martes','M&eacute;rcores','Xoves','Venres','S&aacute;bado'],
		dayNamesShort: ['Dom','Lun','Mar','M&eacute;r','Xov','Ven','S&aacute;b'],
		dayNamesMin: ['Do','Lu','Ma','M&eacute;','Xo','Ve','S&aacute;'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['gl']);
});
/* Hebrew initialisation for the UI Datepicker extension. */
/* Written by Amir Hardon (ahardon at gmail dot com). */
jQuery(function($){
	$.datepicker.regional['he'] = {
		closeText: 'סגור',
		prevText: '&#x3c;הקודם',
		nextText: 'הבא&#x3e;',
		currentText: 'היום',
		monthNames: ['ינואר','פברואר','מרץ','אפריל','מאי','יוני',
		'יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר'],
		monthNamesShort: ['ינו','פבר','מרץ','אפר','מאי','יוני',
		'יולי','אוג','ספט','אוק','נוב','דצמ'],
		dayNames: ['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'],
		dayNamesShort: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
		dayNamesMin: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
		weekHeader: 'Wk',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: true,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['he']);
});

/* Hindi initialisation for the jQuery UI date picker plugin. */
/* Written by Michael Dawart. */
jQuery(function($){
	$.datepicker.regional['hi'] = {
		closeText: 'बंद',
		prevText: 'पिछला',
		nextText: 'अगला',
		currentText: 'आज',
		monthNames: ['जनवरी ','फरवरी','मार्च','अप्रेल','मई','जून',
		'जूलाई','अगस्त ','सितम्बर','अक्टूबर','नवम्बर','दिसम्बर'],
		monthNamesShort: ['जन', 'फर', 'मार्च', 'अप्रेल', 'मई', 'जून',
		'जूलाई', 'अग', 'सित', 'अक्ट', 'नव', 'दि'],
		dayNames: ['रविवार', 'सोमवार', 'मंगलवार', 'बुधवार', 'गुरुवार', 'शुक्रवार', 'शनिवार'],
		dayNamesShort: ['रवि', 'सोम', 'मंगल', 'बुध', 'गुरु', 'शुक्र', 'शनि'],
		dayNamesMin: ['रवि', 'सोम', 'मंगल', 'बुध', 'गुरु', 'शुक्र', 'शनि'],
		weekHeader: 'हफ्ता',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['hi']);
});

/* Croatian i18n for the jQuery UI date picker plugin. */
/* Written by Vjekoslav Nesek. */
jQuery(function($){
	$.datepicker.regional['hr'] = {
		closeText: 'Zatvori',
		prevText: '&#x3c;',
		nextText: '&#x3e;',
		currentText: 'Danas',
		monthNames: ['Siječanj','Veljača','Ožujak','Travanj','Svibanj','Lipanj',
		'Srpanj','Kolovoz','Rujan','Listopad','Studeni','Prosinac'],
		monthNamesShort: ['Sij','Velj','Ožu','Tra','Svi','Lip',
		'Srp','Kol','Ruj','Lis','Stu','Pro'],
		dayNames: ['Nedjelja','Ponedjeljak','Utorak','Srijeda','Četvrtak','Petak','Subota'],
		dayNamesShort: ['Ned','Pon','Uto','Sri','Čet','Pet','Sub'],
		dayNamesMin: ['Ne','Po','Ut','Sr','Če','Pe','Su'],
		weekHeader: 'Tje',
		dateFormat: 'dd.mm.yy.',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['hr']);
});
/* Hungarian initialisation for the jQuery UI date picker plugin. */
/* Written by Istvan Karaszi (jquery@spam.raszi.hu). */
jQuery(function($){
	$.datepicker.regional['hu'] = {
		closeText: 'bezár',
		prevText: 'vissza',
		nextText: 'előre',
		currentText: 'ma',
		monthNames: ['Január', 'Február', 'Március', 'Április', 'Május', 'Június',
		'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December'],
		monthNamesShort: ['Jan', 'Feb', 'Már', 'Ápr', 'Máj', 'Jún',
		'Júl', 'Aug', 'Szep', 'Okt', 'Nov', 'Dec'],
		dayNames: ['Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat'],
		dayNamesShort: ['Vas', 'Hét', 'Ked', 'Sze', 'Csü', 'Pén', 'Szo'],
		dayNamesMin: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
		weekHeader: 'Hét',
		dateFormat: 'yy.mm.dd.',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['hu']);
});

/* Armenian(UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Levon Zakaryan (levon.zakaryan@gmail.com)*/
jQuery(function($){
	$.datepicker.regional['hy'] = {
		closeText: 'Փակել',
		prevText: '&#x3c;Նախ.',
		nextText: 'Հաջ.&#x3e;',
		currentText: 'Այսօր',
		monthNames: ['Հունվար','Փետրվար','Մարտ','Ապրիլ','Մայիս','Հունիս',
		'Հուլիս','Օգոստոս','Սեպտեմբեր','Հոկտեմբեր','Նոյեմբեր','Դեկտեմբեր'],
		monthNamesShort: ['Հունվ','Փետր','Մարտ','Ապր','Մայիս','Հունիս',
		'Հուլ','Օգս','Սեպ','Հոկ','Նոյ','Դեկ'],
		dayNames: ['կիրակի','եկուշաբթի','երեքշաբթի','չորեքշաբթի','հինգշաբթի','ուրբաթ','շաբաթ'],
		dayNamesShort: ['կիր','երկ','երք','չրք','հնգ','ուրբ','շբթ'],
		dayNamesMin: ['կիր','երկ','երք','չրք','հնգ','ուրբ','շբթ'],
		weekHeader: 'ՇԲՏ',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['hy']);
});
/* Indonesian initialisation for the jQuery UI date picker plugin. */
/* Written by Deden Fathurahman (dedenf@gmail.com). */
jQuery(function($){
	$.datepicker.regional['id'] = {
		closeText: 'Tutup',
		prevText: '&#x3c;mundur',
		nextText: 'maju&#x3e;',
		currentText: 'hari ini',
		monthNames: ['Januari','Februari','Maret','April','Mei','Juni',
		'Juli','Agustus','September','Oktober','Nopember','Desember'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Mei','Jun',
		'Jul','Agus','Sep','Okt','Nop','Des'],
		dayNames: ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'],
		dayNamesShort: ['Min','Sen','Sel','Rab','kam','Jum','Sab'],
		dayNamesMin: ['Mg','Sn','Sl','Rb','Km','jm','Sb'],
		weekHeader: 'Mg',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['id']);
});
/* Icelandic initialisation for the jQuery UI date picker plugin. */
/* Written by Haukur H. Thorsson (haukur@eskill.is). */
jQuery(function($){
	$.datepicker.regional['is'] = {
		closeText: 'Loka',
		prevText: '&#x3c; Fyrri',
		nextText: 'N&aelig;sti &#x3e;',
		currentText: '&Iacute; dag',
		monthNames: ['Jan&uacute;ar','Febr&uacute;ar','Mars','Apr&iacute;l','Ma&iacute','J&uacute;n&iacute;',
		'J&uacute;l&iacute;','&Aacute;g&uacute;st','September','Okt&oacute;ber','N&oacute;vember','Desember'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Ma&iacute;','J&uacute;n',
		'J&uacute;l','&Aacute;g&uacute;','Sep','Okt','N&oacute;v','Des'],
		dayNames: ['Sunnudagur','M&aacute;nudagur','&THORN;ri&eth;judagur','Mi&eth;vikudagur','Fimmtudagur','F&ouml;studagur','Laugardagur'],
		dayNamesShort: ['Sun','M&aacute;n','&THORN;ri','Mi&eth;','Fim','F&ouml;s','Lau'],
		dayNamesMin: ['Su','M&aacute;','&THORN;r','Mi','Fi','F&ouml;','La'],
		weekHeader: 'Vika',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['is']);
});
/* Italian initialisation for the jQuery UI date picker plugin. */
/* Written by Antonello Pasella (antonello.pasella@gmail.com). */
jQuery(function($){
	$.datepicker.regional['it'] = {
		closeText: 'Chiudi',
		prevText: '&#x3c;Prec',
		nextText: 'Succ&#x3e;',
		currentText: 'Oggi',
		monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
			'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
		monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
			'Lug','Ago','Set','Ott','Nov','Dic'],
		dayNames: ['Domenica','Luned&#236','Marted&#236','Mercoled&#236','Gioved&#236','Venerd&#236','Sabato'],
		dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
		dayNamesMin: ['Do','Lu','Ma','Me','Gi','Ve','Sa'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['it']);
});

/* Japanese initialisation for the jQuery UI date picker plugin. */
/* Written by Kentaro SATO (kentaro@ranvis.com). */
jQuery(function($){
	$.datepicker.regional['ja'] = {
		closeText: '閉じる',
		prevText: '&#x3c;前',
		nextText: '次&#x3e;',
		currentText: '今日',
		monthNames: ['1月','2月','3月','4月','5月','6月',
		'7月','8月','9月','10月','11月','12月'],
		monthNamesShort: ['1月','2月','3月','4月','5月','6月',
		'7月','8月','9月','10月','11月','12月'],
		dayNames: ['日曜日','月曜日','火曜日','水曜日','木曜日','金曜日','土曜日'],
		dayNamesShort: ['日','月','火','水','木','金','土'],
		dayNamesMin: ['日','月','火','水','木','金','土'],
		weekHeader: '週',
		dateFormat: 'yy/mm/dd',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: '年'};
	$.datepicker.setDefaults($.datepicker.regional['ja']);
});
/* Georgian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Lado Lomidze (lado.lomidze@gmail.com). */
jQuery(function($){
	$.datepicker.regional['ka'] = {
		closeText: 'დახურვა',
		prevText: '&#x3c; წინა',
		nextText: 'შემდეგი &#x3e;',
		currentText: 'დღეს',
		monthNames: ['იანვარი','თებერვალი','მარტი','აპრილი','მაისი','ივნისი', 'ივლისი','აგვისტო','სექტემბერი','ოქტომბერი','ნოემბერი','დეკემბერი'],
		monthNamesShort: ['იან','თებ','მარ','აპრ','მაი','ივნ', 'ივლ','აგვ','სექ','ოქტ','ნოე','დეკ'],
		dayNames: ['კვირა','ორშაბათი','სამშაბათი','ოთხშაბათი','ხუთშაბათი','პარასკევი','შაბათი'],
		dayNamesShort: ['კვ','ორშ','სამ','ოთხ','ხუთ','პარ','შაბ'],
		dayNamesMin: ['კვ','ორშ','სამ','ოთხ','ხუთ','პარ','შაბ'],
		weekHeader: 'კვირა',
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ka']);
});

/* Kazakh (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Dmitriy Karasyov (dmitriy.karasyov@gmail.com). */
jQuery(function($){
	$.datepicker.regional['kk'] = {
		closeText: 'Жабу',
		prevText: '&#x3c;Алдыңғы',
		nextText: 'Келесі&#x3e;',
		currentText: 'Бүгін',
		monthNames: ['Қаңтар','Ақпан','Наурыз','Сәуір','Мамыр','Маусым',
		'Шілде','Тамыз','Қыркүйек','Қазан','Қараша','Желтоқсан'],
		monthNamesShort: ['Қаң','Ақп','Нау','Сәу','Мам','Мау',
		'Шіл','Там','Қыр','Қаз','Қар','Жел'],
		dayNames: ['Жексенбі','Дүйсенбі','Сейсенбі','Сәрсенбі','Бейсенбі','Жұма','Сенбі'],
		dayNamesShort: ['жкс','дсн','ссн','срс','бсн','жма','снб'],
		dayNamesMin: ['Жк','Дс','Сс','Ср','Бс','Жм','Сн'],
		weekHeader: 'Не',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['kk']);
});

/* Khmer initialisation for the jQuery calendar extension. */
/* Written by Chandara Om (chandara.teacher@gmail.com). */
jQuery(function($){
	$.datepicker.regional['km'] = {
		closeText: 'ធ្វើ​រួច',
		prevText: 'មុន',
		nextText: 'បន្ទាប់',
		currentText: 'ថ្ងៃ​នេះ',
		monthNames: ['មករា','កុម្ភៈ','មីនា','មេសា','ឧសភា','មិថុនា',
		'កក្កដា','សីហា','កញ្ញា','តុលា','វិច្ឆិកា','ធ្នូ'],
		monthNamesShort: ['មករា','កុម្ភៈ','មីនា','មេសា','ឧសភា','មិថុនា',
		'កក្កដា','សីហា','កញ្ញា','តុលា','វិច្ឆិកា','ធ្នូ'],
		dayNames: ['អាទិត្យ', 'ចន្ទ', 'អង្គារ', 'ពុធ', 'ព្រហស្បតិ៍', 'សុក្រ', 'សៅរ៍'],
		dayNamesShort: ['អា', 'ច', 'អ', 'ពុ', 'ព្រហ', 'សុ', 'សៅ'],
		dayNamesMin: ['អា', 'ច', 'អ', 'ពុ', 'ព្រហ', 'សុ', 'សៅ'],
		weekHeader: 'សប្ដាហ៍',
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['km']);
});

/* Korean initialisation for the jQuery calendar extension. */
/* Written by DaeKwon Kang (ncrash.dk@gmail.com), Edited by Genie. */
jQuery(function($){
	$.datepicker.regional['ko'] = {
		closeText: '닫기',
		prevText: '이전달',
		nextText: '다음달',
		currentText: '오늘',
		monthNames: ['1월','2월','3월','4월','5월','6월',
		'7월','8월','9월','10월','11월','12월'],
		monthNamesShort: ['1월','2월','3월','4월','5월','6월',
		'7월','8월','9월','10월','11월','12월'],
		dayNames: ['일요일','월요일','화요일','수요일','목요일','금요일','토요일'],
		dayNamesShort: ['일','월','화','수','목','금','토'],
		dayNamesMin: ['일','월','화','수','목','금','토'],
		weekHeader: 'Wk',
		dateFormat: 'yy-mm-dd',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: '년'};
	$.datepicker.setDefaults($.datepicker.regional['ko']);
});
/* Luxembourgish initialisation for the jQuery UI date picker plugin. */
/* Written by Michel Weimerskirch <michel@weimerskirch.net> */
jQuery(function($){
	$.datepicker.regional['lb'] = {
		closeText: 'Fäerdeg',
		prevText: 'Zréck',
		nextText: 'Weider',
		currentText: 'Haut',
		monthNames: ['Januar','Februar','Mäerz','Abrëll','Mee','Juni',
		'Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan', 'Feb', 'Mäe', 'Abr', 'Mee', 'Jun',
		'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
		dayNames: ['Sonndeg', 'Méindeg', 'Dënschdeg', 'Mëttwoch', 'Donneschdeg', 'Freideg', 'Samschdeg'],
		dayNamesShort: ['Son', 'Méi', 'Dën', 'Mët', 'Don', 'Fre', 'Sam'],
		dayNamesMin: ['So','Mé','Dë','Më','Do','Fr','Sa'],
		weekHeader: 'W',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['lb']);
});

/* Lithuanian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* @author Arturas Paleicikas <arturas@avalon.lt> */
jQuery(function($){
	$.datepicker.regional['lt'] = {
		closeText: 'Uždaryti',
		prevText: '&#x3c;Atgal',
		nextText: 'Pirmyn&#x3e;',
		currentText: 'Šiandien',
		monthNames: ['Sausis','Vasaris','Kovas','Balandis','Gegužė','Birželis',
		'Liepa','Rugpjūtis','Rugsėjis','Spalis','Lapkritis','Gruodis'],
		monthNamesShort: ['Sau','Vas','Kov','Bal','Geg','Bir',
		'Lie','Rugp','Rugs','Spa','Lap','Gru'],
		dayNames: ['sekmadienis','pirmadienis','antradienis','trečiadienis','ketvirtadienis','penktadienis','šeštadienis'],
		dayNamesShort: ['sek','pir','ant','tre','ket','pen','šeš'],
		dayNamesMin: ['Se','Pr','An','Tr','Ke','Pe','Še'],
		weekHeader: 'Wk',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['lt']);
});
/* Latvian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* @author Arturas Paleicikas <arturas.paleicikas@metasite.net> */
jQuery(function($){
	$.datepicker.regional['lv'] = {
		closeText: 'Aizvērt',
		prevText: 'Iepr',
		nextText: 'Nāka',
		currentText: 'Šodien',
		monthNames: ['Janvāris','Februāris','Marts','Aprīlis','Maijs','Jūnijs',
		'Jūlijs','Augusts','Septembris','Oktobris','Novembris','Decembris'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jūn',
		'Jūl','Aug','Sep','Okt','Nov','Dec'],
		dayNames: ['svētdiena','pirmdiena','otrdiena','trešdiena','ceturtdiena','piektdiena','sestdiena'],
		dayNamesShort: ['svt','prm','otr','tre','ctr','pkt','sst'],
		dayNamesMin: ['Sv','Pr','Ot','Tr','Ct','Pk','Ss'],
		weekHeader: 'Nav',
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['lv']);
});
/* Macedonian i18n for the jQuery UI date picker plugin. */
/* Written by Stojce Slavkovski. */
jQuery(function($){
	$.datepicker.regional['mk'] = {
		closeText: 'Затвори',
		prevText: '&#x3C;',
		nextText: '&#x3E;',
		currentText: 'Денес',
		monthNames: ['Јануари','Февруари','Март','Април','Мај','Јуни',
		'Јули','Август','Септември','Октомври','Ноември','Декември'],
		monthNamesShort: ['Јан','Фев','Мар','Апр','Мај','Јун',
		'Јул','Авг','Сеп','Окт','Ное','Дек'],
		dayNames: ['Недела','Понеделник','Вторник','Среда','Четврток','Петок','Сабота'],
		dayNamesShort: ['Нед','Пон','Вто','Сре','Чет','Пет','Саб'],
		dayNamesMin: ['Не','По','Вт','Ср','Че','Пе','Са'],
		weekHeader: 'Сед',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['mk']);
});

/* Malayalam (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Saji Nediyanchath (saji89@gmail.com). */
jQuery(function($){
	$.datepicker.regional['ml'] = {
		closeText: 'ശരി',
		prevText: 'മുന്നത്തെ',  
		nextText: 'അടുത്തത് ',
		currentText: 'ഇന്ന്',
		monthNames: ['ജനുവരി','ഫെബ്രുവരി','മാര്‍ച്ച്','ഏപ്രില്‍','മേയ്','ജൂണ്‍',
		'ജൂലൈ','ആഗസ്റ്റ്','സെപ്റ്റംബര്‍','ഒക്ടോബര്‍','നവംബര്‍','ഡിസംബര്‍'],
		monthNamesShort: ['ജനു', 'ഫെബ്', 'മാര്‍', 'ഏപ്രി', 'മേയ്', 'ജൂണ്‍',
		'ജൂലാ', 'ആഗ', 'സെപ്', 'ഒക്ടോ', 'നവം', 'ഡിസ'],
		dayNames: ['ഞായര്‍', 'തിങ്കള്‍', 'ചൊവ്വ', 'ബുധന്‍', 'വ്യാഴം', 'വെള്ളി', 'ശനി'],
		dayNamesShort: ['ഞായ', 'തിങ്ക', 'ചൊവ്വ', 'ബുധ', 'വ്യാഴം', 'വെള്ളി', 'ശനി'],
		dayNamesMin: ['ഞാ','തി','ചൊ','ബു','വ്യാ','വെ','ശ'],
		weekHeader: 'ആ',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ml']);
});

/* Malaysian initialisation for the jQuery UI date picker plugin. */
/* Written by Mohd Nawawi Mohamad Jamili (nawawi@ronggeng.net). */
jQuery(function($){
	$.datepicker.regional['ms'] = {
		closeText: 'Tutup',
		prevText: '&#x3c;Sebelum',
		nextText: 'Selepas&#x3e;',
		currentText: 'hari ini',
		monthNames: ['Januari','Februari','Mac','April','Mei','Jun',
		'Julai','Ogos','September','Oktober','November','Disember'],
		monthNamesShort: ['Jan','Feb','Mac','Apr','Mei','Jun',
		'Jul','Ogo','Sep','Okt','Nov','Dis'],
		dayNames: ['Ahad','Isnin','Selasa','Rabu','Khamis','Jumaat','Sabtu'],
		dayNamesShort: ['Aha','Isn','Sel','Rab','kha','Jum','Sab'],
		dayNamesMin: ['Ah','Is','Se','Ra','Kh','Ju','Sa'],
		weekHeader: 'Mg',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ms']);
});
/* Dutch (Belgium) initialisation for the jQuery UI date picker plugin. */
/* David De Sloovere @DavidDeSloovere */
jQuery(function($){
	$.datepicker.regional['nl-BE'] = {
		closeText: 'Sluiten',
		prevText: '←',
		nextText: '→',
		currentText: 'Vandaag',
		monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
		'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
		monthNamesShort: ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun',
		'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
		dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
		dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
		dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
		weekHeader: 'Wk',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['nl-BE']);
});

/* Dutch (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Mathias Bynens <http://mathiasbynens.be/> */
jQuery(function($){
	$.datepicker.regional.nl = {
		closeText: 'Sluiten',
		prevText: '←',
		nextText: '→',
		currentText: 'Vandaag',
		monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
		'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
		monthNamesShort: ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun',
		'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
		dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
		dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
		dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
		weekHeader: 'Wk',
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional.nl);
});
/* Norwegian initialisation for the jQuery UI date picker plugin. */
/* Written by Naimdjon Takhirov (naimdjon@gmail.com). */

jQuery(function($){
  $.datepicker.regional['no'] = {
    closeText: 'Lukk',
    prevText: '&laquo;Forrige',
    nextText: 'Neste&raquo;',
    currentText: 'I dag',
    monthNames: ['januar','februar','mars','april','mai','juni','juli','august','september','oktober','november','desember'],
    monthNamesShort: ['jan','feb','mar','apr','mai','jun','jul','aug','sep','okt','nov','des'],
    dayNamesShort: ['søn','man','tir','ons','tor','fre','lør'],
    dayNames: ['søndag','mandag','tirsdag','onsdag','torsdag','fredag','lørdag'],
    dayNamesMin: ['sø','ma','ti','on','to','fr','lø'],
    weekHeader: 'Uke',
    dateFormat: 'dd.mm.yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: ''
  };
  $.datepicker.setDefaults($.datepicker.regional['no']);
});

/* Polish initialisation for the jQuery UI date picker plugin. */
/* Written by Jacek Wysocki (jacek.wysocki@gmail.com). */
jQuery(function($){
	$.datepicker.regional['pl'] = {
		closeText: 'Zamknij',
		prevText: '&#x3c;Poprzedni',
		nextText: 'Następny&#x3e;',
		currentText: 'Dziś',
		monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
		'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
		monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
		'Lip','Sie','Wrz','Pa','Lis','Gru'],
		dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
		dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
		dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
		weekHeader: 'Tydz',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['pl']);
});

/* Brazilian initialisation for the jQuery UI date picker plugin. */
/* Written by Leonildo Costa Silva (leocsilva@gmail.com). */
jQuery(function($){
	$.datepicker.regional['pt-BR'] = {
		closeText: 'Fechar',
		prevText: '&#x3c;Anterior',
		nextText: 'Pr&oacute;ximo&#x3e;',
		currentText: 'Hoje',
		monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho',
		'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
		'Jul','Ago','Set','Out','Nov','Dez'],
		dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S&aacute;bado'],
		dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
		dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
});
/* Portuguese initialisation for the jQuery UI date picker plugin. */
jQuery(function($){
	$.datepicker.regional['pt'] = {
		closeText: 'Fechar',
		prevText: '&#x3c;Anterior',
		nextText: 'Seguinte',
		currentText: 'Hoje',
		monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho',
		'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
		'Jul','Ago','Set','Out','Nov','Dez'],
		dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S&aacute;bado'],
		dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
		dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
		weekHeader: 'Sem',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['pt']);
});
/* Romansh initialisation for the jQuery UI date picker plugin. */
/* Written by Yvonne Gienal (yvonne.gienal@educa.ch). */
jQuery(function($){
	$.datepicker.regional['rm'] = {
		closeText: 'Serrar',
		prevText: '&#x3c;Suandant',
		nextText: 'Precedent&#x3e;',
		currentText: 'Actual',
		monthNames: ['Schaner','Favrer','Mars','Avrigl','Matg','Zercladur', 'Fanadur','Avust','Settember','October','November','December'],
		monthNamesShort: ['Scha','Fev','Mar','Avr','Matg','Zer', 'Fan','Avu','Sett','Oct','Nov','Dec'],
		dayNames: ['Dumengia','Glindesdi','Mardi','Mesemna','Gievgia','Venderdi','Sonda'],
		dayNamesShort: ['Dum','Gli','Mar','Mes','Gie','Ven','Som'],
		dayNamesMin: ['Du','Gl','Ma','Me','Gi','Ve','So'],
		weekHeader: 'emna',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['rm']);
});

/* Romanian initialisation for the jQuery UI date picker plugin.
 *
 * Written by Edmond L. (ll_edmond@walla.com)
 * and Ionut G. Stan (ionut.g.stan@gmail.com)
 */
jQuery(function($){
	$.datepicker.regional['ro'] = {
		closeText: 'Închide',
		prevText: '&laquo; Luna precedentă',
		nextText: 'Luna următoare &raquo;',
		currentText: 'Azi',
		monthNames: ['Ianuarie','Februarie','Martie','Aprilie','Mai','Iunie',
		'Iulie','August','Septembrie','Octombrie','Noiembrie','Decembrie'],
		monthNamesShort: ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun',
		'Iul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		dayNames: ['Duminică', 'Luni', 'Marţi', 'Miercuri', 'Joi', 'Vineri', 'Sâmbătă'],
		dayNamesShort: ['Dum', 'Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sâm'],
		dayNamesMin: ['Du','Lu','Ma','Mi','Jo','Vi','Sâ'],
		weekHeader: 'Săpt',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ro']);
});

/* Russian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Andrew Stromnov (stromnov@gmail.com). */
jQuery(function($){
	$.datepicker.regional['ru'] = {
		closeText: 'Закрыть',
		prevText: '&#x3c;Пред',
		nextText: 'След&#x3e;',
		currentText: 'Сегодня',
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
		'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
		'Июл','Авг','Сен','Окт','Ноя','Дек'],
		dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
		dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
		dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
		weekHeader: 'Нед',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ru']);
});
/* Slovak initialisation for the jQuery UI date picker plugin. */
/* Written by Vojtech Rinik (vojto@hmm.sk). */
jQuery(function($){
	$.datepicker.regional['sk'] = {
		closeText: 'Zavrieť',
		prevText: '&#x3c;Predchádzajúci',
		nextText: 'Nasledujúci&#x3e;',
		currentText: 'Dnes',
		monthNames: ['Január','Február','Marec','Apríl','Máj','Jún',
		'Júl','August','September','Október','November','December'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Máj','Jún',
		'Júl','Aug','Sep','Okt','Nov','Dec'],
		dayNames: ['Nedeľa','Pondelok','Utorok','Streda','Štvrtok','Piatok','Sobota'],
		dayNamesShort: ['Ned','Pon','Uto','Str','Štv','Pia','Sob'],
		dayNamesMin: ['Ne','Po','Ut','St','Št','Pia','So'],
		weekHeader: 'Ty',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['sk']);
});

/* Slovenian initialisation for the jQuery UI date picker plugin. */
/* Written by Jaka Jancar (jaka@kubje.org). */
/* c = &#x10D;, s = &#x161; z = &#x17E; C = &#x10C; S = &#x160; Z = &#x17D; */
jQuery(function($){
	$.datepicker.regional['sl'] = {
		closeText: 'Zapri',
		prevText: '&lt;Prej&#x161;nji',
		nextText: 'Naslednji&gt;',
		currentText: 'Trenutni',
		monthNames: ['Januar','Februar','Marec','April','Maj','Junij',
		'Julij','Avgust','September','Oktober','November','December'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
		'Jul','Avg','Sep','Okt','Nov','Dec'],
		dayNames: ['Nedelja','Ponedeljek','Torek','Sreda','&#x10C;etrtek','Petek','Sobota'],
		dayNamesShort: ['Ned','Pon','Tor','Sre','&#x10C;et','Pet','Sob'],
		dayNamesMin: ['Ne','Po','To','Sr','&#x10C;e','Pe','So'],
		weekHeader: 'Teden',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['sl']);
});

/* Albanian initialisation for the jQuery UI date picker plugin. */
/* Written by Flakron Bytyqi (flakron@gmail.com). */
jQuery(function($){
	$.datepicker.regional['sq'] = {
		closeText: 'mbylle',
		prevText: '&#x3c;mbrapa',
		nextText: 'Përpara&#x3e;',
		currentText: 'sot',
		monthNames: ['Janar','Shkurt','Mars','Prill','Maj','Qershor',
		'Korrik','Gusht','Shtator','Tetor','Nëntor','Dhjetor'],
		monthNamesShort: ['Jan','Shk','Mar','Pri','Maj','Qer',
		'Kor','Gus','Sht','Tet','Nën','Dhj'],
		dayNames: ['E Diel','E Hënë','E Martë','E Mërkurë','E Enjte','E Premte','E Shtune'],
		dayNamesShort: ['Di','Hë','Ma','Më','En','Pr','Sh'],
		dayNamesMin: ['Di','Hë','Ma','Më','En','Pr','Sh'],
		weekHeader: 'Ja',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['sq']);
});

/* Serbian i18n for the jQuery UI date picker plugin. */
/* Written by Dejan Dimić. */
jQuery(function($){
	$.datepicker.regional['sr-SR'] = {
		closeText: 'Zatvori',
		prevText: '&#x3c;',
		nextText: '&#x3e;',
		currentText: 'Danas',
		monthNames: ['Januar','Februar','Mart','April','Maj','Jun',
		'Jul','Avgust','Septembar','Oktobar','Novembar','Decembar'],
		monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
		'Jul','Avg','Sep','Okt','Nov','Dec'],
		dayNames: ['Nedelja','Ponedeljak','Utorak','Sreda','Četvrtak','Petak','Subota'],
		dayNamesShort: ['Ned','Pon','Uto','Sre','Čet','Pet','Sub'],
		dayNamesMin: ['Ne','Po','Ut','Sr','Če','Pe','Su'],
		weekHeader: 'Sed',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['sr-SR']);
});

/* Serbian i18n for the jQuery UI date picker plugin. */
/* Written by Dejan Dimić. */
jQuery(function($){
	$.datepicker.regional['sr'] = {
		closeText: 'Затвори',
		prevText: '&#x3c;',
		nextText: '&#x3e;',
		currentText: 'Данас',
		monthNames: ['Јануар','Фебруар','Март','Април','Мај','Јун',
		'Јул','Август','Септембар','Октобар','Новембар','Децембар'],
		monthNamesShort: ['Јан','Феб','Мар','Апр','Мај','Јун',
		'Јул','Авг','Сеп','Окт','Нов','Дец'],
		dayNames: ['Недеља','Понедељак','Уторак','Среда','Четвртак','Петак','Субота'],
		dayNamesShort: ['Нед','Пон','Уто','Сре','Чет','Пет','Суб'],
		dayNamesMin: ['Не','По','Ут','Ср','Че','Пе','Су'],
		weekHeader: 'Сед',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['sr']);
});

/* Swedish initialisation for the jQuery UI date picker plugin. */
/* Written by Anders Ekdahl ( anders@nomadiz.se). */
jQuery(function($){
    $.datepicker.regional['sv'] = {
		closeText: 'Stäng',
        prevText: '&laquo;Förra',
		nextText: 'Nästa&raquo;',
		currentText: 'Idag',
        monthNames: ['Januari','Februari','Mars','April','Maj','Juni',
        'Juli','Augusti','September','Oktober','November','December'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
        'Jul','Aug','Sep','Okt','Nov','Dec'],
		dayNamesShort: ['Sön','Mån','Tis','Ons','Tor','Fre','Lör'],
		dayNames: ['Söndag','Måndag','Tisdag','Onsdag','Torsdag','Fredag','Lördag'],
		dayNamesMin: ['Sö','Må','Ti','On','To','Fr','Lö'],
		weekHeader: 'Ve',
        dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['sv']);
});

/* Tamil (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by S A Sureshkumar (saskumar@live.com). */
jQuery(function($){
	$.datepicker.regional['ta'] = {
		closeText: 'மூடு',
		prevText: 'முன்னையது',
		nextText: 'அடுத்தது',
		currentText: 'இன்று',
		monthNames: ['தை','மாசி','பங்குனி','சித்திரை','வைகாசி','ஆனி',
		'ஆடி','ஆவணி','புரட்டாசி','ஐப்பசி','கார்த்திகை','மார்கழி'],
		monthNamesShort: ['தை','மாசி','பங்','சித்','வைகா','ஆனி',
		'ஆடி','ஆவ','புர','ஐப்','கார்','மார்'],
		dayNames: ['ஞாயிற்றுக்கிழமை','திங்கட்கிழமை','செவ்வாய்க்கிழமை','புதன்கிழமை','வியாழக்கிழமை','வெள்ளிக்கிழமை','சனிக்கிழமை'],
		dayNamesShort: ['ஞாயிறு','திங்கள்','செவ்வாய்','புதன்','வியாழன்','வெள்ளி','சனி'],
		dayNamesMin: ['ஞா','தி','செ','பு','வி','வெ','ச'],
		weekHeader: 'Не',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ta']);
});

/* Thai initialisation for the jQuery UI date picker plugin. */
/* Written by pipo (pipo@sixhead.com). */
jQuery(function($){
	$.datepicker.regional['th'] = {
		closeText: 'ปิด',
		prevText: '&laquo;&nbsp;ย้อน',
		nextText: 'ถัดไป&nbsp;&raquo;',
		currentText: 'วันนี้',
		monthNames: ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน',
		'กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'],
		monthNamesShort: ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.',
		'ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'],
		dayNames: ['อาทิตย์','จันทร์','อังคาร','พุธ','พฤหัสบดี','ศุกร์','เสาร์'],
		dayNamesShort: ['อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'],
		dayNamesMin: ['อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'],
		weekHeader: 'Wk',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['th']);
});
/* Tajiki (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Abdurahmon Saidov (saidovab@gmail.com). */
jQuery(function($){
	$.datepicker.regional['tj'] = {
		closeText: 'Идома',
		prevText: '&#x3c;Қафо',
		nextText: 'Пеш&#x3e;',
		currentText: 'Имрӯз',
		monthNames: ['Январ','Феврал','Март','Апрел','Май','Июн',
		'Июл','Август','Сентябр','Октябр','Ноябр','Декабр'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
		'Июл','Авг','Сен','Окт','Ноя','Дек'],
		dayNames: ['якшанбе','душанбе','сешанбе','чоршанбе','панҷшанбе','ҷумъа','шанбе'],
		dayNamesShort: ['якш','душ','сеш','чор','пан','ҷум','шан'],
		dayNamesMin: ['Як','Дш','Сш','Чш','Пш','Ҷм','Шн'],
		weekHeader: 'Хф',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['tj']);
});
/* Turkish initialisation for the jQuery UI date picker plugin. */
/* Written by Izzet Emre Erkan (kara@karalamalar.net). */
jQuery(function($){
	$.datepicker.regional['tr'] = {
		closeText: 'kapat',
		prevText: '&#x3c;geri',
		nextText: 'ileri&#x3e',
		currentText: 'bugün',
		monthNames: ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran',
		'Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'],
		monthNamesShort: ['Oca','Şub','Mar','Nis','May','Haz',
		'Tem','Ağu','Eyl','Eki','Kas','Ara'],
		dayNames: ['Pazar','Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi'],
		dayNamesShort: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
		dayNamesMin: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
		weekHeader: 'Hf',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['tr']);
});
/* Ukrainian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Maxim Drogobitskiy (maxdao@gmail.com). */
/* Corrected by Igor Milla (igor.fsp.milla@gmail.com). */
jQuery(function($){
	$.datepicker.regional['uk'] = {
		closeText: 'Закрити',
		prevText: '&#x3c;',
		nextText: '&#x3e;',
		currentText: 'Сьогодні',
		monthNames: ['Січень','Лютий','Березень','Квітень','Травень','Червень',
		'Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'],
		monthNamesShort: ['Січ','Лют','Бер','Кві','Тра','Чер',
		'Лип','Сер','Вер','Жов','Лис','Гру'],
		dayNames: ['неділя','понеділок','вівторок','середа','четвер','п’ятниця','субота'],
		dayNamesShort: ['нед','пнд','вів','срд','чтв','птн','сбт'],
		dayNamesMin: ['Нд','Пн','Вт','Ср','Чт','Пт','Сб'],
		weekHeader: 'Тиж',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['uk']);
});
/* Vietnamese initialisation for the jQuery UI date picker plugin. */
/* Translated by Le Thanh Huy (lthanhhuy@cit.ctu.edu.vn). */
jQuery(function($){
	$.datepicker.regional['vi'] = {
		closeText: 'Đóng',
		prevText: '&#x3c;Trước',
		nextText: 'Tiếp&#x3e;',
		currentText: 'Hôm nay',
		monthNames: ['Tháng Một', 'Tháng Hai', 'Tháng Ba', 'Tháng Tư', 'Tháng Năm', 'Tháng Sáu',
		'Tháng Bảy', 'Tháng Tám', 'Tháng Chín', 'Tháng Mười', 'Tháng Mười Một', 'Tháng Mười Hai'],
		monthNamesShort: ['Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 5', 'Tháng 6',
		'Tháng 7', 'Tháng 8', 'Tháng 9', 'Tháng 10', 'Tháng 11', 'Tháng 12'],
		dayNames: ['Chủ Nhật', 'Thứ Hai', 'Thứ Ba', 'Thứ Tư', 'Thứ Năm', 'Thứ Sáu', 'Thứ Bảy'],
		dayNamesShort: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'],
		dayNamesMin: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'],
		weekHeader: 'Tu',
		dateFormat: 'dd/mm/yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['vi']);
});

/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Cloudream (cloudream@gmail.com). */
jQuery(function($){
	$.datepicker.regional['zh-CN'] = {
		closeText: '关闭',
		prevText: '&#x3c;上月',
		nextText: '下月&#x3e;',
		currentText: '今天',
		monthNames: ['一月','二月','三月','四月','五月','六月',
		'七月','八月','九月','十月','十一月','十二月'],
		monthNamesShort: ['一月','二月','三月','四月','五月','六月',
		'七月','八月','九月','十月','十一月','十二月'],
		dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
		dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
		dayNamesMin: ['日','一','二','三','四','五','六'],
		weekHeader: '周',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: '年'};
	$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
});

/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by SCCY (samuelcychan@gmail.com). */
jQuery(function($){
	$.datepicker.regional['zh-HK'] = {
		closeText: '關閉',
		prevText: '&#x3c;上月',
		nextText: '下月&#x3e;',
		currentText: '今天',
		monthNames: ['一月','二月','三月','四月','五月','六月',
		'七月','八月','九月','十月','十一月','十二月'],
		monthNamesShort: ['一月','二月','三月','四月','五月','六月',
		'七月','八月','九月','十月','十一月','十二月'],
		dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
		dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
		dayNamesMin: ['日','一','二','三','四','五','六'],
		weekHeader: '周',
		dateFormat: 'dd-mm-yy',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: '年'};
	$.datepicker.setDefaults($.datepicker.regional['zh-HK']);
});

/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Ressol (ressol@gmail.com). */
jQuery(function($){
	$.datepicker.regional['zh-TW'] = {
		closeText: '關閉',
		prevText: '&#x3c;上月',
		nextText: '下月&#x3e;',
		currentText: '今天',
		monthNames: ['一月','二月','三月','四月','五月','六月',
		'七月','八月','九月','十月','十一月','十二月'],
		monthNamesShort: ['一月','二月','三月','四月','五月','六月',
		'七月','八月','九月','十月','十一月','十二月'],
		dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
		dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
		dayNamesMin: ['日','一','二','三','四','五','六'],
		weekHeader: '周',
		dateFormat: 'yy/mm/dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: '年'};
	$.datepicker.setDefaults($.datepicker.regional['zh-TW']);
});


/* ========================================
 FILE: /includes/js/jquery/cs-autocomplete.js
 ==================== */

/**
 * Upraveny uiautocomplete pre shopy s JS optimalizaciami (pouzity napr. v mod_shop_search, checkoute. atd.
 */

jQuery.widget('custom.csautocomplete', jQuery.ui.autocomplete, {
	_create    : function () {
		this._super();
		this.widget().menu("option", "items", "> :not(.ac_results_counter)");
		//if ( is_cs_user('separate_js') ) {
			var classes = this.options && this.options.classes && this.options.classes["ui-autocomplete"];
			if (typeof classes === 'string') {
				this.menu.element.wrap('<div class="ac_results ui-autocomplete ' + classes + '"></div>');
			} else {
				this.menu.element.wrap('<div class="ac_results ui-autocomplete"></div>');
			}
		//} else {
		//	this.menu.element.wrap('<div class="ac_results ui-autocomplete"></div>' );
		//}
	},
	_renderMenu: function (ul, items) {
		var self = this;
		var resultCounter;
		if (items.length === script_manage_params_aacwpi.uacl) {
			resultCounter = '&ge; ' + items.length + ' ' + js_lang_sphf_result_3;
		} else if (items.length >= 5) {
			resultCounter = items.length + ' ' + js_lang_sphf_result_3;
		} else if (items.length > 1 && items.length < 5) {
			resultCounter = items.length + ' ' + js_lang_sphf_result_2;
		} else if (items.length === 1) {
			resultCounter = items.length + ' ' + js_lang_sphf_result_1;
		}

		if (items[0].value !== cms_js_iterate_notfound) {
			ul.before('<div class="ac_results_counter">' + resultCounter + '</div>');
		}

		ul.parent().show();

		jQuery.each(items, function (index, item) {
			if (item !== null && item !== []) {
				self._renderItemData(ul, item);
			}
		});
	},
	_renderItem: function( ul, item ) {
		if (item.value === cms_js_iterate_notfound) {
			return jQuery('<li>').text(item.value).appendTo( ul );
		}
		var linkElement = jQuery('<a>').attr('href', item.value).append(item.label);
		return jQuery('<li>').append(linkElement).appendTo(ul);
	},
	_suggest   : function (items) {
		var $menu = this.menu.element;
		$menu.prev( '.ac_results_counter' ).remove();
		this._super( items );
		var inputBottom = this.element.offset().top + this.element.height();
		var inputLeft = this.element.offset().left;
		//var inputWidth = $menu.css('width');
		var inputWidth = this.element.css('width');
		$menu.closest('.ac_results').css('top', inputBottom).css('left', inputLeft).css('width', inputWidth).css('position', 'absolute');
		$menu.css('top', '').css('left', '');
		$menu.removeClass('ui-autocomplete');
	},
	_close: function( e ) {
		this._super( e );

		this.menu.element
			.parent()
			.hide();

		this.menu.element
			.prev( '.ac_results_counter' )
			.remove();
	}
});



/* ========================================
 FILE: /includes/js/jquery/cs-jquery-ui-custom-settings.js
 ==================== */

jQuery(function() {
	if (typeof js_get_lang !== 'undefined') {
		var lang = js_get_lang === 'cz' ? 'cs' : js_get_lang;
		jQuery.datepicker.setDefaults(jQuery.datepicker.regional[lang]);
	} else {
		jQuery.datepicker.setDefaults(jQuery.datepicker.regional['']);
	}
});



/* ========================================
 FILE: /includes/js/jquery.lazy.js
 ==================== */

/*! lazysizes - v5.1.0 - pozor zmenene CS srcAttr hodnota bola nahradene, NUTNE loadHidden nastavit na FALSE !  */
(function(window, factory) {
	var lazySizes = factory(window, window.document);
	window.lazySizes = lazySizes;
	if(typeof module == 'object' && module.exports){
		module.exports = lazySizes;
	}
}(typeof window != 'undefined' ?
	window : {}, function l(window, document) {
		'use strict';
		/*jshint eqnull:true */

		var lazysizes, lazySizesCfg;

		(function(){
			var prop;

			var lazySizesDefaults = {
				lazyClass: 'lazyload',
				loadedClass: 'lazyloaded',
				loadingClass: 'lazyloading',
				preloadClass: 'lazypreload',
				errorClass: 'lazyerror',
				//strictClass: 'lazystrict',
				autosizesClass: 'lazyautosizes',
				srcAttr: 'longdesc',
				srcsetAttr: 'data-srcset',
				sizesAttr: 'data-sizes',
				//preloadAfterLoad: false,
				minSize: 40,
				customMedia: {},
				init: true,
				expFactor: 1.5,
				hFac: 0.8,
				loadMode: 2,
				loadHidden: false,
				ricTimeout: 0,
				throttleDelay: 125,
			};

			lazySizesCfg = window.lazySizesConfig || window.lazysizesConfig || {};

			for(prop in lazySizesDefaults){
				if(!(prop in lazySizesCfg)){
					lazySizesCfg[prop] = lazySizesDefaults[prop];
				}
			}
		})();

		if (!document || !document.getElementsByClassName) {
			return {
				init: function () {},
				cfg: lazySizesCfg,
				noSupport: true,
			};
		}

		var docElem = document.documentElement;

		var Date = window.Date;

		var supportPicture = window.HTMLPictureElement;

		var _addEventListener = 'addEventListener';

		var _getAttribute = 'getAttribute';

		var addEventListener = window[_addEventListener];

		var setTimeout = window.setTimeout;

		var requestAnimationFrame = window.requestAnimationFrame || setTimeout;

		var requestIdleCallback = window.requestIdleCallback;

		var regPicture = /^picture$/i;

		var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];

		var regClassCache = {};

		var forEach = Array.prototype.forEach;

		var hasClass = function(ele, cls) {
			if(!regClassCache[cls]){
				regClassCache[cls] = new RegExp('(\\s|^)'+cls+'(\\s|$)');
			}
			return regClassCache[cls].test(ele[_getAttribute]('class') || '') && regClassCache[cls];
		};

		var addClass = function(ele, cls) {
			if (!hasClass(ele, cls)){
				ele.setAttribute('class', (ele[_getAttribute]('class') || '').trim() + ' ' + cls);
			}
		};

		var removeClass = function(ele, cls) {
			var reg;
			if ((reg = hasClass(ele,cls))) {
				ele.setAttribute('class', (ele[_getAttribute]('class') || '').replace(reg, ' '));
			}
		};

		var addRemoveLoadEvents = function(dom, fn, add){
			var action = add ? _addEventListener : 'removeEventListener';
			if(add){
				addRemoveLoadEvents(dom, fn);
			}
			loadEvents.forEach(function(evt){
				dom[action](evt, fn);
			});
		};

		var triggerEvent = function(elem, name, detail, noBubbles, noCancelable){
			var event = document.createEvent('Event');

			if(!detail){
				detail = {};
			}

			detail.instance = lazysizes;

			event.initEvent(name, !noBubbles, !noCancelable);

			event.detail = detail;

			elem.dispatchEvent(event);
			return event;
		};

		var updatePolyfill = function (el, full){
			var polyfill;
			if( !supportPicture && ( polyfill = (window.picturefill || lazySizesCfg.pf) ) ){
				if(full && full.src && !el[_getAttribute]('srcset')){
					el.setAttribute('srcset', full.src);
				}
				polyfill({reevaluate: true, elements: [el]});
			} else if(full && full.src){
				el.src = full.src;
			}
		};

		var getCSS = function (elem, style){
			return (getComputedStyle(elem, null) || {})[style];
		};

		var getWidth = function(elem, parent, width){
			width = width || elem.offsetWidth;

			while(width < lazySizesCfg.minSize && parent && !elem._lazysizesWidth){
				width =  parent.offsetWidth;
				parent = parent.parentNode;
			}

			return width;
		};

		var rAF = (function(){
			var running, waiting;
			var firstFns = [];
			var secondFns = [];
			var fns = firstFns;

			var run = function(){
				var runFns = fns;

				fns = firstFns.length ? secondFns : firstFns;

				running = true;
				waiting = false;

				while(runFns.length){
					runFns.shift()();
				}

				running = false;
			};

			var rafBatch = function(fn, queue){
				if(running && !queue){
					fn.apply(this, arguments);
				} else {
					fns.push(fn);

					if(!waiting){
						waiting = true;
						(document.hidden ? setTimeout : requestAnimationFrame)(run);
					}
				}
			};

			rafBatch._lsFlush = run;

			return rafBatch;
		})();

		var rAFIt = function(fn, simple){
			return simple ?
				function() {
					rAF(fn);
				} :
				function(){
					var that = this;
					var args = arguments;
					rAF(function(){
						fn.apply(that, args);
					});
				}
				;
		};

		var throttle = function(fn){
			var running;
			var lastTime = 0;
			var gDelay = lazySizesCfg.throttleDelay;
			var rICTimeout = lazySizesCfg.ricTimeout;
			var run = function(){
				running = false;
				lastTime = Date.now();
				fn();
			};
			var idleCallback = requestIdleCallback && rICTimeout > 49 ?
				function(){
					requestIdleCallback(run, {timeout: rICTimeout});

					if(rICTimeout !== lazySizesCfg.ricTimeout){
						rICTimeout = lazySizesCfg.ricTimeout;
					}
				} :
				rAFIt(function(){
					setTimeout(run);
				}, true)
			;

			return function(isPriority){
				var delay;

				if((isPriority = isPriority === true)){
					rICTimeout = 33;
				}

				if(running){
					return;
				}

				running =  true;

				delay = gDelay - (Date.now() - lastTime);

				if(delay < 0){
					delay = 0;
				}

				if(isPriority || delay < 9){
					idleCallback();
				} else {
					setTimeout(idleCallback, delay);
				}
			};
		};

		//based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
		var debounce = function(func) {
			var timeout, timestamp;
			var wait = 99;
			var run = function(){
				timeout = null;
				func();
			};
			var later = function() {
				var last = Date.now() - timestamp;

				if (last < wait) {
					setTimeout(later, wait - last);
				} else {
					(requestIdleCallback || run)(run);
				}
			};

			return function() {
				timestamp = Date.now();

				if (!timeout) {
					timeout = setTimeout(later, wait);
				}
			};
		};

		var loader = (function(){
			var preloadElems, isCompleted, resetPreloadingTimer, loadMode, started;

			var eLvW, elvH, eLtop, eLleft, eLright, eLbottom, isBodyHidden;

			var regImg = /^img$/i;
			var regIframe = /^iframe$/i;

			var supportScroll = ('onscroll' in window) && !(/(gle|ing)bot/.test(navigator.userAgent));

			var shrinkExpand = 0;
			var currentExpand = 0;

			var isLoading = 0;
			var lowRuns = -1;

			var resetPreloading = function(e){
				isLoading--;
				if(!e || isLoading < 0 || !e.target){
					isLoading = 0;
				}
			};

			var isVisible = function (elem) {
				if (isBodyHidden == null) {
					isBodyHidden = getCSS(document.body, 'visibility') == 'hidden';
				}

				return isBodyHidden || (getCSS(elem.parentNode, 'visibility') != 'hidden' && getCSS(elem, 'visibility') != 'hidden');
			};

			var isNestedVisible = function(elem, elemExpand){
				var outerRect;
				var parent = elem;
				var visible = isVisible(elem);

				eLtop -= elemExpand;
				eLbottom += elemExpand;
				eLleft -= elemExpand;
				eLright += elemExpand;

				while(visible && (parent = parent.offsetParent) && parent != document.body && parent != docElem){
					visible = ((getCSS(parent, 'opacity') || 1) > 0);

					if(visible && getCSS(parent, 'overflow') != 'visible'){
						outerRect = parent.getBoundingClientRect();
						visible = eLright > outerRect.left &&
							eLleft < outerRect.right &&
							eLbottom > outerRect.top - 1 &&
							eLtop < outerRect.bottom + 1
						;
					}
				}

				return visible;
			};

			var checkElements = function() {
				var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal,
				    beforeExpandVal, defaultExpand, preloadExpand, hFac;
				var lazyloadElems = lazysizes.elements;

				if((loadMode = lazySizesCfg.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)){

					i = 0;

					lowRuns++;

					for(; i < eLlen; i++){

						if(!lazyloadElems[i] || lazyloadElems[i]._lazyRace){continue;}

						if(!supportScroll || (lazysizes.prematureUnveil && lazysizes.prematureUnveil(lazyloadElems[i]))){unveilElement(lazyloadElems[i]);continue;}

						if(!(elemExpandVal = lazyloadElems[i][_getAttribute]('data-expand')) || !(elemExpand = elemExpandVal * 1)){
							elemExpand = currentExpand;
						}

						if (!defaultExpand) {
							defaultExpand = (!lazySizesCfg.expand || lazySizesCfg.expand < 1) ?
								docElem.clientHeight > 500 && docElem.clientWidth > 500 ? 500 : 370 :
								lazySizesCfg.expand;

							lazysizes._defEx = defaultExpand;

							preloadExpand = defaultExpand * lazySizesCfg.expFactor;
							hFac = lazySizesCfg.hFac;
							isBodyHidden = null;

							if(currentExpand < preloadExpand && isLoading < 1 && lowRuns > 2 && loadMode > 2 && !document.hidden){
								currentExpand = preloadExpand;
								lowRuns = 0;
							} else if(loadMode > 1 && lowRuns > 1 && isLoading < 6){
								currentExpand = defaultExpand;
							} else {
								currentExpand = shrinkExpand;
							}
						}

						if(beforeExpandVal !== elemExpand){
							eLvW = innerWidth + (elemExpand * hFac);
							elvH = innerHeight + elemExpand;
							elemNegativeExpand = elemExpand * -1;
							beforeExpandVal = elemExpand;
						}

						rect = lazyloadElems[i].getBoundingClientRect();

						if ((eLbottom = rect.bottom) >= elemNegativeExpand &&
							(eLtop = rect.top) <= elvH &&
							(eLright = rect.right) >= elemNegativeExpand * hFac &&
							(eLleft = rect.left) <= eLvW &&
							(eLbottom || eLright || eLleft || eLtop) &&
							(lazySizesCfg.loadHidden || isVisible(lazyloadElems[i])) &&
							((isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4)) || isNestedVisible(lazyloadElems[i], elemExpand))){
							unveilElement(lazyloadElems[i]);
							loadedSomething = true;
							if(isLoading > 9){break;}
						} else if(!loadedSomething && isCompleted && !autoLoadElem &&
							isLoading < 4 && lowRuns < 4 && loadMode > 2 &&
							(preloadElems[0] || lazySizesCfg.preloadAfterLoad) &&
							(preloadElems[0] || (!elemExpandVal && ((eLbottom || eLright || eLleft || eLtop) || lazyloadElems[i][_getAttribute](lazySizesCfg.sizesAttr) != 'auto')))){
							autoLoadElem = preloadElems[0] || lazyloadElems[i];
						}
					}

					if(autoLoadElem && !loadedSomething){
						unveilElement(autoLoadElem);
					}
				}
			};

			var throttledCheckElements = throttle(checkElements);

			var switchLoadingClass = function(e){
				var elem = e.target;

				if (elem._lazyCache) {
					delete elem._lazyCache;
					return;
				}

				resetPreloading(e);
				addClass(elem, lazySizesCfg.loadedClass);
				removeClass(elem, lazySizesCfg.loadingClass);
				addRemoveLoadEvents(elem, rafSwitchLoadingClass);
				triggerEvent(elem, 'lazyloaded');
			};
			var rafedSwitchLoadingClass = rAFIt(switchLoadingClass);
			var rafSwitchLoadingClass = function(e){
				rafedSwitchLoadingClass({target: e.target});
			};

			var changeIframeSrc = function(elem, src){
				try {
					elem.contentWindow.location.replace(src);
				} catch(e){
					elem.src = src;
				}
			};

			var handleSources = function(source){
				var customMedia;

				var sourceSrcset = source[_getAttribute](lazySizesCfg.srcsetAttr);

				if( (customMedia = lazySizesCfg.customMedia[source[_getAttribute]('data-media') || source[_getAttribute]('media')]) ){
					source.setAttribute('media', customMedia);
				}

				if(sourceSrcset){
					source.setAttribute('srcset', sourceSrcset);
				}
			};

			var lazyUnveil = rAFIt(function (elem, detail, isAuto, sizes, isImg){
				var src, srcset, parent, isPicture, event, firesLoad;

				if(!(event = triggerEvent(elem, 'lazybeforeunveil', detail)).defaultPrevented){

					if(sizes){
						if(isAuto){
							addClass(elem, lazySizesCfg.autosizesClass);
						} else {
							elem.setAttribute('sizes', sizes);
						}
					}

					srcset = elem[_getAttribute](lazySizesCfg.srcsetAttr);
					src = elem[_getAttribute](lazySizesCfg.srcAttr);

					if(isImg) {
						parent = elem.parentNode;
						isPicture = parent && regPicture.test(parent.nodeName || '');
					}

					firesLoad = detail.firesLoad || (('src' in elem) && (srcset || src || isPicture));

					event = {target: elem};

					addClass(elem, lazySizesCfg.loadingClass);

					if(firesLoad){
						clearTimeout(resetPreloadingTimer);
						resetPreloadingTimer = setTimeout(resetPreloading, 2500);
						addRemoveLoadEvents(elem, rafSwitchLoadingClass, true);
					}

					if(isPicture){
						forEach.call(parent.getElementsByTagName('source'), handleSources);
					}

					if(srcset){
						elem.setAttribute('srcset', srcset);
					} else if(src && !isPicture){
						if(regIframe.test(elem.nodeName)){
							changeIframeSrc(elem, src);
						} else {
							elem.src = src;
						}
					}

					if(isImg && (srcset || isPicture)){
						updatePolyfill(elem, {src: src});
					}
				}

				if(elem._lazyRace){
					delete elem._lazyRace;
				}
				removeClass(elem, lazySizesCfg.lazyClass);

				rAF(function(){
					// Part of this can be removed as soon as this fix is older: https://bugs.chromium.org/p/chromium/issues/detail?id=7731 (2015)
					var isLoaded = elem.complete && elem.naturalWidth > 1;

					if( !firesLoad || isLoaded){
						if (isLoaded) {
							addClass(elem, 'ls-is-cached');
						}
						switchLoadingClass(event);
						elem._lazyCache = true;
						setTimeout(function(){
							if ('_lazyCache' in elem) {
								delete elem._lazyCache;
							}
						}, 9);
					}
					if (elem.loading == 'lazy') {
						isLoading--;
					}
				}, true);
			});

			var unveilElement = function (elem){
				if (elem._lazyRace) {return;}
				var detail;

				var isImg = regImg.test(elem.nodeName);

				//allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
				var sizes = isImg && (elem[_getAttribute](lazySizesCfg.sizesAttr) || elem[_getAttribute]('sizes'));
				var isAuto = sizes == 'auto';

				if( (isAuto || !isCompleted) && isImg && (elem[_getAttribute]('src') || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesCfg.errorClass) && hasClass(elem, lazySizesCfg.lazyClass)){return;}

				detail = triggerEvent(elem, 'lazyunveilread').detail;

				if(isAuto){
					autoSizer.updateElem(elem, true, elem.offsetWidth);
				}

				elem._lazyRace = true;
				isLoading++;

				lazyUnveil(elem, detail, isAuto, sizes, isImg);
			};

			var afterScroll = debounce(function(){
				lazySizesCfg.loadMode = 3;
				throttledCheckElements();
			});

			var altLoadmodeScrollListner = function(){
				if(lazySizesCfg.loadMode == 3){
					lazySizesCfg.loadMode = 2;
				}
				afterScroll();
			};

			var onload = function(){
				if(isCompleted){return;}
				if(Date.now() - started < 999){
					setTimeout(onload, 999);
					return;
				}


				isCompleted = true;

				lazySizesCfg.loadMode = 3;

				throttledCheckElements();

				addEventListener('scroll', altLoadmodeScrollListner, true);
			};

			return {
				_: function(){
					started = Date.now();

					lazysizes.elements = document.getElementsByClassName(lazySizesCfg.lazyClass);
					preloadElems = document.getElementsByClassName(lazySizesCfg.lazyClass + ' ' + lazySizesCfg.preloadClass);

					addEventListener('scroll', throttledCheckElements, true);

					addEventListener('resize', throttledCheckElements, true);

					if(window.MutationObserver){
						new MutationObserver( throttledCheckElements ).observe( docElem, {childList: true, subtree: true, attributes: true} );
					} else {
						docElem[_addEventListener]('DOMNodeInserted', throttledCheckElements, true);
						docElem[_addEventListener]('DOMAttrModified', throttledCheckElements, true);
						setInterval(throttledCheckElements, 999);
					}

					addEventListener('hashchange', throttledCheckElements, true);

					//, 'fullscreenchange'
					['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend'].forEach(function(name){
						document[_addEventListener](name, throttledCheckElements, true);
					});

					if((/d$|^c/.test(document.readyState))){
						onload();
					} else {
						addEventListener('load', onload);
						document[_addEventListener]('DOMContentLoaded', throttledCheckElements);
						setTimeout(onload, 20000);
					}

					if(lazysizes.elements.length){
						checkElements();
						rAF._lsFlush();
					} else {
						throttledCheckElements();
					}
				},
				checkElems: throttledCheckElements,
				unveil: unveilElement,
				_aLSL: altLoadmodeScrollListner,
			};
		})();


		var autoSizer = (function(){
			var autosizesElems;

			var sizeElement = rAFIt(function(elem, parent, event, width){
				var sources, i, len;
				elem._lazysizesWidth = width;
				width += 'px';

				elem.setAttribute('sizes', width);

				if(regPicture.test(parent.nodeName || '')){
					sources = parent.getElementsByTagName('source');
					for(i = 0, len = sources.length; i < len; i++){
						sources[i].setAttribute('sizes', width);
					}
				}

				if(!event.detail.dataAttr){
					updatePolyfill(elem, event.detail);
				}
			});
			var getSizeElement = function (elem, dataAttr, width){
				var event;
				var parent = elem.parentNode;

				if(parent){
					width = getWidth(elem, parent, width);
					event = triggerEvent(elem, 'lazybeforesizes', {width: width, dataAttr: !!dataAttr});

					if(!event.defaultPrevented){
						width = event.detail.width;

						if(width && width !== elem._lazysizesWidth){
							sizeElement(elem, parent, event, width);
						}
					}
				}
			};

			var updateElementsSizes = function(){
				var i;
				var len = autosizesElems.length;
				if(len){
					i = 0;

					for(; i < len; i++){
						getSizeElement(autosizesElems[i]);
					}
				}
			};

			var debouncedUpdateElementsSizes = debounce(updateElementsSizes);

			return {
				_: function(){
					autosizesElems = document.getElementsByClassName(lazySizesCfg.autosizesClass);
					addEventListener('resize', debouncedUpdateElementsSizes);
				},
				checkElems: debouncedUpdateElementsSizes,
				updateElem: getSizeElement
			};
		})();

		var init = function(){
			if(!init.i && document.getElementsByClassName){
				init.i = true;
				autoSizer._();
				loader._();
			}
		};

		setTimeout(function(){
			if(lazySizesCfg.init){
				init();
			}
		});

		lazysizes = {
			cfg: lazySizesCfg,
			autoSizer: autoSizer,
			loader: loader,
			init: init,
			uP: updatePolyfill,
			aC: addClass,
			rC: removeClass,
			hC: hasClass,
			fire: triggerEvent,
			gW: getWidth,
			rAF: rAF,
		};

		return lazysizes;
	}
));

/* ========================================
 FILE: /includes/js/tooltipster/tooltipster.min.js
 ==================== */

/*! tooltipster v4.2.6 */!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){function b(a){this.$container,this.constraints=null,this.__$tooltip,this.__init(a)}function c(b,c){var d=!0;return a.each(b,function(a,e){return void 0===c[a]||b[a]!==c[a]?(d=!1,!1):void 0}),d}function d(b){var c=b.attr("id"),d=c?h.window.document.getElementById(c):null;return d?d===b[0]:a.contains(h.window.document.body,b[0])}function e(){if(!g)return!1;var a=g.document.body||g.document.documentElement,b=a.style,c="transition",d=["Moz","Webkit","Khtml","O","ms"];if("string"==typeof b[c])return!0;c=c.charAt(0).toUpperCase()+c.substr(1);for(var e=0;e<d.length;e++)if("string"==typeof b[d[e]+c])return!0;return!1}var f={animation:"fade",animationDuration:350,content:null,contentAsHTML:!1,contentCloning:!1,debug:!0,delay:300,delayTouch:[300,500],functionInit:null,functionBefore:null,functionReady:null,functionAfter:null,functionFormat:null,IEmin:6,interactive:!1,multiple:!1,parent:null,plugins:["sideTip"],repositionOnScroll:!1,restoration:"none",selfDestruction:!0,theme:[],timer:0,trackerInterval:500,trackOrigin:!1,trackTooltip:!1,trigger:"hover",triggerClose:{click:!1,mouseleave:!1,originClick:!1,scroll:!1,tap:!1,touchleave:!1},triggerOpen:{click:!1,mouseenter:!1,tap:!1,touchstart:!1},updateAnimation:"rotate",zIndex:9999999},g="undefined"!=typeof window?window:null,h={hasTouchCapability:!(!g||!("ontouchstart"in g||g.DocumentTouch&&g.document instanceof g.DocumentTouch||g.navigator.maxTouchPoints)),hasTransitions:e(),IE:!1,semVer:"4.2.6",window:g},i=function(){this.__$emitterPrivate=a({}),this.__$emitterPublic=a({}),this.__instancesLatestArr=[],this.__plugins={},this._env=h};i.prototype={__bridge:function(b,c,d){if(!c[d]){var e=function(){};e.prototype=b;var g=new e;g.__init&&g.__init(c),a.each(b,function(a,b){0!=a.indexOf("__")&&(c[a]?f.debug&&console.log("The "+a+" method of the "+d+" plugin conflicts with another plugin or native methods"):(c[a]=function(){return g[a].apply(g,Array.prototype.slice.apply(arguments))},c[a].bridged=g))}),c[d]=g}return this},__setWindow:function(a){return h.window=a,this},_getRuler:function(a){return new b(a)},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_plugin:function(b){var c=this;if("string"==typeof b){var d=b,e=null;return d.indexOf(".")>0?e=c.__plugins[d]:a.each(c.__plugins,function(a,b){return b.name.substring(b.name.length-d.length-1)=="."+d?(e=b,!1):void 0}),e}if(b.name.indexOf(".")<0)throw new Error("Plugins must be namespaced");return c.__plugins[b.name]=b,b.core&&c.__bridge(b.core,c,b.name),this},_trigger:function(){var a=Array.prototype.slice.apply(arguments);return"string"==typeof a[0]&&(a[0]={type:a[0]}),this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,a),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,a),this},instances:function(b){var c=[],d=b||".tooltipstered";return a(d).each(function(){var b=a(this),d=b.data("tooltipster-ns");d&&a.each(d,function(a,d){c.push(b.data(d))})}),c},instancesLatest:function(){return this.__instancesLatestArr},off:function(){return this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},origins:function(b){var c=b?b+" ":"";return a(c+".tooltipstered").toArray()},setDefaults:function(b){return a.extend(f,b),this},triggerHandler:function(){return this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},a.tooltipster=new i,a.Tooltipster=function(b,c){this.__callbacks={close:[],open:[]},this.__closingTime,this.__Content,this.__contentBcr,this.__destroyed=!1,this.__$emitterPrivate=a({}),this.__$emitterPublic=a({}),this.__enabled=!0,this.__garbageCollector,this.__Geometry,this.__lastPosition,this.__namespace="tooltipster-"+Math.round(1e6*Math.random()),this.__options,this.__$originParents,this.__pointerIsOverOrigin=!1,this.__previousThemes=[],this.__state="closed",this.__timeouts={close:[],open:null},this.__touchEvents=[],this.__tracker=null,this._$origin,this._$tooltip,this.__init(b,c)},a.Tooltipster.prototype={__init:function(b,c){var d=this;if(d._$origin=a(b),d.__options=a.extend(!0,{},f,c),d.__optionsFormat(),!h.IE||h.IE>=d.__options.IEmin){var e=null;if(void 0===d._$origin.data("tooltipster-initialTitle")&&(e=d._$origin.attr("title"),void 0===e&&(e=null),d._$origin.data("tooltipster-initialTitle",e)),null!==d.__options.content)d.__contentSet(d.__options.content);else{var g,i=d._$origin.attr("data-tooltip-content");i&&(g=a(i)),g&&g[0]?d.__contentSet(g.first()):d.__contentSet(e)}d._$origin.removeAttr("title").addClass("tooltipstered"),d.__prepareOrigin(),d.__prepareGC(),a.each(d.__options.plugins,function(a,b){d._plug(b)}),h.hasTouchCapability&&a(h.window.document.body).on("touchmove."+d.__namespace+"-triggerOpen",function(a){d._touchRecordEvent(a)}),d._on("created",function(){d.__prepareTooltip()})._on("repositioned",function(a){d.__lastPosition=a.position})}else d.__options.disabled=!0},__contentInsert:function(){var a=this,b=a._$tooltip.find(".tooltipster-content"),c=a.__Content,d=function(a){c=a};return a._trigger({type:"format",content:a.__Content,format:d}),a.__options.functionFormat&&(c=a.__options.functionFormat.call(a,a,{origin:a._$origin[0]},a.__Content)),"string"!=typeof c||a.__options.contentAsHTML?b.empty().append(c):b.text(c),a},__contentSet:function(b){return b instanceof a&&this.__options.contentCloning&&(b=b.clone(!0)),this.__Content=b,this._trigger({type:"updated",content:b}),this},__destroyError:function(){throw new Error("This tooltip has been destroyed and cannot execute your method call.")},__geometry:function(){var b=this,c=b._$origin,d=b._$origin.is("area");if(d){var e=b._$origin.parent().attr("name");c=a('img[usemap="#'+e+'"]')}var f=c[0].getBoundingClientRect(),g=a(h.window.document),i=a(h.window),j=c,k={available:{document:null,window:null},document:{size:{height:g.height(),width:g.width()}},window:{scroll:{left:h.window.scrollX||h.window.document.documentElement.scrollLeft,top:h.window.scrollY||h.window.document.documentElement.scrollTop},size:{height:i.height(),width:i.width()}},origin:{fixedLineage:!1,offset:{},size:{height:f.bottom-f.top,width:f.right-f.left},usemapImage:d?c[0]:null,windowOffset:{bottom:f.bottom,left:f.left,right:f.right,top:f.top}}};if(d){var l=b._$origin.attr("shape"),m=b._$origin.attr("coords");if(m&&(m=m.split(","),a.map(m,function(a,b){m[b]=parseInt(a)})),"default"!=l)switch(l){case"circle":var n=m[0],o=m[1],p=m[2],q=o-p,r=n-p;k.origin.size.height=2*p,k.origin.size.width=k.origin.size.height,k.origin.windowOffset.left+=r,k.origin.windowOffset.top+=q;break;case"rect":var s=m[0],t=m[1],u=m[2],v=m[3];k.origin.size.height=v-t,k.origin.size.width=u-s,k.origin.windowOffset.left+=s,k.origin.windowOffset.top+=t;break;case"poly":for(var w=0,x=0,y=0,z=0,A="even",B=0;B<m.length;B++){var C=m[B];"even"==A?(C>y&&(y=C,0===B&&(w=y)),w>C&&(w=C),A="odd"):(C>z&&(z=C,1==B&&(x=z)),x>C&&(x=C),A="even")}k.origin.size.height=z-x,k.origin.size.width=y-w,k.origin.windowOffset.left+=w,k.origin.windowOffset.top+=x}}var D=function(a){k.origin.size.height=a.height,k.origin.windowOffset.left=a.left,k.origin.windowOffset.top=a.top,k.origin.size.width=a.width};for(b._trigger({type:"geometry",edit:D,geometry:{height:k.origin.size.height,left:k.origin.windowOffset.left,top:k.origin.windowOffset.top,width:k.origin.size.width}}),k.origin.windowOffset.right=k.origin.windowOffset.left+k.origin.size.width,k.origin.windowOffset.bottom=k.origin.windowOffset.top+k.origin.size.height,k.origin.offset.left=k.origin.windowOffset.left+k.window.scroll.left,k.origin.offset.top=k.origin.windowOffset.top+k.window.scroll.top,k.origin.offset.bottom=k.origin.offset.top+k.origin.size.height,k.origin.offset.right=k.origin.offset.left+k.origin.size.width,k.available.document={bottom:{height:k.document.size.height-k.origin.offset.bottom,width:k.document.size.width},left:{height:k.document.size.height,width:k.origin.offset.left},right:{height:k.document.size.height,width:k.document.size.width-k.origin.offset.right},top:{height:k.origin.offset.top,width:k.document.size.width}},k.available.window={bottom:{height:Math.max(k.window.size.height-Math.max(k.origin.windowOffset.bottom,0),0),width:k.window.size.width},left:{height:k.window.size.height,width:Math.max(k.origin.windowOffset.left,0)},right:{height:k.window.size.height,width:Math.max(k.window.size.width-Math.max(k.origin.windowOffset.right,0),0)},top:{height:Math.max(k.origin.windowOffset.top,0),width:k.window.size.width}};"html"!=j[0].tagName.toLowerCase();){if("fixed"==j.css("position")){k.origin.fixedLineage=!0;break}j=j.parent()}return k},__optionsFormat:function(){return"number"==typeof this.__options.animationDuration&&(this.__options.animationDuration=[this.__options.animationDuration,this.__options.animationDuration]),"number"==typeof this.__options.delay&&(this.__options.delay=[this.__options.delay,this.__options.delay]),"number"==typeof this.__options.delayTouch&&(this.__options.delayTouch=[this.__options.delayTouch,this.__options.delayTouch]),"string"==typeof this.__options.theme&&(this.__options.theme=[this.__options.theme]),null===this.__options.parent?this.__options.parent=a(h.window.document.body):"string"==typeof this.__options.parent&&(this.__options.parent=a(this.__options.parent)),"hover"==this.__options.trigger?(this.__options.triggerOpen={mouseenter:!0,touchstart:!0},this.__options.triggerClose={mouseleave:!0,originClick:!0,touchleave:!0}):"click"==this.__options.trigger&&(this.__options.triggerOpen={click:!0,tap:!0},this.__options.triggerClose={click:!0,tap:!0}),this._trigger("options"),this},__prepareGC:function(){var b=this;return b.__options.selfDestruction?b.__garbageCollector=setInterval(function(){var c=(new Date).getTime();b.__touchEvents=a.grep(b.__touchEvents,function(a,b){return c-a.time>6e4}),d(b._$origin)||b.close(function(){b.destroy()})},2e4):clearInterval(b.__garbageCollector),b},__prepareOrigin:function(){var a=this;if(a._$origin.off("."+a.__namespace+"-triggerOpen"),h.hasTouchCapability&&a._$origin.on("touchstart."+a.__namespace+"-triggerOpen touchend."+a.__namespace+"-triggerOpen touchcancel."+a.__namespace+"-triggerOpen",function(b){a._touchRecordEvent(b)}),a.__options.triggerOpen.click||a.__options.triggerOpen.tap&&h.hasTouchCapability){var b="";a.__options.triggerOpen.click&&(b+="click."+a.__namespace+"-triggerOpen "),a.__options.triggerOpen.tap&&h.hasTouchCapability&&(b+="touchend."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){a._touchIsMeaningfulEvent(b)&&a._open(b)})}if(a.__options.triggerOpen.mouseenter||a.__options.triggerOpen.touchstart&&h.hasTouchCapability){var b="";a.__options.triggerOpen.mouseenter&&(b+="mouseenter."+a.__namespace+"-triggerOpen "),a.__options.triggerOpen.touchstart&&h.hasTouchCapability&&(b+="touchstart."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){!a._touchIsTouchEvent(b)&&a._touchIsEmulatedEvent(b)||(a.__pointerIsOverOrigin=!0,a._openShortly(b))})}if(a.__options.triggerClose.mouseleave||a.__options.triggerClose.touchleave&&h.hasTouchCapability){var b="";a.__options.triggerClose.mouseleave&&(b+="mouseleave."+a.__namespace+"-triggerOpen "),a.__options.triggerClose.touchleave&&h.hasTouchCapability&&(b+="touchend."+a.__namespace+"-triggerOpen touchcancel."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){a._touchIsMeaningfulEvent(b)&&(a.__pointerIsOverOrigin=!1)})}return a},__prepareTooltip:function(){var b=this,c=b.__options.interactive?"auto":"";return b._$tooltip.attr("id",b.__namespace).css({"pointer-events":c,zIndex:b.__options.zIndex}),a.each(b.__previousThemes,function(a,c){b._$tooltip.removeClass(c)}),a.each(b.__options.theme,function(a,c){b._$tooltip.addClass(c)}),b.__previousThemes=a.merge([],b.__options.theme),b},__scrollHandler:function(b){var c=this;if(c.__options.triggerClose.scroll)c._close(b);else if(d(c._$origin)&&d(c._$tooltip)){var e=null;if(b.target===h.window.document)c.__Geometry.origin.fixedLineage||c.__options.repositionOnScroll&&c.reposition(b);else{e=c.__geometry();var f=!1;if("fixed"!=c._$origin.css("position")&&c.__$originParents.each(function(b,c){var d=a(c),g=d.css("overflow-x"),h=d.css("overflow-y");if("visible"!=g||"visible"!=h){var i=c.getBoundingClientRect();if("visible"!=g&&(e.origin.windowOffset.left<i.left||e.origin.windowOffset.right>i.right))return f=!0,!1;if("visible"!=h&&(e.origin.windowOffset.top<i.top||e.origin.windowOffset.bottom>i.bottom))return f=!0,!1}return"fixed"==d.css("position")?!1:void 0}),f)c._$tooltip.css("visibility","hidden");else if(c._$tooltip.css("visibility","visible"),c.__options.repositionOnScroll)c.reposition(b);else{var g=e.origin.offset.left-c.__Geometry.origin.offset.left,i=e.origin.offset.top-c.__Geometry.origin.offset.top;c._$tooltip.css({left:c.__lastPosition.coord.left+g,top:c.__lastPosition.coord.top+i})}}c._trigger({type:"scroll",event:b,geo:e})}return c},__stateSet:function(a){return this.__state=a,this._trigger({type:"state",state:a}),this},__timeoutsClear:function(){return clearTimeout(this.__timeouts.open),this.__timeouts.open=null,a.each(this.__timeouts.close,function(a,b){clearTimeout(b)}),this.__timeouts.close=[],this},__trackerStart:function(){var a=this,b=a._$tooltip.find(".tooltipster-content");return a.__options.trackTooltip&&(a.__contentBcr=b[0].getBoundingClientRect()),a.__tracker=setInterval(function(){if(d(a._$origin)&&d(a._$tooltip)){if(a.__options.trackOrigin){var e=a.__geometry(),f=!1;c(e.origin.size,a.__Geometry.origin.size)&&(a.__Geometry.origin.fixedLineage?c(e.origin.windowOffset,a.__Geometry.origin.windowOffset)&&(f=!0):c(e.origin.offset,a.__Geometry.origin.offset)&&(f=!0)),f||(a.__options.triggerClose.mouseleave?a._close():a.reposition())}if(a.__options.trackTooltip){var g=b[0].getBoundingClientRect();g.height===a.__contentBcr.height&&g.width===a.__contentBcr.width||(a.reposition(),a.__contentBcr=g)}}else a._close()},a.__options.trackerInterval),a},_close:function(b,c,d){var e=this,f=!0;if(e._trigger({type:"close",event:b,stop:function(){f=!1}}),f||d){c&&e.__callbacks.close.push(c),e.__callbacks.open=[],e.__timeoutsClear();var g=function(){a.each(e.__callbacks.close,function(a,c){c.call(e,e,{event:b,origin:e._$origin[0]})}),e.__callbacks.close=[]};if("closed"!=e.__state){var i=!0,j=new Date,k=j.getTime(),l=k+e.__options.animationDuration[1];if("disappearing"==e.__state&&l>e.__closingTime&&e.__options.animationDuration[1]>0&&(i=!1),i){e.__closingTime=l,"disappearing"!=e.__state&&e.__stateSet("disappearing");var m=function(){clearInterval(e.__tracker),e._trigger({type:"closing",event:b}),e._$tooltip.off("."+e.__namespace+"-triggerClose").removeClass("tooltipster-dying"),a(h.window).off("."+e.__namespace+"-triggerClose"),e.__$originParents.each(function(b,c){a(c).off("scroll."+e.__namespace+"-triggerClose")}),e.__$originParents=null,a(h.window.document.body).off("."+e.__namespace+"-triggerClose"),e._$origin.off("."+e.__namespace+"-triggerClose"),e._off("dismissable"),e.__stateSet("closed"),e._trigger({type:"after",event:b}),e.__options.functionAfter&&e.__options.functionAfter.call(e,e,{event:b,origin:e._$origin[0]}),g()};h.hasTransitions?(e._$tooltip.css({"-moz-animation-duration":e.__options.animationDuration[1]+"ms","-ms-animation-duration":e.__options.animationDuration[1]+"ms","-o-animation-duration":e.__options.animationDuration[1]+"ms","-webkit-animation-duration":e.__options.animationDuration[1]+"ms","animation-duration":e.__options.animationDuration[1]+"ms","transition-duration":e.__options.animationDuration[1]+"ms"}),e._$tooltip.clearQueue().removeClass("tooltipster-show").addClass("tooltipster-dying"),e.__options.animationDuration[1]>0&&e._$tooltip.delay(e.__options.animationDuration[1]),e._$tooltip.queue(m)):e._$tooltip.stop().fadeOut(e.__options.animationDuration[1],m)}}else g()}return e},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_open:function(b,c){var e=this;if(!e.__destroying&&d(e._$origin)&&e.__enabled){var f=!0;if("closed"==e.__state&&(e._trigger({type:"before",event:b,stop:function(){f=!1}}),f&&e.__options.functionBefore&&(f=e.__options.functionBefore.call(e,e,{event:b,origin:e._$origin[0]}))),f!==!1&&null!==e.__Content){c&&e.__callbacks.open.push(c),e.__callbacks.close=[],e.__timeoutsClear();var g,i=function(){"stable"!=e.__state&&e.__stateSet("stable"),a.each(e.__callbacks.open,function(a,b){b.call(e,e,{origin:e._$origin[0],tooltip:e._$tooltip[0]})}),e.__callbacks.open=[]};if("closed"!==e.__state)g=0,"disappearing"===e.__state?(e.__stateSet("appearing"),h.hasTransitions?(e._$tooltip.clearQueue().removeClass("tooltipster-dying").addClass("tooltipster-show"),e.__options.animationDuration[0]>0&&e._$tooltip.delay(e.__options.animationDuration[0]),e._$tooltip.queue(i)):e._$tooltip.stop().fadeIn(i)):"stable"==e.__state&&i();else{if(e.__stateSet("appearing"),g=e.__options.animationDuration[0],e.__contentInsert(),e.reposition(b,!0),h.hasTransitions?(e._$tooltip.addClass("tooltipster-"+e.__options.animation).addClass("tooltipster-initial").css({"-moz-animation-duration":e.__options.animationDuration[0]+"ms","-ms-animation-duration":e.__options.animationDuration[0]+"ms","-o-animation-duration":e.__options.animationDuration[0]+"ms","-webkit-animation-duration":e.__options.animationDuration[0]+"ms","animation-duration":e.__options.animationDuration[0]+"ms","transition-duration":e.__options.animationDuration[0]+"ms"}),setTimeout(function(){"closed"!=e.__state&&(e._$tooltip.addClass("tooltipster-show").removeClass("tooltipster-initial"),e.__options.animationDuration[0]>0&&e._$tooltip.delay(e.__options.animationDuration[0]),e._$tooltip.queue(i))},0)):e._$tooltip.css("display","none").fadeIn(e.__options.animationDuration[0],i),e.__trackerStart(),a(h.window).on("resize."+e.__namespace+"-triggerClose",function(b){var c=a(document.activeElement);(c.is("input")||c.is("textarea"))&&a.contains(e._$tooltip[0],c[0])||e.reposition(b)}).on("scroll."+e.__namespace+"-triggerClose",function(a){e.__scrollHandler(a)}),e.__$originParents=e._$origin.parents(),e.__$originParents.each(function(b,c){a(c).on("scroll."+e.__namespace+"-triggerClose",function(a){e.__scrollHandler(a)})}),e.__options.triggerClose.mouseleave||e.__options.triggerClose.touchleave&&h.hasTouchCapability){e._on("dismissable",function(a){a.dismissable?a.delay?(m=setTimeout(function(){e._close(a.event)},a.delay),e.__timeouts.close.push(m)):e._close(a):clearTimeout(m)});var j=e._$origin,k="",l="",m=null;e.__options.interactive&&(j=j.add(e._$tooltip)),e.__options.triggerClose.mouseleave&&(k+="mouseenter."+e.__namespace+"-triggerClose ",l+="mouseleave."+e.__namespace+"-triggerClose "),e.__options.triggerClose.touchleave&&h.hasTouchCapability&&(k+="touchstart."+e.__namespace+"-triggerClose",l+="touchend."+e.__namespace+"-triggerClose touchcancel."+e.__namespace+"-triggerClose"),j.on(l,function(a){if(e._touchIsTouchEvent(a)||!e._touchIsEmulatedEvent(a)){var b="mouseleave"==a.type?e.__options.delay:e.__options.delayTouch;e._trigger({delay:b[1],dismissable:!0,event:a,type:"dismissable"})}}).on(k,function(a){!e._touchIsTouchEvent(a)&&e._touchIsEmulatedEvent(a)||e._trigger({dismissable:!1,event:a,type:"dismissable"})})}e.__options.triggerClose.originClick&&e._$origin.on("click."+e.__namespace+"-triggerClose",function(a){e._touchIsTouchEvent(a)||e._touchIsEmulatedEvent(a)||e._close(a)}),(e.__options.triggerClose.click||e.__options.triggerClose.tap&&h.hasTouchCapability)&&setTimeout(function(){if("closed"!=e.__state){var b="",c=a(h.window.document.body);e.__options.triggerClose.click&&(b+="click."+e.__namespace+"-triggerClose "),e.__options.triggerClose.tap&&h.hasTouchCapability&&(b+="touchend."+e.__namespace+"-triggerClose"),c.on(b,function(b){e._touchIsMeaningfulEvent(b)&&(e._touchRecordEvent(b),e.__options.interactive&&a.contains(e._$tooltip[0],b.target)||e._close(b))}),e.__options.triggerClose.tap&&h.hasTouchCapability&&c.on("touchstart."+e.__namespace+"-triggerClose",function(a){e._touchRecordEvent(a)})}},0),e._trigger("ready"),e.__options.functionReady&&e.__options.functionReady.call(e,e,{origin:e._$origin[0],tooltip:e._$tooltip[0]})}if(e.__options.timer>0){var m=setTimeout(function(){e._close()},e.__options.timer+g);e.__timeouts.close.push(m)}}}return e},_openShortly:function(a){var b=this,c=!0;if("stable"!=b.__state&&"appearing"!=b.__state&&!b.__timeouts.open&&(b._trigger({type:"start",event:a,stop:function(){c=!1}}),c)){var d=0==a.type.indexOf("touch")?b.__options.delayTouch:b.__options.delay;d[0]?b.__timeouts.open=setTimeout(function(){b.__timeouts.open=null,b.__pointerIsOverOrigin&&b._touchIsMeaningfulEvent(a)?(b._trigger("startend"),b._open(a)):b._trigger("startcancel")},d[0]):(b._trigger("startend"),b._open(a))}return b},_optionsExtract:function(b,c){var d=this,e=a.extend(!0,{},c),f=d.__options[b];return f||(f={},a.each(c,function(a,b){var c=d.__options[a];void 0!==c&&(f[a]=c)})),a.each(e,function(b,c){void 0!==f[b]&&("object"!=typeof c||c instanceof Array||null==c||"object"!=typeof f[b]||f[b]instanceof Array||null==f[b]?e[b]=f[b]:a.extend(e[b],f[b]))}),e},_plug:function(b){var c=a.tooltipster._plugin(b);if(!c)throw new Error('The "'+b+'" plugin is not defined');return c.instance&&a.tooltipster.__bridge(c.instance,this,c.name),this},_touchIsEmulatedEvent:function(a){for(var b=!1,c=(new Date).getTime(),d=this.__touchEvents.length-1;d>=0;d--){var e=this.__touchEvents[d];if(!(c-e.time<500))break;e.target===a.target&&(b=!0)}return b},_touchIsMeaningfulEvent:function(a){return this._touchIsTouchEvent(a)&&!this._touchSwiped(a.target)||!this._touchIsTouchEvent(a)&&!this._touchIsEmulatedEvent(a)},_touchIsTouchEvent:function(a){return 0==a.type.indexOf("touch")},_touchRecordEvent:function(a){return this._touchIsTouchEvent(a)&&(a.time=(new Date).getTime(),this.__touchEvents.push(a)),this},_touchSwiped:function(a){for(var b=!1,c=this.__touchEvents.length-1;c>=0;c--){var d=this.__touchEvents[c];if("touchmove"==d.type){b=!0;break}if("touchstart"==d.type&&a===d.target)break}return b},_trigger:function(){var b=Array.prototype.slice.apply(arguments);return"string"==typeof b[0]&&(b[0]={type:b[0]}),b[0].instance=this,b[0].origin=this._$origin?this._$origin[0]:null,b[0].tooltip=this._$tooltip?this._$tooltip[0]:null,this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,b),a.tooltipster._trigger.apply(a.tooltipster,b),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,b),this},_unplug:function(b){var c=this;if(c[b]){var d=a.tooltipster._plugin(b);d.instance&&a.each(d.instance,function(a,d){c[a]&&c[a].bridged===c[b]&&delete c[a]}),c[b].__destroy&&c[b].__destroy(),delete c[b]}return c},close:function(a){return this.__destroyed?this.__destroyError():this._close(null,a),this},content:function(a){var b=this;if(void 0===a)return b.__Content;if(b.__destroyed)b.__destroyError();else if(b.__contentSet(a),null!==b.__Content){if("closed"!==b.__state&&(b.__contentInsert(),b.reposition(),b.__options.updateAnimation))if(h.hasTransitions){var c=b.__options.updateAnimation;b._$tooltip.addClass("tooltipster-update-"+c),setTimeout(function(){"closed"!=b.__state&&b._$tooltip.removeClass("tooltipster-update-"+c)},1e3)}else b._$tooltip.fadeTo(200,.5,function(){"closed"!=b.__state&&b._$tooltip.fadeTo(200,1)})}else b._close();return b},destroy:function(){var b=this;if(b.__destroyed)b.__destroyError();else{"closed"!=b.__state?b.option("animationDuration",0)._close(null,null,!0):b.__timeoutsClear(),b._trigger("destroy"),b.__destroyed=!0,b._$origin.removeData(b.__namespace).off("."+b.__namespace+"-triggerOpen"),a(h.window.document.body).off("."+b.__namespace+"-triggerOpen");var c=b._$origin.data("tooltipster-ns");if(c)if(1===c.length){var d=null;"previous"==b.__options.restoration?d=b._$origin.data("tooltipster-initialTitle"):"current"==b.__options.restoration&&(d="string"==typeof b.__Content?b.__Content:a("<div></div>").append(b.__Content).html()),d&&b._$origin.attr("title",d),b._$origin.removeClass("tooltipstered"),b._$origin.removeData("tooltipster-ns").removeData("tooltipster-initialTitle")}else c=a.grep(c,function(a,c){return a!==b.__namespace}),b._$origin.data("tooltipster-ns",c);b._trigger("destroyed"),b._off(),b.off(),b.__Content=null,b.__$emitterPrivate=null,b.__$emitterPublic=null,b.__options.parent=null,b._$origin=null,b._$tooltip=null,a.tooltipster.__instancesLatestArr=a.grep(a.tooltipster.__instancesLatestArr,function(a,c){return b!==a}),clearInterval(b.__garbageCollector)}return b},disable:function(){return this.__destroyed?(this.__destroyError(),this):(this._close(),this.__enabled=!1,this)},elementOrigin:function(){return this.__destroyed?void this.__destroyError():this._$origin[0]},elementTooltip:function(){return this._$tooltip?this._$tooltip[0]:null},enable:function(){return this.__enabled=!0,this},hide:function(a){return this.close(a)},instance:function(){return this},off:function(){return this.__destroyed||this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},open:function(a){return this.__destroyed?this.__destroyError():this._open(null,a),this},option:function(b,c){return void 0===c?this.__options[b]:(this.__destroyed?this.__destroyError():(this.__options[b]=c,this.__optionsFormat(),a.inArray(b,["trigger","triggerClose","triggerOpen"])>=0&&this.__prepareOrigin(),"selfDestruction"===b&&this.__prepareGC()),this)},reposition:function(a,b){var c=this;return c.__destroyed?c.__destroyError():"closed"!=c.__state&&d(c._$origin)&&(b||d(c._$tooltip))&&(b||c._$tooltip.detach(),c.__Geometry=c.__geometry(),c._trigger({type:"reposition",event:a,helper:{geo:c.__Geometry}})),c},show:function(a){return this.open(a)},status:function(){return{destroyed:this.__destroyed,enabled:this.__enabled,open:"closed"!==this.__state,state:this.__state}},triggerHandler:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},a.fn.tooltipster=function(){var b=Array.prototype.slice.apply(arguments),c="You are using a single HTML element as content for several tooltips. You probably want to set the contentCloning option to TRUE.";if(0===this.length)return this;if("string"==typeof b[0]){var d="#*$~&";return this.each(function(){var e=a(this).data("tooltipster-ns"),f=e?a(this).data(e[0]):null;if(!f)throw new Error("You called Tooltipster's \""+b[0]+'" method on an uninitialized element');if("function"!=typeof f[b[0]])throw new Error('Unknown method "'+b[0]+'"');this.length>1&&"content"==b[0]&&(b[1]instanceof a||"object"==typeof b[1]&&null!=b[1]&&b[1].tagName)&&!f.__options.contentCloning&&f.__options.debug&&console.log(c);var g=f[b[0]](b[1],b[2]);return g!==f||"instance"===b[0]?(d=g,!1):void 0}),"#*$~&"!==d?d:this}a.tooltipster.__instancesLatestArr=[];var e=b[0]&&void 0!==b[0].multiple,g=e&&b[0].multiple||!e&&f.multiple,h=b[0]&&void 0!==b[0].content,i=h&&b[0].content||!h&&f.content,j=b[0]&&void 0!==b[0].contentCloning,k=j&&b[0].contentCloning||!j&&f.contentCloning,l=b[0]&&void 0!==b[0].debug,m=l&&b[0].debug||!l&&f.debug;return this.length>1&&(i instanceof a||"object"==typeof i&&null!=i&&i.tagName)&&!k&&m&&console.log(c),this.each(function(){var c=!1,d=a(this),e=d.data("tooltipster-ns"),f=null;e?g?c=!0:m&&(console.log("Tooltipster: one or more tooltips are already attached to the element below. Ignoring."),console.log(this)):c=!0,c&&(f=new a.Tooltipster(this,b[0]),e||(e=[]),e.push(f.__namespace),d.data("tooltipster-ns",e),d.data(f.__namespace,f),f.__options.functionInit&&f.__options.functionInit.call(f,f,{origin:this}),f._trigger("init")),a.tooltipster.__instancesLatestArr.push(f)}),this},b.prototype={__init:function(b){this.__$tooltip=b,this.__$tooltip.css({left:0,overflow:"hidden",position:"absolute",top:0}).find(".tooltipster-content").css("overflow","auto"),this.$container=a('<div class="tooltipster-ruler"></div>').append(this.__$tooltip).appendTo(h.window.document.body)},__forceRedraw:function(){var a=this.__$tooltip.parent();this.__$tooltip.detach(),this.__$tooltip.appendTo(a)},constrain:function(a,b){return this.constraints={width:a,height:b},this.__$tooltip.css({display:"block",height:"",overflow:"auto",width:a}),this},destroy:function(){this.__$tooltip.detach().find(".tooltipster-content").css({display:"",overflow:""}),this.$container.remove()},free:function(){return this.constraints=null,this.__$tooltip.css({display:"",height:"",overflow:"visible",width:""}),this},measure:function(){this.__forceRedraw();var a=this.__$tooltip[0].getBoundingClientRect(),b={size:{height:a.height||a.bottom-a.top,width:a.width||a.right-a.left}};if(this.constraints){var c=this.__$tooltip.find(".tooltipster-content"),d=this.__$tooltip.outerHeight(),e=c[0].getBoundingClientRect(),f={height:d<=this.constraints.height,width:a.width<=this.constraints.width&&e.width>=c[0].scrollWidth-1};b.fits=f.height&&f.width}return h.IE&&h.IE<=11&&b.size.width!==h.window.document.documentElement.clientWidth&&(b.size.width=Math.ceil(b.size.width)+1),b}};var j=navigator.userAgent.toLowerCase();-1!=j.indexOf("msie")?h.IE=parseInt(j.split("msie")[1]):-1!==j.toLowerCase().indexOf("trident")&&-1!==j.indexOf(" rv:11")?h.IE=11:-1!=j.toLowerCase().indexOf("edge/")&&(h.IE=parseInt(j.toLowerCase().split("edge/")[1]));var k="tooltipster.sideTip";return a.tooltipster._plugin({name:k,instance:{__defaults:function(){return{arrow:!0,distance:6,functionPosition:null,maxWidth:null,minIntersection:16,minWidth:0,position:null,side:"top",viewportAware:!0}},__init:function(a){var b=this;b.__instance=a,b.__namespace="tooltipster-sideTip-"+Math.round(1e6*Math.random()),b.__previousState="closed",b.__options,b.__optionsFormat(),b.__instance._on("state."+b.__namespace,function(a){"closed"==a.state?b.__close():"appearing"==a.state&&"closed"==b.__previousState&&b.__create(),b.__previousState=a.state}),b.__instance._on("options."+b.__namespace,function(){b.__optionsFormat()}),b.__instance._on("reposition."+b.__namespace,function(a){b.__reposition(a.event,a.helper)})},__close:function(){this.__instance.content()instanceof a&&this.__instance.content().detach(),this.__instance._$tooltip.remove(),this.__instance._$tooltip=null},__create:function(){var b=a('<div class="tooltipster-base tooltipster-sidetip"><div class="tooltipster-box"><div class="tooltipster-content"></div></div><div class="tooltipster-arrow"><div class="tooltipster-arrow-uncropped"><div class="tooltipster-arrow-border"></div><div class="tooltipster-arrow-background"></div></div></div></div>');this.__options.arrow||b.find(".tooltipster-box").css("margin",0).end().find(".tooltipster-arrow").hide(),this.__options.minWidth&&b.css("min-width",this.__options.minWidth+"px"),this.__options.maxWidth&&b.css("max-width",this.__options.maxWidth+"px"),
this.__instance._$tooltip=b,this.__instance._trigger("created")},__destroy:function(){this.__instance._off("."+self.__namespace)},__optionsFormat:function(){var b=this;if(b.__options=b.__instance._optionsExtract(k,b.__defaults()),b.__options.position&&(b.__options.side=b.__options.position),"object"!=typeof b.__options.distance&&(b.__options.distance=[b.__options.distance]),b.__options.distance.length<4&&(void 0===b.__options.distance[1]&&(b.__options.distance[1]=b.__options.distance[0]),void 0===b.__options.distance[2]&&(b.__options.distance[2]=b.__options.distance[0]),void 0===b.__options.distance[3]&&(b.__options.distance[3]=b.__options.distance[1]),b.__options.distance={top:b.__options.distance[0],right:b.__options.distance[1],bottom:b.__options.distance[2],left:b.__options.distance[3]}),"string"==typeof b.__options.side){var c={top:"bottom",right:"left",bottom:"top",left:"right"};b.__options.side=[b.__options.side,c[b.__options.side]],"left"==b.__options.side[0]||"right"==b.__options.side[0]?b.__options.side.push("top","bottom"):b.__options.side.push("right","left")}6===a.tooltipster._env.IE&&b.__options.arrow!==!0&&(b.__options.arrow=!1)},__reposition:function(b,c){var d,e=this,f=e.__targetFind(c),g=[];e.__instance._$tooltip.detach();var h=e.__instance._$tooltip.clone(),i=a.tooltipster._getRuler(h),j=!1,k=e.__instance.option("animation");switch(k&&h.removeClass("tooltipster-"+k),a.each(["window","document"],function(d,k){var l=null;if(e.__instance._trigger({container:k,helper:c,satisfied:j,takeTest:function(a){l=a},results:g,type:"positionTest"}),1==l||0!=l&&0==j&&("window"!=k||e.__options.viewportAware))for(var d=0;d<e.__options.side.length;d++){var m={horizontal:0,vertical:0},n=e.__options.side[d];"top"==n||"bottom"==n?m.vertical=e.__options.distance[n]:m.horizontal=e.__options.distance[n],e.__sideChange(h,n),a.each(["natural","constrained"],function(a,d){if(l=null,e.__instance._trigger({container:k,event:b,helper:c,mode:d,results:g,satisfied:j,side:n,takeTest:function(a){l=a},type:"positionTest"}),1==l||0!=l&&0==j){var h={container:k,distance:m,fits:null,mode:d,outerSize:null,side:n,size:null,target:f[n],whole:null},o="natural"==d?i.free():i.constrain(c.geo.available[k][n].width-m.horizontal,c.geo.available[k][n].height-m.vertical),p=o.measure();if(h.size=p.size,h.outerSize={height:p.size.height+m.vertical,width:p.size.width+m.horizontal},"natural"==d?c.geo.available[k][n].width>=h.outerSize.width&&c.geo.available[k][n].height>=h.outerSize.height?h.fits=!0:h.fits=!1:h.fits=p.fits,"window"==k&&(h.fits?"top"==n||"bottom"==n?h.whole=c.geo.origin.windowOffset.right>=e.__options.minIntersection&&c.geo.window.size.width-c.geo.origin.windowOffset.left>=e.__options.minIntersection:h.whole=c.geo.origin.windowOffset.bottom>=e.__options.minIntersection&&c.geo.window.size.height-c.geo.origin.windowOffset.top>=e.__options.minIntersection:h.whole=!1),g.push(h),h.whole)j=!0;else if("natural"==h.mode&&(h.fits||h.size.width<=c.geo.available[k][n].width))return!1}})}}),e.__instance._trigger({edit:function(a){g=a},event:b,helper:c,results:g,type:"positionTested"}),g.sort(function(a,b){if(a.whole&&!b.whole)return-1;if(!a.whole&&b.whole)return 1;if(a.whole&&b.whole){var c=e.__options.side.indexOf(a.side),d=e.__options.side.indexOf(b.side);return d>c?-1:c>d?1:"natural"==a.mode?-1:1}if(a.fits&&!b.fits)return-1;if(!a.fits&&b.fits)return 1;if(a.fits&&b.fits){var c=e.__options.side.indexOf(a.side),d=e.__options.side.indexOf(b.side);return d>c?-1:c>d?1:"natural"==a.mode?-1:1}return"document"==a.container&&"bottom"==a.side&&"natural"==a.mode?-1:1}),d=g[0],d.coord={},d.side){case"left":case"right":d.coord.top=Math.floor(d.target-d.size.height/2);break;case"bottom":case"top":d.coord.left=Math.floor(d.target-d.size.width/2)}switch(d.side){case"left":d.coord.left=c.geo.origin.windowOffset.left-d.outerSize.width;break;case"right":d.coord.left=c.geo.origin.windowOffset.right+d.distance.horizontal;break;case"top":d.coord.top=c.geo.origin.windowOffset.top-d.outerSize.height;break;case"bottom":d.coord.top=c.geo.origin.windowOffset.bottom+d.distance.vertical}"window"==d.container?"top"==d.side||"bottom"==d.side?d.coord.left<0?c.geo.origin.windowOffset.right-this.__options.minIntersection>=0?d.coord.left=0:d.coord.left=c.geo.origin.windowOffset.right-this.__options.minIntersection-1:d.coord.left>c.geo.window.size.width-d.size.width&&(c.geo.origin.windowOffset.left+this.__options.minIntersection<=c.geo.window.size.width?d.coord.left=c.geo.window.size.width-d.size.width:d.coord.left=c.geo.origin.windowOffset.left+this.__options.minIntersection+1-d.size.width):d.coord.top<0?c.geo.origin.windowOffset.bottom-this.__options.minIntersection>=0?d.coord.top=0:d.coord.top=c.geo.origin.windowOffset.bottom-this.__options.minIntersection-1:d.coord.top>c.geo.window.size.height-d.size.height&&(c.geo.origin.windowOffset.top+this.__options.minIntersection<=c.geo.window.size.height?d.coord.top=c.geo.window.size.height-d.size.height:d.coord.top=c.geo.origin.windowOffset.top+this.__options.minIntersection+1-d.size.height):(d.coord.left>c.geo.window.size.width-d.size.width&&(d.coord.left=c.geo.window.size.width-d.size.width),d.coord.left<0&&(d.coord.left=0)),e.__sideChange(h,d.side),c.tooltipClone=h[0],c.tooltipParent=e.__instance.option("parent").parent[0],c.mode=d.mode,c.whole=d.whole,c.origin=e.__instance._$origin[0],c.tooltip=e.__instance._$tooltip[0],delete d.container,delete d.fits,delete d.mode,delete d.outerSize,delete d.whole,d.distance=d.distance.horizontal||d.distance.vertical;var l=a.extend(!0,{},d);if(e.__instance._trigger({edit:function(a){d=a},event:b,helper:c,position:l,type:"position"}),e.__options.functionPosition){var m=e.__options.functionPosition.call(e,e.__instance,c,l);m&&(d=m)}i.destroy();var n,o;"top"==d.side||"bottom"==d.side?(n={prop:"left",val:d.target-d.coord.left},o=d.size.width-this.__options.minIntersection):(n={prop:"top",val:d.target-d.coord.top},o=d.size.height-this.__options.minIntersection),n.val<this.__options.minIntersection?n.val=this.__options.minIntersection:n.val>o&&(n.val=o);var p;p=c.geo.origin.fixedLineage?c.geo.origin.windowOffset:{left:c.geo.origin.windowOffset.left+c.geo.window.scroll.left,top:c.geo.origin.windowOffset.top+c.geo.window.scroll.top},d.coord={left:p.left+(d.coord.left-c.geo.origin.windowOffset.left),top:p.top+(d.coord.top-c.geo.origin.windowOffset.top)},e.__sideChange(e.__instance._$tooltip,d.side),c.geo.origin.fixedLineage?e.__instance._$tooltip.css("position","fixed"):e.__instance._$tooltip.css("position",""),e.__instance._$tooltip.css({left:d.coord.left,top:d.coord.top,height:d.size.height,width:d.size.width}).find(".tooltipster-arrow").css({left:"",top:""}).css(n.prop,n.val),e.__instance._$tooltip.appendTo(e.__instance.option("parent")),e.__instance._trigger({type:"repositioned",event:b,position:d})},__sideChange:function(a,b){a.removeClass("tooltipster-bottom").removeClass("tooltipster-left").removeClass("tooltipster-right").removeClass("tooltipster-top").addClass("tooltipster-"+b)},__targetFind:function(a){var b={},c=this.__instance._$origin[0].getClientRects();if(c.length>1){var d=this.__instance._$origin.css("opacity");1==d&&(this.__instance._$origin.css("opacity",.99),c=this.__instance._$origin[0].getClientRects(),this.__instance._$origin.css("opacity",1))}if(c.length<2)b.top=Math.floor(a.geo.origin.windowOffset.left+a.geo.origin.size.width/2),b.bottom=b.top,b.left=Math.floor(a.geo.origin.windowOffset.top+a.geo.origin.size.height/2),b.right=b.left;else{var e=c[0];b.top=Math.floor(e.left+(e.right-e.left)/2),e=c.length>2?c[Math.ceil(c.length/2)-1]:c[0],b.right=Math.floor(e.top+(e.bottom-e.top)/2),e=c[c.length-1],b.bottom=Math.floor(e.left+(e.right-e.left)/2),e=c.length>2?c[Math.ceil((c.length+1)/2)-1]:c[c.length-1],b.left=Math.floor(e.top+(e.bottom-e.top)/2)}return b}}}),a});
/* tooltipster-follower v0.1.5 */
!function(a,b){"function"==typeof define&&define.amd?define(["tooltipster"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("tooltipster")):b(jQuery)}(this,function(a){var b="laa.follower";return a.tooltipster._plugin({name:b,instance:{__defaults:function(){return{anchor:"top-left",maxWidth:null,minWidth:0,offset:[15,-15]}},__init:function(a){var b=this;return b.__displayed,b.__helper,b.__initialROS=a.option("repositionOnScroll"),b.__instance=a,b.__latestMouseEvent,b.__namespace="tooltipster-follower-"+Math.round(1e6*Math.random()),b.__openingTouchEnded,b.__pointerPosition,b.__previousState="closed",b.__size,b.__options,b.__initialROS||b.__instance.option("repositionOnScroll",!0),b.__optionsFormat(),b.__instance._on("destroy."+b.__namespace,function(){b.__destroy()}),b.__instance._on("options."+b.__namespace,function(){b.__optionsFormat()}),b.__instance._on("reposition."+b.__namespace,function(a){b.__reposition(a.event,a.helper)}),b.__instance._on("start."+b.__namespace,function(a){b.__instance._$origin.on("mousemove."+b.__namespace,function(a){b.__latestMouseEvent=a})}),b.__instance._one("startend."+b.__namespace+" startcancel."+b.__namespace,function(a){b.__instance._$origin.off("mousemove."+b.__namespace),"startcancel"==a.type&&(b.__latestMouseEvent=null)}),b.__instance._on("state."+b.__namespace,function(a){"closed"==a.state?b.__close():"appearing"==a.state&&"closed"==b.__previousState&&b.__create(),b.__previousState=a.state}),b},__close:function(){return"object"==typeof this.__instance.content()&&null!==this.__instance.content()&&this.__instance.content().detach(),this.__instance._$tooltip.remove(),this.__instance._$tooltip=null,a(a.tooltipster._env.window.document).off("."+this.__namespace),this.__latestMouseEvent=null,this},__create:function(){var b=this,c=a('<div class="tooltipster-base tooltipster-follower"><div class="tooltipster-box"><div class="tooltipster-content"></div></div></div>'),d=a(a.tooltipster._env.window.document);b.__options.minWidth&&c.css("min-width",b.__options.minWidth+"px"),b.__options.maxWidth&&c.css("max-width",b.__options.maxWidth+"px"),b.__instance._$tooltip=c,b.__displayed=!1,b.__openingTouchEnded=!1,d.on("mousemove."+b.__namespace,function(a){b.__openingTouchEnded&&b.__displayed||b.__follow(a)});var e=b.__instance.option("triggerClose");return e.tap&&d.on("touchend."+b.__namespace+" touchcancel."+b.__namespace,function(a){b.__openingTouchEnded=!0}),b.__instance._trigger("created"),b},__destroy:function(){return this.__instance._off("."+this.__namespace),this.__initialROS||this.__instance.option("repositionOnScroll",!1),this},__follow:function(b){if(b?this.__latestMouseEvent=b:this.__latestMouseEvent&&(b=this.__latestMouseEvent),b){this.__displayed=!0;var c={},d=this.__options.anchor,e=a.merge([],this.__options.offset);switch(this.__helper.geo.window.scroll={left:a.tooltipster._env.window.scrollX||a.tooltipster._env.window.document.documentElement.scrollLeft,top:a.tooltipster._env.window.scrollY||a.tooltipster._env.window.document.documentElement.scrollTop},d){case"top-left":case"left-center":case"bottom-left":c.left=b.pageX+e[0];break;case"top-center":case"bottom-center":c.left=b.pageX+e[0]-this.__size.width/2;break;case"top-right":case"right-center":case"bottom-right":c.left=b.pageX+e[0]-this.__size.width;break;default:console.log("Wrong anchor value")}switch(d){case"top-left":case"top-center":case"top-right":c.top=b.pageY-e[1];break;case"left-center":case"right-center":c.top=b.pageY-e[1]-this.__size.height/2;break;case"bottom-left":case"bottom-center":case"bottom-right":c.top=b.pageY-e[1]-this.__size.height}if("left-center"==d||"right-center"==d){if("right-center"==d)c.left<this.__helper.geo.window.scroll.left&&(b.pageX-e[0]+this.__size.width<=this.__helper.geo.window.scroll.left+this.__helper.geo.window.size.width?(d="left-center",e[0]=-e[0],c.left=b.pageX+e[0]):(d="top-right",e[1]=e[0],c={left:0,top:b.pageY-e[1]}));else if(c.left+this.__size.width>this.__helper.geo.window.scroll.left+this.__helper.geo.window.size.width){var f=b.pageX-e[0]-this.__size.width;f>=0?(d="right-center",e[0]=-e[0],c.left=f):(d="top-left",e[1]=-e[0],c={left:b.pageX+e[0],top:b.pageY-e[1]})}c.top+this.__size.height>this.__helper.geo.window.scroll.top+this.__helper.geo.window.size.height&&(c.top=this.__helper.geo.window.scroll.top+this.__helper.geo.window.size.height-this.__size.height),c.top<this.__helper.geo.window.scroll.top&&(c.top=this.__helper.geo.window.scroll.top),c.top+this.__size.height>this.__helper.geo.document.size.height&&(c.top=this.__helper.geo.document.size.height-this.__size.height),c.top<0&&(c.top=0)}if("left-center"!=d&&"right-center"!=d){c.left+this.__size.width>this.__helper.geo.window.scroll.left+this.__helper.geo.window.size.width&&(c.left=this.__helper.geo.window.scroll.left+this.__helper.geo.window.size.width-this.__size.width),c.left<0&&(c.left=0);var g=b.pageY-this.__helper.geo.window.scroll.top;if(0==d.indexOf("bottom"))c.top<this.__helper.geo.window.scroll.top&&(c.top<0||g<this.__helper.geo.window.size.height-g&&b.pageY+e[1]+this.__size.height<=this.__helper.geo.document.size.height)&&(c.top=b.pageY+e[1]);else{var h=c.top+this.__size.height;if(h>this.__helper.geo.window.scroll.top+this.__helper.geo.window.size.height&&(g>this.__helper.geo.window.size.height-g||g-e[1]+this.__size.height<=this.__helper.geo.document.size.height)){var i=b.pageY+e[1]-this.__size.height;i>=0&&(c.top=i)}}}this.__helper.geo.origin.fixedLineage&&(c.left-=this.__helper.geo.window.scroll.left,c.top-=this.__helper.geo.window.scroll.top);var j={coord:c};this.__instance._trigger({edit:function(a){j=a},event:b,helper:this.__helper,position:a.extend(!0,{},j),type:"follow"}),this.__instance._$tooltip.css({left:j.coord.left,top:j.coord.top}).show()}else this.__instance._$tooltip.hide();return this},__optionsFormat:function(){return this.__options=this.__instance._optionsExtract(b,this.__defaults()),this},__reposition:function(b,c){var d=this,e=d.__instance._$tooltip.clone(),f=a.tooltipster._getRuler(e),g=d.__instance.option("animation");g&&e.removeClass("tooltipster-"+g);var h=f.free().measure(),i={size:h.size};c.geo.origin.fixedLineage?d.__instance._$tooltip.css("position","fixed"):d.__instance._$tooltip.css("position",""),d.__instance._trigger({edit:function(a){i=a},event:b,helper:c,position:a.extend(!0,{},i),tooltipClone:e[0],type:"position"}),f.destroy(),d.__helper=c,d.__size=i.size,d.__instance._$tooltip.css({height:i.size.height,width:i.size.width});var j=a.tooltipster._env.IE&&"click"===b.type?b:null;return d.__follow(j),d.__instance._$tooltip.appendTo(d.__instance.option("parent")),d.__instance._trigger({type:"repositioned",event:b,position:{coord:{left:0,top:0},size:i.size}}),this}}}),a}); 

/* ========================================
 FILE: /includes/virtual_variants/vvar.min.js
 ==================== */

var vvar={version:"1.0",debug:!1,body:{},middle:{},paths:{},loading:0,quirk:!1,settings:{ajax:0,afterLoad:function(){vvar.debug&&csstack("afterLoad")},beforeLoad:function(){vvar.debug&&csstack("beforeLoad")}},init:function(a){vvar.debug=is_cs_user("vvdev"),vvar.debug&&(console.log("Virtual variants [v."+vvar.version+"]"),csstack("init")),vvar.body=jQuery("body"),vvar.head=jQuery("head"),vvar.wrap=jQuery(".vv_wrap"),vvar.middle=jQuery("#mainmiddle_container"),vvar.quirk=!("undefined"!=typeof history&&void 0!==history.replaceState),vvar.middle.css("position","relative"),void 0!==a&&(vvar.settings=jQuery.extend(vvar.settings,a)),vvar.settings.ajax&&(vvar.bind(),vvar.prepare()),vvar.wrap.length&&vvar.wrap.hasClass("vv_table_view")&&vvar.initTableView()},initTableView:function(){vvar.debug&&csstack("initTableView");var a=vvar.wrap.find(".vv_param_wrapper");a.length&&a.mCustomScrollbar({theme:"dark-thick",axis:"x",scrollInertia:0,autoHideScrollbar:!1,alwaysShowScrollbar:2,horizontalScroll:!0,contentTouchScroll:!0,documentTouchScroll:!1,autoDraggerLength:!1,advanced:{autoExpandHorizontalScroll:!0}})},hashUrl:function(a){var e=0;if(void 0!==a&&""!==a&&null!==a)for(var t=0;t<a.length;t++){e=(e<<5)-e+a.charCodeAt(t);e&=e}return e},bind:function(){if(vvar.debug&&csstack("bind"),!vvar.quirk){let e=jQuery(".flypage-right .vv_box.variant_active").find("a.vv_box_text").attr("href");if(config("js_CS_Config_variant_navigation")){let a=new URLSearchParams(window.location.search);a.has("var")&&(e+="?var="+a.get("var"))}history.replaceState({urlPath:e,vv_target:"target_"+vvar.hashUrl(e)},null,e),window.addEventListener("popstate",function(a){!a.state||null===a.state||void 0===a.state.vv_target||(a=jQuery("#"+a.state.vv_target)).length&&vvar.load(a.find("a.vv_box_text")[0],!0)},!1)}},prepare:function(){vvar.debug&&csstack("prepare");var a=vvar.middle.find(".flypage-right");a.off("click.vvar"),a.on("click.vvar","a.vv_box_text",function(){vvar.load(this)}),a.on("click.vvar","a.vv_box_image",function(){vvar.load(this)}),a.find(".vv_box").each(function(){var t=jQuery(this),r=t.hasClass("variant_active");t.find("a").each(function(){var a=jQuery(this),e=a.attr("href");t.attr("id","target_"+vvar.hashUrl(e)),r||a.data("href",e),a.attr("href","javascript:void(0);")})})},appendScript:function(a){if(void 0!==typeof a.children&&a.children.length)for(var e=0;e<a.children.length;e++)"DIV"==a.children[e].nodeName?vvar.appendScript(a.children[e]):"SCRIPT"==a.children[e].nodeName&&"vvar_execute"==a.children[e].className&&vvar.middle.append(a.children[e].outerHTML)},load:function(a,n){if(vvar.debug&&csstack("load"),vvar.loading)return!1;var o=jQuery(a),l=o.closest(".vv_box"),d=o.data("href");if(void 0!==d&&""!==d&&null!==d){var e=window.location.href,a=-1==d.indexOf("#")?d:d.substring(0,d.indexOf("#")-1);if(-1!==e.indexOf("#")&&(a+=e.substring(e.indexOf("#"))),void 0===(d=a))return!1;a={virtual_variant_ajax:1};vvar.settings.beforeLoad.call("undefined",o),vvar.loader(),vvar.loading=1,vvar.middle.load(d+" #mainmiddle",a,function(a){var e=jQuery(a);if(e.length)for(var t=0;t<e.length;t++)"DIV"==e[t].nodeName?vvar.appendScript(e[t]):"SCRIPT"==e[t].nodeName&&"vvar_execute"==e[t].className&&vvar.middle.append(e[t].outerHTML);vvar.loading=0,vvar.quirk||null!=n||history.pushState({urlPath:d,vv_target:l.attr("id")},null,d),"function"==typeof attribute_change_custom&&attribute_change_custom(),vvar.settings.afterLoad.call("undefined",o,e),window.dispatchEvent(new Event("productDetailReload")),"function"==typeof initFancybox&&initFancybox(),"function"==typeof js_flypage_custom&&js_flypage_custom(),"function"==typeof setProductAvailabilityTime&&setProductAvailabilityTime(),vvar.prepare(),jQuery("body").removeClass("unavailable_product");var r,i,v="";"object"==typeof e&&(i=r="",t=0,jQuery.each(e,function(a,e){if(void 0===e.localName)return!0;if("title"==e.localName)vvar.head.find("title").text(e.text),v=String(e.text);else if("meta"==e.localName&&e.attributes.length){for(i=r="",t=0;t<e.attributes.length;t++)"property"==e.attributes[t].nodeName?r='meta[property="'+e.attributes[t].value+'"]':"name"==e.attributes[t].nodeName?r='meta[name="'+e.attributes[t].value+'"]':"content"==e.attributes[t].nodeName&&(i=e.attributes[t].value);""!==r&&vvar.head.find(r).attr("content",i)}else if("link"==e.localName&&e.attributes.length){for(i=r="",t=0;t<e.attributes.length;t++)"rel"==e.attributes[t].nodeName&&"canonical"==e.attributes[t].value?r='link[rel="canonical"]':"href"==e.attributes[t].nodeName&&(i=e.attributes[t].value);""!==r&&vvar.head.find(r).attr("href",i)}})),"function"==typeof ga&&(ga("set",{page:d,title:v}),ga("send","pageview"))})}},loader:function(){vvar.debug&&csstack("loader");var a=jQuery("<div>").addClass("vvar_loader");vvar.middle.find("#middle").append(a),a.fadeIn(300)},initVirtualTypes:function(){vvar.debug&&csstack("initVirtualTypes");var e,t,r,i=jQuery(".vig-type-wrapper"),v=jQuery(".vig-type-group-wrapper");i.on("click",function(){i.removeClass("active"),jQuery(this).addClass("active"),e=jQuery(this).data("value").toString().split(" "),v.removeClass("active");for(var a=0;a<e.length;a++)v.each(function(){if(t=jQuery(this),r=t.attr("class").split(" "),-1<jQuery.inArray(e[a],r))return t.addClass("active"),"undefined"!=typeof js_CS_Config_choose_first_vv_after_click&&1==js_CS_Config_choose_first_vv_after_click&&t.find("a > img:first").trigger("click"),!1})})}};

/* ========================================
 FILE: /includes/js/shop/shop.product_details_attrib_change.js
 ==================== */

function js_adv_attribs_onchange(e, doNotReplacePriceLabel) {
	if (typeof js_eur_list === 'undefined') {
		return;
	}
	//v prípade, že je potrebné meniť aj input button -> napríklad pri množstevných nákupoch
	//TODO pridať podmienky na zmenu vlastností input buttonu + pridať dáta
	jsChangeVariantAddon(e);
	var elem = jQuery(e);
	var js_list_init = (document.getElementById("product-detail-price-value")!=null) ? document.getElementById("product-detail-price-value").innerHTML : '' ;
	var js_eur_list_init = (document.getElementById("product-detail-eur-price-value")!=null) ? document.getElementById("product-detail-eur-price-value").innerHTML : '' ;
	var js_title_list_init = (document.getElementById("product-detail-price-title")!=null) ? document.getElementById("product-detail-price-title").innerHTML : '' ;
	var price_value_elem = jQuery('#product-detail-price-value');
	var price_title_elem = jQuery('#product-detail-price-title');
	var base_price_title_elem = jQuery('#product-detail-base-price-value');

	doNotReplacePriceLabel = (typeof doNotReplacePriceLabel !== 'undefined') ? doNotReplacePriceLabel : false;
    if (e != null && e.selectedIndex >= 0) {	// selectbox

	    if (typeof js_CS_Config_display_min_max_variant_price !== 'undefined' && js_CS_Config_display_min_max_variant_price == 1) {
			jQuery('#product-detail-price-value-second, .min_max_delimeter').hide();
	    }

	    //dostupne od
	    if (typeof js_CS_Config_vm_product_attributes_use_available_from !== 'undefined' && js_CS_Config_vm_product_attributes_use_available_from) {
		    js_show_attribute_available_from(e);
	    }

        if (js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED) {
            if (typeof js_list !== 'undefined' && js_list != null && e.selectedIndex <= js_list.length && document.getElementById("product-detail-price-value") != null) {
                if (e.selectedIndex == 0)
	                price_value_elem.html(js_list_init);
                else {
	                price_value_elem.html(js_list[e.selectedIndex - 1]);

                    if (js_no_vat_list != null && typeof(js_no_vat_list[e.selectedIndex]) != 'undefined') {
	                    price_value_elem.parent().parent().find('.akcia-cena-bdph').html(js_no_vat_list[e.selectedIndex]);
                    }
                }
            }

            if (js_eur_list != null && e.selectedIndex <= js_eur_list.length && document.getElementById("product-detail-eur-price-value") != null) {
                if (e.selectedIndex == 0)
                    document.getElementById("product-detail-eur-price-value").innerHTML = js_eur_list_init;
                else
                    document.getElementById("product-detail-eur-price-value").innerHTML = js_eur_list[e.selectedIndex - 1];
            }

            if ( typeof js_global_CS_Config_product_detail_price_title_no_change !== 'undefined' && !js_global_CS_Config_product_detail_price_title_no_change && !doNotReplacePriceLabel && !price_title_elem.hasClass('shopper_group_title')) {
            	if (typeof js_title_list !== 'undefined' && js_title_list != null && e.selectedIndex <= js_title_list.length && document.getElementById("product-detail-price-title") != null) {
                    if (e.selectedIndex == 0)
                        document.getElementById("product-detail-price-title").innerHTML = js_title_list_init;
                    else
                        document.getElementById("product-detail-price-title").innerHTML = js_title_list[e.selectedIndex - 1];
                }
                // variant desc visibility
                (price_title_elem.html() != '') ? price_title_elem.addClass('visible') : price_title_elem.removeClass('visible');
            }

			// saky - variant base price
			if ( e.selectedIndex != 0 && base_price_title_elem.length && js_base_price_list ) {
            	var variantPrice = js_base_price_list[e.selectedIndex - 1];

				base_price_title_elem.text(variantPrice.format);
				jQuery('.flypage-base-price .base-cena-bdph').text(variantPrice.format_wo_vat);

				jQuery('.flypage-base-price').toggle(!(js_list.length && variantPrice.value == parseFloat(js_list[e.selectedIndex - 1].match(/[0-9,.]+/)[0].replace(',', '.'))));
			}

        } else {
        	if (typeof js_list !== 'undefined' && js_list != null && e.selectedIndex <= js_list.length && document.getElementById("product-detail-price-value") != null && typeof(js_list[e.selectedIndex]) != 'undefined') {
                document.getElementById("product-detail-price-value").innerHTML = js_list[e.selectedIndex];

                if (js_no_vat_list != null && typeof(js_no_vat_list[e.selectedIndex]) != 'undefined') {
	                price_value_elem.parent().parent().find('.akcia-cena-bdph').html(js_no_vat_list[e.selectedIndex]);
				}
            }
            if (js_eur_list != null && e.selectedIndex <= js_eur_list.length && document.getElementById("product-detail-eur-price-value") != null && typeof(js_eur_list[e.selectedIndex]) != 'undefined')
                document.getElementById("product-detail-eur-price-value").innerHTML = js_eur_list[e.selectedIndex];

            if ( typeof js_global_CS_Config_product_detail_price_title_no_change !== 'undefined' && !js_global_CS_Config_product_detail_price_title_no_change && !doNotReplacePriceLabel && !price_title_elem.hasClass('shopper_group_title')) {
                if (typeof js_title_list !== 'undefined' && js_title_list != null && e.selectedIndex <= js_title_list.length && document.getElementById("product-detail-price-title") != null && typeof(js_title_list[e.selectedIndex]) != 'undefined')
                    document.getElementById("product-detail-price-title").innerHTML = js_title_list[e.selectedIndex];
            }
        }

		if (typeof(js_sep1_visibility_change) != 'undefined' && js_sep1_visibility_change == '1') {
			jQuery('.pt-separator.sep1').css('display', (elem.val() != '') ? 'inline' : 'none');
		}	// emanuela local.js :)


    } else {	// radio
        var radio_element = jQuery(e);
        var attrib_comb_id = /attrib_comb_([0-9]+)(\s|$)/.exec(radio_element.attr('class'));

        if (attrib_comb_id != null && attrib_comb_id != '') {
            attrib_comb_id = parseInt(attrib_comb_id[1]);
            if (!isNaN(attrib_comb_id) && typeof js_list !== 'undefined' && js_list != null && typeof(js_list[attrib_comb_id]) !== 'undefined') {
	            price_value_elem.html(js_list[attrib_comb_id]);

                if (js_no_vat_list != null && typeof(js_no_vat_list[attrib_comb_id]) != 'undefined') {
	                price_value_elem.parent().parent().find('.akcia-cena-bdph').html(js_no_vat_list[attrib_comb_id]);
				}

                if (js_op_list != null && typeof(js_op_list[attrib_comb_id]) != 'undefined') {
					var parsed = jQuery('<div/>').append(js_op_list[attrib_comb_id]);
					var valprice = parsed.find(".old-price").text();
					if(valprice == ''){
						valprice = js_op_list[attrib_comb_id];
					}

                    var current_curency = shop_currency_info[shop_vendor_currency_code];
                    var valprice_val = parseFloat(valprice.replace(current_curency['1000_SYMBOL'],'').replace(current_curency['DEC_SYMBOL'],'.'));
                    var js_list_val = parseFloat(js_list[attrib_comb_id].replace(current_curency['1000_SYMBOL'],'').replace(current_curency['DEC_SYMBOL'],'.'));
                    if (valprice_val > js_list_val) {
	                    jQuery(".flypage-prices .old-price, .flypage-price .old-price, .flypage-cena .old-price, .flypage-prices .flypage-old-price").html(valprice);
                    } else {
	                    jQuery(".flypage-prices .old-price, .flypage-price .old-price, .flypage-cena .old-price, .flypage-prices .flypage-old-price").html('');
                    }
                }

	            //CS_Config_product_sg_prices
	            if(!jQuery('.user_logged_in').length) {
	            	//cena s dph
		            if (typeof js_sg_list !== 'undefined' && js_sg_list != null && typeof js_sg_list[attrib_comb_id] !== 'undefined' && js_sg_list[attrib_comb_id] != null) {
			            jQuery('.flypage-sg-price .akcia-cena-sdph').html(js_sg_list[attrib_comb_id]);
		            }
		            //cena bez dph
		            if (typeof js_sg_no_vat_list !== 'undefined' && js_sg_no_vat_list != null && typeof js_sg_no_vat_list[attrib_comb_id] !== 'undefined' && js_sg_no_vat_list[attrib_comb_id] != null) {
			            jQuery('.flypage-sg-price .akcia-cena-bdph').html(js_sg_no_vat_list[attrib_comb_id]);
		            }
	            }
            }
        }
    }

    if (js_global_PSHOP_PRODUCT_ATTRIB_USE_IMG) {
        // change flypage image
        var jqo_this_elem = jQuery(e);
        var jqo_default_flypage_img = jQuery('.flypage-image .default_flypage_img');
        var jqo_default_flypage_img_lightbox = jQuery('.flypage-image > a');
        jQuery('.flypage-image img.variant_img').remove();

        if (jqo_this_elem.val() != '' && jqo_this_elem.val().indexOf('{IMG') !== -1) {	// set variant image
            var jqo_variant_img = jqo_default_flypage_img.clone();
            var variant_img_src = js_global_skvelyweb_site + '/images/shop-active-images/' + jqo_this_elem.val().match(/\{IMG\=([^\}]+)\}/)[1];

            jqo_variant_img
                    .attr({'class': 'variant_img', 'src': variant_img_src, 'width': js_product_def_img_max_w})
                    .on('error', function() {
							jQuery(this).attr('src', js_product_def_img_url);
						})
                    .show();

            jqo_default_flypage_img.after(jqo_variant_img);
            jqo_default_flypage_img.hide();
            jqo_default_flypage_img_lightbox.attr('href', variant_img_src);
        } else {	// set default image
            jqo_default_flypage_img.show();
            jqo_default_flypage_img_lightbox.attr('href', js_product_def_img_url);
        }
    }

    if (typeof(price_null_rounding) != 'undefined' && price_null_rounding > '0')
        js_price_null_rounding(); 	// drevona local

    // JAN doplnky produktov
    if( typeof(product_accessory_show) == 'function' ){
    	product_accessory_show(elem);
    }
    if (typeof paccf !== 'undefined'){ paccf.show(elem); }

    if (typeof(js_adv_attribs_onchange_after) != 'undefined')
    	js_adv_attribs_onchange_after(elem);

    // JAN product last pieces html box
	if (typeof js_last_pieces_html_box == 'function') js_last_pieces_html_box(elem);

	if ( typeof js_Config_ahoj_pay !== 'undefined' && js_Config_ahoj_pay && jQuery('.ahoj-pay-banner').length > 0 && typeof ahojpay !== 'undefined' && js_list != null && typeof ahojBannerUpdate != "function" ) {
		if ( e != null && e.selectedIndex >= 0 ) {
			ahojpay.productBanner(parseFloat(js_list[e.selectedIndex]).toFixed(2), '.ahoj-pay-banner');
		} else {
			ahojpay.productBanner(parseFloat(js_list[attrib_comb_id]).toFixed(2), '.ahoj-pay-banner');
		}
	}

	if ( typeof js_Config_ahoj_pay !== 'undefined' && js_Config_ahoj_pay && jQuery('.ahoj-pay-banner').length > 0 && typeof ahojBannerUpdate === "function" && js_list != null ) {
		if ( e != null && e.selectedIndex >= 0 ) {
			ahojBannerUpdate(parseFloat(js_list[e.selectedIndex]).toFixed(2));
		} else {
			var tmpAhojPrice = js_list[attrib_comb_id];
			if ( typeof js_Config_ahojpay_thousands_symbol_fix !== 'undefined' && js_Config_ahojpay_thousands_symbol_fix && typeof current_curency !== 'undefined' && current_curency['DEC_SYMBOL'] != current_curency['1000_SYMBOL'] ) {
				tmpAhojPrice = tmpAhojPrice.split(current_curency['1000_SYMBOL']).join('');
			}
			ahojBannerUpdate(parseFloat(tmpAhojPrice).toFixed(2));
		}
	}

	if(typeof js_Config_product_detail_free_shipping_info !== 'undefined' && js_Config_product_detail_free_shipping_info && typeof js_flypage_free_shipping_update_info == 'function'){
		js_flypage_free_shipping_update_info();
	}

}


function js_set_attribute_value_from_select(elem, option_order, mode) {
	elem = jQuery(elem);
	// pre 2 urovnove varianty
	if (typeof(mode) != "undefined" && mode == 'sublevel') {
		elem.siblings('.button_tag2').removeClass('button_tag_active2');
		elem.addClass('button_tag_active2');
	} else {
		elem.siblings('.button_tag').removeClass('button_tag_active');
		elem.addClass('button_tag_active');
	}
	var select_elem = elem.parents('.flypage1:first').find('.prod_adv_attrib_select select');
	select_elem.find('option').prop('selected', false);
	select_elem.children('option:nth-child('+option_order+')').prop('selected', true);
	select_elem.change();

	return false;
}

function js_set_attribute_group(elem, class_id) {
	elem = jQuery(elem);
	var product_form = elem.parents('form:first');
	product_form.find('.button_tag').removeClass('button_tag_active');
	elem.addClass('button_tag_active');

	product_form.find('.button_tag2').hide();
	product_form.find('.button_tag_class_' + class_id).show();
	product_form.find('.button_tag_class_' + class_id + ':first').trigger('click');

	return false;
}

function js_show_attribute_available_from(elem) {

	elem                    = jQuery(elem);
	var avail_from_div      = elem.closest('.flypage1').find('.prod_in_stock_available_from');
	var avail_timestamp     = elem.val().replace(/^(.*?){AF=(.*?)}(.*?)$/i, '$2');

	if (elem.val().indexOf('{AF=') > -1) {
		//zobrazime predpokladanu dostuponost pre variant
		var avail_date          = new Date(avail_timestamp * 1000);
		var avail_date_formated = avail_date.toLocaleDateString().replace(/\s/g, '');

		avail_from_div.show();
		avail_from_div.find('.avail_date_again').text(avail_date_formated);
	} else {
		//skryjeme predpokladanu dostuponost pre variant (nie je setnuta)

		var tmpVar = avail_from_div.find('.avail_date_again');
		if (typeof tmpVar.data('default') !== 'undefined') {
			tmpVar.text(tmpVar.data('default'));
		} else {
			avail_from_div.hide();
		}
	}
}


/* ========================================
 FILE: /includes/rotate_active_images/rotate_active_images.js
 ==================== */

var js_rotate_active_images = {
	options: {
		delay: 0,
		animationDuration: 200,
		changeAfter: 3000,
		firstDelay: 0,
		imagesLimit: 0
	},

	/**
	 * Init function
	 * @param {Object} data - Custom options
	 */
	init: function (data) {
		var ajaxUrlData = {
			ajax_call: 1,
			ajax_func: 'get_product_active_images',
			option: 'com_shop',
			page: 'shop.cart'
		};

		if (typeof data === 'object') {
			js_rotate_active_images.options = jQuery.extend({}, js_rotate_active_images.options, data);
		}

		jQuery.post(js_global_live_site + '/administrator/components/com_shop/html/shop.browse.ajax.php?' + jQuery.param(ajaxUrlData), {
			product_ids: jQuery.map(jQuery('body:not(.is_touch_device) #product_list').find('.shop-category-product').map(function () {
				return jQuery(this).attr('class').match(/product_id_([0-9]*)/)[1];
			}), function (value) {
				return [value];
			})
		}, function (response) {
			var jsonResponse = csJsonParse(response) || {};
			//var jsonResponseTEST = JSON.parse(response);
			var productImages, productIds;

			if (typeof jsonResponse !== 'object') {

			}

			if (typeof jsonResponse === 'object' && typeof jsonResponse.success === 'boolean' && jsonResponse.success && typeof jsonResponse.data === 'object') {
				productImages = jsonResponse.data;
				productIds = Object.keys(productImages);

				if (js_rotate_active_images.options.imagesLimit > 0) {
					jQuery.each(productImages, function (id, images) {
						if (Object.keys(images).length && (js_rotate_active_images.options.imagesLimit <= Object.keys(images).length)) {
							productImages[id] = Object.entries(images).slice(0, js_rotate_active_images.options.imagesLimit).map(function (entry) {
								return entry[1];
							});
						}
					});
				}
				//if (js_rotate_active_images.options.imagesLimit) {
				//	jQuery.each(productImages, function (id, images) {
				//		if (images.length) {
				//			productImages[id] = images.slice(0, js_rotate_active_images.options.imagesLimit);
				//		}
				//	});
				//}
				jQuery('body:not(.is_touch_device) #product_list').find('.shop-category-product')
					.filter(productIds
						.map(function (value) {
							return '.product_id_' + value;
						})
						.join())
					.off('mouseenter.rotate')
					.on('mouseenter.rotate', function () {
						js_rotate_active_images.imageMouseenter(this, productImages);
					})
					.off('mouseleave.rotate')
					.on('mouseleave.rotate', function () {
						js_rotate_active_images.imageMouseleave(this);
					});
			}
		});

		// var elementSelector = '.featured-prod, .table_featured_prod, .related_product1, .related_product2, .related_product3';
		if (typeof window.rotate_active_images_init === 'undefined') {
			window.rotate_active_images_init = [];
		}

		if (js_rotate_active_images_in_modules) {
			window.addEventListener('CSProductGroupLoaded', function (event) {
				var mp_id = jQuery(event.detail.moduleId).closest('.mp').attr('class');

				if (typeof window.rotate_active_images_init[mp_id] === 'undefined') {
					window.rotate_active_images_init[mp_id] = true;

					jQuery.post(js_global_live_site + '/administrator/components/com_shop/html/shop.browse.ajax.php?' + jQuery.param(ajaxUrlData), {
						product_ids: jQuery.map(jQuery('body:not(.is_touch_device) .slick-track, .table_featured_prod, .jcarousel-list').find('.featured-prod, .related_product1, .related_product2, .related_product3').map(function () {
							var matchClass = jQuery(this).attr('class').match(/product_id_([0-9]*)/);
							if(matchClass instanceof Array){
								return matchClass[1];
							}
						}), function (value) {
							return [value];
						})
					}, function (response) {
						var jsonResponse = csJsonParse(response) || {};
						var productImages, productIds;

						if (typeof jsonResponse === 'object' && typeof jsonResponse.success === 'boolean' && jsonResponse.success && typeof jsonResponse.data === 'object') {
							productImages = jsonResponse.data;
							productIds    = Object.keys(productImages);
							if (js_rotate_active_images.options.imagesLimit > 0) {
								jQuery.each(productImages, function (id, images) {
									if (Object.keys(images).length && (js_rotate_active_images.options.imagesLimit <= Object.keys(images).length)) {
										productImages[id] = Object.entries(images).slice(0, js_rotate_active_images.options.imagesLimit).map(function (entry) {
											return entry[1];
										});
									}
								});
							}

							jQuery('body:not(.is_touch_device) .slick-track, .table_featured_prod, .jcarousel-list').find('.featured-prod, .related_product1, .related_product2, .related_product3')
								.filter(productIds
									.map(function (value) {
										return '.product_id_' + value;
									})
									.join())
								.off('mouseenter.rotate')
								.on('mouseenter.rotate', function () {
									js_rotate_active_images.imageMouseenter(this, productImages);
								})
								.off('mouseleave.rotate')
								.on('mouseleave.rotate', function () {
									js_rotate_active_images.imageMouseleave(this);
								});
						}
					});
				}
			});
		}
	},
	/**
	 *
	 * @param {Object} element - jQuery object
	 * @param {Object} productImages - Object of all product images
	 */
	imageMouseenter: function (element, productImages) {
		var productId    = jQuery(element).closest('.shop-category-product, .featured-prod, .related_product1, .related_product2, .related_product3').attr('class').match(/product_id_([0-9]*)/)[1];
		var images       = Object.keys(productImages[productId]).map(function (key) {
			return productImages[productId][key];
		});
		var imagesCount  = images.length;
		var currentIndex = 1;
		if ( is_cs_user('kiko') ) {
			if (typeof jQuery(element).data('origImageSrc') === 'undefined') {
				jQuery(element).data('origImageSrc', jQuery(element).find('.browse_top img:first, .shop-cat-img img:first, .featured-image-span img:first').attr('src'));
			}
			if (typeof jQuery(element).data('origSrcSet') === 'undefined') {
				jQuery(element).data('origSrcSet', jQuery(element).find('.browse_top img:first, .shop-cat-img img:first, .featured-image-span img:first').attr('srcset'));
			}
			jQuery(element).data('imageRotateTimeout', setTimeout(function () {
				js_rotate_active_images.changeImage(jQuery(element).find('.browse_top img:first, .shop-cat-img img:first, .featured-image-span img:first'), images[0]);

				clearInterval(jQuery(element).data('imageRotateInterval'));
				jQuery(element).removeData('imageRotateInterval');

				jQuery(element).data('imageRotateInterval', setInterval(function () {
					js_rotate_active_images.changeImage(jQuery(element).find('.browse_top img:first, .shop-cat-img img:first, .featured-image-span img:first'), images[currentIndex]);

					currentIndex = (currentIndex + 1 < imagesCount) ? currentIndex + 1 : 0;

				}, js_rotate_active_images.options.changeAfter));

			}, js_rotate_active_images.options.firstDelay));
		} else {
			if (typeof jQuery(element).data('origImageSrc') === 'undefined') {
				jQuery(element).data('origImageSrc', jQuery(element).find('img:first').attr('src'));
			}
			if (typeof jQuery(element).data('origSrcSet') === 'undefined') {
				jQuery(element).data('origSrcSet', jQuery(element).find('img:first').attr('srcset'));
			}
			jQuery(element).data('imageRotateTimeout', setTimeout(function () {
				js_rotate_active_images.changeImage(jQuery(element).find('img:first'), images[0]);

				clearInterval(jQuery(element).data('imageRotateInterval'));
				jQuery(element).removeData('imageRotateInterval');

				jQuery(element).data('imageRotateInterval', setInterval(function () {
					js_rotate_active_images.changeImage(jQuery(element).find('img:first'), images[currentIndex]);

					currentIndex = (currentIndex + 1 < imagesCount) ? currentIndex + 1 : 0;

				}, js_rotate_active_images.options.changeAfter));

			}, js_rotate_active_images.options.firstDelay));
		}
	},

	/**
	 *
	 * @param {Object} element - jQuery object
	 */
	imageMouseleave: function (element) {
		clearInterval(jQuery(element).data('imageRotateInterval'));
		clearTimeout(jQuery(element).data('imageRotateTimeout'));
		jQuery(element).removeData('imageRotateInterval');
		jQuery(element).removeData('imageRotateTimeout');
		if ( is_cs_user('kiko') ) {
			js_rotate_active_images.changeImage(jQuery(element).find('.browse_top img:first, .shop-cat-img img:first, .featured-image-span img:first'), jQuery(element).data('origImageSrc'));
			js_rotate_active_images.changeImage(jQuery(element).find('.browse_top img:first, .shop-cat-img img:first, .featured-image-span img:first'), jQuery(element).data('origSrcSet'));
		} else{
			js_rotate_active_images.changeImage(jQuery(element).find('img:first'), jQuery(element).data('origImageSrc'));
			js_rotate_active_images.changeImage(jQuery(element).find('img:first'), jQuery(element).data('origSrcSet'));
		}
	},
	/**
	 *
	 * @param {Object} imgElem - jQuery image object
	 * @param {String} imgSrc - new image source
	 * @return {Boolean}
	 */
	changeImage: function (imgElem, imgSrc) {

		if (imgElem instanceof jQuery && typeof imgSrc === 'string') {
			imgElem.attr('src', imgSrc);
			imgElem.attr('srcset', imgSrc);
			return true;
		}
		return false;
	}
};


/* ========================================
 FILE: /includes/rotate_active_images/rotate_active_images_detail.js
 ==================== */

/**
 * @author Hucci
 */
var js_rotate_active_images_detail = {
	options: {
		slidesToShow: 1,
		slidesToScroll: 1,
		infinite: true,
		variableWidth: false,
		prevArrow: '<button type="button" class="slick-prev slick-arrow" title="'+ cms_js_prev +'"><i class="fa fa-chevron-left" aria-hidden="true"></i></button>',
		nextArrow: '<button type="button" class="slick-next slick-arrow" title="'+ cms_js_next +'"><i class="fa fa-chevron-right" aria-hidden="true"></i></button>',
		dots: true,		
		autoplay: true,
		autoplaySpeed: 3000
	},
	
	/**
	 * Init function
	 * @param {Object} data - Custom options
	 */
	init: function(data) {
		var flypageImageElem = jQuery('.flypage-slick-images');
		var defaultOptions = {};

		if (typeof data === 'object') {

			this.options = jQuery.extend(defaultOptions, this.options, data);
		}
		if (flypageImageElem.length) {
			if ( typeof generateXXLLink === 'function' ) {
				flypageImageElem.on('init change afterChange', function () {
					jQuery(".flypage-image a:first").attr('href', jQuery('.slick-active').attr('href'));
				});
			}

			if ( typeof js_Config_new_jquery_and_fancybox !== 'undefined' && js_Config_new_jquery_and_fancybox ) {
				// test
				if ( typeof js_CS_Config_lighthouse6_opt === 'undefined' ) {
					if (!flypageImageElem.hasClass('slick-initialized')) {
						flypageImageElem
							.slick(this.options);
					}
				}

				if (typeof fancyboxOptions === 'undefined') {
					fancyboxOptions = {};
				}
				flypageImageElem
					.find('a:not(.slick-cloned)')
					.fancybox(fancyboxOptions);
				//var selector = '.flypage-slick-images .slick-slide:not(.slick-cloned)';
				var selector = '.slick-slide:not(.slick-cloned)';
				jQuery(document).on('click', '.flypage-slick-images .slick-cloned', function(e) {
					jQuery(selector)
						.eq( ( jQuery(e.currentTarget).attr("data-slick-index") || 0) % jQuery(selector).length )
						.trigger("click.fb-start", {
							$trigger: jQuery(this)
						});

					return false;
				});
			} else {
				flypageImageElem
					.slick(this.options)
					.find('a:not(.slick-cloned)')
					.lightBox({});
			}
			if (typeof(js_rotate_active_images_detail_after_init) !== 'undefined') {
				js_rotate_active_images_detail_after_init();
			}
		}
	}
};

/* ========================================
 FILE: /modules/mod_wishlist_new/mod_wishlist_new.js
 ==================== */

// global vars
var wishlist_new_count = 0;

(function () {
	script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};

	var params = {
		'wishlist': typeof script_manage_params.wishlist !== 'undefined' && script_manage_params.wishlist != 0 ? JSON.parse(script_manage_params.wishlist) : {},
		'ph_id':    typeof script_manage_params.ph_id !== 'undefined' ? script_manage_params.ph_id : ''
	};

	window.onload = function () {
		js_wishlist_new_check_after_page_load();

		jQuery(document).on('addToWishlist removeFromWishlist', function(event, data) {
			if (typeof data !== 'undefined' && data.after_js) {
				eval(data.after_js);
			}
		});
	};

	window.js_wishlist_new_check_after_page_load = function() {
		var my_id        = params.ph_id;
		var wishlist_new = params.wishlist;

		if (my_id == 0) {
			wishlist_new = '';
			if ( Cookies.get('wishlist') !== undefined ) { wishlist_new = Cookies.get('wishlist'); }
			wishlist_new = wishlist_new.split(",");
			if (wishlist_new.length == 1 && wishlist_new[0] == '') wishlist_new = [];
		}

		wishlist_new_count = wishlist_new.length;

		for (i in wishlist_new) {
			if (wishlist_new.hasOwnProperty(i)) {
				var el = jQuery('.flypage_wishlist_'+wishlist_new[i]);
				el.find('.flypage_wishlist_add').hide();
				el.find('.flypage_wishlist_delete').show();
				el.find('.flypage_wishlist_in_wishlist').show();

				if (el.length > 0) {
					jQuery('body').addClass('in_wishlist');
				}

				el.parents('.slick-slide').addClass('product_in_wishlist');

				var product_list_elem = jQuery('#product_list').find('.product_id_'+wishlist_new[i]);
				product_list_elem.addClass('product_in_wishlist');

				const pw_el = jQuery('.product_wishlist_' + wishlist_new[i]);
				const slickSlide = pw_el.parents('.slick-slide');
				const articleProduct = pw_el.parents('.article_product_listing:first');
				const csProductItem = pw_el.parents('.cs_product_item:first');

				if (slickSlide.length > 0) {
					slickSlide.addClass('product_in_wishlist');
				} else if (articleProduct.length > 0) {
					articleProduct.addClass('product_in_wishlist');
					if (csProductItem.length > 0) {
						csProductItem.addClass('product_in_wishlist');
					}
				} else if (csProductItem.length > 0) {
					csProductItem.addClass('product_in_wishlist');
				}

				jQuery('.product_wishlist_' + wishlist_new[i]).find('a').remove();
					jQuery('.product_wishlist_'+wishlist_new[i]).prepend('<a class="wishlist_btn_remove" href="javascript:void(0)" onclick="return js_wishlist_b_delete_click(this, '+my_id+', '+wishlist_new[i]+')" title="'+js_lang_wishlist_item_delete+'">'+js_lang_wishlist_item_delete+'</a>');
					//jednotlive moduly
					var modul_elems = jQuery(' .featured-prod.product_id_'+wishlist_new[i]+', .module-latest-viewed-item.product_id_'+wishlist_new[i]+', .related_product1.product_id_'+wishlist_new[i]+', .related_product2.product_id_'+wishlist_new[i]+', .related_product3.product_id_'+wishlist_new[i]+'');
					modul_elems.addClass('product_in_wishlist');
			}
		}

		if (typeof(js_wishlist_change_count) != 'undefined') { js_wishlist_change_count(); }
	};

	window.js_wishlist_change = function(typ) {
		if (typ == 'add') wishlist_new_count++;
		if (typ == 'remove' && wishlist_new_count > 0) wishlist_new_count--;
		if (typeof(js_wishlist_change_count) != 'undefined') { js_wishlist_change_count(typ); }
	};

// ---------- FUNKCIE VOLANE Z MODULU --------------

	window.js_wishlist_item_to_cart_click = function(elem, product_id, category_id) {
		document.wlnf_addtocart.quantity.value = "1";
		document.wlnf_addtocart.category_id.value = category_id;
		document.wlnf_addtocart.product_id.value = product_id;
		document.wlnf_addtocart.func.value = "cartadd";
		document.wlnf_addtocart.submit();
	};


	window.js_wishlist_item_delete_click = function(elem, user_id, product_id) {
		elem = jQuery(elem);

		var cookie_wl = '';
		if (user_id == 0) {
			cookie_wl = Cookies.get('wishlist') || '';
			cookie_wl = cookie_wl.split(",");
			for (i=cookie_wl.length-1; i>=0; i--) {
				if (cookie_wl[i] == product_id) cookie_wl.splice(i, 1);
			}
			cookie_wl = cookie_wl.toString();
			Cookies.set('wishlist', cookie_wl, { expires: 365, path: '/' });
		}
		var options = {ajax_func: 'item_delete', user_id: user_id, product_id: product_id};

		jQuery.post(js_global_live_site+'/modules/mod_wishlist_new/mod_wishlist_new_ajax.php', options, function(r) {
			var rdata = JSON.parse(r);
			var wlitems = elem.closest('.wishlist_items').get(0);

			if ( typeof wlitems !== 'undefined' ) {
				wlitems.innerHTML = rdata.wlhtml;
			}

			var wlpdclass = '.flypage_wishlist_'+rdata.product_id;
			var wlbclass = '.product_wishlist_'+rdata.product_id;
			if (jQuery(wlpdclass)[0]) {
				jQuery('body').removeClass('in_wishlist');
				jQuery(wlpdclass).html(rdata.wl_pd_html);
			}
			jQuery(wlbclass).html(rdata.wl_b_html);
			jQuery('.product_id_'+rdata.product_id).removeClass('product_in_wishlist');
			jQuery('.product_wishlist_'+rdata.product_id).parents('.slick-slide').removeClass('product_in_wishlist');

			//dynamicke ceny pre tripsy
			if (typeof _aws != 'undefined' && jQuery('.user_logged_in').length) {
				_aws.init('.module-wishlist');
			}

			js_add_to_cart_form_ajax_cart_bind();

		});
		js_wishlist_change('remove');
	};

// ---------- FUNKCIE VOLANE Z DETAILU PRODUKTU --------------

	window.js_wishlist_pd_add_click = function(elem, user_id, product_id) {
		var $elem = jQuery(elem);

		$elem.css('pointer-events', 'none');

		var cookie_wl = '';
		if (user_id == 0) {
			cookie_wl = Cookies.get('wishlist') || '';
			if (cookie_wl == null || cookie_wl == '') {
				Cookies.set('wishlist', product_id, { expires: 365, path: '/' });
			} else {
				Cookies.set('wishlist', cookie_wl + ',' + product_id, { expires: 365, path: '/' });
			}
			cookie_wl = Cookies.get('wishlist') || '';
		}

		var options = {ajax_func: 'pd_add', user_id: user_id, product_id: product_id, cookie_wl: cookie_wl};

		jQuery.post(js_global_live_site+'/modules/mod_wishlist_new/mod_wishlist_new_ajax.php', options, function(r) {
			$elem.css('pointer-events', 'auto');

			var rdata = JSON.parse(r);
			var wl_pd = $elem.closest('.flypage_wishlist').get(0);

			if ( typeof wl_pd !== 'undefined' ) {
				wl_pd.innerHTML = rdata.wl_pd_html;
			}

			jQuery('.wishlist_items').html(rdata.wl_mod_html);
			jQuery('body').addClass('in_wishlist');

			jQuery(document).trigger('addToWishlist', [rdata]);
		});

		js_wishlist_change('add');

		setTimeout(function(){
			jQuery('.flypage_wishlist').find('.flypage_wishlist_added').hide();
		}, 4000);
	};

	window.js_wishlist_pd_delete_click = function(elem, user_id, product_id) {
		elem = jQuery(elem);

		var cookie_wl = '';
		if (user_id == '0') {
			cookie_wl = Cookies.get('wishlist') || '';
			cookie_wl = cookie_wl.split(",");
			for (i=cookie_wl.length-1; i>=0; i--) {
				if (cookie_wl[i] == product_id) cookie_wl.splice(i, 1);
			}
			cookie_wl = cookie_wl.toString();
			Cookies.set('wishlist', cookie_wl, { expires: 365, path: '/' });
		}
		var options = {ajax_func: 'pd_delete', user_id: user_id, product_id: product_id, cookie_wl: cookie_wl};
		jQuery.post(js_global_live_site+'/modules/mod_wishlist_new/mod_wishlist_new_ajax.php', options, function(r) {
			var rdata = JSON.parse(r);
			var wl_pd = elem.closest('.flypage_wishlist').get(0);

			if ( typeof wl_pd !== 'undefined' ) {
				wl_pd.innerHTML = rdata.wl_pd_html;
			}

			jQuery('.wishlist_items').html(rdata.wl_mod_html);
			jQuery('body').removeClass('in_wishlist');

			jQuery(document).trigger('removeFromWishlist', [rdata]);
		});

		js_wishlist_change('remove');

		setTimeout(function(){
			jQuery('.flypage_wishlist').find('.flypage_wishlist_added').hide();
		}, 4000);
	};

// ---------- FUNKCIE VOLANE Z BROWSU --------------

	window.js_wishlist_b_add_click = function(elem, user_id, product_id) {
		var $elem = jQuery(elem);

		$elem.css('pointer-events', 'none');

		var cookie_wl = '';
		if (user_id == 0) {
			cookie_wl = Cookies.get('wishlist') || '';
			if (cookie_wl == null || cookie_wl == '') {
				Cookies.set('wishlist', product_id, { expires: 365, path: '/' });
			} else {
				Cookies.set('wishlist', cookie_wl + ',' + product_id, { expires: 365, path: '/' });
			}
			cookie_wl = Cookies.get('wishlist') || '';
		}
		var options = {ajax_func: 'b_add', user_id: user_id, product_id: product_id, cookie_wl: cookie_wl};
		jQuery.post(js_global_live_site+'/modules/mod_wishlist_new/mod_wishlist_new_ajax.php', options, function(r) {
			$elem.css('pointer-events', 'auto');

			var rdata = JSON.parse(r);
			var wl_p = $elem.closest('.product_wishlist_'+product_id).get(0);
			$elem.closest('div.browse_listing').addClass('product_in_wishlist');

			if ( typeof wl_p !== 'undefined' ) {
				wl_p.innerHTML = rdata.wl_b_html;
			}

			if ( user_id > 0 ) {
				params && params.wishlist && params.wishlist.push(product_id.toString());
			}

			jQuery('.wishlist_items').html(rdata.wl_mod_html);
			jQuery('.product_id_'+product_id).addClass('product_in_wishlist');
			const pw_el = jQuery('.product_wishlist_' + product_id);
			const slickSlide = pw_el.parents('.slick-slide');
			const articleProduct = pw_el.parents('.article_product_listing:first');
			const csProductItem = pw_el.parents('.cs_product_item:first');

			if (slickSlide.length > 0) {
				slickSlide.addClass('product_in_wishlist');
			} else if (articleProduct.length > 0) {
				articleProduct.addClass('product_in_wishlist');
				if (csProductItem.length > 0) {
					csProductItem.addClass('product_in_wishlist');
				}
			} else if (csProductItem.length > 0) {
				csProductItem.addClass('product_in_wishlist');
			}

			jQuery(document).trigger('addToWishlist', [rdata]);
		});

		js_wishlist_change('add');
	};

	window.js_wishlist_b_delete_click = function(elem, user_id, product_id) {
		elem = jQuery(elem);

		var cookie_wl = '';
		if (user_id == '0') {
			cookie_wl = Cookies.get('wishlist') || '';
			cookie_wl = cookie_wl.split(",");
			for (i=cookie_wl.length-1; i>=0; i--) {
				if (cookie_wl[i] == product_id) cookie_wl.splice(i, 1);
			}
			cookie_wl = cookie_wl.toString();
			Cookies.set('wishlist', cookie_wl, { expires: 365, path: '/' });
		}
		var options = {ajax_func: 'b_delete', user_id: user_id, product_id: product_id, cookie_wl: cookie_wl};
		jQuery.post(js_global_live_site+'/modules/mod_wishlist_new/mod_wishlist_new_ajax.php', options, function(r) {
			var rdata = JSON.parse(r);
			var wl_p = elem.closest('.product_wishlist_'+product_id).get(0);
			elem.closest('div.browse_listing').removeClass('product_in_wishlist');

			if ( typeof wl_p !== 'undefined' ) {
				wl_p.innerHTML = rdata.wl_b_html;
			}

			if(user_id > 0){
				params.wishlist = params.wishlist && jQuery.grep(params.wishlist, function(value) {
					return value != product_id.toString();
				});
			}

			jQuery('.wishlist_items').html(rdata.wl_mod_html);
			jQuery('.product_id_'+product_id).removeClass('product_in_wishlist');
			const pw_el = jQuery('.product_wishlist_' + product_id);
			const slickSlide = pw_el.parents('.slick-slide');
			const articleProduct = pw_el.parents('.article_product_listing:first');
			const csProductItem = pw_el.parents('.cs_product_item:first');

			if (slickSlide.length > 0) {
				slickSlide.removeClass('product_in_wishlist');
			} else if (articleProduct.length > 0) {
				articleProduct.removeClass('product_in_wishlist');
				if (csProductItem.length > 0) {
					csProductItem.removeClass('product_in_wishlist');
				}
			} else if (csProductItem.length > 0) {
				csProductItem.removeClass('product_in_wishlist');
			}

			jQuery(document).trigger('removeFromWishlist', [rdata]);
		});

		js_wishlist_change('remove');
	};
})();


/* ========================================
 FILE: /includes/js/system/cs_lib.js
 ==================== */

String.prototype.toJSON = function() {
	var text = this;
// 	if (typeof(text) != 'string')
// 		text = encodeURIComponent(text);
	return JSON.parse(decodeURIComponent(text));
};

//function importJs(name,url) {
//	if(jQuery('[data-id="'+name+'"]').length > 0){
//		return;
//	}
//	var scriptTag = document.createElement('script');
//
//			scriptTag.setAttribute('data-id', name);
//			scriptTag.onload = _success;
//			scriptTag.onreadystatechange = _success;
//			scriptTag.src = url;
//			document.head.appendChild(scriptTag);
//}

function csJsonParse( strJson, errFunc ) {
	var jsonRes = null;
	if (strJson != null && (typeof(strJson) == 'string' || strJson instanceof String) && strJson.trim() != '') {
		try {
			jsonRes = JSON.parse(strJson);
		} catch( jso_err ) {
			jsonRes = null;
			if (typeof(errFunc) == 'function') {
				//errFunc.call(null, jso_err);
				errFunc(jso_err, strJson);
			}
		}
	} else {
		jsonRes = null;
	}
	return jsonRes;
};

/**
 *
 * @example csClean(['1', 'lorem', true, 55698], '1', true);
 * @example csClean(['1', 'lorem', true, 55698], [true, 'lorem']);
 *
 * @param {Array} - Array
 * @param {String|Array} deleteValue - Value to be deleted from array
 * @param {Boolean} strict - Compare data types - Default: false
 * @return {Array}
 */
function csClean(arr, deleteValue, strict)
{
	strict = typeof strict === 'boolean' ? strict : false;

	if (!(deleteValue instanceof Array)) {
		deleteValue = [deleteValue];
	}

	if (deleteValue instanceof Array) {
		for (var i = 0; i < arr.length; i++) {
			deleteValue.forEach(function(value) {
				if (strict) {
					if (arr[i] === value) {
						arr.splice(i, 1);
						i--;
					}

				} else {
					if (arr[i] == value) {
						arr.splice(i, 1);
						i--;
					}
				}
			});
		}
	}

	return arr;
};

/**
 * Compare 2 or more objects
 * @author Hucci
 * @example csCompareObjects({a: 1, b: 2}, {b: 2, a: 1}) > true
 * @return {Boolean}
 */
function csCompareObjects()
{
	var i, l, leftChain, rightChain;

	function compare2Objects(x, y)
	{
		var p;

		if ((isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') || x === y) {
			return true;
		}

		if ((typeof x === 'function' && typeof y === 'function') ||
			(x instanceof Date && y instanceof Date) ||
			(x instanceof RegExp && y instanceof RegExp) ||
			(x instanceof String && y instanceof String) ||
			(x instanceof Number && y instanceof Number)
		) {
			return x.toString() === y.toString();
		}

		if (!(x instanceof Object && y instanceof Object) ||
			x.isPrototypeOf(y) || y.isPrototypeOf(x) ||
			x.constructor !== y.constructor ||
			x.prototype !== y.prototype ||
			leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1
		) {
			return false;
		}

		for (p in y) {
			if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || typeof y[p] !== typeof x[p]) {
				return false;
			}
		}

		for (p in x) {
			if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || typeof y[p] !== typeof x[p]) {
				return false;
			}

			switch (typeof (x[p])) {
				case 'object':
				case 'function':
					leftChain.push(x);
					rightChain.push(y);

					if (!compare2Objects (x[p], y[p])) {
						return false;
					}

					leftChain.pop();
					rightChain.pop();

					break;

				default:
					if (x[p] !== y[p]) {
						return false;
					}

					break;
			}
		}

		return true;
	}

	if (arguments.length < 1) {
		return true;
	}

	for (i = 1, l = arguments.length; i < l; i++) {
		leftChain = [];
		rightChain = [];

		if (!compare2Objects(arguments[0], arguments[i])) {
			return false;
		}
	}

	return true;
}

/**
 * @author Hucci
 * @param {Number} price
 * @param {Object} currencySettings
 * @return {String}
 */
function csFormatPrice(price, currencySettings, only_number)
{
	var price = typeof price === 'number' ? price : (typeof js_parse_float === 'function') ? js_parse_float(price) : 0;
	var currencySettings = typeof currencySettings === 'object'
		? currencySettings
		: ((typeof shop_currency_info === 'object' && typeof shop_vendor_currency_code === 'string' && shop_vendor_currency_code in shop_currency_info)
			? shop_currency_info[shop_vendor_currency_code]
			: {
				'DECIMALS': 2,
				'1000_SYMBOL': ' ',
				'DEC_SYMBOL': ',',
				'POSIT': 1,
				'NEGAT': 8,
				'SYMBOL': '€'
			});
	var negative = price < 0 ? '-' : '';
	var full = String(parseInt(price = Math.abs(Number(price) || 0).toFixed(currencySettings.DECIMALS)));
	var thousands = (thousands = full.length) > 3 ? thousands % 3 : 0;
	var formattedPrice = negative + (thousands ? full.substr(0, thousands) + currencySettings['1000_SYMBOL'] : '') + full.substr(thousands).replace(/(\d{3})(?=\d)/g, "$1" + currencySettings['1000_SYMBOL']) + (price && currencySettings.DECIMALS ? currencySettings.DEC_SYMBOL + Math.abs(price - full).toFixed(currencySettings.DECIMALS).slice(2) : '');

	if ( only_number === true ) return formattedPrice;

	var symbol = currencySettings.SYMBOL;

	var elem = document.createElement('textarea');
	elem.innerHTML = symbol;
	symbol = elem.value;

	if (price >= 0) {
		switch (currencySettings.POSIT) {
			case 0:	formattedPrice = formattedPrice + symbol; break;
			case 1:	formattedPrice = formattedPrice +' '+ symbol; break;
			case 2:	formattedPrice = symbol + formattedPrice; break;
			case 3:	formattedPrice = symbol +' '+ formattedPrice; break;

			default: formattedPrice = formattedPrice +' '+ symbol; break;
		}

	} else {
		formattedPrice = (formattedPrice[0] === '-') ? formattedPrice.substr(1) : formattedPrice;

		switch (currencySettings.NEGAT) {
			case 0: formattedPrice = '('+ symbol + formattedPrice +')'; break;
			case 1: formattedPrice = '-'+ symbol + formattedPrice; break;
			case 2: formattedPrice = symbol +'-'+ formattedPrice; break;
			case 3: formattedPrice = symbol + formattedPrice +'-'; break;
			case 4:	formattedPrice = '('+ formattedPrice + symbol +')'; break;
			case 5:	formattedPrice = '-'+ formattedPrice + symbol; break;
			case 6:	formattedPrice = formattedPrice +'-'+ symbol; break;
			case 7:	formattedPrice = formattedPrice + symbol +'-'; break;
			case 8:	formattedPrice = '-'+ formattedPrice +' '+ symbol; break;
			case 9:	formattedPrice = '-'+ symbol +' '+ formattedPrice; break;
			case 10: formattedPrice = formattedPrice +' '+ symbol +'-'; break;
			case 11: formattedPrice = symbol +' '+ formattedPrice +'-'; break;
			case 12: formattedPrice = symbol +' -'+ formattedPrice; break;
			case 13: formattedPrice = formattedPrice +'- '+ symbol; break;
			case 14: formattedPrice = '('+ symbol +' '+ formattedPrice +')'; break;
			case 15: formattedPrice = '('+ formattedPrice +' '+ symbol +')'; break;

			default: formattedPrice = '-'+ formattedPrice +' '+ symbol; break;
		}
	}

	return formattedPrice;
}

/**
 * Create breakpoint when object property has changed
 *
 * @example csConsoleWatch(jQuery('#cbi_5').get(0), 'checked');
 * @example csConsoleWatch(document.getElementById('cbi_5'), 'checked');
 *
 * @param {Object} obj - Javascript Object
 * @param {String} prop - Object property to watch
 */
function csConsoleWatch(obj, prop)
{
	privateProp = "$_"+ prop +"_$";		// to minimize the name clash risk
	obj[privateProp] = obj[prop];

	// overwrite with accestor
	Object.defineProperty(obj, prop, {
		get:	function() {
			return obj[privateProp];
		},
		set:	function(value) {
			console.log(' # # # csConsoleWatch: # # # ');
			console.log('Setting \''+ prop +'\' to \''+ value +'\' on ', obj);
			console.trace();
			console.log(' # # # # # # # # # # # # # # ');
			debugger;					// sets breakpoint
			obj[privateProp] = value;
		}
	});
}

/**
 *
 * @param {Object} element - jQuery element
 * @param {Boolean} getChilds - If true - get also events of element childs - Default: true
 * @return {Array} - Array of Objects - {object: {Object} - jQuery element, events: {Object}}
 */
function csGetBindedEvents(element, getChilds)
{
	getChilds = typeof getChilds === 'boolean' ? getChilds : true;
	var selection = getChilds ? element.add(element.find('*')) : element;
	var retArr = [];

	selection.each(function() {
		if (typeof (events = jQuery._data(jQuery(this).get(0), 'events')) === 'object') {
			retArr.push({
				object:	jQuery(this),
				events:	events
			});
		}
	});

	return retArr;
}


/**
 *
 * @example csGetUrlParamByName('order_id', '...?page=order.invoice_printdetails&order_id=425000087') -> '425000087'
 * @example csGetUrlParamByName('type', '...?page=order.invoice_printdetails&order_id=425000087') -> undefined
 *
 * @param {String} name - Parameter name to get
 * @param {String} url
 * @return {String|Undefined}
 */
function csGetUrlParamByName(name, url) {
	url = (!url || url === '') ? window.location.href : url;
	name = name.replace(/[\[\]]/g, "\\$&");

	var regex = new RegExp('[?&]'+ name +'(=([^&#]*)|&|#|$)'),

	results = regex.exec(url);

	if (!results) {
		return;

	} else if (!results[2]) {
		return '';

	} else {
		return decodeURIComponent(results[2].replace(/\+/g, ' '));
	}
}


jQuery.fn.justtext = function() {
	// fn vrati text len aktalneho elementu bez jeho childrens
    return jQuery(this).clone()
            .children()
            .remove()
            .end()
            .text();
};

var emailProtection = 'encode';

var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();

function str_repeat(patern, n) {
    var s = '';
    for (;;) {
        if (n & 1) s += patern;
        n >>= 1;
        if (n) patern += patern;
        else break;
    }
    return s;
}

function js_prettyphoto_close() {
  if (jQuery('.pp_pic_holder').length == 0)
  	  return false;

  jQuery.prettyPhoto.close();
  jQuery(document).off('keyup');
  return false;
}

function js_toggle_input_fields(elem){
	var checkbox = jQuery(elem);
	var box = checkbox.closest('div');
	if (checkbox.is(':checked')){

		box.find('.inputbox').show();
	} else {

		box.find('.inputbox').hide();
	}
}

function js_toggle_ckmsyts_fields(elem){
	var checkbox = jQuery(elem);
	var box = checkbox.closest('div');
	var coupon = jQuery('[name="coupon_code"]');
	var placeholder = '';
	if (checkbox.is(':checked')){
		placeholder = coupon.data('ckmpsytslaceholder');
		box.find('.inputbox').show();
	} else {
		placeholder = coupon.data('couponplaceholder');
		box.find('.inputbox').hide();
	}
	coupon.attr('placeholder', placeholder);
}

function js_setLimitedInterval( func, msec, repeat_limit ) {
	//	variacia funkcie setInterval( function () {...} ) s limitom poctu opakovania
	//	opakuje volanie funkcie func pokial tato nevrati == true, alebo pokial neuplynie limit poctu opakovani
	//	prve volanie funkcie func je po uplynuti msec (rovnako ako v setInterval)
	//	//	pouzitie 1.: js_setLimitedInterval( function () { return my_func(); }, 1000, 3 );
	//	//	vykonava v sekundovych intervaloch, pokial my_func() nevrati true, ale max. 3x
	//	//	pouzitie 2.: js_setLimitedInterval( function () { return if ( ... ) { ...; return true; } else { ...; return false; } ; }, 1000, 3 )
	//	//	vykonava v sekundovych intervaloch, pokial function nevrati true, ale max. 3x
	if (typeof(func) == 'function' && typeof(msec) == 'number' && msec > 0 && typeof(repeat_limit) == 'number' && repeat_limit > 0) {
		if (func.hasOwnProperty('own_func_prop__repeat_count')) {
			var func_ret = func.call();
			func.own_func_prop__repeat_count ++;
		} else {
			var func_ret = null;
			func.own_func_prop__repeat_count = 0;
		}
		if (typeof(func_ret) != 'boolean' || func_ret != true) {
			if (func.own_func_prop__repeat_count < repeat_limit) {
				setTimeout(function () { js_setLimitedInterval(func, msec, repeat_limit); }, msec);
			}
		}
	}
	return null;
}

function js_load_external(url) {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
}

function js_load_external_css(url) {
	var style = document.createElement("link");
	style.rel = "stylesheet";
	style.type = 'text/css';
	style.href = url;
	document.getElementsByTagName("head")[0].appendChild(style);
}

function pathinfo(path, options) {
  //  discuss at: http://phpjs.org/functions/pathinfo/
  // original by: Nate
  //  revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Brett Zamir (http://brett-zamir.me)
  //    input by: Timo
  //        note: Inspired by actual PHP source: php5-5.2.6/ext/standard/string.c line #1559
  //        note: The way the bitwise arguments are handled allows for greater flexibility
  //        note: & compatability. We might even standardize this code and use a similar approach for
  //        note: other bitwise PHP functions
  //        note: php.js tries very hard to stay away from a core.js file with global dependencies, because we like
  //        note: that you can just take a couple of functions and be on your way.
  //        note: But by way we implemented this function, if you want you can still declare the PATHINFO_*
  //        note: yourself, and then you can use: pathinfo('/www/index.html', PATHINFO_BASENAME | PATHINFO_EXTENSION);
  //        note: which makes it fully compliant with PHP syntax.
  //  depends on: basename
  //   example 1: pathinfo('/www/htdocs/index.html', 1);
  //   returns 1: '/www/htdocs'
  //   example 2: pathinfo('/www/htdocs/index.html', 'PATHINFO_BASENAME');
  //   returns 2: 'index.html'
  //   example 3: pathinfo('/www/htdocs/index.html', 'PATHINFO_EXTENSION');
  //   returns 3: 'html'
  //   example 4: pathinfo('/www/htdocs/index.html', 'PATHINFO_FILENAME');
  //   returns 4: 'index'
  //   example 5: pathinfo('/www/htdocs/index.html', 2 | 4);
  //   returns 5: {basename: 'index.html', extension: 'html'}
  //   example 6: pathinfo('/www/htdocs/index.html', 'PATHINFO_ALL');
  //   returns 6: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}
  //   example 7: pathinfo('/www/htdocs/index.html');
  //   returns 7: {dirname: '/www/htdocs', basename: 'index.html', extension: 'html', filename: 'index'}

  var opt = '',
    optName = '',
    optTemp = 0,
    tmp_arr = {},
    cnt = 0,
    i = 0;
  var have_basename = false,
    have_extension = false,
    have_filename = false;

  // Input defaulting & sanitation
  if (!path) {
    return false;
  }
  if (!options) {
    options = 'PATHINFO_ALL';
  }

  // Initialize binary arguments. Both the string & integer (constant) input is
  // allowed
  var OPTS = {
    'PATHINFO_DIRNAME': 1,
    'PATHINFO_BASENAME': 2,
    'PATHINFO_EXTENSION': 4,
    'PATHINFO_FILENAME': 8,
    'PATHINFO_ALL': 0
  };
  // PATHINFO_ALL sums up all previously defined PATHINFOs (could just pre-calculate)
  for (optName in OPTS) {
    OPTS.PATHINFO_ALL = OPTS.PATHINFO_ALL | OPTS[optName];
  }
  if (typeof options !== 'number') {
    // Allow for a single string or an array of string flags
    options = [].concat(options);
    for (i = 0; i < options.length; i++) {
      // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
      if (OPTS[options[i]]) {
        optTemp = optTemp | OPTS[options[i]];
      }
    }
    options = optTemp;
  }

  // Internal Functions
  var __getExt = function (path) {
    var str = path + '';
    var dotP = str.lastIndexOf('.') + 1;
    return !dotP ? false : dotP !== str.length ? str.substr(dotP) : '';
  };

  // Gather path infos
  if (options & OPTS.PATHINFO_DIRNAME) {
    var dirName = path.replace(/\\/g, '/')
      .replace(/\/[^\/]*\/?$/, ''); // dirname
    tmp_arr.dirname = dirName === path ? '.' : dirName;
  }

  if (options & OPTS.PATHINFO_BASENAME) {
    if (false === have_basename) {
      have_basename = this.basename(path);
    }
    tmp_arr.basename = have_basename;
  }

  if (options & OPTS.PATHINFO_EXTENSION) {
    if (false === have_basename) {
      have_basename = this.basename(path);
    }
    if (false === have_extension) {
      have_extension = __getExt(have_basename);
    }
    if (false !== have_extension) {
      tmp_arr.extension = have_extension;
    }
  }

  if (options & OPTS.PATHINFO_FILENAME) {
    if (false === have_basename) {
      have_basename = this.basename(path);
    }
    if (false === have_extension) {
      have_extension = __getExt(have_basename);
    }
    if (false === have_filename) {
      have_filename = have_basename.slice(0, have_basename.length - (have_extension ? have_extension.length + 1 :
        have_extension === false ? 0 : 1));
    }

    tmp_arr.filename = have_filename;
  }

  // If array contains only 1 element: return string
  cnt = 0;
  for (opt in tmp_arr) {
    cnt++;
  }
  if (cnt == 1) {
    return tmp_arr[opt];
  }

  // Return full-blown array
  return tmp_arr;
}

function basename(path, suffix) {
  //  discuss at: http://phpjs.org/functions/basename/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Ash Searle (http://hexmen.com/blog/)
  // improved by: Lincoln Ramsay
  // improved by: djmix
  // improved by: Dmitry Gorelenkov
  //   example 1: basename('/www/site/home.htm', '.htm');
  //   returns 1: 'home'
  //   example 2: basename('ecra.php?p=1');
  //   returns 2: 'ecra.php?p=1'
  //   example 3: basename('/some/path/');
  //   returns 3: 'path'
  //   example 4: basename('/some/path_ext.ext/','.ext');
  //   returns 4: 'path_ext'

  var b = path;
  var lastChar = b.charAt(b.length - 1);

  if (lastChar === '/' || lastChar === '\\') {
    b = b.slice(0, -1);
  }

  b = b.replace(/^.*[\/\\]/g, '');

  if (typeof suffix === 'string' && b.substr(b.length - suffix.length) == suffix) {
    b = b.substr(0, b.length - suffix.length);
  }

  return b;
}

// JAN mnozstevna automaticka zlava na produkt: povolenie zlavy
function js_product_automatic_discount_click( link_element ) {
	link_element = jQuery(link_element);
	var container_element = jQuery('.product_automatic_discount_add_new');

	if ( link_element.prop('checked') ) {
		container_element.css('display', 'block');
	}
	else {
		container_element.css('display', 'none');
	}
}

function js_product_automatic_discount_handler_shopper_groups( action ) {
	var variantBox = jQuery('.product_automatic_discount_add_new');
	var variantCount = variantBox.children('.product_auto_discount_variant').length;
	var options = {
		function: 'getBulkDiscountSgHtml',
		variantIndex: variantCount + action,
	};
	jQuery.post('/includes/frontend_ajax.php', options, function (res) {
		var shopperGroupInputs = '';
		if (res != '') {
			var content = JSON.parse(res);
			if (typeof content.sgInputs != 'undefined' && content.sgInputs != '') {
				shopperGroupInputs = content.sgInputs;
			}
		}

		var variant_box = jQuery('.product_automatic_discount_add_new');
		var last_element = variant_box.children('.product_auto_discount_variant:last');
		var variant_count = variant_box.children('.product_auto_discount_variant').length;
		var variant_start = parseInt( jQuery('input[name=auto_discount_to_'+variant_count+']').val() ) + 1;
		var variant_r_count = variant_count + action;

		var variant_div = '<div class="product_auto_discount_variant" id="auto_discount_variant_' + variant_r_count + '"><div class="br-setting"><!-- --></div><div class="pad_v_count_from"><label><span class="pad_vc_nr">' + variant_r_count + '.</span>od:</label><input onkeyup="js_product_automatic_discount_check_numeric_decimal(this);" onblur="return js_product_automatic_discount_check_field(this);" type="text" name="auto_discount_from_' + variant_r_count + '" maxlength="15" value="' + variant_start + '" /></div><div class="pad_v_count_to"><label>ks&nbsp;&nbsp;-&nbsp;&nbsp;do:</label><input onkeyup="js_product_automatic_discount_check_numeric_decimal(this);" onblur="return js_product_automatic_discount_check_field(this);" type="text" name="auto_discount_to_' + variant_r_count + '" maxlength="15" value="" /></div><div class="pad_variants_value"><label>ks&nbsp;&nbsp;</label>' + shopperGroupInputs + '</div><a class="pad_v_remove_btton" style="display:block;" class="product_auto_discount_remove" onclick="return js_product_automatic_discount_handler(-1);" title="Zmazať posledný variant"><img src="/templates/global/manage/images/template-module-h_x.png" title="Zmazať posledný variant" alt="Zmazať"></a></div>';

		if( typeof( action ) !== 'undefined' && action == 1 && js_product_automatic_discount_check_field( false, true ) ){
			last_element.after( variant_div );
			last_element.find('a.product_auto_discount_remove').css('display', 'none');
		}
	});
	return false;
}

// JAN mnozstevna automaticka zlava na produkt: pridanie variantu
function js_product_automatic_discount_handler( action ) {

	if ( typeof js_Config_shop_product_bulk_discounts_shopper_group !== 'undefined' && js_Config_shop_product_bulk_discounts_shopper_group && typeof action !== 'undefined' && action == 1 ) {
		js_product_automatic_discount_handler_shopper_groups(action);
		return false;
	}

	var variant_box = jQuery('.product_automatic_discount_add_new');
	var last_element = variant_box.children('.product_auto_discount_variant:last');
	var variant_count = variant_box.children('.product_auto_discount_variant').length;
	var variant_start = parseInt( jQuery('input[name=auto_discount_to_'+variant_count+']').val() ) + 1;
	var variant_r_count = variant_count + action;

	var extraHtml = '';
	if ( typeof js_Config_shop_product_bulk_discounts_favorite_option !== 'undefined' && js_Config_shop_product_bulk_discounts_favorite_option ) {
		extraHtml += '<div class="pad_favorite_option"><input type="checkbox" id="auto_discount_favorite_option_' + variant_r_count + '" name="auto_discount_favorite_option_' + variant_r_count + '" /><label for="auto_discount_favorite_option_' + variant_r_count + '">Obľúbená možnosť</label></div>';
	}

	var variant_div = '<div class="product_auto_discount_variant" id="auto_discount_variant_'+variant_r_count+'"><div class="br-setting"><!-- --></div><div class="pad_v_count_from"><label><span class="pad_vc_nr">'+variant_r_count+'.</span>od:</label><input onkeyup="js_product_automatic_discount_check_numeric_decimal(this);" onblur="return js_product_automatic_discount_check_field(this);" type="text" name="auto_discount_from_'+variant_r_count+'" maxlength="15" value="'+variant_start+'" /></div><div class="pad_v_count_to"><label>ks&nbsp;&nbsp;-&nbsp;&nbsp;do:</label><input onkeyup="js_product_automatic_discount_check_numeric_decimal(this);" onblur="return js_product_automatic_discount_check_field(this);" type="text" name="auto_discount_to_'+variant_r_count+'" maxlength="15" value="" /></div><div class="pad_variants_value"><label>ks&nbsp;&nbsp;-&nbsp;&nbsp;aplikovať zľavu</label><input onkeyup="js_product_automatic_discount_check_numeric_decimal(this);" onblur="return js_product_automatic_discount_check_field(this);" type="text" name="auto_discount_value_'+variant_r_count+'" maxlength="15" value="" /><span class="auto_discount_symbol_percentage">&#37;</span></div>' + extraHtml + '<a class="pad_v_remove_btton" style="display:block;" class="product_auto_discount_remove" onclick="return js_product_automatic_discount_handler(-1);" title="Zmazať posledný variant"><img src="/templates/global/manage/images/template-module-h_x.png" title="Zmazať posledný variant" alt="Zmazať"></a></div>';

	if( typeof( action ) !== 'undefined' && action == 1 && js_product_automatic_discount_check_field( false, true ) ){
		last_element.after( variant_div );
		last_element.find('a.product_auto_discount_remove').css('display', 'none');
	}
	else if( typeof( action ) !== 'undefined' && action == -1 && variant_count > 1 ){
		last_element.remove( );
		var last_element = variant_box.children('.product_auto_discount_variant:last');
		last_element.find('a.product_auto_discount_remove').css('display', 'block');
	}
	return false;
}

// JAN mnozstevna atomaticka zlava : ciselna kontrola pola
function js_product_automatic_discount_check_numeric( field ){
	var field_box = jQuery(field);
	if (event.keyCode > 105 || event.keyCode < 96 ) { // key is not number
		var new_val = field_box.val().match(/\d+/g);
		console.log(new_val);
		field_box.val( new_val != null ? new_val.join('') : '');
	}
}

//Riso mnozstevna automaticka zlava : ciselna kontrola tak aby sa dali zadavat nie len cele cisla
function js_product_automatic_discount_check_numeric_decimal( field ){
	var field_box = jQuery(field);
	if ( (event.keyCode > 105 || event.keyCode < 96) && ( event.keyCode !== 190 || field_box.val().includes('.') || field_box.val().includes(',') ) ) { // key is not number
		if ( field_box.val().includes('.') && field_box.val().includes(',') ) {
			if ( field_box.val().slice(-1) == '.' ) {
				var new_val = field_box.val().match(/\d+\,?\d*/g);
				field_box.val( new_val != null ? new_val.join('') : '');
			} else {
				var new_val = field_box.val().match(/\d+\.?\d*/g);
				field_box.val(new_val != null ? new_val.join('') : '');
			}
		} else if ( field_box.val().includes('.') ) {
			var new_val = field_box.val().match(/\d+\.?\d*/g);
			field_box.val( new_val != null ? new_val.join('') : '');
		} else if ( field_box.val().includes(',') ) {
			var new_val = field_box.val().match(/\d+\,?\d*/g);
			field_box.val( new_val != null ? new_val.join('').replace(',','.') : '');
		}
	}
}

// JAN mnozstevna automaticka zlava na produkt: kontrola variantov
function js_product_automatic_discount_check_field( focused, add ){
	var add = typeof add !== 'undefined' ? add : false;
	if( typeof( focused ) == 'undefined' || focused == false ) var focused = jQuery('.product_auto_discount_variant').last().find('input').last().attr('name');
	else var focused = jQuery(focused).attr('name');
	var variant_count = jQuery('.product_automatic_discount_add_new').children('.product_auto_discount_variant').length;
	if( typeof( variant_count ) !== 'undefined' ){
		var last_to_value = 0;
		var last_discount_value = 0;
		for (var i = 1; i <= variant_count; i++) {


			if (typeof js_Config_vm_use_decimal_product_quantity != 'undefined') {
				var from = parseFloat(jQuery('input[name=auto_discount_from_'+i+']').val());
				var to = parseFloat(jQuery('input[name=auto_discount_to_'+i+']').val());
				var val = parseFloat(jQuery('input[name=auto_discount_value_'+i+']').val());
			} else {
				var from = parseInt(jQuery('input[name=auto_discount_from_'+i+']').val());
				var to = parseInt(jQuery('input[name=auto_discount_to_'+i+']').val());
				var val = parseInt(jQuery('input[name=auto_discount_value_'+i+']').val());
			}



			// kontrola prazdnych alebo neciselnych poli
			if( add && ( typeof(from) == 'undefined' || isNaN( from ) ) ) { js_product_automatic_discount_warning( 'from', i, 1 ); return false; }
			if( add && ( typeof(to) == 'undefined' || isNaN( to ) ) ) { js_product_automatic_discount_warning( 'to', i, 1 ); return false; }
			if ( !( typeof js_Config_shop_product_bulk_discounts_shopper_group !== 'undefined' && js_Config_shop_product_bulk_discounts_shopper_group ) ) {
				if( add && ( typeof(val) == 'undefined' || isNaN( val ) ) ) { js_product_automatic_discount_warning( 'value', i, 1 ); return false; }

				// Kontrola zlavy nad 100 percent
				if( val > 100 ) { js_product_automatic_discount_warning( 'value', i, 4 ); return false; }
			}

			// Hodnota from nemoze byt nula
			if( from == 0 ) { js_product_automatic_discount_warning( 'from', i, 5 ); return false; }
			// kontrola prekrivania od - do
			if ( from > to  ) { js_product_automatic_discount_warning('to', i, 2); return false; }

			//janB úprava -> aby kusy mohli byť od 2 do 2
			if (from > to && to != 99999 && add) {
				js_product_automatic_discount_warning('to', i, 2);
				return false;
			}
			// kontrola poslednej navecsej hodnoty "do" a noveho variantu "from"
			if (typeof (last_to_value) !== 'undefined' && last_to_value > 0 && last_to_value >= from ){ js_product_automatic_discount_warning( 'from', i, 3 ); return false; }

			// kontrola poslednej nekonecnej hodnoty, nemozeme pridavat dalsie varianty
			if (add && i == variant_count && (to.length == 0 || to == '99999')) {
				js_product_automatic_discount_warning('to', i, 6);
				return false;
			}
			if (!(typeof js_Config_shop_product_bulk_discounts_shopper_group !== 'undefined' && js_Config_shop_product_bulk_discounts_shopper_group)) {
				// kontrola nizsej percentualnej zlavy ako predosly variant
				if( val != '' && i != 1 && val <= last_discount_value ) {js_product_automatic_discount_warning( 'value', i, 7 ); return false; }
			}

			// zapis posledne najvacsie hodnoty pre nasledujucu kontrolu
			last_to_value = to;

			if ( !( typeof js_Config_shop_product_bulk_discounts_shopper_group !== 'undefined' && js_Config_shop_product_bulk_discounts_shopper_group ) ) {
				last_discount_value = val;
			}
		}
		return true;
	}
	return false;
}

// JAN mnozstevna automaticka zlava na produkt: upozornenie
function js_product_automatic_discount_warning( field, variant, message ){
	var messages = [
		cms_js_admin_product_bulk_discount_message_1,
		cms_js_admin_product_bulk_discount_message_2,
		cms_js_admin_product_bulk_discount_message_3,
		cms_js_admin_product_bulk_discount_message_4,
		cms_js_admin_product_bulk_discount_message_5,
		cms_js_admin_product_bulk_discount_message_6,
		cms_js_admin_product_bulk_discount_message_7,
		cms_js_admin_product_bulk_discount_message_8
	];
	var target = jQuery( 'input[name=auto_discount_'+field+'_'+variant+']' );
	var message_box = jQuery( '.product_automatic_discount_message_box' ).text('');
	target.effect("highlight", {}, 3000);
	message_box.effect("highlight", {}, 3000);
	message_box.append( messages[message] ).delay(500).fadeOut();
}

// JAN member zone zrusenie clenstva
function js_member_zone_cancel_subsc( user, type ){
	if( confirm( cms_js_lang_member_zone_cancel_subsc_dialog ) ){
		jQuery.post( js_global_live_site+'/public_scripts_M4r7ft/member_zone_ajax.php', {'ajax_func': type, 'user': user}, function(res) {
			// Skontroluj spravy a aktivuj messengera
			if (typeof messenger != 'undefined') messenger.check(res);
			return;
		});
	}
    return false;
}

// JAN member zone poziadavka na zmenu balika
function js_member_zone_change_subsc( user, type ){
	if( confirm( cms_js_lang_member_zone_change_subsc_dialog ) ){
		jQuery.post( js_global_live_site+'/public_scripts_M4r7ft/member_zone_ajax.php', {'ajax_func': type, 'user': user}, function(res) {
			// Skontroluj spravy a aktivuj messengera
			if (typeof messenger != 'undefined') messenger.check(res);
			return;
		});
	}
    return false;
}

// JAN nastavenie wishlist filtra
function js_set_wishlist_filter(bit){
	var wsh_filter = Cookies.get( 'wishlistFilter' );
	if( js_wishlist_filter_type == 'checkbox') wsh_filter = wsh_filter ^ bit;
	else if( wsh_filter == bit ) wsh_filter = 0;
	else wsh_filter = bit;
	Cookies.set( 'wishlistFilter', wsh_filter, {expires: 365, path: '/'});
	document.location.reload();
}

// JAN wishlist manual product add (used in wishlist and product accessories)
function js_wishlist_product_search( self ) {
	jQuery(self).trigger('click');
	if( !(jQuery(self).hasClass('wsh_initialized')) ){
		var pr_search = jQuery(self);
		pr_search.addClass('wsh_initialized');
		pr_search.autocomplete(js_global_live_site+"/administrator/index3.php?option=com_shop&page=product.product_list&no_html=1&no_vm_html=1&no_menu=1&no_css=1&ajax_call=2&ajax_func=get-product-list-for-autocompleter", {
		width: 180,
		parentClass: "wishlist_manual_add_content"
		});

		pr_search.result(function(event, data, formatted) {
			var hidden_id = jQuery(this).parent('.wishlist_manual_add_content').find('.wsh_add_product_id');
			hidden_id.val( data['2'] );
			var full_product_name = '';
			var formatted_jqo = jQuery('<div>'+formatted+'</div>');
			jQuery(formatted_jqo).find('span').each( function(index) {
				if ( index == 0 ) full_product_name += jQuery(this).text();
				else full_product_name += ' (' + jQuery(this).text() + ')';
			});
			formatted = full_product_name;
			if (data && data[1] != '' && data[2] > 0) jQuery(this).val( data['1'] );
			else jQuery(this).val(formatted);
			return;
		});
		pr_search.removeClass('wsh_initialized');
	}
	return;
}

// JAN wishlist add product
function js_add_product_to_wishlist( button, user_id ){
	var elem = jQuery(button);
	var product = elem.parent('.wishlist_manual_add_content').find('.wsh_add_product_id').val();
	var tab = elem.parent('.wishlist_manual_add_content').find(':selected').val();
	if ( typeof(product) == 'undefined' || product == '') return false;
	if ( typeof(tab) == 'undefined' || tab == '') return false;

	var options = {'ajax_func': 'forced', 'product_id': product, 'user_id': user_id, 'tab_id': tab};

	jQuery.post('/modules/mod_wishlist_ajax.php', options, function (ajax_res) {
		var result = JSON.parse(decodeURIComponent(ajax_res));
		// Zla poziadavka
		if( typeof(result.result) != 'undefined' && result.result == '0' ){
			alert('Chýbajú údaje pre spracovanie');
			return false;
		}
		// Produkt existuje
		if( typeof(result.result) != 'undefined' && result.result == '1' ){
			alert('Produkt neexistuje');
			return false;
		}
		// Produkt bol pridany
		if( typeof(result.result) != 'undefined' && result.result == '2' ){
			elem.parents('fieldset:first').find('table tr:last').after(result.content);
			return false;
		}
		// Produkt uz existuje
		if( typeof(result.result) != 'undefined' && result.result == '4' ){
			alert('Produkt sa už nachádza v tejto záložke');
			return false;
		}
	});
}

/**
 * Vytvori duplicitnu instanciu DOM elementu, ktory je surodencom interagovaneho, volajuceho elementu.
 *
 * @author Marek J. Kolcun
 *
 * @param me string           - interagovany, volajuci element
 * @param target string       - DOM nazov elementu, ktory chceme skopirovat
 * @param insertAfter boolean - rozhodne, ci sa novy element ma vlozit pred alebo za interagovany element. True = after, false = before
 *
 * @return mixed - JS objekt daneho elementu, ak element bol uspesne vytvoreny, inac null
 */
function copySiblingDomElement(data) {
	if (typeof data.me === 'undefined' || typeof data.target === 'undefined') {
		return false;
	}

	insertAfter = (typeof data.insertAfter === 'boolean') ? data.insertAfter : false;
	var $me = jQuery(data.me);
	var $target = jQuery(data.target);

	if (!$target.length) {
		if (typeof console !== 'undefined') console.log('copySiblingDomElement(): Element "' + data.target + '" neexistuje.');
		return null;
	}
	var time = new Date().getTime();
	var $clone = jQuery(data.target + ':first').clone().data('_id', time).hide();

	$clone.find('input, select, textarea').val('').prop('checked', false);

	if (!insertAfter)
		$me.before($clone);
	else
		$me.after($clone);

	var siblings = $me.siblings();
	jQuery(siblings).each(function(i) {
		if (jQuery(siblings[i]).data('_id') == time)
			jQuery(siblings[i]).show(250, function(){ jQuery(this).css({'overflow':'visible'}); }).removeData('_id');
	});

	if (typeof data.callback === 'function')
		data.callback();
	return $clone;
}

/**
 * Odstrani cielovy element
 *
 * @author Marek J. Kolcun
 *
 * @param target string     - DOM nazov cieloveho elementu, ktory bude odstraneny
 * @param callback function - Callback funkcia, ktora sa vykona bezprostredne po odstraneni cieloveho elementu.
 *
 * @return boolean - True, ak bol element odstraneny, inac false
 */
function removeDomElement(target, callback) {
	jQuery(target).hide(500, function() {
		jQuery(this).remove();
	});
	if (typeof callback === 'function') {
		setTimeout(function() {
			callback();
		}, 510);
	}
}

/**
 * Vsetkym suvisiacim selectom aktualizuje mozne option hodnoty tak, ze vybrana hodnota v jednom selecte sa nezobrazi v inom/zobrazi sa ako disabled.
 *
 * @author Marek J. Kolcun
 *
 * @param me string            - DOM nazov cieloveho elementu, ktory bude odstraneny
 * @param makeDisabled boolean - Ak je "true", hodnoty sa nezmazu, ale dostanu parameter disabled="disabled"
 *
 * @return void
 */
function refreshExclusiveSelect(me, makeDisabled) {
	makeDisabled = (typeof makeDisabled === 'boolean') ? makeDisabled : false;
	let list = jQuery(me);

	if (list.length < 2) {
		return;
	}

	let optionList = jQuery(list[0]).children('option');
	let selectedOptions = [];

	jQuery(list).each(function(i) {
		if (typeof jQuery(list[i]).val() !== 'undefined' && jQuery(list[i]).val() != null) {
			selectedOptions.push(jQuery(list[i]).val());
		}
	});

	jQuery(list).children().each(function(i) {
		jQuery(this).prop('disabled', false).show();

		for (let j in selectedOptions) {
			if (jQuery(this).val() == selectedOptions[j]) {
				if (makeDisabled) {
					jQuery(this).prop('disabled', true);
				} else {
					jQuery(this).hide();
				}
			}
		}
	});
}


/**
 * Otestuje hodnotu atributu (val()) cieloveho elementu, porovna ju so zelanou hodnotou a pripadne vykona odpovedajucu callback funkciu.
 * Ak je porovnavana hodnota typu "string", v pripade nerovnosti s compareTo premennou sa porovnaju dlzky tychto retazcov. Nasledne sa
 * zavola callback funkcia callbackLess alebo callbackMore. V pripade, ze su retazce rovnake, zavola sa funkcia callbackEqual.
 *
 * @author Marek J. Kolcun
 *
 * @param target string          - identifikator cieloveho DOM elementu (trieda, ID).
 * @param compareTo mixed        - hodnota, s ktorou sa ma porovnavat hodnota zadaneho DOM elementu.
 * @param callbackLess function  - funkcia, ktora sa ma vykonat, ak je hodnota v elemente mensia nez porovnavana hodnota.
 * @param callbackEqual function - funkcia, ktora sa ma vykonat, ak je hodnota v elemente rovnaka ako porovnavana hodnota.
 * @param callbackMore function  - funkcia, ktora sa ma vykonat, ak je hodnota v elemente vacsia nez porovnavana hodnota.
 *
 */
function testValueAndCallback(target, compareTo, callbackLess, callbackEqual, callbackMore) {
	callbackLess = (typeof callbackLess === 'function') ? callbackLess : function() {};
	callbackEqual = (typeof callbackEqual === 'function') ? callbackEqual : function() {};
	callbackMore = (typeof callbackMore === 'function') ? callbackMore : function() {};

	jQuery(target).animate({'outline': '3px solid #a55'}, 500, 'linear', function() {jQuery(this).css('outline', 'none');});
	var value = jQuery(target).val();

	if (typeof value === 'string' && value != compareTo) {
		value     = value.length;
		compareTo = compareTo.length;
	}

	if (value < compareTo)
		return callbackLess();
	if (value == compareTo)
		return callbackEqual();
	if (value > compareTo)
		return callbackMore();
}

//	funkcia pre Cetelem. Baf.
function js_toggle_cetelem_web_calculator( jso_this ) {
	console.log('klik');
	var jqo = jQuery('div.cetelem_web_calculator_main');
	if (jqo.length > 0) {
		if (jqo.html() == '') {
			jqo.startAjaxLoader();
			jQuery(jso_this).parents('div:first').find('[name="payment_method_id"]:first').prop('checked', true);
			jQuery.post('/administrator/components/com_shop/html/checkout.one_step.index.php?option=com_shop&ajax_call=1&ajax_func=get_cetelem_web_calculator', function ( ret ) {
				jqo.replaceWith(ret.cetelem_web_calculator);
			});
		} else {
			jqo.slideToggle(250);
		}
	} else {
		console.log('nefungujeme');
	}
	return false;
}

var defaultDiacriticsRemovalMap = [
		{'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
		{'base':'AA','letters':/[\uA732]/g},
		{'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
		{'base':'AO','letters':/[\uA734]/g},
		{'base':'AU','letters':/[\uA736]/g},
		{'base':'AV','letters':/[\uA738\uA73A]/g},
		{'base':'AY','letters':/[\uA73C]/g},
		{'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
		{'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
		{'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
		{'base':'DZ','letters':/[\u01F1\u01C4]/g},
		{'base':'Dz','letters':/[\u01F2\u01C5]/g},
		{'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
		{'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
		{'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
		{'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
		{'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
		{'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
		{'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
		{'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
		{'base':'LJ','letters':/[\u01C7]/g},
		{'base':'Lj','letters':/[\u01C8]/g},
		{'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
		{'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
		{'base':'NJ','letters':/[\u01CA]/g},
		{'base':'Nj','letters':/[\u01CB]/g},
		{'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
		{'base':'OI','letters':/[\u01A2]/g},
		{'base':'OO','letters':/[\uA74E]/g},
		{'base':'OU','letters':/[\u0222]/g},
		{'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
		{'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
		{'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
		{'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
		{'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
		{'base':'TZ','letters':/[\uA728]/g},
		{'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
		{'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
		{'base':'VY','letters':/[\uA760]/g},
		{'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
		{'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
		{'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
		{'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
		{'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
		{'base':'aa','letters':/[\uA733]/g},
		{'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
		{'base':'ao','letters':/[\uA735]/g},
		{'base':'au','letters':/[\uA737]/g},
		{'base':'av','letters':/[\uA739\uA73B]/g},
		{'base':'ay','letters':/[\uA73D]/g},
		{'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
		{'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
		{'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
		{'base':'dz','letters':/[\u01F3\u01C6]/g},
		{'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
		{'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
		{'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
		{'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
		{'base':'hv','letters':/[\u0195]/g},
		{'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
		{'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
		{'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
		{'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
		{'base':'lj','letters':/[\u01C9]/g},
		{'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
		{'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
		{'base':'nj','letters':/[\u01CC]/g},
		{'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
		{'base':'oi','letters':/[\u01A3]/g},
		{'base':'ou','letters':/[\u0223]/g},
		{'base':'oo','letters':/[\uA74F]/g},
		{'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
		{'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
		{'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
		{'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
		{'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
		{'base':'tz','letters':/[\uA729]/g},
		{'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
		{'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
		{'base':'vy','letters':/[\uA761]/g},
		{'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
		{'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
		{'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
		{'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
	];

function js_remove_accents( str ) {

    changes = defaultDiacriticsRemovalMap;

    for(var i=0; i<changes.length; i++) {
        str = str.replace(changes[i].letters, changes[i].base);
    }
    return str;
}

function js_format_Money( number, places, symbol, thousand, decimal) {

	number = number || 0;
	places = !isNaN(places = Math.abs(places)) ? places : 2;
	symbol = symbol !== undefined ? symbol : " $";
	thousand = thousand || ".";
	decimal = decimal || ",";
	var negative = number < 0 ? "-" : "",
	    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
	    j = (j = i.length) > 3 ? j % 3 : 0;
	return negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "") + ' ' + symbol;
}

function js_format_bytes(bytes, decimals){
   if(bytes == 0) return '0 Bytes';
   var k = 1024,
       dm = decimals || 2,
       sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
       i = Math.floor(Math.log(bytes) / Math.log(k));
   return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

/**
 * Vrati microtime pre debug
 * @param {boolean} getAsFloat - Ak true bude hodnota vratena ako desatinne cislo
 */
function microtime(getAsFloat){
	var s;
	var now;
	if (typeof performance !== 'undefined' && performance.now) {

		now = (performance.now() + performance.timing.navigationStart) / 1e3;

		if (getAsFloat) { return now; }

		s = now | 0;

		return (Math.round((now - s) * 1e6) / 1e6) + ' ' + s;
	} else {

		now = (Date.now ? Date.now() : new Date().getTime()) / 1e3;
		if (getAsFloat) { return now; }

		s = now | 0;

		return (Math.round((now - s) * 1e3) / 1e3) + ' ' + s;
	}
}

var js_image_import_interval = 0;
var js_image_import_loading = 0;
function js_image_import_info(){

	if (js_image_import_loading == 1) return;

	var wrap = jQuery('.import_data_upload_container_wrapper');
	var box = wrap.find('.img_import_prog');

	if (box.length == 0){

		wrap.append('<div class="img_import_prog"></div>');
		box = jQuery('.img_import_prog');
	}

	js_image_import_loading = 1;
	var html = '';
	var options = {};
	options.function = 'check_image_import';
	jQuery.post('/includes/frontend_ajax.php', options, function(res){

		var result = JSON.parse(res);
		if (result.success == 1 && result.content != ''){

			box.html(result.content);

			// Maly pocet obrazkov dame po 1 sekunde
			var interval = 5000;
			if (result.total > 0 && result.total < 100){ interval = 1000; }
			else if (result.total < 500){ interval = 2000; }
			else if (result.total < 1000){ interval = 3000; }
			else if (result.total < 3000){ interval = 4000; }
			else if (result.total < 5000){ interval = 5000; }

			// Import pripraveny
			if (result.status == 1){

				var now = new Date();
				var eta_ms = new Date(now.getFullYear(), now.getMonth(), now.getDate(), result.sheduled[0], result.sheduled[1]).getTime() - Date.now();

				var timeout = setTimeout(function(){

					if (js_image_import_interval == 0){

						js_image_import_interval = setInterval(function(){

							js_image_import_info();
						}, interval);
					}
				}, eta_ms);
			}
			// Import bezi
			else if(result.status == 2){

				if (js_image_import_interval == 0){

					js_image_import_interval = setInterval(function(){

						js_image_import_info();
					}, interval);
				}
			}
			// Import zbehol
			else if (result.status == 3){

				if (js_image_import_interval > 0) clearInterval(js_image_import_interval);
			}
			else {

				box.remove();
				if (js_image_import_interval > 0) clearInterval(js_image_import_interval);
			}
		} else {

			box.remove();
			clearInterval(js_image_import_interval);
		}
		js_image_import_loading = 0;
	});
}

function js_image_import_cancel(){

	if ( confirm('Zruší sa import všetkých nespracovaných obrázkov. Pokračovať?') ){

		var options = {};
		options.function = 'cancel_image_import';
		jQuery.post('/includes/frontend_ajax.php', options, function(res){

			var result = JSON.parse(res);
			if (result.success == 1){

				js_image_import_info_close();
			}
		});
	}
}

function js_image_import_info_close(){

	var box = jQuery('.img_import_prog');
	box.remove();
	var options = {};
	if (js_image_import_interval > 0) clearInterval(js_image_import_interval);
	js_image_import_loading = 0;
	options.function = 'close_image_import';
	jQuery.post('/includes/frontend_ajax.php', options, function(res){});
}

function validateEmail(email){
	var re = new RegExp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,63}$');
	//var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    return re.test(email);
}

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

/**
 * Nahrada zastaralej/pomalej kiniznice overlib_mini lepsim systemom
 * @param {object} elem Html element
 * @param {object} data Vysvetlenie v komentoch nizsie
 */
function cs_overlib(elem, data){

	var el = jQuery(elem);
	var pos = 'top';
	var plugs = [];
	var disableTooltipster = data.disableTooltipster || false;

	if (el.hasClass('tooltipstered')) return;

	if (typeof data.content === 'undefined') return;

	if (typeof data.position !== 'undefined'){

		if (data.position == 0) pos = 'top';
		if (data.position == 1) pos = 'right';
		if (data.position == 2) pos = 'bottom';
		if (data.position == 3) pos = 'left';
	}

	if (typeof data.follow !== 'undefined' && data.follow == 1){

		//plugs.push('follower');
	}

	var html = decodeURIComponent(atob(data.content));

	var instances = jQuery.tooltipster.instances();
	jQuery.each(instances, function(i, instance){
	    instance.close();
	});

	var _show = function(html){
		if ( disableTooltipster ) {
			el.removeAttr('onmouseover');
			el.find('.preview_product_image').html(html);
		} else {
			el.tooltipster({
				plugins: plugs,
				theme: ['tooltipster-base', 'tooltipster-overlib'],
				content: html+'<div class="cs_overlib_cleaner"></div>',
				contentAsHTML: true,
				trigger: 'custom',
				triggerOpen: {
					click: true,  // For mouse
					tap: true    // For touch device
				},
				triggerClose: {
					click: true,  // For mouse
					tap: true    // For touch device
				},
				delay: (typeof data.delay !== 'undefined' ? data.delay : 0),
				animationDuration: (typeof data.animationDuration !== 'undefined' ? data.animationDuration : 0),
				interactive: (typeof data.interactive !== 'undefined'),
				side: pos,
				functionInit: function(){

				}
			});

			el.tooltipster({
				plugins: plugs,
				theme: ['tooltipster-base', 'tooltipster-overlib'],
				content: html+'<div class="cs_overlib_cleaner"></div>',
				contentAsHTML: true,
				trigger: (typeof data.trigger !== 'undefined' ? data.trigger : 'hover'),
				delay: (typeof data.delay !== 'undefined' ? data.delay : 0),
				animationDuration: (typeof data.animationDuration !== 'undefined' ? data.animationDuration : 0),
				interactive: (typeof data.interactive !== 'undefined'),
				side: pos,
				functionInit: function(){

				}
			});

			el.tooltipster('open');
		}
	};

	// Preload obrazkov kvoli dynamickemu setnutiu rozmerov
	var _html = jQuery(html);
	var imgs = (_html.is('img') ? [_html] : _html.find('img'));
	if (imgs.length){

		var sources = [];
		for(var i=0; i<imgs.length; i++){
			sources[i] = imgs[0].attr('src');
		}
		cs_preload_images(sources, function(images){

			for(var i=0; i<imgs.length; i++){

				var ratio = 1;
				var rx = 0;
				var ry = 0;
				var width = images[i].width;
				var height = images[i].height;
				var percentage = 0;

				// Aplikujeme maxDim ak je nastavene
				if (typeof data.maxDim !== 'undefined' && data.maxDim > 0 && (data.maxDim < width || data.maxDim < height)){

					if (width > height) {
				        ratio = height/width;
				        rx = (width-data.maxDim) * (percentage/100);
				        ry = (height-data.maxDim * ratio) * (percentage/100);
				        width = rx+data.maxDim;
				        height = ry+data.maxDim * ratio;
				    } else {
				        ratio = width/height;
				        rx = (width-data.maxDim * ratio) * (percentage/100);
				        ry = (height-data.maxDim) * (percentage/100);
				        width = rx+data.maxDim * ratio;
				        height = ry+data.maxDim;
				    }
				}

				imgs[0].attr('width', width).attr('height', height);
			}
			html = _html[0].outerHTML;
			_show(html);
		});
	} else {

		_show(html);
	}
}

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

function js_related_products_show_button(elem){
	jQuery(elem).closest('.set_cont').toggleClass('open');
}
function js_related_products_change_tab(elem){
	jQuery(elem).closest('.related_products_set').find('.set_cont.open').removeClass('open');
}

function cs_preload_images(sources, callback){

	if (jQuery.isEmptyObject(sources)){ callback([]); return; }

	var completed = 0;
	var errors = 0;
	var imgs = [];

	var complete = function(){
		if ((completed + errors) == sources.length) callback(imgs);
	};

	if (sources.length){

		// Load obrazkov
		jQuery.each(sources, function(c,s){

			imgs[c] = new Image();

			imgs[c].onerror = imgs[c].onabort = function(){

				errors++;
				complete();
			};

			imgs[c].onload = function(){

				completed++;
				complete();
			};

			imgs[c].src = s;
		});
	} else {

		complete();
	}
}

/**
 * Zasle error na server a vypise ho do konzoli
 * @param message
 * @param {boolean} [local] Echovat message iba do konzoli
 */
function cserror(message,local){

	try {
		throw new Error(message);
	} catch (e){
		console.error(e.message);
		if (typeof local === 'undefined' || !local){
			var _e = new ErrorEvent('error', {message:e.message,error:e});
            window.dispatchEvent(_e);
		}
	}
}

// Pomocna funkcia pre debug kodu, iba pre csuserov!!! NEDAVAT ONLINE !!!
function csstack(func, params){

	var _params = '';
	if (typeof params === 'undefined') _params = '';
	else if (typeof params === 'object'){
		try{
			_params = JSON.stringify(params);
		} catch (err){
			_params = 'ERROR: '+err;
		}
		_params = _params.substring(1, _params.length-1);
	}

	var callstack = '';
	var s = new Error().stack;

	// Pre browsre nepodporujuce Error constructor
	if (s == null || typeof s == 'undefined') {
		console.log(func+'( '+_params+' )');
		return;
	}
	var lines = s.split('\n');
	lines.shift();
	lines.shift();
	var rows = (lines.length > 2 ? 2 : 1);
	for (var i=0; i < rows; i++){

		func = lines[i].match(/^\s*?at\s(.+)\s+?\(.*[?|/](.*)\)/);

		if (func !== null){
			if (i == 0){
				if (typeof func[1] != 'undefined') {
					var f = func[1].replace('Object.', '') + '('+_params+')';
					if (f.length < 80){
						for(var k=f.length; k<80; k++){
							f += ' ';
						}
					}
					callstack += f;
				}
			}
		}
	}

	console.log('%s Stacktrace: %O', callstack, lines);
}

const messenger = {
	body: {},
	options: {
		delay: 8000
	},
	init: function(){
		messenger.body = jQuery('body');
		messenger.activate();
	},
	check: function(m){

		if (typeof m != 'string') return false;
		var res = m.indexOf('<div class="msg_wrap">');
		if(res != -1) messenger.activate(m);
	},
	activate: function(m){

		if (typeof m === 'string') messenger.body.append(m);
		var msg_wrap = messenger.body.find('.msg_wrap');

		if (msg_wrap.length){

			var time = 8000;
			var autohide = true;
			msg_wrap.find('.msg_box').each(function(){

				var msg = jQuery('<div>').addClass('msg_wrap');
				var box = jQuery(this);
				time = (box.data('time') ? parseInt(box.data('time')) : messenger.options.delay);
				autohide = box.data('autohide') != 0;
				msg.html(box[0].outerHTML);
				messenger.body.append(msg);

				messenger.center(msg);
				messenger.body.addClass('messenger_opened');

				if (autohide){

					window.setTimeout(function(){

						msg.fadeOut(300, function(){ jQuery(this).remove(); messenger.body.removeClass('messenger_opened'); });
					}, time);
				}

				msg.on('click', function(){ jQuery(this).remove(); messenger.body.removeClass('messenger_opened'); });
			});

			msg_wrap.remove();
		}
	},
	center: function(e){

		if (e.length > 0){

			var ml = (window.screen.width - e.width()) / 2;
			var mt = (window.screen.availHeight / 2) - (e.height() / 2);
			e.css({'left':ml+'px', 'top':mt+'px'});
		}
	}
};

window.addEventListener('DOMContentLoaded', function() {
	messenger.init();

	// ak uiautocomplete nie je definovany on ready, tak ho definujeme
	if ( typeof jQuery.fn.uiautocomplete === 'undefined' && jQuery.fn.autocomplete !== 'undefined' ) {
		jQuery.fn.uiautocomplete = jQuery.fn.autocomplete;
	}
});


/* ========================================
 FILE: /includes/js/system/system_functions.js
 ==================== */

if (typeof Object.assign != 'function') {
	// Must be writable: true, enumerable: false, configurable: true
	Object.defineProperty(Object, "assign", {
		value: function assign(target, varArgs) { // .length of function is 2
			'use strict';
			if (target == null) { // TypeError if undefined or null
				throw new TypeError('Cannot convert undefined or null to object');
			}

			var to = Object(target);

			for (var index = 1; index < arguments.length; index++) {
				var nextSource = arguments[index];

				if (nextSource != null) { // Skip over if undefined or null
					for (var nextKey in nextSource) {
						// Avoid bugs when hasOwnProperty is shadowed
						if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
							to[nextKey] = nextSource[nextKey];
						}
					}
				}
			}
			return to;
		},
		writable: true,
		configurable: true
	});
}


//JB pre budúcu funckionalitu sa pridáva keylistener aby sme mali nahodené aký key sa stlačil
//pridaná nová funkcionalita

window.addEventListener('DOMContentLoaded', function () {

	jQuery(document).keydown(function(event) {
		pressedKeyValue = event.which;
	}).keyup(function(event) {

		//keypress nezachytí ESCAPE takže aj tu riešime stlačenie ESC
		processKeyUp(event);
		delete pressedKeyValue;}
	);

	if(typeof js_CS_Config_display_comment_ajax_slick !== 'undefined' && js_CS_Config_display_comment_ajax_slick) {
		js_comment_slide();
	}

	if(typeof js_CS_Config_shop_coupon_auto_use_tooltip !== 'undefined' && js_CS_Config_shop_coupon_auto_use_tooltip) {
		bindAutoCouponTooltip();
	}

	if(typeof js_CS_Config_product_active_image_slick !== 'undefined' && js_CS_Config_product_active_image_slick.active) {
		bindProductActiveImageSlick();
	}

	if (typeof js_Config_product_store_reservation !== 'undefined' && js_Config_product_store_reservation) {
		toggleProductReservationButton();
	}
});

function processKeyUp(event) {
	if (typeof jsOpenedOrderList !== 'undefined' && jsOpenedOrderList.length && event.key === 'Escape') {
		var lastOrderId = jsOpenedOrderList.pop();
		var orderCloseButtonElement = jQuery('tr.row_order_id_' + lastOrderId).find('a.icon_orders_detail_close:first');
		_order.detail.cancel(orderCloseButtonElement, lastOrderId);
	}
}

function escapeHtml(text) {
	if ( typeof( text ) == 'string' )
		return text
		.replace(/&/g, "&amp;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;")
		.replace(/"/g, "&quot;")
		.replace(/'/g, "&#039;");
}

//JB pridaná možnosť pri zmene variantu meniť aj ďalšie dáta (tie čo by mali byť vrámci variantu vykreslené na frontende)
function jsChangeVariantAddon(elem) {

	var $elem = jQuery(elem);

	var $productWrapper = null;

	if ($elem.closest('.cs_product_item').length != 0) {
		$productWrapper = $elem.closest('.cs_product_item');
	} else if ($elem.closest('.flypage1').length != 0) {
		$productWrapper = $elem.closest('.flypage1');
	} else {
		//nemáme wrap -> return
		return;
	}

	productChangeQuantity: if (typeof js_Config_vm_forced_quantity_multiplier != 'undefined' && typeof js_Config_vm_forced_quantity_multiplier.allowVariantQuantityMultiplier != 'undefined') {

		//TODO ak má jeden variant nastavené tieto hodnoty -> musia to mať nastavené všetky varianty
		// -> riešenie vytvoriť nejakú js premennú v ktorej sa bude uskladňovať pôvodná hodnota
		// -> druhé, lepšie riešenie, variantu dať hodnoty hlavného produktu -> tak sa nič nepokazía a vždy bude situácia fungovať


		//je potrebné si rozparsovať vybratý variant a len na základe toho zistiť, či vôbec budeme riešiť či sa niečo bude upravovať
		var variantData = jsParseVariant($elem.val());

		var mQ = variantData.mQ;
		var fQ = variantData.fQ;
		var MQ = variantData.MQ;
//ak nie je nastavené ani fQ ani mQ ani MQ .. nemáme čo riešiť
		if ((typeof mQ == 'undefined' || mQ.length == 0) && (typeof fQ == 'undefined' || fQ.length == 0) && (typeof MQ == 'undefined' || MQ.length == 0)) {
			//break productChangeQuantity;
		}

		if ((typeof mQ == 'undefined') && (typeof fQ == 'undefined') && (typeof MQ == 'undefined')) {
			//break productChangeQuantity;
		}

		//v tomto prípade riešime input a tlačidlá +/-ps

		var $quantityField = $productWrapper.find('input[name="quantity"]');

		var $addButton = $productWrapper.find('a.count_up');
		var $subButton = $productWrapper.find('a.count_down');

		//v tomto pripade meníme pre input výberu množstva nejakého produktu
		if (typeof js_Config_vm_forced_quantity_multiplier.minimumQuantity != 'undefined') {
			console.log('realMinimumQuantity');
			var realMinimumQuantity = (mQ > 0 ? mQ : 1 );
			//$quantityField.data('quantity', realMinimumQuantity);
		}

		if (typeof js_Config_vm_forced_quantity_multiplier.forcedQuantity != 'undefined') {
			var realForcedQuantity = (fQ > 0 ? fQ : 1 );
			console.log('realForcedQuantity');
			$addButton.data('quantity', parseFloat(realForcedQuantity));
			$subButton.data('quantity', parseFloat(realForcedQuantity));
			$quantityField.data('forced_quantity', parseFloat(realForcedQuantity));
		}

		if (typeof js_Config_vm_forced_quantity_multiplier.maximumQuantity != 'undefined') {
			var realMaximumQuantity = (MQ > 0 ? MQ : 1 );
			console.log('realMaximumQuantity');
			$quantityField.data('maximum_quantity', parseFloat(realMaximumQuantity));
		}

		$quantityField.trigger('blur');
	}

	if ( typeof js_Config_custom_variant_fields_display !== 'undefined' && typeof js_Config_custom_variant_fields !== 'undefined' ) {
		var attributeData = jsParseVariant($elem.val());
		js_Config_custom_variant_fields.forEach( function(entry) {
			if ( js_Config_custom_variant_fields_display.includes(entry.name) ) {
				var elementDiv = jQuery('.flypage_variant_' + entry.name); //Tu sa vypisuje custom field variantu
				var mainCustomAttr = jQuery('.flypage_' + entry.name); //Tu sa vypisuje custom field hlavneho produktu
				if ( typeof attributeData[entry.name] !== 'undefined' ) {
					if ( mainCustomAttr.length > 0 ) {
						mainCustomAttr.hide();
					}
					elementDiv.html('<span class="custom_variant_' + entry.name + '_label">' + entry.title + ':</span><span class="custom_variant_' + entry.name + '_value">' + attributeData[entry.name] + '</span>');
				} else {
					if ( mainCustomAttr.length > 0 ) {
						mainCustomAttr.show();
					}
					elementDiv.html('');
				}
			}
		});
	}

	if ( typeof js_Config_shipping_day_of_delivery_show_in_product_details !== 'undefined' && js_Config_shipping_day_of_delivery_show_in_product_details ) {
		var elementValue = $elem.val();
		var tooltip = jQuery('.delivery-day-tooltip');
		if ( typeof tooltip !== 'undefined' && tooltip.find('[data-variant="' + elementValue + '"]').length > 0 ) {
			//These shippings already have been loaded so we just need to hide the current one and diplay the selected one
			tooltip.hide();
			tooltip.find('[data-variant="' + elementValue + '"]').parent('.delivery-day-tooltip').show();
		} else {
			//Load variant deliveries with ajax
			var options = {
				function: 'getProductVariantShippings',
				product_id: js_product_id,
				variant: elementValue,
			};
			jQuery.post('/includes/frontend_ajax.php', options, function (res) {
				if ( res != '' ) {
					//insert after content
					var content = JSON.parse(res);
					if ( typeof content.tooltip != 'undefined' && content.tooltip != '' ) {
						var variantCode = jQuery(content.tooltip).find('.tooltip-content').data().variant;
						var pageTooltip = jQuery('.delivery-day-tooltip');
						if ( pageTooltip.length > 0 && pageTooltip.find('[data-variant="' + variantCode + '"]').length == 0 ) {
							pageTooltip.hide();
							jQuery(content.tooltip).insertAfter('.delivery-day-tooltip:last');
						} else if ( pageTooltip.length == 0 ) {
							jQuery(content.tooltip).appendTo('.flypage-shipping');
						}
					}
				}
			});
		}
	}
}

//táto funckia zabezpečuje po kliknutí na span, aby sa vedľa neho otvoril input, ktorý následne
function jsOpenInputFieldForEditing(elem) {
	if (typeof pressedKeyValue !== 'undefined' && pressedKeyValue == 17 ) {
		elem = jQuery(elem);
		var wrapper = elem.closest('div.cs_field_editor');

		if (wrapper.find('input').length < 1) {
			elem.hide();

			var value       = ((elem.data('value') == '- - -' ) ? '' : elem.data('value'));
			var placeHolder = ((elem.data('value') == '- - -' ) ? '- - -' : '');
			var inputToAppend = jQuery('<input type="text" class="fieldname" placeholder="' + placeHolder + '" onfocus="jsCreateEventlistenerOnFocus(this)"  value="' + value + '"data-default="' + value + '" maxlength="32"/>');
			wrapper.append(inputToAppend).find('input').focus();
		}

	}
}

function jsCreateEventlistenerOnFocus(elem) {
	elem = jQuery(elem);
	var wrapper = elem.closest('div.cs_field_editor');
	//bindujeme event on change a potom následne event keypress, oba navzájom
	elem.unbind('keyup').bind('keyup', function(e) {
		jsCheckIfInputChanged(elem);
		if (e.key === "Escape"){
			wrapper.find('div.cs_field_editor_value').show();
			elem.remove();
		}

	}).unbind('keypress').bind('keypress', function (e) {
		elem.removeClass('error');
		if (e.which == 13) {
			jsEditProductParameter(elem);
		}
	});
}

function jsOpenTrustPayPopup(elem) {
	elem = jQuery(elem);
	var TrustPayFrames = jQuery('[id^=TrustPayFrame]');
	if ( TrustPayFrames.length > 1 ) {
		TrustPayFrames.attr('id', 'TrustPayFrameInactive');
		var activeTrustPayFrame = elem.siblings('[id^=TrustPayFrame]');
		activeTrustPayFrame.attr('id', 'TrustPayFrame');
		activeTrustPayFrame.css('position', 'fixed');
		activeTrustPayFrame.css('left', 0);
		activeTrustPayFrame.css('right', 0);
		activeTrustPayFrame.css('top', 0);
		activeTrustPayFrame.css('bottom', 0);
		activeTrustPayFrame.css('width', 0);
		activeTrustPayFrame.css('height', 0);
		activeTrustPayFrame.css('border', 'none');
		activeTrustPayFrame.css('opacity', 0);
		activeTrustPayFrame.css('transition', 'opacity .5s ease-in-out');
		activeTrustPayFrame.css('zIndex', '99999');
		if ( activeTrustPayFrame.css('display') == 'none' ) {
			activeTrustPayFrame.show();
		}

		if (typeof openPopup == 'function' ) {
			openPopup();
		}
	} else {
		if ( typeof openPopup == 'function' ) {
			openPopup();
		}
	}
}

function jsCheckIfInputChanged(elem) {
	elem = jQuery(elem);
	if (elem.data('default') != elem.val()) {
		elem.addClass('changed');
	} else {
		elem.removeClass('changed');
	}
}

function jsEditProductParameter(elem) {
	//pozrieť sa ktoré dáta máme nastaviť, potom ich nastaviť pre daný produkt
	elem = jQuery(elem);
	var wrapper = elem.closest('div.cs_field_editor');

	wrapper.addClass('ajaxLoader');
	valueElement = wrapper.find('div.cs_field_editor_value');

	var jsonData = {
		'productId' : valueElement.data('id'),
		'value' : elem.val(),
	};

	//momentálne len pre produkty.. neriešime zvyšné úpravy

	new AjaxRequest(jsonData)
		.setMethod('POST')
		.setController(valueElement.data('controller'))
		.setAction(valueElement.data('action'))
		.setAsync(false) //asi nerobi nic
		.onSuccess(function (response) {
			wrapper.removeClass('ajaxLoader');

			valueElement.data('value',elem.val()).html(elem.val()).show();
			elem.remove();
		})
		.onError(function (response) {
			wrapper.removeClass('ajaxLoader');
			elem.addClass('error');
		})
		.send();
}



jQuery.fn.changeElementType = function(newType) {
    var attrs = {};
    var newelements = [];
    jQuery.each(this, function () {
    	var elem = this;
    	jQuery.each(elem.attributes, function(idx, attr) {
			attrs[attr.nodeName] = attr.nodeValue;
		});
		var newelement = jQuery("<" + newType + "/>", attrs).append(jQuery(elem).contents());
		jQuery(elem).replaceWith(newelement);
		newelements.push(newelement.get(0));
    });
    return newelements;
};

jQuery.fn.getCursorPosition = function() {
    var pos = 0;
    var el = jQuery(this).get(0);
    // IE Support
    if (document.selection) {
        el.trigger('focus');
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    // Firefox support
    else if (el.selectionStart || el.selectionStart == '0') {
	    pos = el.selectionStart;
    }

    return pos;
};

jQuery.fn.startAjaxLoader = function ( loader_image_filename, svg, destination ) {
	svg = typeof svg !== 'undefined';
	destination = typeof destination !== 'undefined' ? destination : false;

	var addToCartButton = this.find('input[type="submit"].prod_add_to_cart');
	var autoloaderHtml;

	if (svg) {
		autoloaderHtml = '<span class="small_graph_ajax_loader full-page-loader"></span>';
	} else {
		autoloaderHtml = '<span class="small_graph_ajax_loader"><img src="' + js_global_live_site + '/images/' + (loader_image_filename != null ? loader_image_filename : 'ajax-loader-05.gif') + '" alt="..." /></span>';
	}

	if ( addToCartButton.length ) {
		addToCartButton.prop('disabled', true).after(autoloaderHtml);
		//console.log(this, autoloaderHtml);
	} else if (this.data('ajax-loader-pre-html-content') == null) {
		if (svg && destination) {
			jQuery(destination).append(autoloaderHtml);
		} else {
			this.data('ajax-loader-pre-html-content', this.html()).html(autoloaderHtml);
		}
	}
	return this;
};

jQuery.fn.stopAjaxLoader = function () {
	var addToCartButton = this.find('input[type="submit"].prod_add_to_cart');

	if ( addToCartButton.length ) {
		addToCartButton.prop('disabled', false);
	} else if (this.data('ajax-loader-pre-html-content') != null) {
		this.html(this.data('ajax-loader-pre-html-content')).removeData('ajax-loader-pre-html-content');
	}

	this.find('.small_graph_ajax_loader').remove();
	return this;
};

jQuery.fn.inputAllowNumericOnly = function () {
	return this.each(function () {
		var element    = jQuery(this);
		var regexKey   = /^[A-Za-z ]/;
		var regexPaste = /^\d*$/;
		//var regexPaste = /[a-zA-Z]+/g;
		jQuery(this).on({
			paste  : function (e) {
				//Kontrola ci paste obsahuje znak, ak ano, nepastne
				if (e.originalEvent.clipboardData.getData('text/plain')) {
					var clipBoardData = e.originalEvent.clipboardData.getData('text/plain');

					if (!clipBoardData.match(regexPaste)) {
						e.preventDefault();
						element.tooltipster({
							theme    : 'tooltipster-noir',
							animation: 'fade',
							side     : 'left',
							delay    : 10,
							timer    : 1600
						})
							.tooltipster('content', js_lang_must_be_number)
							.tooltipster('open');
					}
				}
			},
			keydown: function (e) {
				var key = e.which || e.keyCode;
				if ((key >= 35 && key <= 40)) {
					return true;
				}
				if (e.key.match(regexKey) && e.key.length == 1 && e.ctrlKey === false) {
					element.tooltipster({
						theme    : 'tooltipster-noir',
						animation: 'fade',
						side     : 'left',
						delay    : 10,
						timer    : 1600
					})
						.tooltipster('content', js_lang_must_be_number)
						.tooltipster('open');
				} else if (element.val().length == 0 && e.key == 0) {
					e.preventDefault();
					element.tooltipster({
						theme    : 'tooltipster-noir',
						animation: 'fade',
						side     : 'left',
						delay    : 10,
						timer    : 1600
					})
						.tooltipster('content', js_lang_must_be_number)
						.tooltipster('open');
				}

				//console.log(key, e.key);
				if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
					// numbers
					e.key >= 0 && e.key <= 9 ||
					// allow: Ctrl+A
					(e.keyCode == 65 && e.ctrlKey === true) ||
					// allow: Ctrl+C
					(key == 67 && e.ctrlKey === true) ||
					// Allow: Ctrl+V
					(key == 86 && e.ctrlKey === true) ||
					// Allow: Ctrl+X
					(key == 88 && e.ctrlKey === true) ||
					// allow: home, end, left, right
					(key >= 35 && key <= 39) ||
					// Backspace and Tab and Enter
					key == 8 || key == 9 || key == 13 ||
					// Del and Ins
					key == 46 || key == 45) {
					return true;
				}
				e.preventDefault();

				return false;
			}
		});
	});
};

jQuery.fn.ForceNumericOnly = function () {
	return this.each(function () {
			jQuery(this).on('keydown', function (e) {
				var key = e.charCode || e.keyCode || 0;
				return (
					key == 8 ||
					key == 9 ||
					key == 13 ||
					key == 46 ||
					key == 110 ||
					key == 190 ||
					(key >= 35 && key <= 40) ||
					(key >= 48 && key <= 57) ||
					(key >= 96 && key <= 105));
			});
	});
};

/**
 * @desc Replace all occurrences of match except first
 * @author Martin Hucko (Hucci)
 *
 * @param {RegExp|String} searchVal
 * @param {String|Function} newVal
 * @return {String}
 */
String.prototype.cs_replaceNotFirst = function(searchVal, newVal) {
    return this.replace(searchVal, function(match, offset, all) {
        return (all.indexOf(match) === offset) ? match
        	: (typeof newVal === 'function') ? newVal(match, offset, all) : newVal;
    });
};

/**
 * @desc create slug from string
 * @author Martin Hucko (Hucci)
 *
 * @return {String}
 */
String.prototype.cs_slugify = function() {
	return this.toLowerCase()
		.latinize()						// Replace latin characters
		.replace(/\s+/g, '-')           // Replace spaces with -
		.replace(/[^\w\-]+/g, '')       // Remove all non-word chars
		.replace(/\-\-+/g, '-')         // Replace multiple - with single -
		.replace(/^-+/, '')             // Trim - from start of text
		.replace(/-+$/, '');            // Trim - from end of text
};

Date.prototype.getWeek = function() {
    var determinedate = new Date();
    determinedate.setFullYear(this.getFullYear(), this.getMonth(), this.getDate());
    var D = determinedate.getDay();
    if(D == 0) D = 7;
    determinedate.setDate(determinedate.getDate() + (4 - D));
    var YN = determinedate.getFullYear();
    var ZBDoCY = Math.floor((determinedate.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
    var WN = 1 + Math.floor(ZBDoCY / 7);
    return WN;
};

var Latinise={};Latinise.latin_map={"Á":"A","Ă":"A","Ắ":"A","Ặ":"A","Ằ":"A","Ẳ":"A","Ẵ":"A","Ǎ":"A","Â":"A","Ấ":"A","Ậ":"A","Ầ":"A","Ẩ":"A","Ẫ":"A","Ä":"A","Ǟ":"A","Ȧ":"A","Ǡ":"A","Ạ":"A","Ȁ":"A","À":"A","Ả":"A","Ȃ":"A","Ā":"A","Ą":"A","Å":"A","Ǻ":"A","Ḁ":"A","Ⱥ":"A","Ã":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ḃ":"B","Ḅ":"B","Ɓ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ć":"C","Č":"C","Ç":"C","Ḉ":"C","Ĉ":"C","Ċ":"C","Ƈ":"C","Ȼ":"C","Ď":"D","Ḑ":"D","Ḓ":"D","Ḋ":"D","Ḍ":"D","Ɗ":"D","Ḏ":"D","ǲ":"D","ǅ":"D","Đ":"D","Ƌ":"D","Ǳ":"DZ","Ǆ":"DZ","É":"E","Ĕ":"E","Ě":"E","Ȩ":"E","Ḝ":"E","Ê":"E","Ế":"E","Ệ":"E","Ề":"E","Ể":"E","Ễ":"E","Ḙ":"E","Ë":"E","Ė":"E","Ẹ":"E","Ȅ":"E","È":"E","Ẻ":"E","Ȇ":"E","Ē":"E","Ḗ":"E","Ḕ":"E","Ę":"E","Ɇ":"E","Ẽ":"E","Ḛ":"E","Ꝫ":"ET","Ḟ":"F","Ƒ":"F","Ǵ":"G","Ğ":"G","Ǧ":"G","Ģ":"G","Ĝ":"G","Ġ":"G","Ɠ":"G","Ḡ":"G","Ǥ":"G","Ḫ":"H","Ȟ":"H","Ḩ":"H","Ĥ":"H","Ⱨ":"H","Ḧ":"H","Ḣ":"H","Ḥ":"H","Ħ":"H","Í":"I","Ĭ":"I","Ǐ":"I","Î":"I","Ï":"I","Ḯ":"I","İ":"I","Ị":"I","Ȉ":"I","Ì":"I","Ỉ":"I","Ȋ":"I","Ī":"I","Į":"I","Ɨ":"I","Ĩ":"I","Ḭ":"I","Ꝺ":"D","Ꝼ":"F","Ᵹ":"G","Ꞃ":"R","Ꞅ":"S","Ꞇ":"T","Ꝭ":"IS","Ĵ":"J","Ɉ":"J","Ḱ":"K","Ǩ":"K","Ķ":"K","Ⱪ":"K","Ꝃ":"K","Ḳ":"K","Ƙ":"K","Ḵ":"K","Ꝁ":"K","Ꝅ":"K","Ĺ":"L","Ƚ":"L","Ľ":"L","Ļ":"L","Ḽ":"L","Ḷ":"L","Ḹ":"L","Ⱡ":"L","Ꝉ":"L","Ḻ":"L","Ŀ":"L","Ɫ":"L","ǈ":"L","Ł":"L","Ǉ":"LJ","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ń":"N","Ň":"N","Ņ":"N","Ṋ":"N","Ṅ":"N","Ṇ":"N","Ǹ":"N","Ɲ":"N","Ṉ":"N","Ƞ":"N","ǋ":"N","Ñ":"N","Ǌ":"NJ","Ó":"O","Ŏ":"O","Ǒ":"O","Ô":"O","Ố":"O","Ộ":"O","Ồ":"O","Ổ":"O","Ỗ":"O","Ö":"O","Ȫ":"O","Ȯ":"O","Ȱ":"O","Ọ":"O","Ő":"O","Ȍ":"O","Ò":"O","Ỏ":"O","Ơ":"O","Ớ":"O","Ợ":"O","Ờ":"O","Ở":"O","Ỡ":"O","Ȏ":"O","Ꝋ":"O","Ꝍ":"O","Ō":"O","Ṓ":"O","Ṑ":"O","Ɵ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Õ":"O","Ṍ":"O","Ṏ":"O","Ȭ":"O","Ƣ":"OI","Ꝏ":"OO","Ɛ":"E","Ɔ":"O","Ȣ":"OU","Ṕ":"P","Ṗ":"P","Ꝓ":"P","Ƥ":"P","Ꝕ":"P","Ᵽ":"P","Ꝑ":"P","Ꝙ":"Q","Ꝗ":"Q","Ŕ":"R","Ř":"R","Ŗ":"R","Ṙ":"R","Ṛ":"R","Ṝ":"R","Ȑ":"R","Ȓ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꜿ":"C","Ǝ":"E","Ś":"S","Ṥ":"S","Š":"S","Ṧ":"S","Ş":"S","Ŝ":"S","Ș":"S","Ṡ":"S","Ṣ":"S","Ṩ":"S","Ť":"T","Ţ":"T","Ṱ":"T","Ț":"T","Ⱦ":"T","Ṫ":"T","Ṭ":"T","Ƭ":"T","Ṯ":"T","Ʈ":"T","Ŧ":"T","Ɐ":"A","Ꞁ":"L","Ɯ":"M","Ʌ":"V","Ꜩ":"TZ","Ú":"U","Ŭ":"U","Ǔ":"U","Û":"U","Ṷ":"U","Ü":"U","Ǘ":"U","Ǚ":"U","Ǜ":"U","Ǖ":"U","Ṳ":"U","Ụ":"U","Ű":"U","Ȕ":"U","Ù":"U","Ủ":"U","Ư":"U","Ứ":"U","Ự":"U","Ừ":"U","Ử":"U","Ữ":"U","Ȗ":"U","Ū":"U","Ṻ":"U","Ų":"U","Ů":"U","Ũ":"U","Ṹ":"U","Ṵ":"U","Ꝟ":"V","Ṿ":"V","Ʋ":"V","Ṽ":"V","Ꝡ":"VY","Ẃ":"W","Ŵ":"W","Ẅ":"W","Ẇ":"W","Ẉ":"W","Ẁ":"W","Ⱳ":"W","Ẍ":"X","Ẋ":"X","Ý":"Y","Ŷ":"Y","Ÿ":"Y","Ẏ":"Y","Ỵ":"Y","Ỳ":"Y","Ƴ":"Y","Ỷ":"Y","Ỿ":"Y","Ȳ":"Y","Ɏ":"Y","Ỹ":"Y","Ź":"Z","Ž":"Z","Ẑ":"Z","Ⱬ":"Z","Ż":"Z","Ẓ":"Z","Ȥ":"Z","Ẕ":"Z","Ƶ":"Z","Ĳ":"IJ","Œ":"OE","ᴀ":"A","ᴁ":"AE","ʙ":"B","ᴃ":"B","ᴄ":"C","ᴅ":"D","ᴇ":"E","ꜰ":"F","ɢ":"G","ʛ":"G","ʜ":"H","ɪ":"I","ʁ":"R","ᴊ":"J","ᴋ":"K","ʟ":"L","ᴌ":"L","ᴍ":"M","ɴ":"N","ᴏ":"O","ɶ":"OE","ᴐ":"O","ᴕ":"OU","ᴘ":"P","ʀ":"R","ᴎ":"N","ᴙ":"R","ꜱ":"S","ᴛ":"T","ⱻ":"E","ᴚ":"R","ᴜ":"U","ᴠ":"V","ᴡ":"W","ʏ":"Y","ᴢ":"Z","á":"a","ă":"a","ắ":"a","ặ":"a","ằ":"a","ẳ":"a","ẵ":"a","ǎ":"a","â":"a","ấ":"a","ậ":"a","ầ":"a","ẩ":"a","ẫ":"a","ä":"a","ǟ":"a","ȧ":"a","ǡ":"a","ạ":"a","ȁ":"a","à":"a","ả":"a","ȃ":"a","ā":"a","ą":"a","ᶏ":"a","ẚ":"a","å":"a","ǻ":"a","ḁ":"a","ⱥ":"a","ã":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ḃ":"b","ḅ":"b","ɓ":"b","ḇ":"b","ᵬ":"b","ᶀ":"b","ƀ":"b","ƃ":"b","ɵ":"o","ć":"c","č":"c","ç":"c","ḉ":"c","ĉ":"c","ɕ":"c","ċ":"c","ƈ":"c","ȼ":"c","ď":"d","ḑ":"d","ḓ":"d","ȡ":"d","ḋ":"d","ḍ":"d","ɗ":"d","ᶑ":"d","ḏ":"d","ᵭ":"d","ᶁ":"d","đ":"d","ɖ":"d","ƌ":"d","ı":"i","ȷ":"j","ɟ":"j","ʄ":"j","ǳ":"dz","ǆ":"dz","é":"e","ĕ":"e","ě":"e","ȩ":"e","ḝ":"e","ê":"e","ế":"e","ệ":"e","ề":"e","ể":"e","ễ":"e","ḙ":"e","ë":"e","ė":"e","ẹ":"e","ȅ":"e","è":"e","ẻ":"e","ȇ":"e","ē":"e","ḗ":"e","ḕ":"e","ⱸ":"e","ę":"e","ᶒ":"e","ɇ":"e","ẽ":"e","ḛ":"e","ꝫ":"et","ḟ":"f","ƒ":"f","ᵮ":"f","ᶂ":"f","ǵ":"g","ğ":"g","ǧ":"g","ģ":"g","ĝ":"g","ġ":"g","ɠ":"g","ḡ":"g","ᶃ":"g","ǥ":"g","ḫ":"h","ȟ":"h","ḩ":"h","ĥ":"h","ⱨ":"h","ḧ":"h","ḣ":"h","ḥ":"h","ɦ":"h","ẖ":"h","ħ":"h","ƕ":"hv","í":"i","ĭ":"i","ǐ":"i","î":"i","ï":"i","ḯ":"i","ị":"i","ȉ":"i","ì":"i","ỉ":"i","ȋ":"i","ī":"i","į":"i","ᶖ":"i","ɨ":"i","ĩ":"i","ḭ":"i","ꝺ":"d","ꝼ":"f","ᵹ":"g","ꞃ":"r","ꞅ":"s","ꞇ":"t","ꝭ":"is","ǰ":"j","ĵ":"j","ʝ":"j","ɉ":"j","ḱ":"k","ǩ":"k","ķ":"k","ⱪ":"k","ꝃ":"k","ḳ":"k","ƙ":"k","ḵ":"k","ᶄ":"k","ꝁ":"k","ꝅ":"k","ĺ":"l","ƚ":"l","ɬ":"l","ľ":"l","ļ":"l","ḽ":"l","ȴ":"l","ḷ":"l","ḹ":"l","ⱡ":"l","ꝉ":"l","ḻ":"l","ŀ":"l","ɫ":"l","ᶅ":"l","ɭ":"l","ł":"l","ǉ":"lj","ſ":"s","ẜ":"s","ẛ":"s","ẝ":"s","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ᵯ":"m","ᶆ":"m","ń":"n","ň":"n","ņ":"n","ṋ":"n","ȵ":"n","ṅ":"n","ṇ":"n","ǹ":"n","ɲ":"n","ṉ":"n","ƞ":"n","ᵰ":"n","ᶇ":"n","ɳ":"n","ñ":"n","ǌ":"nj","ó":"o","ŏ":"o","ǒ":"o","ô":"o","ố":"o","ộ":"o","ồ":"o","ổ":"o","ỗ":"o","ö":"o","ȫ":"o","ȯ":"o","ȱ":"o","ọ":"o","ő":"o","ȍ":"o","ò":"o","ỏ":"o","ơ":"o","ớ":"o","ợ":"o","ờ":"o","ở":"o","ỡ":"o","ȏ":"o","ꝋ":"o","ꝍ":"o","ⱺ":"o","ō":"o","ṓ":"o","ṑ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","õ":"o","ṍ":"o","ṏ":"o","ȭ":"o","ƣ":"oi","ꝏ":"oo","ɛ":"e","ᶓ":"e","ɔ":"o","ᶗ":"o","ȣ":"ou","ṕ":"p","ṗ":"p","ꝓ":"p","ƥ":"p","ᵱ":"p","ᶈ":"p","ꝕ":"p","ᵽ":"p","ꝑ":"p","ꝙ":"q","ʠ":"q","ɋ":"q","ꝗ":"q","ŕ":"r","ř":"r","ŗ":"r","ṙ":"r","ṛ":"r","ṝ":"r","ȑ":"r","ɾ":"r","ᵳ":"r","ȓ":"r","ṟ":"r","ɼ":"r","ᵲ":"r","ᶉ":"r","ɍ":"r","ɽ":"r","ↄ":"c","ꜿ":"c","ɘ":"e","ɿ":"r","ś":"s","ṥ":"s","š":"s","ṧ":"s","ş":"s","ŝ":"s","ș":"s","ṡ":"s","ṣ":"s","ṩ":"s","ʂ":"s","ᵴ":"s","ᶊ":"s","ȿ":"s","ɡ":"g","ᴑ":"o","ᴓ":"o","ᴝ":"u","ť":"t","ţ":"t","ṱ":"t","ț":"t","ȶ":"t","ẗ":"t","ⱦ":"t","ṫ":"t","ṭ":"t","ƭ":"t","ṯ":"t","ᵵ":"t","ƫ":"t","ʈ":"t","ŧ":"t","ᵺ":"th","ɐ":"a","ᴂ":"ae","ǝ":"e","ᵷ":"g","ɥ":"h","ʮ":"h","ʯ":"h","ᴉ":"i","ʞ":"k","ꞁ":"l","ɯ":"m","ɰ":"m","ᴔ":"oe","ɹ":"r","ɻ":"r","ɺ":"r","ⱹ":"r","ʇ":"t","ʌ":"v","ʍ":"w","ʎ":"y","ꜩ":"tz","ú":"u","ŭ":"u","ǔ":"u","û":"u","ṷ":"u","ü":"u","ǘ":"u","ǚ":"u","ǜ":"u","ǖ":"u","ṳ":"u","ụ":"u","ű":"u","ȕ":"u","ù":"u","ủ":"u","ư":"u","ứ":"u","ự":"u","ừ":"u","ử":"u","ữ":"u","ȗ":"u","ū":"u","ṻ":"u","ų":"u","ᶙ":"u","ů":"u","ũ":"u","ṹ":"u","ṵ":"u","ᵫ":"ue","ꝸ":"um","ⱴ":"v","ꝟ":"v","ṿ":"v","ʋ":"v","ᶌ":"v","ⱱ":"v","ṽ":"v","ꝡ":"vy","ẃ":"w","ŵ":"w","ẅ":"w","ẇ":"w","ẉ":"w","ẁ":"w","ⱳ":"w","ẘ":"w","ẍ":"x","ẋ":"x","ᶍ":"x","ý":"y","ŷ":"y","ÿ":"y","ẏ":"y","ỵ":"y","ỳ":"y","ƴ":"y","ỷ":"y","ỿ":"y","ȳ":"y","ẙ":"y","ɏ":"y","ỹ":"y","ź":"z","ž":"z","ẑ":"z","ʑ":"z","ⱬ":"z","ż":"z","ẓ":"z","ȥ":"z","ẕ":"z","ᵶ":"z","ᶎ":"z","ʐ":"z","ƶ":"z","ɀ":"z","ﬀ":"ff","ﬃ":"ffi","ﬄ":"ffl","ﬁ":"fi","ﬂ":"fl","ĳ":"ij","œ":"oe","ﬆ":"st","ₐ":"a","ₑ":"e","ᵢ":"i","ⱼ":"j","ₒ":"o","ᵣ":"r","ᵤ":"u","ᵥ":"v","ₓ":"x"};
String.prototype.latinise=function(){return this.replace(/[^A-Za-z0-9\[\] ]/g,function(a){return Latinise.latin_map[a]||a;});};
String.prototype.latinize=String.prototype.latinise;
String.prototype.isLatin=function(){return this==this.latinise();};
var emailProtection = 'encode';

// Tu sa inicializuje SimpleModal. Ten sa nachadza v /includes/simple_modal/simple_modal.min.js
if (typeof SimpleModal !== 'undefined') {
	var simpleModal = new SimpleModal({autoShow: false});
}

// - - - - - - - - - - - - - - - - - -

function protectEmailAddressAsEncodedString(email) {
	return  "'"+encodeURI(email)+"'";
}

function escapeSingleQuote( argList ) {
	if (typeof(console) != 'undefined') console.log('argList', argList);
	return encodeURI(argList);
}

function js_html_special_chars( text ) {
  return (text.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/"/g, '&quot;'));
}

// bez anchor
function js_get_current_page_url() {
	return (document.location.href).replace(/#[^#]*$/i,'');
}

// bez parametrov a anchor
function js_get_current_page_clean_url() {
	return js_get_current_page_url().replace(/\?[^\/\?]*$/,'');
}

function js_reload_current_page() {
  document.location.href = js_get_current_page_url();
}

function js_reload_page_with_added_params( params ) {

  if ( typeof(params) != 'object' || params == null ) {
    js_reload_current_page();
  }

  var orig_location = js_get_current_page_url();
  var new_location = orig_location.match(/^[^\?]*/);  // cesta bez parametrov

  var location_parameters = '';

  if ( new_location == '' ) {
    new_location = '/';
    location_parameters = orig_location;
  }
  else {
    location_parameters = orig_location.replace( new_location, '' );
  }

  if ( location_parameters.charAt(0) == '?' ) {
    location_parameters = location_parameters.substr(1);
  }
  location_parameters = location_parameters.split('&');

  var has_params = false;
  var param_replaced = false;
  var name = '';
  var encoded_name = '';

  // prejdi vsetky parametre, ktore treba pridat
  for( name in params ) {

    if ( name == '' )
      continue;

	// fix ktory upravy limitStart na zaklade limitu (mohlo nastat ze sme boli na 1. strane a zacinali od 21 obj/ zak/ prod, a nevedeli sa dostat spat)
	if (name == 'limit') {
	  var newLimit = parseInt(params[name]);
    }

	  encoded_name = encodeURIchars( name );

    if ( params[name] != null ) {
      params[name] = encodeURIchars( params[name] );
    }

    param_replaced = false;

    for ( var i = 0; i < location_parameters.length; i++ ) {

      if ( location_parameters[i] == '' ) {
        continue;
      }

	  if ( typeof newLimit !== 'undefined' ) {
	  	if( location_parameters[i].indexOf('limitstart') == 0) {
		  var limitStart =  parseInt(location_parameters[i].replace('limitstart=', ''));
		  if (limitStart > 0) {
			  if(newLimit%limitStart != 0 || (limitStart < newLimit)){
				  limitStart = Math.floor(limitStart/newLimit)*newLimit;
				  location_parameters[i] = ('limitstart='+limitStart.toString());
			  }
		  }
	    }
	  }

      // nahrad hodnotu existujuceho parametra
      if ( location_parameters[i].indexOf( name + '=' ) == 0 || location_parameters[i].indexOf( encoded_name + '=' ) == 0 ) {

      	// odstranujeme parameter
        if ( params[name] == null ) {
          location_parameters[i] = '';
        }
        else {
          location_parameters[i] = ( encoded_name + '=' + params[name] );
        }
        param_replaced = true;
        break;
      }
    }

    if ( param_replaced ) {
      continue;
    }
    // pridanie noveho parametra

    if ( params[name] == null ) {
      continue;
    }

    //if ( has_params && new_location.indexOf('?') == 0 ) {
    if ( has_params ) {
      new_location += '&';
    }
    else {
      new_location += '?';
    }

    new_location += ( encoded_name + '=' + params[name] );
    has_params = true;
  }

  // pridaj povodne parametre
  for ( var i = 0; i < location_parameters.length; i++ ) {

    if ( location_parameters[i] == '' ) {
      continue;
    }

    new_location += ((has_params ? '&' : '?') + location_parameters[i]);
    has_params = true;
  }

  document.location.href = new_location;
}

var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();

function js_round(x, places, fix) {
	var rounded_ret = Math.round(x * Math.pow(10, places)) / Math.pow(10, places);
	if (fix && rounded_ret!=parseInt(rounded_ret)) rounded_ret = rounded_ret.toFixed(places);
	return rounded_ret;
}

function doRound(x, places, fix) {
	return js_round(x, places, fix);
}

function js_get_page_scroll() {
  var xScroll, yScroll;
  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
    xScroll = self.pageXOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
    yScroll = document.documentElement.scrollTop;
    xScroll = document.documentElement.scrollLeft;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
    xScroll = document.body.scrollLeft;
  }
  return new Array(xScroll,yScroll);
}

function js_array_index_of( items, searched_item ) {

	if ( typeof(items) != 'object' ) {
		return -1;
	}

  for( var item_id in items ) {
    if ( items[item_id] == searched_item )
      return item_id;
  }
  return -1;  // nenasli sme
}

function js_prettyphoto_close() {
  if (jQuery('.pp_pic_holder').length == 0)
  	  return false;

  jQuery.prettyPhoto.close();
  jQuery('body').removeClass('fancybox-lock');
  jQuery(document).off('keyup');
  return false;
}

function js_prettyphoto_center() {
	var prettyphoto_element = jQuery('.pp_pic_holder:first');
	if ( prettyphoto_element.length == 0 )
		return;
	var page_scroll = js_get_page_scroll();
	prettyphoto_element.animate({'left': (page_scroll[0] + Math.round( parseInt(jQuery(window).width()) / 2 ) - Math.round( parseInt(prettyphoto_element.width()) / 2 )).toString() + 'px', 'top': (page_scroll[1] + Math.round( parseInt(jQuery(window).height()) / 2 ) - Math.round( parseInt(prettyphoto_element.height()) / 2 )).toString() + 'px'}, 100);
	return;
}


function js_trim_input_value( input_elements ) {
	input_elements = jQuery(input_elements);

	if ( input_elements.length == 0 ) {
	  return;
	}

	input_elements.each( function() {
		jQuery(this).attr('value', jQuery.trim( jQuery(this).val() ));
	});
}

function js_default_text_input_focus( input_element ) {
	input_element = jQuery(input_element);

	if ( input_element.hasClass('tooltip_input_def_text') ) {
		input_element.attr('value', '').removeClass('tooltip_input_def_text');
	}
}

function js_default_text_input_blur( input_element, default_text, trim ) {
	input_element = jQuery(input_element);

	if (trim !== false) js_trim_input_value( input_element );

	if ( input_element.val() == '' ) {
		input_element.attr('value', default_text).addClass('tooltip_input_def_text');
	}
}

function js_select_option_value( select_element, selected_value ) {
	select_element = jQuery(select_element);
	var selected_option_element = select_element.children('option[value="'+selected_value+'"]:first');

	if ( selected_option_element.length == 0 ) {
		return;
	}

	select_element.children('option').removeAttr('selected');
	selected_option_element.attr('selected', 'selected');
}

function js_get_object_length( obj ) {
	var size = 0, key = null;
	if (obj == null) {
		return size;
	}

	for (key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
};

function js_are_objects_identical( obj1, obj2, is_type_strict ) {
	if ( typeof(obj1) == 'undefined' || typeof(obj2) == 'undefined' ) {
		return false;
	}
	if ( typeof(obj1) != 'object' || typeof(obj2) != 'object' ) {
		return false;
	}

	if ( js_get_object_length(obj1) != js_get_object_length(obj2) ) {
		return false;
	}

	for (key in obj1) {

		if ( !obj1.hasOwnProperty(key) ) {
			continue;
		}

		if ( typeof(obj2[key]) == 'undefined' ) {
			return false;
		}

		if ( obj1[key] != obj2[key] ) {
			return false;
		}
		if ( is_type_strict && typeof(obj1[key]) != typeof(obj2[key]) ) {
			return false;
		}
	}

	return true;
}

function js_clear_css_attribute( element, css_name ) {

  if ( css_name != '' ) {
    jQuery(element).css(css_name, '');
  }
}

function js_set_css_attribute( element, css_name, css_value ) {

  if ( css_name != '' && css_value != '' ) {
    jQuery(element).css(css_name, css_value);
  }
}

function js_is_empty( variable ) {

  return ( typeof(variable) == 'undefined' || variable == null || (typeof(variable) == 'string' && variable == '') || (typeof(variable.length) != 'undefined' && variable.length == 0) || (typeof(variable) == 'object' && jQuery.isEmptyObject( variable )) );
}

function js_is_valid_json( obj, params ) {
  if ( typeof(obj) != 'object' ) {
    return false;
  }

  if ( typeof(params) != 'object' || params == null ) {
  	return true;
  }

  for( var param in params ) {

    if ( typeof(obj[param]) == 'undefined' ) {
    	return false;
    }

    if ( params[param] == null ) {
      continue;
    }

    if ( obj[param] != params[param] ) {
    	return false;
    }
  }
  return true;
}

function js_merge_objects( obj_1, obj_2 ) {
  return jQuery.extend(true, {}, obj_1, obj_2);
}

function js_is_email_banned( email ) {
	return ( email.substr(-10) == '@jnxjn.com' || email.substr(-23) == '@guerrillamailblock.com' || email.substr(-16) == '@spamgourmet.com' || email.substr(-10) == 'e4ward.com' || email.substr(-11) == '@spambox.us' || email.substr(-13) == '@pookmail.com' || email.substr(-16) == '@mailmetrash.com' || email.substr(-12) == '@jetable.org' || email.substr(-14) == '@tempemail.net' || /spamfree[24]{0,2}\.[^\.]+$/.exec(email) != null || email.substr(-12) == 'spamspot.com' || email.substr(-7) == 'spam.la' );
}

function js_check_sef_input_caret( input_element, special_sef ) {
	input_element = jQuery(input_element);

	if (input_element.length == 0)
		return false;

	var cur_caret_pos          = input_element.caret().start;
	var cur_caret_end_pos      = input_element.caret().end;
	var text_from_user         = input_element.val();
	var new_text               = '';
	var change_position_cursor = false;

	if ((text_from_user.search('http') != -1) || (text_from_user.search('https') != -1)) {
		// nasiel som "http", alebo "https"
		if (text_from_user.search('/') == 0) { // ak na 0.mieste v stringu je "/"
			text_from_user = text_from_user.substr(1); // odstrani prvy znak v stringu, cize '/'
			//text_from_user = text_from_user.slice(1); // odstrani prvy znak v stringu, cize '/'
			change_position_cursor = true;
			--cur_caret_pos;
			--cur_caret_end_pos;
		}

		var stringLength = text_from_user.length;
		if ((text_from_user.charAt(stringLength - 1) === '/') && (text_from_user.charAt(stringLength - 2) === '/')) {
			// ak predposledny a sucasne posledny znak je "/", tak jedno lomitko zmaz
			text_from_user = text_from_user.slice(0, -1);
		}

		new_text = text_from_user;
		input_element.val(new_text);
		if (change_position_cursor) {
			input_element.caret(cur_caret_pos, cur_caret_end_pos);
			change_position_cursor = false;
		}

		return;
	} else {
		// nenasiel som "http", ani "https"
		new_text = '/' + input_element.val().replace(/\s*\//g, '') + '/';
		if (typeof(special_sef) != "undefined" && special_sef == 2) {	// povoluje SEF s "/" vo vnutri
			//new_text = input_element.val().replace(/^\s*\//, '').replace(/\/\s*$/, '').replace(/\/{2,}/, '/').replace(/ +/, '-').replace(/\-{2,}/, '-') + '/';
			new_text = '/' + input_element.val().replace(/^\s*\//, '').replace(/\/\s*$/, '').replace(/\/{2,}/, '/').replace(/ +/, '-').replace(/\-{2,}/, '-') + '/';
			//var slash_count = new_text.length - new_text.replace(/\//gi,'').length);
		}
		if ((typeof(special_sef) != "undefined" && special_sef == 3) || (input_element.val().indexOf('http://') != -1 || input_element.val().indexOf('https://') != -1 || input_element.val().indexOf('www.') != -1)) {
			new_text = input_element.val();
		} else {
			if (input_element.val() != new_text) {
				input_element.val(new_text);
			}

			if (input_element.data('no_caret_change') == '1')
				return;

			if (!input_element.is(':visible')) {
				return;
			}

			cur_caret_pos     = input_element.caret().start;
			cur_caret_end_pos = input_element.caret().end;
			//var cur_caret_pos     = input_element.caret().start;
			//var cur_caret_end_pos = input_element.caret().end;

			if (cur_caret_pos == 0)
				cur_caret_pos = 1;

			if (cur_caret_pos == input_element.val().length)
				cur_caret_pos = input_element.val().length - 1;

			if (cur_caret_end_pos == 0)
				cur_caret_end_pos = 1;

			if (cur_caret_end_pos == input_element.val().length)
				cur_caret_end_pos = input_element.val().length - 1;

			if (cur_caret_pos == input_element.caret().start && cur_caret_end_pos == input_element.caret().end)
				return;

			input_element.caret(cur_caret_pos, cur_caret_end_pos);
		}

	}


}



function js_bind_sef_input_events( input_element, special_sef ) {

  if (typeof js_sef_control_disabled != 'undefined' && js_sef_control_disabled == 1) {
	  if(is_cs_user()) {
		  console.log('test inside binding -> unreachable');
	  }
	  return;
  }
	jQuery(input_element).on('focus keyup click', function () {
		js_check_sef_input_caret(jQuery(this), special_sef);
	});
}
function js_multiple_select_option_click(option_element) {
	option_element = jQuery(option_element);
	if (option_element.val() != '') {
		option_element.parents('select:first').find('option[value=""]').prop('selected', false);
	}
}
function js_jq_clearCalendarField(input_jq_selector, container_jq_selector, clear_val, jso ) {
	if (typeof(jso) != 'undefined' && jso) {
		var jqo = jQuery(jso);
		var jqo_container = jqo.parents(container_jq_selector);	//	'.adminlist-edit-main-div.product:first'
		if (jqo_container.length > 0) {
			var jqo_input = jqo_container.find(input_jq_selector);	//	'[name="'+input_name+'"]:first'
			if (jqo_input.length > 0) {
				jqo_input.val(clear_val);
			}
		}
	}
}

function js_jq_showCalendar( id, date_format, jq_jso ) {
	if (typeof(jq_jso) != 'undefined' && jq_jso) {
		var jqo = jQuery(jq_jso);
		var jqo_container = jqo.parents('.adminlist-edit-main-div.product:first');
		if (jqo_container.length > 0) {
			var el = jqo_container.find('[name="'+id+'"]:first').get(0);
		}
	} else {
		var el = document.getElementById(id);
	}
	if (calendar != null) {
		// we already have one created, so just update it.
		calendar.hide();		// hide the existing calendar
		calendar.parseDate(el.value); // set it to a new date
	} else {
		// first-time call, create the calendar
		var cal = new Calendar(true, null, selected, closeHandler);
		calendar = cal;		// remember the calendar in the global
		cal.setRange(1900, 2070);	// min/max year allowed
		if (date_format && date_format.indexOf('%') > -1) cal.setDateFormat(date_format);
		calendar.create();		// create a popup calendar
		calendar.parseDate(el.value); // set it to a new date
	}
	calendar.sel = el;		// inform it about the input field in use
	calendar.showAtElement(el);	// show the calendar next to the input field

	// catch mousedown on the document
	Calendar.addEvent(document, "mousedown", checkCalendar);
	return false;
}

// general utility for browsing a named array or object
function xshow(o) {
	s = '';
	for(e in o) {s += e+'='+o[e]+'\n';}
	alert( s );
}

/**
* Writes a dynamically generated list
* @param selectParams string The parameters to insert into the <select> tag
* @param source array A javascript array of list options in the form [key,value,text]
* @param key string The key to display for the initial state of the list
* @param orig_key string The original key that was selected
* @param orig_val string The original item value that was selected
*/
function writeDynaList( selectParams, source, key, orig_key, orig_val ) {
	console.log('WRITE DL');
	var html = '\n	<select ' + selectParams + '>';
	var i = 0;
	for (x in source) {
		if (source[x][0] == key) {
			var selected = '';
			if ((orig_key == key && orig_val == source[x][1]) || (i == 0 && orig_key != key)) {
				selected = 'selected="selected"';
			}
			html += '\n		<option value="'+source[x][1]+'" '+selected+'>'+source[x][2]+'</option>';
		}
		i++;
	}
	html += '\n	</select>';

	document.writeln( html );
}

/**
* Changes a dynamically generated list
* @param listname string The name of the list to change
* @param source array A javascript array of list options in the form [key,value,text]
* @param key string The key to display
* @param orig_key string The original key that was selected
* @param orig_val string The original item value that was selected
*/
function changeDynaList( listname, source, key, orig_key, orig_val ) {
	var list = eval( 'jQuery(\'[name="' + listname + '"]:first\').get(0)' );

	// empty the list
	for (i in list.options.length) {
		list.options[i] = null;
	}
	i = 0;
	for (x in source) {
		if (source[x][0] == key) {
			opt = new Option();
			opt.value = source[x][1];
			opt.text = source[x][2];

			if ((orig_key == key && orig_val == opt.value) || i == 0) {
				opt.selected = true;
			}
			list.options[i++] = opt;
		}
	}
	list.length = i;
}

/**
* Adds a select item(s) from one list to another
*/
function addSelectedToList( frmName, srcListName, tgtListName, jQ, ex_params ) {

	var srcList;
	var tgtList;

	if (typeof(ex_params.imagefiles_jq_selector) != 'undefined' && typeof(ex_params.imagelist_jq_selector) != 'undefined' && typeof(jQuery) != 'undefined') {
		srcList = jQuery(ex_params.imagefiles_jq_selector).get(0);
		tgtList = jQuery(ex_params.imagelist_jq_selector).get(0);
	} else {
		var form = eval( 'document.' + frmName );
		if (jQ) {
			srcList = jQuery("form[name='"+frmName+"'] select[name='"+srcListName+"']").get(0);
			tgtList = jQuery("form[name='"+frmName+"'] select[name='"+tgtListName+"']").get(0);
		} else {
			srcList = eval( 'form.' + srcListName );
			tgtList = eval( 'form.' + tgtListName );
		}
	}

	if ( typeof srcList === 'undefined' || typeof tgtList === 'undefined' ) {
		return;
	}

	var srcLen = srcList.length;
	var tgtLen = tgtList.length;
	var tgt = "x";

	//build array of target items
	for (var i=tgtLen-1; i > -1; i--) {
		tgt += "," + tgtList.options[i].value + ",";
	}

	//Pull selected resources and add them to list
	//for (var i=srcLen-1; i > -1; i--) {
	for (var i=0; i < srcLen; i++) {
		if (srcList.options[i].selected && tgt.indexOf( "," + srcList.options[i].value + "," ) == -1) {

				var subFolderPath = jQuery(srcList).closest('.admin-product-edit-active-images').find('select[name="folders"] option:selected').val();
				//Zbavenie sa Lomitka pri tahani subFoldru
				subFolderPath = (subFolderPath[0] == '/') ? subFolderPath.substr(1) : subFolderPath;
				opt = new Option(srcList.options[i].text, subFolderPath + srcList.options[i].text);
				tgtList.options[tgtList.length] = opt;

				//opt = new Option(srcList.options[i].text, srcList.options[i].value );
				//tgtList.options[tgtList.length] = opt;
		}
	}
}

function delSelectedFromList( frmName, srcListName, ex_params ) {
	if (typeof(ex_params.imagelist_jq_selector) != 'undefined' && typeof(jQuery) != 'undefined') {
		var srcList = jQuery(ex_params.imagelist_jq_selector).get(0);
	} else {
		var form = eval( 'document.' + frmName );
		var srcList = eval( 'form.' + srcListName );
	}

	var srcLen = srcList.length;

	for (var i=srcLen-1; i > -1; i--) {
		if (srcList.options[i].selected) {
			srcList.options[i] = null;
		}
	}
}

function moveInList( frmName, srcListName, index, to, jQ, ex_params ) {
	if (ex_params != null && typeof(ex_params.imagelist_jq_selector) != 'undefined' && typeof(jQuery) != 'undefined') {
		var srcList = jQuery(ex_params.imagelist_jq_selector).get(0);
		index = jQuery(ex_params.imagelist_jq_selector).find('option:selected').index();
	} else {
		if (jQ) {
			var srcList = jQuery("form[name='"+frmName+"'] select[name='"+srcListName+"']").get(0);
		} else {
			var form = eval( 'document.' + frmName );
			var srcList = eval( 'form.' + srcListName );
		}
	}
	var total = srcList.options.length-1;

	if (index == -1) {
		return false;
	}
	if (to == +1 && index == total) {
		return false;
	}
	if (to == -1 && index == 0) {
		return false;
	}

	var items = new Array;
	var values = new Array;

	var classes = new Array;

	for (i=total; i >= 0; i--) {
		items[i] = srcList.options[i].text;
		values[i] = srcList.options[i].value;
			classes[i] = jQuery(srcList.options[i]).attr('class');
	}
	for (i = total; i >= 0; i--) {
		if (index == i) {
			srcList.options[i + to] = new Option(items[i],values[i], 0, 1);
			srcList.options[i] = new Option(items[i+to], values[i+to]);
				jQuery(srcList.options[i + to]).addClass(classes[i]);
				jQuery(srcList.options[i]).addClass(classes[i + to]);
			i--;
		} else {
			srcList.options[i] = new Option(items[i], values[i]);
				jQuery(srcList.options[i]).addClass(classes[i]);
		}
	}

	if (typeof srcList === 'object' && srcList.length) jQuery(srcList).trigger('focus');
}

function getSelectedOption( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		return srcList.options[i];
	} else {
		return null;
	}
}

function setSelectedValue( frmName, srcListName, value ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	var srcLen = srcList.length;

	for (var i=0; i < srcLen; i++) {
		srcList.options[i].selected = false;
		if (srcList.options[i].value == value) {
			srcList.options[i].selected = true;
		}
	}
}

function getSelectedRadio( frmName, srcGroupName ) {
	var form = eval( 'document.' + frmName );
	var srcGroup = eval( 'form.' + srcGroupName );

	if (srcGroup[0]) {
		for (var i=0, n=srcGroup.length; i < n; i++) {
			if (srcGroup[i].checked) {
				return srcGroup[i].value;
			}
		}
	} else {
		if (srcGroup.checked) {
			return srcGroup.value;
		} // if the one button is checked, return zero
	}
   // if we get to this point, no radio button is selected
   return null;
}

function getSelectedValue( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		return srcList.options[i].value;
	} else {
		return null;
	}
}

function getSelectedText( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		return srcList.options[i].text;
	} else {
		return null;
	}
}

function chgSelectedValue( frmName, srcListName, value ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		srcList.options[i].value = value;
		return true;
	} else {
		return false;
	}
}

function jq_showImageProps( base_path, ex_params) {
//id="images-page461"
//if (typeof(console) != 'undefined') console.log(ex_params);
	if (typeof(ex_params.imagelist_jq_selector) != 'undefined' && typeof(ex_params.view_imagelist_jq_selector) != 'undefined') {
		value = jQuery(ex_params.imagelist_jq_selector+' option:selected').val();
		if (typeof value !== 'undefined' && value != '') {
			parts = value.split( '|' );
			var view_imagelist = jQuery(ex_params.view_imagelist_jq_selector).get(0);
				var imagelist_jq_selector = jQuery(ex_params.view_imagelist_jq_selector);
				if(jQuery(ex_params.imagelist_jq_selector+' option:selected').hasClass('removed')){
					if(!jQuery('img[name="view_imagelist"]').parent().find('span.error').length){
						imagelist_jq_selector.after('<span class="error">'+ cms_js_lang_product_img_path_change + ' ('+parts[0]+')</span>');

					} else {
						jQuery('img[name="view_imagelist"]').parent().find('span.error').text( cms_js_lang_product_img_path_change+ ' ('+parts[0]+')');

					}
					console.log(imagelist_jq_selector.closest('span .error').length);
					imagelist_jq_selector.hide();
				} else {
					imagelist_jq_selector.show();
					jQuery('img[name="view_imagelist"]').parent().find('span.error').remove();
					view_imagelist.src = base_path + parts[0];
				}
		}
	}
}

function applyImageProps() {
	form = document.adminForm;
	if (!getSelectedValue( 'adminForm', 'imagelist' )) {
		alert( "Select and image from the list" );
		return;
	}
	value = form._source.value + '|'
	+ getSelectedValue( 'adminForm', '_align' ) + '|'
	+ form._alt.value + '|'
	+ parseInt( form._border.value ) + '|'
	+ form._caption.value + '|'
	+ getSelectedValue( 'adminForm', '_caption_position' ) + '|'
	+ getSelectedValue( 'adminForm', '_caption_align' ) + '|'
	+ form._width.value;
	chgSelectedValue( 'adminForm', 'imagelist', value );
}

function previewImage( list, image, base_path, ex_params ) {
	//	calim
	var srcList;
	var srcImage;

	if (typeof(ex_params.imagefiles_jq_selector) != 'undefined' && typeof(ex_params.view_imagefiles_jq_selector) != 'undefined' && typeof(jQuery) != 'undefined') {

		srcList = jQuery(ex_params.imagefiles_jq_selector).get(0);
		srcImage = jQuery(ex_params.view_imagefiles_jq_selector).get(0);

	} else {

		var form = document.adminForm;
		srcList = eval( "form." + list );
		srcImage = eval( "document." + image );
	}

	if (srcList.selectedIndex >= 0) {

		var fileName = srcList.options[srcList.selectedIndex].text;
		var fileName2 = srcList.options[srcList.selectedIndex].value;
		if (fileName.length == 0 || fileName2.length == 0) {
			srcImage.src = 'images/blank.gif';
		} else {
			srcImage.src = base_path + fileName2;
		}
	}
}

// Form specific functions for editting content images

function showImageProps( base_path, ex_params ) {
	if (typeof(ex_params.func) != "undefined" && ex_params.func == "jq_showImageProps" && typeof(jQuery) != 'undefined') {
		return jq_showImageProps(base_path, ex_params);
	}
	form = document.adminForm;
	value = getSelectedValue( 'adminForm', 'imagelist' );
	parts = value.split( '|' );
	form._source.value = parts[0];
	setSelectedValue( 'adminForm', '_align', parts[1] || '' );
	form._alt.value = parts[2] || '';
	form._border.value = parts[3] || '0';
	form._caption.value = parts[4] || '';
	setSelectedValue( 'adminForm', '_caption_position', parts[5] || '' );
	setSelectedValue( 'adminForm', '_caption_align', parts[6] || '' );
	form._width.value = parts[7] || '';

	//previewImage( 'imagelist', 'view_imagelist', base_path );
	var srcImage = eval( "document." + 'view_imagelist' );
	srcImage.src = base_path + parts[0];
}

/**
 * Toggles the check state of a group of boxes
 *
 * Checkboxes must have an id attribute in the form cb0, cb1...
 * @param The number of box to 'check'
 * @param An alternative field name
*/
function checkAll( n, fldName ) {
  if (!fldName) {
     fldName = 'cb';
  }
	var f = document.adminForm;
	var c = f.toggle.checked;
	var n2 = 0;
	for (i=0; i < n; i++) {
		cb = eval( 'f.' + fldName + '' + i );
		if (cb) {
			cb.checked = c;
			n2++;
		}
	}
	if (c) {
		document.adminForm.boxchecked.value = n2;
	} else {
		document.adminForm.boxchecked.value = 0;
	}
}

function listItemTask( id, task ) {
    var f = document.adminForm;
    cb = eval( 'f.' + id );
    if (cb) {
        for (i = 0; true; i++) {
            cbx = eval('f.cb'+i);
            if (!cbx) break;
            cbx.checked = false;
        } // for
        cb.checked = true;
        f.boxchecked.value = 1;
        submitbutton(task);
    }
    return false;
}

function hideMainMenu()
{
	document.adminForm.hidemainmenu.value=1;
}

function isChecked(isitchecked){

	if ( typeof document.adminForm.boxchecked !== 'undefined' ) {
		if (isitchecked == true) {
			document.adminForm.boxchecked.value++;
		}
		else {
			document.adminForm.boxchecked.value--;
		}
	}
}

/**
* Default function.  Usually would be overriden by the component
*/
function submitbutton(pressbutton) {
	submitform(pressbutton);
}

/**
* Submit the admin form
*/
function submitform(pressbutton){
	document.adminForm.task.value=pressbutton;
	try {
		document.adminForm.onsubmit();
		}
	catch(e){}
	document.adminForm.submit();
}

/**
* Submit the control panel admin form
*/
function submitcpform(sectionid, id){
	document.adminForm.sectionid.value=sectionid;
	document.adminForm.id.value=id;
	submitbutton("edit");
}

/**
* Getting radio button that is selected.
*/
function getSelected(allbuttons){
	for (i=0;i<allbuttons.length;i++) {
		if (allbuttons[i].checked) {
			return allbuttons[i].value;
		}
	}
}

// JS Calendar
var calendar = null; // remember the calendar object so that we reuse
// it and avoid creating another

// This function gets called when an end-user clicks on some date
function selected(cal, date) {
	cal.sel.value = date; // just update the value of the input field
	if ( is_cs_user('separate_js') ) {
		console.log(date);
	}
	jQuery(cal.sel).trigger('change'); // trigger event after input value replace
}
// And this gets called when the end-user clicks on the _selected_ date,
// or clicks the "Close" (X) button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
	cal.hide();			// hide the calendar

	// don't check mousedown on document anymore (used to be able to hide the
	// calendar when someone clicks outside it, see the showCalendar function).
	Calendar.removeEvent(document, "mousedown", checkCalendar);
}

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
function checkCalendar(ev) {
	var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
	for (; el != null; el = el.parentNode)
	// FIXME: allow end-user to click some link without closing the
	// calendar.  Good to see real-time stylesheet change :)
	if (el == calendar.element || el.tagName == "A") break;
	if (el == null) {
		// calls closeHandler which should hide the calendar.
		calendar.callCloseHandler(); Calendar.stopEvent(ev);
	}
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar( id, date_format, jq_jso ) {
	if (typeof(jq_jso) != 'undefined' && jq_jso) {
		var jqo = jQuery(jq_jso);
		var jqo_container = jqo.parents('.adminlist-edit-main-div.product:first');
		if (jqo_container.length > 0) {
			var el = jqo_container.find('[name="'+id+'"]:first').get(0);
		}
	} else {
		var el = document.getElementById(id);
	}
	if (calendar != null) {
		// we already have one created, so just update it.
		calendar.hide();		// hide the existing calendar
		calendar.parseDate(el.value); // set it to a new date
	} else {
		// first-time call, create the calendar
		var cal = new Calendar(true, null, selected, closeHandler);
		calendar = cal;		// remember the calendar in the global
		cal.setRange(1900, 2070);	// min/max year allowed
		if (date_format && date_format.indexOf('%') > -1) cal.setDateFormat(date_format);
		calendar.create();		// create a popup calendar
		calendar.parseDate(el.value); // set it to a new date
	}
	calendar.sel = el;		// inform it about the input field in use
	calendar.showAtElement(el);	// show the calendar next to the input field

	// catch mousedown on the document
	Calendar.addEvent(document, "mousedown", checkCalendar);
	return false;
}

/**
* Pops up a new window in the middle of the screen
*/
function popupWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable';
	win = window.open(mypage, myname, winprops);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

// LTrim(string) : Returns a copy of a string without leading spaces.
function ltrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(0)) != -1) {
      var j=0, i = s.length;
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      s = s.substring(j, i);
   }
   return s;
}

//RTrim(string) : Returns a copy of a string without trailing spaces.
function rtrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;       // Get length of string
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }
   return s;
}

// Trim(string) : Returns a copy of a string without leading or trailing spaces
function trim(str) {
   return rtrim(ltrim(str));
}

function mosDHTML(){
	this.ver=navigator.appVersion;
	this.agent=navigator.userAgent;
	this.dom=document.getElementById?1:0;
	this.opera5=this.agent.indexOf("Opera 5")<-1;
	this.ie5=(this.ver.indexOf("MSIE 5")<-1 && this.dom && !this.opera5)?1:0;
	this.ie6=(this.ver.indexOf("MSIE 6")<-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6;
	this.mac=this.agent.indexOf("Mac")<-1;
	this.ns6=(this.dom && parseInt(this.ver) <= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6||this.ie5||this.ie4||this.ns4||this.ns6||this.opera5);

	this.activeTab = '';
	this.onTabStyle = 'ontab';
	this.offTabStyle = 'offtab';

	this.setElemStyle = function(elem,style) {
		document.getElementById(elem).className = style;
	};
	this.showElem = function(id) {
		if (elem = document.getElementById(id)) {
			elem.style.visibility = 'visible';
			elem.style.display = 'block';
		}
	};
	this.hideElem = function(id) {
		if (elem = document.getElementById(id)) {
			elem.style.visibility = 'hidden';
			elem.style.display = 'none';
		}
	};
	this.cycleTab = function(name) {
		if (this.activeTab) {
			this.setElemStyle( this.activeTab, this.offTabStyle );
			page = this.activeTab.replace( 'tab', 'page' );
			this.hideElem(page);
		}
		this.setElemStyle( name, this.onTabStyle );
		this.activeTab = name;
		page = this.activeTab.replace( 'tab', 'page' );
		this.showElem(page);
	};
	return this;
}
var dhtml = new mosDHTML();

function MM_findObj(n, d) { //v4.01
	var p,i,x;
	if(!d) d=document;
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n);
	return x;
}
function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments;
	document.MM_sr=new Array;
	for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;
	if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr;
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
	var d=document;
	if(d.images){
	if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
	for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


function saveorder( n, ls, lm, save_order_func ) {
	if (!isNaN(ls) && !isNaN(lm)) {
		if (!(ls==0 && lm >= (n+1))) {
			alert('Pre uloženie zmien poradia je potrebné zvoliť zobrazenie všetkých (resp. aspoň '+(n+1)+') položiek.');
			return;
		}
	}
	checkAll_button( n, save_order_func );
}

//needed by saveorder function
function checkAll_button( n, save_order_func ) {
	for ( var j = 0; j <= n; j++ ) {
		box = eval( "document.adminForm.cb" + j );
		if ( box ) {
			if ( box.checked == false ) {
				box.checked = true;
			}
		} else {
			alert("You cannot change the order of items, as an item in the list is `Checked Out`");
			return;
		}
	}
	if (!isNaN(save_order_func)) submitform(save_order_func);
	//if (save_order_func!='') submitform(save_order_func);
	else submitform('saveorder');
}
/**
* @param object A form element
* @param string The name of the element to find
*/
function getElementByName( f, name ) {
	if (f.elements) {
		for (i=0, n=f.elements.length; i < n; i++) {
			if (f.elements[i].name == name) {
				return f.elements[i];
			}
		}
	}
	return null;
}

function cs_set_cookie ( name, value, expires, path, domain, secure ) {
	var today = new Date(); // set time, it's in milliseconds
	today.setTime( today.getTime() );

	if ( expires ) { // if the expires variable is set, make the correct expires time, the current script below will set it for x number of days, to make it for hours, delete * 24, for minutes, delete * 60 * 24
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ( ( path ) ? ";path=" + path : "" ) + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" );
}

function cs_get_cookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function encodeURIchars ( text ) {
	//	funkcia zakoduje text, ktory sa ma pouzit ako parameter v URL
	return encodeURIComponent(text).replace('~','%7E').replace('!','%21').replace('*','%2A').replace('(','%28').replace(')','%29').replace('\'','%27');
}

// Create XML request variable
var ajaxGlobalRequest = false;

// function ajaxAsyncContainer() {
// 	if (!ajaxGlobalRequestObjectList) ajaxGlobalRequestObjectList = new Array();
// 	ajaxGlobalRequestObjectList[ajaxGlobalRequestObjectList.length] = '1';
// 	alert(ajaxGlobalRequestObjectList.length);
// }

function ajaxSyncProcess ( myURL, requestPostParams, requestHeaderContentType, requestMimeType ) {
     // Clear ajaxGlobalRequest
     ajaxGlobalRequest = false;
     // For browsers: Safari, Firefox, etc. use one XML model
     if (window.XMLHttpRequest) {
          ajaxGlobalRequest = new XMLHttpRequest();
          if (requestMimeType==null) ajaxGlobalRequest.overrideMimeType('text/html');	//	text/html, text/xml
//           if (ajaxGlobalRequest.overrideMimeType && requestHeaderContentType==null && requestPostParams==null) {
//                ajaxGlobalRequest.overrideMimeType('text/xml');
//           }
     } else if (window.ActiveXObject) {
          // For browsers: IE, version 6 and before, use another model
          try {
               ajaxGlobalRequest = new
                    ActiveXObject("Msxml2.XMLHTTP");
          } catch (e) {
               try {
                    ajaxGlobalRequest = new
                         ActiveXObject("Microsoft.XMLHTTP");
               } catch (e) {}
          }
     }
     // Make sure the request object is valid
     if (!ajaxGlobalRequest) {
          alert('AJAX ERROR: Cannot create XMLHTTP object');
          return false;
     }
     // Open the URL request
     if (requestPostParams==null) {
	     ajaxGlobalRequest.open('get', myURL, false);		//	SYNC (waiting mode)
     } else {
	     ajaxGlobalRequest.open('post', myURL, false);		//	SYNC (waiting mode)
     }
     // Send request
     //	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     //	"Content-Type","application/x-www-form-urlencoded"
     if (requestPostParams==null) {
	     if (requestHeaderContentType==null) ajaxGlobalRequest.setRequestHeader("Content-Type","text/html; charset=utf-8");
	     ajaxGlobalRequest.send(null);
     } else {
	     ajaxGlobalRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	     ajaxGlobalRequest.setRequestHeader("Content-Length", requestPostParams.length);
	     ajaxGlobalRequest.setRequestHeader("Connection", "close");
	     ajaxGlobalRequest.send(requestPostParams);
     }
     return ajaxGlobalRequest.responseText;
}

function ajaxAsyncProcess ( myURL, myAjaxCallbackFuncName, requestPostParams, requestHeaderContentType, requestMimeType ) {
     // Clear ajaxGlobalRequest
     ajaxGlobalRequest = false;
     // For browsers: Safari, Firefox, etc. use one XML model
     if (window.XMLHttpRequest) {
          ajaxGlobalRequest = new XMLHttpRequest();
          if (requestMimeType==null) ajaxGlobalRequest.overrideMimeType('text/html');	//	text/html, text/xml
//           if (ajaxGlobalRequest.overrideMimeType) {
//                ajaxGlobalRequest.overrideMimeType('text/xml');
//           }
     } else if (window.ActiveXObject) {
          // For browsers: IE, version 6 and before, use another model
          try {
               ajaxGlobalRequest = new
                    ActiveXObject("Msxml2.XMLHTTP");
          } catch (e) {
               try {
                    ajaxGlobalRequest = new
                         ActiveXObject("Microsoft.XMLHTTP");
               } catch (e) {}
          }
     }
     // Make sure the request object is valid
     if (!ajaxGlobalRequest) {
          alert('AJAX ERROR: Cannot create XMLHTTP object');
          return false;
     }
     // Link to display function activated when result returned
     if (myAjaxCallbackFuncName=='') myAjaxCallbackFuncName = 'ajaxAsyncDisplayReturn';
     eval('ajaxGlobalRequest.onreadystatechange = '+myAjaxCallbackFuncName+';');
     // Open the URL request
     if (requestPostParams==null) {
	     ajaxGlobalRequest.open('get', myURL, true);	//	ASYNC (no waiting mode)
     } else {
	     ajaxGlobalRequest.open('post', myURL, true);	//	ASYNC (no waiting mode)
     }
     // Send request
     if (requestPostParams==null) {
	     if (requestHeaderContentType==null) ajaxGlobalRequest.setRequestHeader("Content-Type","text/html; charset=utf-8");
	     ajaxGlobalRequest.send(null);
     } else {
	     ajaxGlobalRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	     ajaxGlobalRequest.setRequestHeader("Content-Length", requestPostParams.length);
	     ajaxGlobalRequest.setRequestHeader("Connection", "close");
	     ajaxGlobalRequest.send(requestPostParams);
     }
     return true;	//	ajaxGlobalRequest.responseText
}

function ajaxAsyncDisplayReturn () {
	// Check to make sure result came through, 4=complete
	if (ajaxGlobalRequest.readyState == 4) {
		// Check HTTP status code
		if (ajaxGlobalRequest.status == 200) {
			// Display the responseText
			alert(ajaxGlobalRequest.responseText);
		} else {
			alert('AJAX ERROR: There was a problem with the request.');
		}
	}
}

function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B);}
function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}


function js_comma_to_dot( text ) {
    text = text.toString();
    var pattern = new RegExp("\,");
	return no_comma = text.replace( pattern, "." );
}

// preklad pomocou TRANSLATE kniznice  MODE >> input/textarea/sef
// podporovane langy https://docs.microsoft.com/en-us/azure/cognitive-services/translator/languages
function jf_translate_field( elem, container, lang, margin_left, mode, prevAll ) {

	// kod na ziskanie langov z microsoft webu ...
	/*jQuery("#main > div:nth-child(6) > table > tbody").find("code").each(function() {
		a.push(jQuery(this).html());
	});*/
	if (typeof(mode) == "undefined")
		mode = '';

	prevAll = prevAll || false;

	var tmp_at = false;

	// redefine language iso podla podporovanych jazykov jquery.translate
	if ( lang == 'cz') {
		lang = 'cs';
	} else if ( lang == 'at' ) {
		lang = 'de';
		tmp_at = true;
	} else if ( lang == 'si') {
		lang = 'sl';
	} else if (lang == 's2' || lang == 's3') {
		tmp_sk = lang;
		lang = 'sk';
	} else if (lang == 'c2') {
		tmp_cz = lang;
		lang = 'cs';
	}

	var alloved_lang_codes = [
		"af", "ar", "apc", "bn", "bs", "bg", "yue", "ca", "zh-Hans", "zh-Hant", "hr", "cs",
		"da", "nl", "en", "et", "fj", "fil", "fi", "fr", "de", "el", "ht", "he", "hi", "mww",
		"hu", "is", "id", "it", "ja", "sw", "tlh", "tlh-Qaak", "ko", "lv", "lt", "mg", "ms",
		"mt", "nb", "fa", "pl", "pt", "otq", "ro", "ru", "sm", "sr-Cyrl", "sr-Latn", "sk",
		"sl", "es", "sv", "ty", "ta", "te", "th", "to", "tr", "uk", "ur", "vi", "cy", "yua"
	];

	if (alloved_lang_codes.indexOf(lang) == -1) {
		lang = "en";
	}


	if (typeof(console) != 'undefined') console.log('typeof(mode)',typeof(mode));

	var elem_type = 'input';
	if ( mode == 'textarea' )
		elem_type = 'textarea';

	elem = jQuery(elem);

	var container = elem.parents(container+':first');
	var dest_elem = elem.prev(elem_type);

	if (prevAll) {
		dest_elem = elem.prevAll(elem_type);
	}

	var dest_parent = dest_elem.parents();
	var dest_name = dest_elem.attr('name');
	var translated;

	var nameAttr = dest_elem.attr('name') || '';
	var source_elem = nameAttr.substr(0, (nameAttr.length - 3));

	if ( typeof js_Config_menu_type_blog_separated !== 'undefined' && js_Config_menu_type_blog_separated ) {
		translated = container.find('[name='+source_elem+']:visible').val();
	} else {
		translated = container.find('[name='+source_elem+']').val();
	}

	if ( typeof js_Config_product_special_category_translate_field_fix !== 'undefined' && js_Config_product_special_category_translate_field_fix && typeof translated == 'undefined') {
		if ( source_elem.indexOf('new') == 0 ) {
			source_elem = source_elem.substr(4, source_elem.length);
		}
		translated = container.find('[name='+source_elem+']').val();
	}


	if ( mode == 'sef' ) {
		translated = translated.replace('/', ' ');
		var dest_sef_val = dest_elem.val();
		if ( dest_sef_val == '//' || dest_sef_val == '' ) {}
		else {
			if (typeof(console) != 'undefined') console.log('return jf_translate_field()',dest_sef_val);
			return;
		}
	}

	if (typeof(console) != 'undefined') console.log('container:', container);

	if (translated != '') 	{
		elem.before('<img class="ajax-loader" src="'+js_global_live_site+'/images/ajax-loader-05-14x14.gif" style="position:absolute; margin-left: '+margin_left+'px; margin-top: 3px;"/>');
		dest_elem.val('');

		var local_js_curr_lang = js_curr_lang;
		if (local_js_curr_lang == 'cz') {
			local_js_curr_lang = 'cs';
		} else if (local_js_curr_lang == 'at') {
			local_js_curr_lang = 'de';
		} else if (local_js_curr_lang == 's2' || local_js_curr_lang == 's3') {
			local_js_curr_lang = 'sk';
		} else if (local_js_curr_lang == 'c2') {
			local_js_curr_lang = 'cs';
		}

		if (lang == local_js_curr_lang) {
			//stopneme loader
			dest_parent.children('.ajax-loader').remove();

			if (container.children().find('[name='+dest_name+']').length != 0) {
				container.children().find('[name='+dest_name+']').val(translated).addClass('changed').trigger('keyup').trigger('blur').trigger('focus');
			} else {
				container.children('[name='+dest_name+']').val(translated).trigger('focus');
			}

			// re-make sef
			if (lang == 'sk' && typeof tmp_sk !== 'undefined') {
				lang = tmp_sk;
			} else if (lang == 'cs') {
				if (typeof tmp_cz !== 'undefined') {
					lang = tmp_cz;
				} else {
					lang = 'cz';
				}
			} else if (lang == 'de' && tmp_at) {
				lang = 'at';
			}

			if (mode != 'no_sef') {
				try {
					js_update_categ_sef_name_input(container.attr('id'), lang );
				} catch (e) {
					if (typeof(console) != 'undefined' && is_cs_user() ) console.log('catchERR:',e);
				}
			}
		} else {
			if(typeof js_Config_google_cloud_translation_in_administration !== 'undefined' && js_Config_google_cloud_translation_in_administration) {
				//google cloud translation

				if (typeof translated !== 'undefined') {
					new AjaxRequest({"text": translated, "from": local_js_curr_lang, "to": lang})
						.setMethod('POST')
						.setController('Admin')
						.setAction('getGoogleTranslation')
						.onSuccess(function (response) {
							//stopneme loader
							dest_parent.children('.ajax-loader').remove();
							//prelozeny text umiestnime do textarea / inputu
							if (typeof response.data.translation !== 'undefined') {

								if ( container.children().find('[name='+dest_name+']').length != 0 ) {
									container.children().find('[name='+dest_name+']').val(response.data.translation).addClass('changed').trigger('keyup').trigger('blur').trigger('focus');
								} else {
									container.children('[name='+dest_name+']').val(response.data.translation).trigger('focus');
								}

								// re-make sef
								if (lang == 'sk' && typeof tmp_sk !== 'undefined') {
									lang = tmp_sk;
								} else if (lang == 'cs') {
									if (typeof tmp_cz !== 'undefined') {
										lang = tmp_cz;
									} else {
										lang = 'cz';
									}
								} else if (lang == 'de' && tmp_at) {
									lang = 'at';
								}

								if ( mode != 'no_sef' ) {
									try {
										js_update_categ_sef_name_input(container.attr('id'), lang );
									} catch (e) {
										if (typeof(console) != 'undefined' && is_cs_user() ) console.log('catchERR:',e);
									}

								}
							}
						})
						.onError(function(jsonData) {
							dest_parent.children('.ajax-loader').remove();
							if (jsonData && jsonData.errors) {
								showNotification(jsonData.errors.join(' '), 'Google Cloud Translation API', 'error');
							}
						})
						.send();
				}
			} else {
				//bing translate

				var p = {};
				p.appid = 'A4E71E156D495ECB110138FFFDE4159C57447BEE';
				p.to = lang;
				p.from = local_js_curr_lang;
				p.text = translated;
				jQuery.ajax({
					url: '//api.microsofttranslator.com/V2/Ajax.svc/Translate',
					data: p,
					dataType: 'jsonp',
					jsonp: 'oncomplete',
					success: function(data) {
						dest_parent.children('.ajax-loader').remove();

						if ( container.children().find('[name='+dest_name+']').length != 0 ) {
							container.children().find('[name='+dest_name+']').val(data).addClass('changed').trigger('keyup').trigger('blur').trigger('focus');
						} else {
							container.children('[name='+dest_name+']').val(data).trigger('focus');
						}

						// re-make sef
						if (lang == 'sk' && typeof tmp_sk !== 'undefined') {
							lang = tmp_sk;
						} else if (lang == 'cs') {
							if (typeof tmp_cz !== 'undefined') {
								lang = tmp_cz;
							} else {
								lang = 'cz';
							}
						} else if (lang == 'de' && tmp_at) {
							lang = 'at';
						}

						if ( mode != 'no_sef' ) {
							try {
								js_update_categ_sef_name_input(container.attr('id'), lang );
							} catch (e) {
								if (typeof(console) != 'undefined' && is_cs_user() ) console.log('catchERR:',e);
							}

						}
					}
				});
			}
		}



		return false;

		/*
		// GOOGLE TRANSLATE
		jQuery.translate( translated, lang, {	// js_curr_lang
		  complete: function(translation){
			if (typeof(console) != 'undefined') console.log('translation',translation);
			if ( mode == 'sef' ) {
				translation = '/' + translation + '/';
				translation = translation.replace(' ','-');
				translation = translation.replace('//','/');

			}

			dest_parent.children('.ajax-loader').remove();

			if ( container.children().find('[name='+dest_name+']').length != 0 )
				container.children().find('[name='+dest_name+']').val(translation).blur().focus();
			else
				container.children('[name='+dest_name+']').val(translation).focus();

			// re-make sef
			if ( lang == 'cs')
				lang = 'cz';

			if ( mode != 'no_sef' ) {
				js_update_categ_sef_name_input(container.attr('id'), lang );
			}
		  }
		});*/


	}

  return false;
}

function jf_translate_all_fields(elem, container, elem_name) {
	elem = jQuery(elem);
	container_obj = jQuery(container);
	container_obj.children().find('input').each(function(){
			var input_elem = jQuery(this);
			input_elem.next('img').trigger('click');
	});

	// reload menu poloziek pri uprave
	if (container == '#categ_edit_panel_content') {
		//js_update_menu_sef_name_input(container.replace('#','') );
		jQuery(jf_langs).each(function(i,val){
				var sef_value = container_obj.children().find('[name=menu_item_sef_'+val+']').val();
				if (typeof(elem_name)!="undefined") {
					sef_value = container_obj.children().find('[name=category_sef_name_'+val+']').val();
				}

				if (typeof(console) != 'undefined') console.log('sef_value',sef_value);

				if (sef_value == '' || sef_value == '//') {
					js_update_menu_sef_name_input(container.replace('#',''), val );
					//container_obj.children().find('input')
					setTimeout("js_check_input_sef_name( '"+container+"', 'menu_item_sef_"+val+"')", 1000);
				}
		});
	}

	js_update_categ_sef_name_input(container_obj.attr('id'));
	return false;
}



function js_function_vex_open(data) {
	var options = jQuery.extend({}, {
		title: '',
		input: '',
		buttons: '',
		afterOpen: function(vexContent) { }
	}, data);

	vex.open({
		className: options.className,
		content  : [
			'<form class="vex-dialog-form">',
			(options.title == '') ? '' : [
				'<div class="vex-dialog-message">',
				'<span class="login-title">',
				options.title,
				'</span>',
				'</div>'
			].join(''),
			(options.input == '') ? '' : [
				'<div class="vex-dialog-input" style="padding-top: 1.5em;">',
				options.input,
				'</div>'
			].join(''),
			(options.buttons == '') ? '' : [
				'<div class="vex-dialog-buttons">',
				options.buttons,
				'</div>'
			].join(''),
			'</form>'
		].join(''),
		afterOpen: function (vexContent) {
			if (typeof options.afterOpen === 'function') {
				options.afterOpen(vexContent);
			}
		}
	});
}
function hexc(colorval) {
	var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	if (typeof parts === 'undefined' || parts === null) {
		return;
	}
	delete (parts[0]);
	for (var i = 1; i <= 3; ++i) {
		parts[i] = parseInt(parts[i]).toString(16);
		if (parts[i].length === 1) {
			parts[i] = '0' + parts[i];
		}
	}
	return '#' + parts.join('');
}
// Scroll to top button content new
function js_scroll_top_content_new() {
	var enableScrollToTopButton = true;  // pripadne dodefinovanie
	if (!enableScrollToTopButton === true) {
		return false;
	}
	var scroll_top_el = jQuery('.scroll_to_top_content_new');

	if ( !scroll_top_el.length ) { return; }

	scroll_top_el.on('click', function () {
		jQuery('html,body').animate({scrollTop: 0}, 300);
	});
	jQuery(window).on('scroll.to_top',function(){
		if (jQuery(window).scrollTop() > 300){
			scroll_top_el.fadeIn(200);
		}
		else {
			scroll_top_el.fadeOut(200);
		}
	}).trigger('scroll.to_top');
}

jQuery(function() {
	js_scroll_top_content_new();

	var $themeColorDiv = jQuery("meta[name='theme-color']");
	if ( $themeColorDiv.length > 0 && Cookies.get('themeColor') === undefined ) {
		var colorDivs = jQuery('#menu_div, #header, .button:first');
		colorDivs.each(function (key, item) {
			item = jQuery(item);

			if (typeof item !== 'undefined') {
				var themeColorRgb = item.css('background-color');

				if (typeof themeColorRgb !== 'undefined' && themeColorRgb !== '') {
					var themeColorHex = hexc(themeColorRgb);

					if ( typeof themeColorHex !== 'undefined' ) {
						Cookies.set('themeColor', themeColorHex, { path: '/' });

						$themeColorDiv.attr('content', themeColorHex);
						jQuery("meta[name='msapplication-navbutton-color']").attr('content', themeColorHex);

						return false;
					}
				}
			}
		});
	}

	if (typeof js_config_enable_article_modal === 'boolean' && js_config_enable_article_modal){
		jQuery(document).on('click', 'a[rel="vex"]', function(event) {
			event.preventDefault();

			var $me = jQuery(this);

			jQuery.ajax({
				url: $me.attr('href'),
				method: 'GET',
				success: function(data) {
					var content = jQuery(data).find('#middle_content_inner');

					if (content.length > 0 && content.text().trim() !== '') {

						js_function_vex_open({
							input: content.html(),
							afterOpen: function(vexContent) {
								vexContent.css({
									width: '95%',
									maxWidth: '1200px'

								}).closest('.vex').addClass('flypage_vex');
							}
						});

					} else {
						window.location.href = $me.attr('href');
					}
				}
			});

			return false;
		});
	}
});

function jf_translate_textarea(elem, lang, source_elem, dest_elem) {

	//google cloud translation
	if(typeof js_Config_google_cloud_translation_in_administration !== 'undefined' && js_Config_google_cloud_translation_in_administration) {
		var elemContainer       = jQuery(elem).parent();
		var translateContainer  = elemContainer.parents('fieldset:first');
		//ziskame statistiku
		new AjaxRequest()
			.setMethod('POST')
			.setController('Admin')
			.setAction('getGoogleTranslationStats')
			.onSuccess(function (response) {
				if ( typeof js_Config_blog_textarea_translate_button_fix !== 'undefined' && js_Config_blog_textarea_translate_button_fix) {
					if (translateContainer.length < 1) {
						translateContainer = jQuery(source_elem).parents('.admin_add_content_form');
					}
				} else {
					if (translateContainer.length < 1) {
						translateContainer = elemContainer.parent().parent();
					}
				}

				source_elem = translateContainer.find(source_elem);
				dest_elem   = translateContainer.find(dest_elem);

				//pripravime text pre vex
				var vexContent = '<br>'+
					'<span style="display:block;width: 360px" >'+
					'    <span class="cs_icon csi-bar-chart csi_c_black" style="font-size: 19px"></span>'+
					'    <span style="font-weight: bold; font-size:19px; text-transform: uppercase;">'+cms_js_lang_admin_google_cloud_label_1+'</span>'+
					'</span>'+
					'<br>'+
					'<br>'+
					'<table style="text-align: center;border-collapse: collapse;">'+
					'    <tr style="border-bottom: 1px solid #8e8e8e">'+
					'        <th style="padding: 5px 30px">'+cms_js_lang_admin_google_cloud_label_2+'</th>'+
					'        <th style="padding: 5px 30px;">'+cms_js_lang_admin_google_cloud_label_3+'</th>'+
					'        <th style="padding: 5px 30px;">'+cms_js_lang_admin_google_cloud_label_4+'*</th>'+
					'    </tr>';

				//statistiky za posledne 3 mesiace
				if (typeof response.data.statistic !== 'undefined' && Object.keys(response.data.statistic).length) {
					jQuery.each(response.data.statistic, function(i,v){
						vexContent += '<tr style="border-top: 1px solid #8e8e8e">'+
							'    <td style="padding: 5px 30px">'+v.year+'</td>'+
							'    <td style="padding: 5px 30px;">'+v.month+'</td>'+
							'    <td style="padding: 5px 30px;text-align: right;">'+parseFloat(v.count).toLocaleString()+'</td>'+
							'</tr>';
					});
				} else {
					var currentDate = new Date();
					vexContent += '<tr style="border-top: 1px solid #8e8e8e">'+
						'    <td style="padding: 5px 30px">'+currentDate.getFullYear()+'</td>'+
						'    <td style="padding: 5px 30px;">'+(currentDate.getMonth() + 1)+'</td>'+
						'    <td style="padding: 5px 30px;text-align: right;">0</td>'+
						'</tr>';
				}

				//vyzva na preklad
				vexContent += '</table>'+
					'<br>'+
					'<span style="width: 350px;display:block;">'+
					'    <i>* '+cms_js_lang_admin_google_cloud_label_5+'</i>'+
					'</span>'+
					'<br>'+
					'<br>'+
					'<span style="font-size: 19px;width: 360px;display:block;">'+
						cms_js_lang_admin_google_cloud_label_6+' <span style="font-weight: bold">'+parseFloat(source_elem.val().length).toLocaleString()+'</span> '+cms_js_lang_admin_google_cloud_label_7+
					'</span>'+
					'<img style="padding:10px 0px;" src="/components/com_joomfish/images/translated-by-google.svg">';


				//otvorime vex
				vex.dialog.confirm({
					className: 'vex-cs',
					message: '<span style="font-weight: bold">'+cms_js_lang_admin_google_cloud_label_8+'</span> (Cloud Translation API)',
					input: vexContent,
					buttons: [
						jQuery.extend({}, vex.dialog.buttons.NO, {text: cms_js_lang_products_group_3}),
						jQuery.extend({}, vex.dialog.buttons.YES, {
							text: cms_js_lang_admin_google_cloud_label_9,
							click: function() {

								if (typeof source_elem.val() !== 'undefined') {
									//zavolame preklad
									new AjaxRequest({"text": source_elem.val(), "from": js_curr_lang, "to": lang})
										.setMethod('POST')
										.setController('Admin')
										.setAction('getGoogleTranslation')
										.onSuccess(function (response) {
											//prelozeny text umiestnime do textarea / inputu
											if (typeof response.data.translation !== 'undefined') {
												dest_elem.val(response.data.translation);
											}
										})
										.send();
								}
							}
						})
					]
				});

			})
			.send();

		return false;
	}


	vex.dialog.alert({
		className: 'vex-cs',
		message: '',
		input: 'Externá bezplatná služba na prekladanie textov je aktuálne nedostupná.<br>Použite manuálny a bezplatný režim pomocou: <a href="https://translate.google.com/">translate.google.com</a><br><br>V prípade záujmu existuje alternatívna možnosť implementácie spoplatnenej Google Translate API.',
		buttons: [
			jQuery.extend({}, vex.dialog.buttons.NO, {text: cms_js_lang_products_group_3}),
			jQuery.extend({}, vex.dialog.buttons.YES, {
				text: 'Mám záujem o alternatívu',
				click: function(elm) {
					window.open('mailto:info@creativesites.sk?subject=' + encodeURI('Máme záujem o preklady cez Google Translate API') + '&body=' + encodeURI('Dobrý deň,\n\nmáme záujem o preklady cez Google Translate API pre https://' + js_global_main_domain + '\n\nĎakujeme :-)'));
				}
			})
		]
	});

	return false;
}

function js_admin_translate_content_save(elem) {
	elem = jQuery(elem);

	var translate_html = js_make_clean_translated_value( elem.parents('.vex-content:first').find('.translate_html').html() );
	var dest_elem = jQuery('.t-data').data('dest_elem');

	dest_elem.val(translate_html);
	vex.close();

	return false;
}



function js_make_clean_translated_value(ret) {
	if (typeof(ret) != 'undefined' && ret != null && ret.length > 0)
		return ret.replace(/\<\/?font\s*[^\>]*\>/gi, '');
// 		return ret.replace(/<font>/gi, '').replace(/<\/font>/gi, '').replace(/<font class="">/gi, '');

	return '';
}

function js_check_input_sef_name(container, input_name) {
	//if (typeof(console) != 'undefined') console.log('input_name',input_name);
	container = jQuery(container);
	input_elem = container.children().find('input[name='+input_name+']');
	var sef_value = input_elem.val().replace(/\/{2,}/g, '/').split('/');

	//if (typeof(console) != 'undefined') console.log('sef_value', sef_value);

	var options = { 'sef_name': sef_value };

	jQuery.post(js_global_live_site+'/administrator/components/com_shop/html/frontend.edit_category.php?option=com_shop&ajax_call=1&ajax_func=make_sef_name&no_html=1&no_vm_html=1&no_menu=1&no_css=1', options, function (res) {
		//if (typeof(console) != 'undefined') console.log('make_sef_name', input_elem, res);

		if (res == '0') {
			//alert('ERR: system_functions.js > fcia js_check_input_sef_name()');
			return;
		}

		input_elem.val( res );
	});
}

function js_bindQQFileUploader( json_params, json_ret_info ) {
	//	'element_id': file_upload_selector_container-mosCreateGUID()
	//	'action': '/administrator/components/com_shop/html/frontend.edit_category.php'
	//	'params': { 'option': 'com_shop', 'ajax_call': '1', 'ajax_func': 'upload_category_full_image', 'no_html': '1', 'no_vm_html': '1', 'no_menu': '1', 'no_css': '1', 'category_id': < ? php echo $req_category_id; ? > }
	//	'allowedExtensions': ['jpg', 'jpeg', 'png', 'gif'],
	//	'onComplete': function( id, fileName, json_res )
	ret = false;
	if (js_is_valid_json(json_params, {'element_id': null, 'action': null, 'params': null, 'onComplete': null})) {
		var element_id = json_params.element_id;
		var jqo_element = jQuery('#'+element_id);
		if (jqo_element.length == 1) {
			var jso_element = jqo_element.get(0);
			if (jso_element) {
				var uploader = new qq.FileUploader({
					element: jso_element,
					action: json_params.action,
					allowedExtensions: (typeof(json_params.allowedExtensions) != 'undefined' && json_params.allowedExtensions ? json_params.allowedExtensions : ['jpg', 'jpeg', 'png', 'gif']),
					params: json_params.params,
					onSubmit: function( id, fileName ) {
						jqo_element.find('.qq-upload-list li').remove();
					},
					onComplete: json_params.onComplete,
					debug: 0 && js_global_is_csu,
					multiple: (typeof(json_params.multiple) != 'undefined' && json_params.multiple ? json_params.multiple : false)
				});

				if (1 || js_global_is_csu) {
					if (typeof(console) != 'undefined') console.log('GREDXuploader:',uploader);
				}

				setTimeout("jQuery('.full_img_container #"+element_id+"').find('.qq-upload-button').css('left','0px');", 500);
				if (json_ret_info != null && typeof(json_ret_info) == 'object') {
					json_ret_info.result = ret;
				}
				ret = true;
			} else {
				if (json_ret_info != null && typeof(json_ret_info) == 'object') {
					json_ret_info.result = ret;
					json_ret_info.msg = 'jso_element is: null';
				}
			}
		} else {
			if (json_ret_info != null && typeof(json_ret_info) == 'object') {
				json_ret_info.result = ret;
				json_ret_info.msg = 'jqo_element.length is: '+jqo_element.length;
			}
		}
	} else {
		if (json_ret_info != null && typeof(json_ret_info) == 'object') {
			json_ret_info.result = ret;
			json_ret_info.msg = 'js_is_valid_json(json_params) is: false';
		}
	}
	return ret;
}

function js_get_editor_templates() {
	var result = [];

	if (typeof ckeditor_custom_tmp == 'undefined' || ckeditor_custom_tmp == 0) return result;

	jQuery.ajax({
		url: js_global_live_site + '/public_scripts_M4r7ft/global_scripts/product_actions.php?',
		method: 'POST',
		data: {
			option: 'com_shop',
			ajax_call: 1,
			ajax_func: 'get_editor_templates',
			no_html: 1,
			no_vm_html: 1,
			no_menu: 1,
			no_css: 1
		},
		async: false,
		success: function (res) {
			result = JSON.parse(res);
		}
	});
	return result;
}

function admin_panel_cke_post_init( textarea_name ) {
    //	spolocne volana funkcia, po zobrazeni ckeditora
    if (typeof js_dont_use_ckeditor_4_5_0 === 'undefined') {
    	js_bind_jwmmxtd_on_cke_containers2(textarea_name);
    } else {
	    js_bind_jwmmxtd_on_cke_containers(textarea_name);
    }
}

function js_bind_jwmmxtd_on_cke_containers( textarea_name ) {
	//	pri zadanom textarea_name prida prislusnej arei tlacitko na start jwmmxtd
	//	inak existujucim aream s ck-editorom prida tlacitko na start jwmmxtd

	// JAN, 3.10.2016 toto nie je dobre Quickfix, treba to poriesit inak
	return false;

	if (typeof(js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb) === 'undefined') js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb = 0;
	var container_selector = (textarea_name != null) ? ('span#cke_'+textarea_name+'.cke_editor_'+textarea_name) : ('span[id^="cke_"][class^="cke_"]');

	if (jQuery(container_selector+':first').length == 0) {
		js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb = js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb + 1;
		if (js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb < 21) setTimeout('js_bind_jwmmxtd_on_cke_containers('+((textarea_name != null) ? ('"'+textarea_name+'"') : '')+');', 250);	//	timeout 5 sec.
		return false;
	}

	jQuery(container_selector).each(function (idx, jso) {
		var jqo = jQuery(jso);
		if (jQuery('textarea#'+jqo.attr('id').substr(4)+', textarea[name="'+jqo.attr('id').substr(4)+'"]').length > 0 && jqo.find('a.'+jqo.attr('id')+'_jwmmxtd').length == 0) {
			var jqo_cke_toolgroup = jQuery('span#'+jqo.attr('id')+' span.cke_toolbar span.cke_toolgroup span.cke_button a.cke_button_image:first').parents('span.cke_toolgroup:first');
			jqo_cke_toolgroup.append('<span class="cke_button"><a href="/administrator/index2.php?option=com_media&jwmmxtd_template_refresh=1&iframe=true&width=1040&height=700" class="cke_off cke_button_jwmmxtd '+jqo.attr('id')+'_jwmmxtd" title="'+cms_adminlang_mod_fullmenu_swe_mediamanag+'"><span class="cke_icon">&nbsp;</span><span class="cke_label">'+cms_adminlang_mod_fullmenu_swe_mediamanag+'</span></a></span>');
			jqo_cke_toolgroup.find('span.cke_button a.cke_button_jwmmxtd:first').prettyPhoto({
				'show_title':false,
				'allow_resize':false,
				'modal':true,
				'theme':'facebook',
				changepicturecallback: function() {
				jQuery('body > .pp_pic_holder:last').css('z-index', '10002');	//	kvoli poshytipu.. bleee
				var jqo_pp_full_res = jQuery('body > .pp_pic_holder:last #pp_full_res:first');
				if (jqo_pp_full_res && jqo_pp_full_res.length > 0) {
					jqo_pp_full_res.find('iframe').attr('width', parseInt(jqo_pp_full_res.find('iframe').attr('width')) - 10);
					jqo_pp_full_res.append('<div class="cs_prettyphoto_close"><a href="#" onclick="return js_prettyphoto_close();" title="'+cms_js_lang_close+'"><img src="/includes/js/jquery/prettyphoto/images/closelabel.png" alt="X"/></a></div>');
				}
				  jQuery(document).on('keyup', function(event) {
					if ( event.keyCode == 27 ) {

					  if ( in_tooltip == 1 ) {
						js_product_special_groups_closed( in_tooltip );
					  }
					  else {
						js_prettyphoto_close();
					  }
					}
				  });
				}
			  });
		}
	});
	js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb = 0;
	return true;
}

function js_bind_jwmmxtd_on_cke_containers2( textarea_name ) {
	if (typeof(js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb) === 'undefined')
		js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb = 0;

	var container_selector = (textarea_name != null) ? ('div#cke_'+textarea_name+'.cke_editor_'+textarea_name) : ('div[id^="cke_"][class^="cke_"]');

// 	console.log(container_selector);

	if (jQuery(container_selector+':first').length == 0) {
		js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb = js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb + 1;
		if (js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb < 21) setTimeout('js_bind_jwmmxtd_on_cke_containers('+((textarea_name != null) ? ('"'+textarea_name+'"') : '')+');', 250);	//	timeout 5 sec.
		return false;
	}

	jQuery(container_selector).each(function (idx, jso) {
		var jqo = jQuery(jso);
		if (jQuery('textarea#'+jqo.attr('id').substr(4)+', textarea[name="'+jqo.attr('id').substr(4)+'"]').length > 0 && jqo.find('a.'+jqo.attr('id')+'_jwmmxtd').length == 0) {
			var jqo_cke_toolgroup = jQuery('div#'+jqo.attr('id')+' span.cke_toolbar span.cke_toolgroup a.cke_button__image:first').parents('span.cke_toolgroup:first');

			if ( typeof js_Config_ckeditor_v4_19 != 'undefined' && js_Config_ckeditor_v4_19 ) {
				jqo_cke_toolgroup.append('<a href="/administrator/index2.php?option=com_media&jwmmxtd_template_refresh=0" target="_blank" class="cke_button cke_button_off cke_button_jwmmxtd '+jqo.attr('id')+'_jwmmxtd" title="'+cms_adminlang_mod_fullmenu_swe_mediamanag+'"><span class="cke_button_icon cke_button__button_icon">&nbsp;</span><span class="cke_button_label">'+cms_adminlang_mod_fullmenu_swe_mediamanag+'</span></a>');
			} else {
				jqo_cke_toolgroup.append('<a href="/administrator/index2.php?option=com_media&jwmmxtd_template_refresh=0" target="_blank" class="cke_button cke_button_off cke_button_jwmmxtd '+jqo.attr('id')+'_jwmmxtd" title="'+cms_adminlang_mod_fullmenu_swe_mediamanag+'"><span class="cke_button_icon">&nbsp;</span><span class="cke_button_label">'+cms_adminlang_mod_fullmenu_swe_mediamanag+'</span></a>');

			}

		}
	});
	js_internal_counter_f0b7de8b3a88b0788aa6b348ac4ebbeb = 0;
	return true;
}

function js_strip_alowed_tags(input, allowed) {
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}

function js_strip_tags(input) {
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, '');
}

// BING TRANSLATE
function ajaxTranslate(textToTranslate, fromLanguage, toLanguage) {
	var p = {};
	p.appid = 'A4E71E156D495ECB110138FFFDE4159C57447BEE';
	p.to = toLanguage;
	p.from = fromLanguage;
	p.text = textToTranslate;
	jQuery.ajax({
		url: '//api.microsofttranslator.com/V2/Ajax.svc/Translate',
		data: p,
		dataType: 'jsonp',
		jsonp: 'oncomplete',
// 		jsonpCallback: 'ajaxTranslateCallback',
// 		complete: function(request, status) {
// 			alert('complete: '+status);
// 		},
		success: function(data, status) {
			alert('success: data-'+data+',status-'+status);
		} //,
// 		error: function(request, status, error) {
// 			alert('error: status-'+status+',desc-'+error);
// 		}
	});
}

function ajaxTranslateCallback(response) {
	alert('ajaxTranslateCallback('+response+')');
}

function jsGetJSON( json_text, required_vars ) {
	//	funkcia vrati JSON object zo stringovej formy (json_encode)
	//	v pripade ze required_vars je pole (nazvov premennych), musi objekt obsahovat tieto premenne
	//	chyby su osetrene, v pripade chyby vracia null
	var ret = null;
	if (json_text > '') {
		try {
			eval('ret = ' + json_text + ';');
			if (ret != null && required_vars != null) {
				jQuery.each(required_vars, function (i, u) {
					if (typeof(ret[u]) == 'undefined') {
						ret = null;
						return false;
					}
					return true;
				});
			}
		} catch( jso_err ) {
			ret = null;
		}
	}
	return ret;
}

function js_module_edit_categ_list_click(elem) {
	elem = jQuery(elem);

	if (elem.find('option:selected').length)
		elem.parents('.module_display_list_categories:first').find('.module_prod_show_container input, .module_prod_show_container label').fadeIn(300);
	else
		elem.parents('.module_display_list_categories:first').find('.module_prod_show_container input, .module_prod_show_container label').fadeOut(300);
}

function is_valid_email(email) {
	//return !(email == '' || /^[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,}$/i.exec(email) == null );
	var re = new RegExp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,63}$');
	return re.test(email);
}

/**
 * Validates whether phoneNumber contains only allowed characters
 * @param phoneNumber {String}
 * @returns {boolean}
 */
function is_valid_phone_number(phoneNumber) {
	if ( is_cs_user('new_phone_validation') && typeof js_CS_Config_new_phone_validation !== 'undefined' && js_CS_Config_new_phone_validation ) {
		if ( typeof phoneNumber === 'undefined' || phoneNumber == '' ) return false;

		return RegExp('^[+]*[-0-9\s–\/]+$').test(phoneNumber); // 15 povolenych znakov: 0-9, +, [space], /, -, –

	} else {
		if ( typeof phoneNumber === 'undefined' || phoneNumber == '' ) return false;

		return !RegExp(/[^-–\/+\s0-9]/g).test(phoneNumber); // 15 povolenych znakov: 0-9, +, [space], /, -, –
	}
}

/**
 * Validates whether phoneNumber is of correct length (at least 6 digits)
 * @param phoneNumber {String}
 * @param length {Number}
 * @returns {boolean}
 */
function is_correct_length_phone_number(phoneNumber, length) {
	if ( typeof phoneNumber === 'undefined' || phoneNumber == '' ) { return false; }

	var matches = phoneNumber.match(/[0-9]/g);

	if (matches === null) { return false; }

	return matches.length >= (length || 6);
}

// CENY
function js_remove_right_zeros( price ) {
	price = price.toString();

	if ( price.indexOf('.') == -1 ) {
		return price;
	}

	var zero_index = -1;

	for ( var i = price.length - 1; i >= 0; i-- ) {

		if ( price[i] != '0' ) {
			break;
		}

		zero_index = i;
	}

	if ( zero_index == -1 ) {
		return price;
	}

	price = price.substr(0, zero_index);

	if ( price.substr(-1) == '.' ) {
		price = price.substr(0, price.length - 1);
	}

	return price;
}

function js_jq_remove_right_zeros_from_input( input_element ) {
	input_element = jQuery(input_element);

	input_element.attr('value', js_remove_right_zeros(input_element.val()));
}

function js_remove_not_numeric(elem) {
	var e = jQuery(elem);
	var r = /\.[0-9]{0,}[.,]/;
	while (r.test(e.val())) e.val(e.val().substr(0, e.val().length - 1));

	r = /\,/;
	e.val(e.val().replace(r, '.'));
	e.val(e.val().replace(/(?!^)[\+\-]/g, ''));

	r = /[^0-9\.\+\-]/g;
	e.val(e.val().replace(r, ''));

	r = /[0-9]/;
	if (!r.test(e.val())) e.val('');
}

function js_set_element_changed(elem) {
	jQuery(elem).addClass('elem_changed');
}


function js_jq_update_price_gross( jqo_price_net, jqo_tax_rate, jqo_price_gross, decimals, remove ) {
	remove = typeof remove !== 'undefined' ? remove : true;
	decimals = typeof decimals !== 'undefined' ? parseInt(decimals) : 2;

	var rates = (typeof _product !== 'undefined' ? _product.options.tax_rates : 0);

	if( jqo_price_net.val() != '' ) {

		js_remove_not_numeric(jqo_price_net);

		var grossValue = jqo_price_net.val();

		var taxRate;
		if (typeof(jqo_tax_rate) != 'object')
			taxRate = parseFloat(jqo_tax_rate);
		else
			taxRate = rates[jqo_tax_rate.val()];

		if ( typeof js_Config_VM_direct_prices_editing_for_shopper_group !== "undefined" ) {
			$tmp_sgp = jqo_price_net.parents('.pp_other_price_content').find('select.pp_op_shopper_group_select option:selected').val();

			if (typeof js_Config_VM_direct_prices_editing_for_shopper_group !== "undefined" && typeof js_Config_VM_direct_prices_editing_for_shopper_group[$tmp_sgp] !== "undefined" && js_Config_VM_direct_prices_editing_for_shopper_group[$tmp_sgp].dph !== '') {
				taxRate = parseFloat(js_Config_VM_direct_prices_editing_for_shopper_group[$tmp_sgp].dph);
			}
		}

		if (taxRate > 0) grossValue = grossValue * (taxRate + 1);

		var price = doRound(grossValue, decimals);

		price = remove ? js_remove_right_zeros(price) : parseFloat(price).toFixed(decimals);

		if (grossValue == '') {
			jqo_price_gross.val('');
		} else {
			jqo_price_gross.val(price);
		}

		var cn = jqo_price_net['0'].className;
		var ppsgid = jqo_price_net.parents('.pp_other_price_content').find('.pp_op_shopper_group_select').val();
		var sgdis = 1 - ((typeof(phsg) != 'undefined' && ppsgid != 0 ? phsg[ppsgid] : 0) / 100);
		//JANB fixnutie 07-04-2020 zlý prepočet sumy .. bude to treba skontrolovať !!!
		var phcena = jqo_price_net.val() * sgdis * (1 + taxRate);

		if (phcena % 1 == 0) phcena = phcena;
		else phcena = phcena.toFixed(2);

		if (cn.indexOf('product_price_input') > -1) {

			if ( grossValue == '' ) {
				jqo_price_net.parents('.pp_other_price_content').find('.product_price_incl_tax_dis').val('');
			} else {
				jqo_price_net.parents('.pp_other_price_content').find('.product_price_incl_tax_dis').val(phcena);
			}
		}
	}
}

function js_jq_updateOldPriceGross( product_id, event ) {
	if (event && (event.keyCode==9 || event.keyCode==13 || (event.keyCode>34 && event.keyCode<41))) return;

	jqo_price_net = jQuery('.product_old_price_input_'+product_id);
	jqo_tax_rate = jQuery('.product_tax_select_'+product_id);
	jqo_price_gross = jQuery('.product_old_price_incl_vat_input_'+product_id);

	if ( jqo_price_net.length == 0 || jqo_tax_rate.length == 0 || jqo_price_gross == 0 ) {
		return;
	}

	js_jq_update_price_gross( jqo_price_net, jqo_tax_rate, jqo_price_gross );
}

function js_jq_updateGross( product_id, event, price_net_jq_selector, price_gross_jq_selector ) {
	if (event && (event.keyCode==9 || event.keyCode==13 || (event.keyCode>34 && event.keyCode<41))) return;
	jqo_price_net = jQuery((price_net_jq_selector != null && price_net_jq_selector != '') ? price_net_jq_selector : ('.product_price_input_'+product_id));
	jqo_tax_rate = jQuery('.product_tax_select_'+product_id);
	jqo_price_gross = jQuery((price_gross_jq_selector != null && price_gross_jq_selector != '') ? price_gross_jq_selector : ('.product_price_incl_tax_input_'+product_id));
	if (typeof event != 'undefined' && typeof event.keyCode != 'undefined') js_set_element_changed(jqo_price_net);

	js_jq_update_price_gross( jqo_price_net, jqo_tax_rate, jqo_price_gross );
}

function js_jq_updateOtherPricesGross( product_id ) {
	var jq_list = jQuery('.pp_info_container [name="pp_value_wo_tax\[\]"]');
	if (jq_list && jq_list.length > 0) {
		var jqo_tax_rate = jQuery('.product_tax_select_'+product_id);
		jq_list.each(function () {
			var jqo_price_net = jQuery(this);
			var jqo_price_gross = jqo_price_net.parents('.pp_info_container:first').find('input[name="pp_value_w_tax\[\]"]:first');
			js_jq_update_price_gross(jqo_price_net, jqo_tax_rate, jqo_price_gross);
		});
	}
}

function js_jq_updatePurchasePriceGross( product_id, event ) {
	if (event && (event.keyCode==9 || event.keyCode==13 || (event.keyCode>34 && event.keyCode<41))) return;

	jqo_price_net = jQuery('.product_purchase_price_input_'+product_id);
	jqo_tax_rate = jQuery('.product_tax_select_'+product_id);
	jqo_price_gross = jQuery('.product_purchase_price_incl_vat_input_'+product_id);

	if ( jqo_price_net.length == 0 || jqo_tax_rate.length == 0 || jqo_price_gross == 0 ) {
		return;
	}

	js_jq_update_price_gross( jqo_price_net, jqo_tax_rate, jqo_price_gross );
}

function js_jq_update_price_net( jqo_price_net, jqo_tax_rate, jqo_price_gross, decimals, remove ) {
	remove = typeof remove !== 'undefined' ? remove : true;
	decimals = typeof decimals !== 'undefined' ? parseInt(decimals) : 5;

	var rates = (typeof _product !== 'undefined' ? _product.options.tax_rates : (typeof _order !== 'undefined' ? _order.options.tax_rates : tax_rates));

	js_remove_not_numeric(jqo_price_gross);
	js_set_element_changed(jqo_price_gross);

	var netValue = jqo_price_gross.val();
	if (typeof (jqo_tax_rate) != 'object') {
		var taxRate = parseFloat(jqo_tax_rate);
	} else
		var taxRate = rates[jqo_tax_rate.val()];

	if ( typeof js_Config_VM_direct_prices_editing_for_shopper_group !== "undefined" ) {
		$tmp_sgp = jqo_price_net.parents('.pp_other_price_content').find('select.pp_op_shopper_group_select option:selected').val();

		if (typeof js_Config_VM_direct_prices_editing_for_shopper_group !== "undefined" && typeof js_Config_VM_direct_prices_editing_for_shopper_group[$tmp_sgp] !== "undefined" && js_Config_VM_direct_prices_editing_for_shopper_group[$tmp_sgp].dph !== '') {
			taxRate = parseFloat(js_Config_VM_direct_prices_editing_for_shopper_group[$tmp_sgp].dph);
		}
	}
	if (taxRate > 0) {
		netValue = netValue / (taxRate + 1);
	}
	var price = doRound(netValue, decimals);
	price     = remove ? js_remove_right_zeros(price) : parseFloat(price).toFixed(decimals);

	if ( netValue == '' ) {
		jqo_price_net.val('');
	} else {
		jqo_price_net.val(price);
	}

	var cn = jqo_price_net['0'].className;
	var ppsgid = jqo_price_net.parents('.pp_other_price_content').find('.pp_op_shopper_group_select').val();
	var sgdis = 1 - ((typeof(phsg) != 'undefined' && ppsgid != 0 ? phsg[ppsgid] : 0) / 100);
	//JANB fix 07-02-2020 zlý prepočet potrebné poriadne skontrolovať !!!
	var phcena = jqo_price_net.val() * sgdis * (taxRate + 1);

	if (phcena % 1 == 0) {
		phcena = phcena;
	} else phcena = phcena.toFixed(2);

	if (cn.indexOf('product_price_input') > -1) {

		if ( netValue == '' ) {
			jqo_price_net.parents('.pp_other_price_content').find('.product_price_incl_tax_dis').val('');
		} else {
			jqo_price_net.parents('.pp_other_price_content').find('.product_price_incl_tax_dis').val(phcena);
		}
	}
}

function js_jq_updateOldPriceNet( product_id, event ) {
	if (event && (event.keyCode==9 || event.keyCode==13 || (event.keyCode>34 && event.keyCode<41))) return;
	jqo_price_net = jQuery('.product_old_price_input_'+product_id);
	jqo_tax_rate = jQuery('.product_tax_select_'+product_id);
	jqo_price_gross = jQuery('.product_old_price_incl_vat_input_'+product_id);

	if ( jqo_price_net.length == 0 || jqo_tax_rate.length == 0 || jqo_price_gross == 0 ) {
		return;
	}

	js_jq_update_price_net( jqo_price_net, jqo_tax_rate, jqo_price_gross );
}

function js_jq_updateNet( product_id, event, price_net_jq_selector, price_gross_jq_selector ) {
	if (event && (event.keyCode==9 || event.keyCode==13 || (event.keyCode>34 && event.keyCode<41))) return;
	jqo_price_net = jQuery((price_net_jq_selector != null && price_net_jq_selector != '') ? price_net_jq_selector : ('.product_price_input_'+product_id));
	jqo_tax_rate = jQuery('.product_tax_select_'+product_id);
	jqo_price_gross = jQuery((price_gross_jq_selector != null && price_gross_jq_selector != '') ? price_gross_jq_selector : ('.product_price_incl_tax_input_'+product_id));

	js_jq_update_price_net( jqo_price_net, jqo_tax_rate, jqo_price_gross );
}

function js_jq_updatePurchasePriceNet( product_id, event ) {
	if (event && (event.keyCode==9 || event.keyCode==13 || (event.keyCode>34 && event.keyCode<41))) return;
	jqo_price_net = jQuery('.product_purchase_price_input_'+product_id);
	jqo_tax_rate = jQuery('.product_tax_select_'+product_id);
	jqo_price_gross = jQuery('.product_purchase_price_incl_vat_input_'+product_id);

	if ( jqo_price_net.length == 0 || jqo_tax_rate.length == 0 || jqo_price_gross == 0 ) {
		return;
	}

	js_jq_update_price_net( jqo_price_net, jqo_tax_rate, jqo_price_gross );
}

function js_parse_float( num ) {
	var ret = ''+num;
	if (ret.indexOf(',') > -1) {
		ret = ret.replace(/\./g, '').replace(/,/g, '.');
	}
	ret = parseFloat(ret.replace(/ /g, ''));
	if (isNaN(ret)) {
		ret = 0;
	}
	return ret;
}

function apiRequest(trigger, params, callback, onetime) {
	if ( typeof isApiActive === 'undefined' || !isApiActive || typeof activeApiTriggers === 'undefined' || activeApiTriggers.indexOf(trigger) == -1 ) {
		return false;
	}

	if (typeof onetime !== 'undefined' && onetime && typeof localStorage !== 'undefined') {
		var apiKey = 'apiRequest_' + trigger;
		var apiStorage = localStorage.getItem(apiKey);

		apiStorage = apiStorage ? JSON.parse(apiStorage) : [];

		// pri novom nacitani local storage zmaz
		if (typeof window[apiKey] === 'undefined') {
			localStorage.removeItem(apiKey);
			window[apiKey] = true;
			apiStorage = [];
		}

		for (var x in apiStorage) {
			if ( typeof apiStorage[x].params !== 'undefined' && apiStorage[x].params === JSON.stringify(params) ) {
				/*if (typeof apiStorage[x].result !== 'undefined') {
					eval(apiStorage[x].result);
				}

				if (typeof callback === 'function') {
					callback();
				}*/

				return;
			}
		}
	}

	if (typeof params === 'undefined') {
		params = {};
	}

	// nieco musi byt v params, inac to neposle v requeste
	params.isAjax = true;

	new AjaxRequest({'trigger': trigger, 'params': params})
		.setController('Api')
		.setAction('get')
		.onSuccess(function (jsonData) {
			if( typeof jsonData != 'undefined' && typeof jsonData.data != 'undefined' ){
				var res = jsonData.data;

				if ( typeof res.jsCode !== 'undefined' ) {
					//pokial dostaneme kod wrapnuty v tagoch <script></script> je potrebne ich odstranit kvoli eval()
					var cleanJsCode = res.jsCode;
					cleanJsCode = cleanJsCode.replace(/<(|\/)script.*?>/gm, ''); //tagy script
					cleanJsCode = cleanJsCode.replace(/<!--(.*?)-->/gm, '/*$1*/'); //html koment

					if (typeof onetime !== 'undefined' && onetime && typeof localStorage !== 'undefined') {
						apiStorage.push({
							'params': JSON.stringify(params),
							//'result': cleanJsCode
						});

						localStorage.setItem(apiKey, JSON.stringify(apiStorage));
					}

					//eval is evil
					eval(cleanJsCode);
				}

				if (typeof callback === 'function') {
					callback();
				}
			}
		})
		.send();
}

/**
 *
 * @param elem HTMLElement Kliknuty element
 * @param productId int
 * @param attribute string
 * @param action string "+" | "-"
 * @param quantity nmber
 * @param inputRef HTMLElement<input> input ktoremu sa zmeni mnozstvo podla action
 * @oaram cartItemId int ak je definovane odstrani sa variant podla "description" a prida sa "cart_item_id" nutne hlavne pre akciu "-" tam sa to sprava dost zvlastne
 * @oaram disableAnimation vypne animaciu
 */
function simpleAddToCart(elem, productId, attribute, action, quantity, inputRef, cartItemId, disableAnimation, wishlist) {
	var jQueryBody = jQuery('body');

	if (['+', '-'].indexOf(action) === -1) {
		//jQueryBody.trigger('addToCartErrorWrongAction');
		console.warn('simpleAddToCart called with wrong action, action should be "+" / "-"');
		return false;
	}
	if (quantity < 1 || typeof quantity !== 'number') {
		//jQueryBody.trigger('addToCartErrorWrongQuantity');
		console.warn('simpleAddToCart called with wrong quantity, quantity should be more or equal to 1 and valid number');
		return false;
	}
	if (productId < 0 || typeof productId !== 'number') {
		//jQueryBody.trigger('addToCartErrorWrongProductId');
		console.warn('simpleAddToCart called with wrong productId, productId should be more then 0 and valid number');
		return false;
	}
	if (typeof inputRef !== 'undefined') {
		if (action == '-' && inputRef.val() - quantity == 0) {
			return false;
		}
	}

	// osetrenie modal pre attiibut
	if (typeof tmpAttributeModalInstance !== 'undefined') {
		tmpAttributeModalInstance.close();
		tmpAttributeModalInstance = undefined;
	}

	var ajaxUrl     = '/modules/mod_shop_cart_ajax.php';
	var ajaxOptions = {
		ajax_func           : 'get_ajax_cart',
		ajax_cart_product_id: productId,
		ajax_cart_action    : action, // +, -
		ajax_cart_quantity  : quantity,
		is_gift             : false,
		is_special_offer    : false,
		category_id         : 0
	};

	if (typeof attribute !== 'undefined' && attribute !== '') {
		ajaxOptions.select_name  = 'faadd750a6fbb9ea11a94c6074db79144';
		ajaxOptions.select_value = attribute;
	}

	if (typeof cartItemId !== 'undefined') {
		ajaxOptions.cart_item_id = cartItemId;
	}

	if (config('js_Config_epredplatne_wishlist_compatibility') && typeof wishlist !== 'undefined') {
		if (wishlist === 1) {
			ajaxOptions.fromWishlist = true;
		} else if (wishlist === 2) {
			if (typeof attribute !== 'undefined' && attribute !== '') {
				ajaxOptions.select_name  = 'f9f243829b48214b20c0a53f6dfe35002';
				ajaxOptions.category_id = 3; //Toto este asi upravit nejak dynamicky a pozriet ci je to vobec potrebne
			} else {
				ajaxOptions.fromWishlist = true;
			}
		}
	}

	jQuery.post(ajaxUrl, ajaxOptions, function (res) {
		if (res.indexOf('{') === -1) {
			jQueryBody.trigger('addToCartErrorNoAttribute');
			// nemame attribut ...
			console.error('simpleAddToCart called with wrong attribute, attribute should not be empty for produt with attributes');

			var tmpButtons = '';
			var decodedRes = JSON.parse(decodeURIComponent(res));

			tmpButtons = '<div class="vex_cart_quantity">';
			// mnozstvo
			tmpButtons += '<input class="inputbox shop-addtocart-quantity-inputbox" type="text" size="3" name="quantity" value="1" onkeyup="(parseInt(this.value)>0)?this.style.borderColor=\'\' : this.style.borderColor=\'red\';">';

			let attribSelector = '[name=faadd750a6fbb9ea11a94c6074db79144] option:selected';
			if (config('js_Config_epredplatne_wishlist_compatibility') && decodedRes.html_variants.includes('f9f243829b48214b20c0a53f6dfe35002')) {
				attribSelector = '[name=f9f243829b48214b20c0a53f6dfe35002] option:selected';
				var is_epredplatne = true;
			}

			var quantity = 'parseFloat(jQuery(this).closest(\'.cs_modal_actions\').find(\'input[name=quantity]\').val())';
			// pridat do kosika btn
			var tmpAttributeSelectedValue = 'jQuery(this).closest(\'.vex-content\').find(\'' + attribSelector + '\').val()'; // toto je podla man zle "vex-content" neexistuje v niektorych pripadoch
			// nove rarianty
			if ( typeof js_Config_product_variant !== 'undefined' && js_Config_product_variant ) {
				tmpAttributeSelectedValue = 'ProductVariantInstance_' + productId + '.getSelectedAttribute().source';
			}

			if (typeof is_epredplatne !== 'undefined' && is_epredplatne === true) {
				tmpButtons += '<input onclick="simpleAddToCart(this, ' + productId + ', ' + tmpAttributeSelectedValue +', \'+\', ' + quantity + ', undefined, undefined, undefined, 2)" type="button" class="button" name="submit" title="" value="' + js_lang_luigibox_addtocart + '">';
			} else {
				tmpButtons += '<input onclick="simpleAddToCart(this, ' + productId + ', ' + tmpAttributeSelectedValue +', \'+\', ' + quantity + ')" type="button" class="button" name="submit" title="" value="' + js_lang_luigibox_addtocart + '">';
			}
			tmpButtons += '</div>';

			// detail produktu btn
			tmpButtons += '<input onclick="window.location=\'' + jQuery('.cs_product_item[data-product-id="' + productId + '"] a:first').attr('href') + '\';" type="button" class="vex-dialog-button-secondary vex-dialog-button vex-last button" value="' + (typeof js_shop_flypage_lbl !== 'undefined' ? js_shop_flypage_lbl : '') + '">';

			window['tmpAttributeModalInstance'] = new CsModal()
				.setType('info')
				.setTitle(decodedRes.product_name)
				.setContent(decodedRes.html_variants)
				.setButtons(tmpButtons)
				.setActionsClassName('vex-dialog-buttons')
				.afterOpen(function () {
					jQueryBody.trigger('addToCartAttributeModalShown', [{
						productId: productId
					}]);
				})
				.open();

			return false;
		}

		res = JSON.parse(res);
		if (typeof res['update_res']['success'] === 'undefined') {
			var ajaxRes     = res['update_res'],
			    stripedText = jQuery(ajaxRes).text().replace('\n', '<br>');
			if (stripedText) {
				jQuery(elem).tooltipster({
					theme        : "tooltipster-gdpr",
					contentAsHTML: true,
					trackTooltip : true,
					trackOrigin  : true,
					multiple     : false,
					timer        : 5000,
					trigger      : 'custom',
					onlyOne      : false,
					content      : stripedText
				}).tooltipster('open');
			}
			return false;
		}

		if (typeof inputRef !== 'undefined') {
			if (action === '+') {
				inputRef.val(parseFloat(inputRef.val()) + quantity);
			} else {
				inputRef.val(parseFloat(inputRef.val()) - quantity);
			}
		}

		jQuery('.moduleCartInfo').html(res['html_cart_values']);
		jQuery('.cart_ajax_container').replaceWith(res['html_products']);
		//ajax cart fix
		jQuery('div.module-cart').removeClass('empty');
		jQuery('a.cartLink').removeAttr('onclick');
		if (typeof disableAnimation === 'undefined') {
			js_cart_image_animate(elem);
		}

		if (typeof js_product_as_gift_init === 'function') {
			js_product_as_gift_init();
		}

		var tmpIdx = undefined;
		if (typeof res.cart_item_id === 'undefined' && typeof res.update_res.log_d !== 'undefined' && typeof res.update_res.log_d.cart_item_id !== 'undefined') {
			tmpIdx = res.update_res.log_d.cart_item_id;
		}

		jQueryBody.trigger('addToCartFinished', [{
			productId: productId,
			attribute: typeof attribute !== 'undefined' ? attribute : '',
			action: action,
			quantity: quantity,
			cart_item_id: tmpIdx
		}]);

		if (typeof isApiActive !== 'undefined' && isApiActive) {
			var apiAction = action === '+' ? 'addToCart' : 'removeFromCart';
			var pageMatch = typeof js_server_request_uri !== 'undefined' ? js_server_request_uri.match(/(&|;|\?)page\=([^&]+)/) : undefined;
			var manMatch  = typeof js_server_request_uri !== 'undefined' ? js_server_request_uri.match(/(&|;|\?)pc_manufacturer_id\=([^&]+)/) : undefined;
			var page      = '';
			if (typeof manMatch === 'object' && manMatch !== null) {
				page = 'manufacturer';
			} else if (typeof pageMatch === 'object' && pageMatch !== null && typeof pageMatch[2] !== 'undefined') {
				page = pageMatch[2];
			}
			apiRequest(apiAction, {
				'products': [{
					'product_id' : productId,
					'quantity'   : quantity,
					'description': typeof attribute !== 'undefined' ? attribute : '',
					'idx'        : ''
				}],
				'page'    : page,
				'isAjax'  : true
			});
		}

		return false;
	});

	return false;
}

function js_shopcart_submit(elem) {
	if (typeof js_shopcart_submit_custom != 'undefined') {
		return js_shopcart_submit_custom(elem);
	}

	var $elem = jQuery(elem);
	var $form = $elem.is('form') ? $elem : $elem.parents('form:first');
	var $quantity = $form.find('[name="quantity"]');
	let productId = $form.find('input[name=product_id]').val();

	if (($quantity.val().indexOf(',')) != -1) {  // nebralo ciarku pri 'Nákup produktov v desatinných množstvách'
		$quantity.val($quantity.val().replace(/\,/g, '.'));
	}

	if ($quantity.length && parseFloat($quantity.val()) == 0) {
		$quantity.trigger('focus');
		return false;
	}

	//RB vex pre custom field
	if ( $elem.hasClass('is_restricted_product') ) {
		vex.dialog.alert( $elem.data('vex_url') );
	}

	if ( $elem.hasClass('vex_product_is_in_spg') && typeof js_Config_show_vex_after_add_to_cart !== 'undefined' && js_Config_show_vex_after_add_to_cart && typeof CsModal !== "undefined" ) {
		//#15177
		showMessageAfterAddToCart(elem);
		return false;
	}

	if (typeof js_Config_product_variant !== 'undefined' && js_Config_product_variant) {
		// neskor presunut do vnutra `checkIfVariantIsSelected`
		if (typeof window[`ProductVariantInstance_${productId}`] !== 'undefined' && (window[`ProductVariantInstance_${productId}`].attributeList.length > 0 || Object.keys(window[`ProductVariantInstance_${productId}`].attributeList).length > 0)) {
			return window[`ProductVariantInstance_${productId}`].checkIfVariantIsSelected();
		}

		return true;
	}

	// dusan pridani ehlasky pri nevybere variantu
	if (js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED != '2') {
		var is_checked = false;
		var variant_element = '';
		if(jQuery('.attr_group_sel_div').length != '0'){
			// pri vybere variantu z attr_group_sel_div a
			jQuery('.attr_group_sel_div a').each( function () {
				if (jQuery(this).hasClass('selected_attr')){
					is_checked = true;
				}
			});
			variant_element = '.attr_group_sel_div a';

		} else if(jQuery('.prod_adv_attrib_select select').length != '0'){
			//zo selectu
			if( jQuery('.prod_adv_attrib_select select').val() != ''){
				is_checked = true;
			}

			variant_element = '.prod_adv_attrib_select select';

		} else {

			if ( is_cs_user('separate_js') && ( typeof js_CS_Config_empy_radio_select_variant !== 'undefined' && js_CS_Config_empy_radio_select_variant == '1' ) ) {
				var form_varaints = jQuery('.prod_adv_attribs_div').find('.shop_addtocart_advanced_attribute_radio');
				if( ( typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED !== 'undefined' && js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED == '1') && ( form_varaints.length > 0 ) && (form_varaints.is(':checked') == false ) ){
					is_checked = false;
					variant_element = '.prod_adv_attribs_div';
				} else {
					// nieje vyber variantu
					return true;
				}

			}else {
				// nieje vyber variantu
				return true;
			}
		}
		if (is_checked == true){
			return true;
		} else {
            var attribsWrapperTop = jQuery('.prod_adv_attribs_div').offset().top - 70;

            jQuery(variant_element).each( function () {
				jQuery(this).addClass('please_choose_variant');
			});
			if ( attribsWrapperTop < jQuery(window).scrollTop() ) {
                jQuery('html, body').animate({
                    scrollTop: attribsWrapperTop
                }, 600);
			}
			jQuery(variant_element + ':first').tooltipster({
				theme        : "tooltipster-gdpr tooltipster-choose-attr",
				contentAsHTML: true,
				trackTooltip : true,
				trackOrigin  : true,
				multiple     : true,
				timer        : 5000,
				content      : (typeof js_cart_select_item !== 'undefined' ? js_cart_select_item : '')
			}).tooltipster('open');
			return false;
		}
	}

	return true;
}
function js_add_bind_data(jso, name, value) {
	var jqo  = jQuery(jso);
	var bind = jqo.data('bind');
	jqo.data('bind', jQuery.extend(bind, {name: value}));
}
/////-------------- PEXF LOAD PRE PARAMETRE - FINALNY
var js_external_url_link = '';
function js_pexf_load( page_count, asc_desc, mode ) {
	if (js_global_is_csu) {
		console.log('FN: js_pexf_load', {page_count: page_count, asc_desc: asc_desc, mode: mode});
	}

	if ( typeof js_category_id === 'undefined' ) return;

	// Neloaduj ak je poziadavka z nekonecneho scrolovania
	if( typeof inf_clear_pexf !== 'undefined' && inf_clear_pexf == true ) return;

	js_global_c_pp_filter_processing = null;
	js_global_pexf_processing = null;
	var options = {'option': 'com_shop', 'page': 'shop.browse', 'Itemid': '1040', 'category_id': js_category_id, 'no_html': '1', 'no_css': '1', 'no_menu': '1', 'no_vm_html': '1', 'sef_rewrite_index2_index': '1'};

	if (jQuery('.pexf_reset_container .pexf_cancel_values').hasClass('active') && mode != 'reset_product_filter') {
		jQuery('.pexf_reset_container .pexf_cancel_values').fadeIn(300);
	} else
		jQuery('.pexf_reset_container .pexf_cancel_values').fadeOut(300);


	jQuery('body').find('.pexf_selected_values').html('');	// zmazanie zoznamu vsetkych selectnutych attribute filtrov

	// filter cenove hladiny
	jQuery('.pexf_value input[type="checkbox"][name="ch_pexf_price_level"]:checked').each(function ( idx_v, jso_v ) {
		options[jQuery(jso_v).attr('name')+'['+idx_v+']'] = jQuery(jso_v).val();
		var pexf_selected_values_container = jQuery(this).parents('.pexf_container').find('.pexf_selected_values:first');
// 		if (typeof(console) != 'undefined') console.log('pexf_selected_values_container', pexf_selected_values_container, jQuery(jso_v), jQuery(jso_v).siblings('label'));
		var this_attr_value = jQuery(jso_v).siblings('label').html();
		if (typeof(console) != 'undefined') console.log('this_attr_value', pexf_selected_values_container,  this_attr_value);
		pexf_selected_values_container.html(pexf_selected_values_container.html() + this_attr_value + '<br/>');
	});

	// filtry podla atributov
	if (jQuery('body').find('input.attr_value_filter:checked').length) {

		options.attr_filter_values_enabled = 1;
		options.attr_filter_values = {};

		jQuery('body').find('input.attr_value_filter:checked').each(function(i){
			// naplnenie do zoznamu vybratych filtrov
			var pexf_selected_values_container = jQuery(this).parents('.pexf_container').find('.pexf_selected_values:first');
			var this_attr_value = jQuery(this).val().split(':');
			pexf_selected_values_container.html(pexf_selected_values_container.html() + this_attr_value[1] + '<br/>');
			//var input_class = jQuery(this).attr
			var attr_val_index_arr = jQuery(this).attr('class').match(/(^| )pexf_by_attr_value_([0-9]+)/);

			if (attr_val_index_arr != null && attr_val_index_arr.length > 2 )
				var attr_val_index = attr_val_index_arr[attr_val_index_arr.length - 1];

			if (typeof(options.attr_filter_values[attr_val_index]) != "object")
				options.attr_filter_values[attr_val_index] = [];

			options.attr_filter_values[attr_val_index][ options.attr_filter_values[attr_val_index].length ] = jQuery(this).val();
		});
	}

	// filtry podla atributov - type image
	if (jQuery('body').find('input.attr_image_value_filter_selected').length) {

		options.attr_filter_values_enabled = 1;
		if (typeof(options.attr_filter_values) == "undefined" )
			options.attr_filter_values = {};


		jQuery('body').find('input.attr_image_value_filter_selected').each(function(i) {
			var pexf_selected_values_container = jQuery(this).parents('.pexf_container').find('.pexf_selected_values:first');
			var this_attr_image_value = jQuery(this).css('background-image').replace(/"/gi, '').replace(/'/gi,'');
			pexf_selected_values_container.html(pexf_selected_values_container.html() + '<input type="button" class="attr_image_value_filter attr_image_value_filter_active" style="background:' + this_attr_image_value + ' repeat center 50%" value=""/> ');

			var attr_val_index_arr = jQuery(this).attr('class').match(/(^| )pexf_by_attr_value_([0-9]+)/);

			if (attr_val_index_arr != null && attr_val_index_arr.length > 2 )
				var attr_val_index = attr_val_index_arr[attr_val_index_arr.length - 1];

			if (typeof(options.attr_filter_values[attr_val_index]) != "object")
				options.attr_filter_values[attr_val_index] = [];

			options.attr_filter_values[attr_val_index][ options.attr_filter_values[attr_val_index].length ] = jQuery(this).val();

		});
	}

	// filter vyrobcu
	var manufacturer_select = jQuery('select[name=product_manufacturer_shop_browse_filter]');
	if ( manufacturer_select.length > 0 ) {
		if(is_cs_user()) console.log(manufacturer_select.val());
		if (manufacturer_select.val() != '') {
			options.pc_manufacturer_id = manufacturer_select.val();
			if (typeof(options.pc_manufacturer_id) == 'string' && isNaN(options.pc_manufacturer_id)) {// palo
				options.pc_manufacturer_id = options.pc_manufacturer_id.substring(0, options.pc_manufacturer_id.length - 1);
				var start_id = options.pc_manufacturer_id.lastIndexOf('-') + 1;
				options.pc_manufacturer_id = options.pc_manufacturer_id.substring(start_id);
			}


			if (Array.isArray(options.pc_manufacturer_id)) {	// multiple
				jQuery('.pexf_manu_container').find('.pexf_selected_values').html('');
				var selected_values = [];
				jQuery.each(options.pc_manufacturer_id, function (i, val) {
					if (val > 0)
						selected_values.push( manufacturer_select.find('option[value="' + val + '"]').html() );
				});
				jQuery('.pexf_manu_container').find('.pexf_selected_values').html( selected_values.join(', ') );

			} else 												// standard
				jQuery('.pexf_manu_container').find('.pexf_selected_values').html(manufacturer_select.find('option[value="' + options.pc_manufacturer_id + '"]').html());
		}
	}

	// limit produktov na stranku
	options.limit = jQuery('#middle').find('select[name=limit]:first').val();
	if (typeof(options.limit)=='undefined') {
		if ( typeof js_custom_page_limit != 'undefined')
			options.limit = js_custom_page_limit;
		else
			options.limit = 20;	// lebo
	}

	// limit - strankovanie
	options.limitstart = 0;
	if ( typeof(page_count) != "undefined" && page_count > 0 ) 	// Zobraziť na stránku
		options.limitstart = page_count;

	// zoradit produkty podla ...
	options.orderby = jQuery('#middle').find('select[name=orderby]:first').val();
	if (typeof(options.orderby) == 'undefined' || options.orderby == 'undefined')
		options.orderby = 'vm_product.product_name';
	if (jQuery('#middle').find('select[name=orderby]:first option:selected').index() != 0 ) {
		jQuery('.pexf_order_by_container .pexf_selected_values').html( jQuery('#middle').find('select[name=orderby]:first option:selected').html() );
	} else
		jQuery('.pexf_order_by_container .pexf_selected_values').html('');

	// zoradit produkty ASC/DESC
	if (typeof(mode) != "undefined" && mode == 'select_order') {
		asc_desc_ico = 'sort_desc.png';
		asc_desc = '1';
	}
	if (typeof(asc_desc_ico) != "undefined" && asc_desc_ico == '' && jQuery('.orderby_img').length) {
		asc_desc_ico = jQuery('.orderby_img:first').attr('src').indexOf('sort_asc') > -1 ? 'sort_asc.png' : 'sort_desc.png';
	}
	if ( typeof(asc_desc) != "undefined" && asc_desc != '' ) {
		if (typeof(asc_desc_ico) != "undefined" &&  asc_desc_ico == 'sort_asc.png') {
			options.DescOrderBy = 'DESC';
			asc_desc_ico = 'sort_desc.png';
		} else {
			options.DescOrderBy = 'ASC';
			asc_desc_ico = 'sort_asc.png';
		}

		Cookies.set('shop_browse_orderby_price_asc_desc', options.DescOrderBy, { path: '/' });
		jQuery('.pexf_order_by_value_container').find('.asc_desc_img').attr('src', js_global_live_site + '/images/M_images/' + asc_desc_ico);
		jQuery('.pexf_order_by_container .pexf_selected_values').append('<img class="pexf_asc_desc_img_set" src="/images/M_images/' + asc_desc_ico + '" />');
	}
	if (typeof asc_desc == 'undefined' && jQuery('.orderby_img').length) {
		asc_desc_ico = jQuery('.orderby_img:first').attr('src').indexOf('sort_asc') > -1 ? 'sort_asc.png' : 'sort_desc.png';
		if (typeof(asc_desc_ico) != "undefined" && asc_desc_ico == 'sort_asc.png') {
			options.DescOrderBy = 'ASC';
		} else {
			options.DescOrderBy = 'DESC';
		}
	}
	// END: ordering

	// adaptivny filter podla ceny
	if (jQuery('#pexf_range').length && mode != 'reset_product_filter') {
		var $pexf_range = jQuery('#pexf_range');
		var slider_params = $pexf_range.data('params') || {};
		options.pexf_price_from = $pexf_range.slider('values')[0];
		options.pexf_price_to = $pexf_range.slider('values')[1];
		options.pexf_price_tax = slider_params.max_tax;
		jQuery('#pexf_range').parents('.pexf_price_lvl:first').find('.pexf_selected_values').html('');

		// cudzojazycny filter, hodnoty treba prepocitat na default currency
		if (!js_is_empty(slider_params.orig) && !js_is_empty(slider_params.orig.currency_rate) && slider_params.orig.currency_rate != 1) {
			options.pexf_price_from = options.pexf_price_from / slider_params.orig.currency_rate;
			options.pexf_price_to = options.pexf_price_to / slider_params.orig.currency_rate;
		}

	}

	// skupina produktov
	if (jQuery('select#product_special_group').length)
		options.product_special_group = jQuery('select#product_special_group').val();

	options.is_pexf = 1;
	options.shop_browse_ajax_mode = 1;	// shop ajax mode enabled

	jQuery('#middle').css('height', 'auto');

	// filter dostupnostosti
	if (jQuery('#product_availability_shop_browse_filter').length) {
		options.pc_avail_id = jQuery('#product_availability_shop_browse_filter').val();
		var avails = jQuery('#product_availability_shop_browse_filter').val();
		if (jQuery('#product_availability_shop_browse_filter').attr('multiple') == 'multiple' && avails != null && avails.length > 0){
			var avail_opt = avails.join(',');
		} else {
			var avail_opt = avails;
		}
		Cookies.set('pc_avail_id_' + js_category_id, avail_opt, { path: '/' });

		var selected_values = [];
		if (jQuery('#product_availability_shop_browse_filter').val() != '' ) {
			jQuery('#product_availability_shop_browse_filter :selected').each(function () {
				selected_values.push(jQuery(this).text());
			});
		}
		jQuery('.pexf_avail_container .pexf_selected_values').html(selected_values.join(', '));
	}

	// JAN external link filter parameter, zostavenie linku
	if (typeof js_filter_param_from_url != 'undefined' && js_filter_param_from_url == 1){

		var opt = {};
		var fu_params = Cookies.get('c_pp_filter_' + js_category_id);
		var fu_avails = Cookies.get('pc_avail_id_' + js_category_id);

		if (typeof fu_params !== 'undefined' && fu_params !== null && fu_params !== '') opt.x = 'c_pp_filter_'+js_category_id+'='+fu_params;
		if (typeof fu_avails !== 'undefined' && fu_avails !== null && fu_avails !== '') opt.y = 'pc_avail_id_'+js_category_id+'='+fu_avails;

		var optKey = {'limit':'a','limitstart':'b','orderby':'c','pexf_price_from':'d','pexf_price_tax':'e','pexf_price_to':'f'};
		for(var keyIndex in options) {
		   if (options.hasOwnProperty(keyIndex)) {
			   if(typeof(optKey[keyIndex]) != 'undefined'){
				   opt[optKey[keyIndex]] = options[keyIndex];
			   }
		   }
		}
		var encoded_url = btoa(JSON.stringify(opt));
		js_external_url_link = js_global_live_site+js_url.replace(/&amp;/g, '&')+'?fp='+encoded_url;
		cs_set_cookie('filter_param_from_url', js_external_url_link);
	}

// 	if (typeof(console) != 'undefined') console.log(options);
	if (typeof(js_pexf_load_before_ajax_init) == 'function')
			js_pexf_load_before_ajax_init();

	if (typeof(js_pexf_load_change_options_init) == 'function')
		options = js_pexf_load_change_options_init(options);

	// scroll to top of produtct list after pexf_load
	if (typeof js_pexf_load_autoscroll != 'undefined' && js_pexf_load_autoscroll == 1 && jQuery('.shop_browse_category_h2').length) {
		var top_pos = jQuery('.shop_browse_category_h2').offset().top || -1;
		setTimeout(function () {
			if (top_pos > 0)
				jQuery.scrollTo(top_pos, 800);
		}, 250);
	}

	// set category last page
	Cookies.set('shop_browse_pexf_limitstart_' + js_category_id, options.limitstart, { path: '/' });

	// JAN dynamic category product counter
	js_pexf_product_counter();
	jQuery('#middle_content_inner').html('<div class="middle_progress" style="text-align:center"><img src="/images/ajax-loader-01.gif" alt="..." /></div>').load('/index2.php', options, function () {

		jQuery('.shop_category_limit').show();

		// presunutie pagination limitboxu do tela modulu
		if (typeof js_move_pagination_to_filter_module != 'undefined' && typeof js_filter_pagination_enabled != 'undefined' && js_filter_pagination_enabled == 1){
			js_move_pagination_to_filter_module();
		}

		// vymazanie selected values elementov
		if (typeof(mode) != "undefined" && mode == 'reset_product_filter')
			jQuery('.pexf_selected_values').html('');

		if (typeof js_get_selectboxes_height != 'undefined')
			js_get_selectboxes_height();

		// na konci vzdy
		if (typeof(js_pexf_load_after_ajax_init) == 'function')
			js_pexf_load_after_ajax_init();


	});
	return false;
}

// JAN filter dynamic category product counter
function js_pexf_product_counter(){

	var filter_box = jQuery('body').find('.c_pp_filter_container');

	if( filter_box.length > 0 && filter_box.hasClass('c_pp_counter') ){

		var options = {};

		jQuery.post('/public_scripts_M4r7ft/ajax/pexf_count_product.php', options, function (res) {

			var result = JSON.parse(res);

			if( typeof result === 'object' ){

				jQuery.each(result.counter, function(c, v){

					var elem = jQuery('.module_cont-kateg .category_id_'+c);

					if (elem.find('span.pexf_counter').length > 0){
						elem.find('span.pexf_counter').html(v).attr('class', result.filter);
					} else {
						elem.append('<span class="'+result.filter+'">'+v+'</span>');
					}
				});
			}
		});
	}
}

function js_update_text_counter(elem, max_count, counterElement) {
	if (typeof max_count == 'undefined')
		return;

	counterElement = counterElement || false;

	var $elem = jQuery(elem);
	var $counter = $elem.parent().find('.txt_count');

	if (counterElement) {
		$counter = jQuery(counterElement);
	}

	$counter.text(parseInt(max_count) - $elem.val().length);
}

function is_admin() {
	return ((typeof js_global_is_admin !== 'undefined' ? js_global_is_admin : false) || jQuery('body').hasClass('admin_design'));
}

function is_cs_user(cookieValue) {
	if (typeof js_global_is_csu !== 'undefined') {
		if (typeof cookieValue !== 'undefined') {
			if (Cookies.get('cs_whois') !== undefined && Cookies.get('cs_whois') !== '') {
				return Cookies.get('cs_whois').split('|').includes(cookieValue);
			}

			return false;
		}

		return js_global_is_csu;
	}

	return false;
}

function isDesignTools(param) {
	if( typeof design_tools !== 'undefined' ) {
		if( typeof param !== 'undefined' && typeof design_tools[param] !== 'undefined' ) {
			return design_tools[param];
		}

		if( typeof param !== 'undefined' && typeof design_tools[param] === 'undefined' ) {
			return false;
		}

		return design_tools;
	}

	return false;
}

/**
 * Vrati ID modulu
 * @param elem - jQuery element modulu, ktoreho ID chceme ziskat
 * @return int - ID modulu. Ak element neobsahuje triedu s definiciou modulu, vrati 0.
 */
function getModuleId(elem) {
	if (typeof elem === 'undefined')
		return 0;

	var classes = jQuery(elem).attr('class');

	console.log(classes);

	if (typeof classes === 'undefined')
		return 0;

	var mpid = classes.match(/mp_id(\d+)/);
	if (mpid != null && mpid instanceof Array)
		return parseInt(mpid[1]);
	return 0;
}

function vmExplodeProductVariant(attributes = '', ex_params = null) {
	let ret = {};
	if (typeof attributes === 'string' && attributes !== '') {
		attributes = attributes.replace('$@#@$:', '');
		let l = attributes.split(';');
		if (l !== null) {
			l.forEach((v) => {
				v = v.trim();
				if (v !== '') {
					let ret1 = {};
					let matches;

					// SPECIAL CHARS $@#@$:
					if (!(ex_params && ex_params['no_strip_special_replacement'])) {
						v = v.replace(/^\$\@\#\@\$\[\:\,]/, '');
					}

					if ((matches = v.match(/(.+?)(\[|\{|$)/)) && matches[1].trim() !== '') {
						// ATTR DATA
						let a = matches[1].replace(/[ ]{0,}\:[ ]{0,}/g, ':').trim();
						let l2 = a.split('-');
						l2.forEach((v2) => {
							let l3 = v2.split(':');

							if (typeof ret1['attr'] === 'undefined') {
								ret1['attr'] = {};
							}

							ret1['attr'][l3[0].trim()] = l3[1] ? l3[1].trim() : '';
						});

						// GROUPS
						v.match(/\{([\w]+)=(.+?)\}/g).forEach((match) => {
							let props = match.slice(1, -1).split('=');
							let propName = props[0];
							let propValue = props[1];

							if (typeof ret1['prop'] === 'undefined') {
								ret1['prop'] = {};
							}

							if (['CDATA', 'IMG', 'AID'].includes(propName)) {
								ret1['prop'][propName] = decodeURIComponent(propValue);
							} else {
								ret1['prop'][propName] = propValue;
							}
						});

						// PRICE
						if ((matches = v.match(/\[(.+?)\]/)) && matches[1].trim() !== '') {
							ret1['prop']['price'] = matches[1];

							let matches2;
							if ((matches2 = matches[1].match(/^(\+|\-|\=?)(.+)/))) {
								if (matches2[1]) {
									ret1['prop']['price_sign'] = matches2[1];
								}
								if (matches2[2]) {
									ret1['prop']['price_num'] = matches2[2];
								}
							}
						}

						// CUSTOM - SGP PAIR
						if (ret1['prop']['SGP']) {
							let prices = ret1['prop']['SGP'].split('|');
							ret1['prop']['SGP'] = {};
							prices.forEach((price) => {
								let sgp = price.split(':');
								ret1['prop']['SGP'][sgp[0]] = sgp[1];
							});
						}

						if (ex_params && ex_params['special_variant_key_underscores_replacement']) {
							a = a.replace(/ /g, '_');
						}

						ret1['source'] = v;

						if (ex_params && ex_params['assoc_by_code'] && ret1['prop']['CODE'] !== '') {
							a = ret1['prop']['CODE'];
						}

						ret[a] = ret1;
					}
				}
			});
		}
	}
	return ret;
}


function jsParseVariant(variant){
	var split = variant.split('{');
	var variants = {};
	jQuery(split).each(function (k,v){
		if (v.substr(-1) === "}") {
			v = v.slice(0, -1);
		}
		var v_split = [];
		if (v.indexOf(":")>0){
			v_split = v.split(':');
		} else if(v.indexOf("=")>0){
			v_split = v.split('=');
		}
		variants[v_split[0]] = v_split[1];
	});
	return variants;

}

function js_show_delivery_date_by_max_stock(element) {
	/*if( !jQuery('body').hasClass('shop_page_class_shop_product_details') ) return;
	if ( jQuery('.shop_product_availability_value').length > 0 && typeof product_stock !== 'undefined' && typeof productInCart !== 'undefined' ) {
		if( parseInt(product_stock) < parseInt(productInCart) ) {
			jQuery('.shop_product_availability_value:last').text('Nedostupne');
		}
	}*/
	var jqo = jQuery(element);
	var avail_jqo = jqo.parents('.variant-info-group').siblings('.vig-availability');
	var product_stock = avail_jqo.find('.product_in_stock').text();
	var jqo_value = parseInt(jqo.val());
	if ( jqo_value < 0 ) {
		jqo_value = 0;
	}
	if ( jqo_value > parseInt(product_stock) ) {
		avail_jqo.find('.variant-info-value').text('doba dodania sa môže líšiť');
		avail_jqo.removeClass('vig-avail-3');
		avail_jqo.addClass('vig-avail-4');
	} else {
		avail_jqo.find('.variant-info-value').text('skladom');
		avail_jqo.removeClass('vig-avail-4');
		avail_jqo.addClass('vig-avail-3');

	}
}

// dusko product delivery max stock
function js_show_delivery_max_stock(product_stock){
	// ak niesme v product_details
	var max_stock = false;
	if( !jQuery('body').hasClass('shop_page_class_shop_product_details') ) return;

	if( jQuery('.variant_btns_custom').length > 0 ) {
		if( jQuery('.variant_btn_custom_selected').length > 0 ){
			// armymarket ma zapnute custom varianty
			var variant_index = jQuery('.variant_btn_custom_selected').data('index');
			var variant_attrib = jQuery('.prod_adv_attribs_div select .attrib_comb_' + variant_index).val();
			var variant = jsParseVariant(variant_attrib);
			var stock = typeof variant.SS !== 'undefined' && typeof variant.S !== 'undefined' && variant.S == 0 ? variant.SS : variant.S;
			jQuery('.dodanie .date-container .text').remove();
			if ( parseInt(stock) > 0 ){
				var text = js_lang_max_product_stock_per_order.replace('{stock}', stock);
				jQuery('.dodanie .date-container').append('<span class="text">' + text  +'</span>');
				max_stock = true;
			}

		} else if( product_stock > 0){
			// toto je volane z product details vzdy tak to nechajte ako poslednu podmienku
			var text = js_lang_max_product_stock_per_order.replace('{stock}', product_stock);
			jQuery('.dodanie .date-container').append('<span class="text">' + text  +'</span>');
			max_stock = true;
		}

		if( jQuery('.dodanie .dodanie_inner.max_stock').length > 0 && !max_stock){
			jQuery('.dodanie .dodanie_inner').removeClass('max_stock');
		}
		if( jQuery('.dodanie .dodanie_inner.max_stock').length == 0 && max_stock){
			jQuery('.dodanie .dodanie_inner').addClass('max_stock');
		}

		return;
	}
	if ( is_cs_user() ) {
		console.log('treba este dorobit ine druhy variantov');
		return;
	}
}

// JAN product last pieces box
function js_last_pieces_html_box(elem){

	if( !jQuery('body').hasClass('shop_page_class_shop_product_details') ) return;

	var container = jQuery('.product_last_piece_box');

	if( container.length == 0 || typeof(last_pieces_info_enabled) == 'undefined' || last_pieces_info_enabled == 0 ) return;

	// Ak ma produkt atributy musi sa to spustit z local.js cez change (co sa deje vo vecsine pripadov)
	var hasattribs = (jQuery('#addtocart .prod_adv_attribs_div').length > 0);

	if (elem === 0 && hasattribs) return;

	// O Aky typ zobrazenia ide?
	var box_val = '';
	var anchork = jQuery(elem);
	var classes = anchork.attr('class');
	if (typeof classes !== 'undefined'){
		var classList = classes.split(/\s+/);

		for (var i = 0; i < classList.length; i++) {
			switch(classList[i]){
				// Radio inputs
				case 'shop_addtocart_advanced_attribute_tbl' : {
					box_val = anchork.attr('data-value');
					break;
				}
				// Href / image inputs
				case 'shop_addtocart_advanced_attribute_block' : {
					box_val = anchork.val();
					break;
				}
				// Select box
				case 'main_attr_select' : {
					box_val = anchork.val();
					break;
				}
			}
		}

		if (box_val === '' && anchork.is('input')) box_val = anchork.val();
	}

	var _render_last_pieces = function(result) {
		if (typeof result !== 'object' || result == null || typeof result.content == 'undefined') {
			container.html('');
			return;
		}
		var inner_html = '<div class="last_pieces_detail_tag ' + result.class + '"><span>' + result.content + '</span></div>';
		container.html(inner_html);
		var filter_object = jQuery('.last_pieces_detail_tag span');
		var orig_color = filter_object.css('color');
			  filter_object
			  .css('color','#FFF')
			  .css('transition', 'all 0.3s ease-out')
			  .css('-webkit-transition', 'all 0.3s ease-out')
			  .css('-moz-transition', 'all 0.3s ease-out')
			  .css('-o-transition', 'all 0.3s ease-out');
				setTimeout( function(){
					filter_object
					.css('color',orig_color);
			},200);
	};

	if (typeof window.last_pieces_cache === 'undefined') window.last_pieces_cache = {};

	var box_val_key = btoa(encodeURIComponent(box_val));

	if (typeof window.last_pieces_cache[box_val_key] !== 'undefined'){

		_render_last_pieces(window.last_pieces_cache[box_val_key]);
	} else {

		// Setneme to uz teraz aby sa to nevolalo dookola
		window.last_pieces_cache[box_val_key] = {};

		var options = {};
		var prodIdClass = jQuery('body').attr('class').match(/product_id_(\d+)/gm);

		options.function = 'get_last_pieces';
		options.product_id = prodIdClass.length > 0 ? prodIdClass[0].replace('product_id_', '') : jQuery('input[name="product_id"]').val();
		options.variant = box_val;

		jQuery.post('/includes/frontend_ajax.php', options, function(res){

			// If json response is null, then set result to an empty object
			result = csJsonParse(res) || {};
			if (result.status == '1'){

				window.last_pieces_cache[box_val_key] = result;
				_render_last_pieces(window.last_pieces_cache[box_val_key]);
			} else {
				if (result.status == '0') {
					container.html('');
				}
			}
		});
	}
}
function printStackTrace() {
	var callstack = [];
  var isCallstackPopulated = false;
  try {
	i.dont.exist+=0; //doesn't exist- that's the point
  } catch(e) {
  	console.log(e.stack);
	if (e.stack) { //Firefox
	  var lines = e.stack.split("\n");
	  for (var i=0, len=lines.length; i<len; i++) {
		if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
		  callstack.push(lines[i]);
		}
	  }
	  //Remove call to printStackTrace()
	  callstack.shift();
	  isCallstackPopulated = true;
	}
	else if (window.opera && e.message) { //Opera
	  var lines = e.message.split("\n");
	  for (var i=0, len=lines.length; i<len; i++) {
		if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
		  var entry = lines[i];
		  //Append next line also since it has the file info
		  if (lines[i+1]) {
			entry += " at " + lines[i+1];
			i++;
		  }
		  callstack.push(entry);
		}
	  }
	  //Remove call to printStackTrace()
	  callstack.shift();
	  isCallstackPopulated = true;
	}
  }
  if (!isCallstackPopulated) { //IE and Safari
	var currentFunction = arguments.callee.caller;
	while (currentFunction) {
	  var fn = currentFunction.toString();
	  var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
	  callstack.push(fname);
	  currentFunction = currentFunction.caller;
	}
  }

  output(callstack);
}

function output(arr) {
  //Output whatever you want
  console.info('stack trace', arr.join("nn"));
}

//peter

	//vytvorenie odkazu na editaciu po mouse over na produkt
	if (typeof js_global_user_info !='undefined' && js_global_user_info.gid >= 24) {
		jQuery(function() {

			var _body = jQuery('body');

			_body.on('mouseenter', '#product_list .shop-category-product', function(){

				var productId = jQuery(this).find('.product-cart input[name="product_id"]').val();

				if (typeof productId === 'undefined') {
					productId = jQuery(this).find('input[name="product_id"]').val();
				}

				if (typeof productId === 'undefined') {
					productId = jQuery(this).find('input[name="shop_no_price_product"]').val();
				}

				if (typeof productId === 'undefined') {
					var classNames = jQuery(this).attr('class').split(/\s+/)
						.filter(function(className) { return className.substr(0, 11) === 'product_id_'; })
						.map(function(className) { return className.substr(11); });

					if (classNames.length) {
						productId = parseInt(classNames.pop());
					}
				}

				if (typeof productId !== 'undefined') {
					jQuery(this).append([
						'<div class="edit-me" style="z-index:999; position:absolute; top:20px; right:20px;">',
							'<a href="/administrator/index2.php?option=com_shop&page=product.product_list&show_id='+ productId +'" target="_blank">',
								'<img src="/administrator/components/com_shop/css/edit.svg" alt="" title="' + js_lang_edit_label + '">',
							'</a>',
						'</div>'
					].join(''));
				}
			});

			_body.on('mouseleave', '#product_list .shop-category-product', function(){

				jQuery(this).find('.edit-me').remove();
			});
		});

	}

	//vytvorenie odkazu na editaciu po mouse over na detail produktu
	if (typeof js_global_user_info !== 'undefined' && js_global_user_info.gid >= 24) {
		jQuery(function() {
			var product = jQuery(jQuery('.flypage1 .flypage-top').find('h1, h2, h3')[0]);
			var flypageTitle = jQuery('.flypage1 .flypage-h1');

			if (flypageTitle.length) {
				product = flypageTitle;
			}

			if (typeof product === 'undefined') {
				return;
			}

			product.on('mouseenter',function() {
				jQuery(this).append('<span class="edit-me"><a href="/administrator/index2.php?option=com_shop&page=product.product_list&show_id=' + js_product_id + '" target="_blank" ><img src="/administrator/components/com_shop/css/edit.svg" alt="" title="' + js_lang_edit_label + '" ></a></span>');
			});
			product.on('mouseleave', function () {
				jQuery(this).find('.edit-me').remove();
			});
		});
	}
//END
//peter
if (typeof Config_accept_cookies_bar !== 'undefined' && Config_accept_cookies_bar == 1) {
	jQuery(function () {
		jQuery.acceptCookies({
			fixed: true
		});
	});
}
//END peter
/**
 * Najde a vrati zoznam hladanych javascriptovych premennych.
 * Funkcia preleti polom vsetkych globalnych (resp. definovanych vo window scope) JS premennych a funkcii a vrati
 * indexovane pole tych, v ktorych nazve sa nachadza hladany vyraz.
 * Hladany vyraz musi mat aspon tri znaky, inac sa hladanie vykonavat nebude.
 *
 * @author Marek J. Kolcun
 * @param string searchFor - retazec, ktory chceme najst v nazvoch JS premennych/funkciach
 * @param boolean onlyVariables - ak je zadana boolean hodnota, vyhladaju sa: iba premenne (TRUE), iba funkcie (FALSE), inac vrati vsetky vysledky
 * @return array - indexovane pole so zoznamom najdenych vysledkov
 */
function searchForVar(searchFor, onlyVariables) {
	if (typeof searchFor === 'undefined' || searchFor.length < 3) {
		console.warn('Zadaj aspon 3 znaky.');
		return [];
	}

	var reg = new RegExp(searchFor, 'i');
	var results = Object.keys(window).reduce(function(res, val, key) {
		if (val.match(reg)) {
			if (typeof window[val] === 'function')
				res.functions.push(val);
			else
				res.variables.push(val);
		}
		return res;
	}, {variables: [], functions: []});

	if (typeof onlyVariables === 'boolean') {
		return (onlyVariables) ? results.variables : results.functions;
	}
	return results;
}

var newsletter_setting = {
	confirm : {},
	data : {},
	original_data : {},
	box : {},
	rbox : {},
	init : function(){

		newsletter_setting.box = jQuery('.ans_wrap');
		newsletter_setting.rbox = jQuery('.ans_res_box');
		newsletter_setting.confirm = jQuery('.ans_confirm');
		newsletter_setting.loader = jQuery('.ans_loader');

		newsletter_setting.confirm.on('click', function(){
			var btn = jQuery(this);
			newsletter_setting.saveData();
		});

		jQuery('.ans_input').on('click', function(){
			var input = jQuery(this);
			if (!newsletter_setting.check()){
				newsletter_setting.confirm.show();
			} else {
				newsletter_setting.confirm.hide();
			}
		});

		newsletter_setting.getData();
		newsletter_setting.original_data = JSON.stringify(newsletter_setting.data);
	},
	check : function(){

		newsletter_setting.getData();
		return (typeof newsletter_setting.original_data !== 'undefined' && newsletter_setting.original_data === JSON.stringify(newsletter_setting.data));
	},
	saveData : function(){

		newsletter_setting.getData();
		var options = {};
		options.function = 'save_newsletter_setting';
		options.data = JSON.stringify(newsletter_setting.data);
		newsletter_setting.confirm.hide();
		newsletter_setting.loader.show();
		jQuery.post('/includes/frontend_ajax.php', options, function(res){

			var result = JSON.parse(res);
			newsletter_setting.loader.hide();
			if (result.status == '1'){

				newsletter_setting.original_data = options.data;

				newsletter_setting.rbox.append(result.content);
				setTimeout(function (){newsletter_setting.rbox.find('.ans_msg').remove();}, 5000);
			}
		});
	},
	getData : function(){

		newsletter_setting.data = {};
		newsletter_setting.box.find('.ans_box').each(function(){

			var name = jQuery(this).find('input').attr('name');
			var value = parseInt(jQuery(this).find('input:checked').val());
			newsletter_setting.data[name] = value;
		});
	}
};

function disableOrderGroup(comp, disable) {
		jQuery(comp).find('input[type=checkbox]').each(function(){
			if(jQuery(this).hasClass('disabled')){
				jQuery(this).prop('disabled', true);
			} else {
				jQuery(this).prop('disabled', disable);
			}
		});
		comp.find('label').css({'color': (disable ? '#868686' : 'black')});
	//	comp.find('input[type=checkbox]').prop('disabled', disable);
	//	comp.find('label').css({'color': (disable ? '#868686' : 'black')});

}

function clickOrderGroup(bool) {
	disableOrderGroup(jQuery('#simpleStepOrder'), !bool);
	disableOrderGroup(jQuery('#twoStepOrder'), bool);

	var comp = bool ?  jQuery('#simpleStepOrder') : jQuery('#twoStepOrder');
	var def = jQuery('select[name=conf_VM_BROWSE_ORDERBY_FIELD]');
	var selected = def.find('option:selected').val();
	var html = '';

	def.html('');
	comp.find('input').each(function() {
		var newVal = jQuery(this).val().replace(/_2$/g, '');

		html += "<option value=\"" + newVal + "\"";

		if(selected == newVal)
			html += " selected=\"selected\" ";

		html += ">" + jQuery(this).next('label').html() + "</option>\n";
	});

	def.html(html);
}

function setCookieOrder() {
	Cookies.set('stepOrder', '');

	jQuery('#simpleStepOrder input').each(function() {
		var cookie = Cookies.get('stepOrder');

		if(jQuery(this).is(':checked'))
			Cookies.set('stepOrder', cookie + ((cookie != '') ? ',' : '') + jQuery(this).val());
	});

	jQuery('#twoStepOrder input').each(function() {
		var cookie = Cookies.get('stepOrder');

		if(jQuery(this).is(':checked'))
			Cookies.set('stepOrder', cookie + ((cookie != '') ? ',' : '') + jQuery(this).val());
	});
}

jQuery(function() {
	if(jQuery('#simpleStepOrder').length > 0 && jQuery('#twoStepOrder').length > 0) {
		clickOrderGroup(jQuery('#order_type1').is(':checked'));
		setCookieOrder();

		jQuery('#simpleStepOrder input, #twoStepOrder input').on('change', function() {
			setCookieOrder();
		});
	}

});

function showConfirmUrl(comp) {
	jQuery("#url_confirm").toggle(jQuery(comp).is(':checked'));
}

function js_verify_coupon_code(elem){

	var btn = jQuery(elem);
	var options = {};
	options.function = 'verify_coupon_code';
	options.coupon_code = jQuery('input[name="coupon_code"]').val();
	btn.startAjaxLoader();
	jQuery.post(js_global_live_site+'/includes/frontend_ajax.php', options, function (res) {
		btn.stopAjaxLoader();
		var result = JSON.parse(res);
		jQuery('.coupon_verify_result').html(result.content);
	});
}

function js_convertToDate(timestamp, format){

if (typeof format == "undefined" ) var format = "date.month.year hour:min:sec";
  var a = new Date(timestamp * 1000);
  var year = a.getFullYear();
  var month = parseInt(a.getMonth()) + 1;
  var date = a.getDate();
  var hour = a.getHours();
  var min = a.getMinutes();
  var sec = a.getSeconds();
  if(sec < 10) var bsec = '0';
  else var bsec = '';
  if(min < 10) var bmin = '0';
  else var bmin = '';
  if(hour < 10) var bhour = '0';
  else var bhour = '';
  hour = bhour + hour;
  min = bmin + min;
  sec = bsec + sec;
  var r = "";
  r = format.replace("date",date);
  r = r.replace("month",month);
  r = r.replace("year",year);
  r = r.replace("hour",hour);
  r = r.replace("min",min);
  r = r.replace("sec",sec);
  return r;
}

/***********/

function js_pp_confirm(main_text, button1_text, button2_text, options, after_close_callback_fn, before_close_callback_fn) {
    //if (is_cs_user() && typeof options === 'object' && 'useVex' in options && options.useVex)
	return js_vex_confirm(main_text, button1_text, button2_text, options, after_close_callback_fn, before_close_callback_fn);
}



function itemsAreIdentical(array) {
    for(var i = 0; i < array.length - 1; i++) {
        if(array[i] !== array[i+1]) {
            return false;
        }
    }
    return true;
}



function js_vex_confirm(main_text, button1_text, button2_text, options, after_close_callback_fn, before_close_callback_fn){

	if (typeof(js_global_is_csu) != 'undefined' && js_global_is_csu && typeof(console) != 'undefined') {
        console.log('js_vex_confirm');
    }

	var main_text_html = main_text;

	if (typeof(closing_allowed) != 'undefined' ) {
		if (button1_text != '' || button2_text != '') {
			main_text_html += '<div class="vex-dialog-form">';

			if (button1_text != '') {
				main_text_html += '<div class="save-icon-container "><a class="pp_confirm_button1 vex-dialog-button-primary vex-dialog-button vex-last" href="#">' + button1_text + '</a></div>';
			}

			if (button2_text != '') {
				main_text_html += '<div class="cancel-icon-container"><a href="#" class="pp_confirm_button2 vex-dialog-button-secondary vex-dialog-button vex-last">' + button2_text + '</a></div>';
			}

			main_text_html += '</div>';
		}
    }

	var vexOptions = {
		content: main_text_html,
		afterOpen: function () {
			jQuery('input[type="button"].button.two')
				.off()
				.on('click', function () {
					vex.close();
				});
		},
		beforeClose: function () {
			if (typeof(before_close_callback_fn) == 'function') {
				before_close_callback_fn(false, options);
			}
		},
		afterClose: function() {
			if (typeof(after_close_callback_fn) == 'function') {
				after_close_callback_fn(false, options);
			}
		}
	};

	if (typeof options !== 'undefined' && options.extra_class) {
		vexOptions.className = options.extra_class;
	}

	vex.open(vexOptions);

   return false;
}

/**
 * Skonvertuje timestamp na datum
 */
function convertDate(timestamp, format){

	var c = '';

	if (typeof format == 'undefined') format = 'Y-m-d';

	try{

		format = format.split('');

		var date = new Date(parseInt(timestamp) * 1000);

		if (!format.length || timestamp.split('').length !== 10) throw 'Invalid format';

		for(var i=0; i<format.length; i++){

			var h = '';
			switch(format[i]){

				case 'Y' : { c += date.getFullYear(); break; }
				case 'm' : {
					h = date.getMonth() + 1;
					c += (h < 10 ? '0'+h : h);
					break;
				}
				case 'd' : {
					h = date.getDate();
					c += (h < 10 ? '0'+h : h);
					break;
				}
				default : c+= format[i];
			}
		}

		return c;

	} catch (e){

		return timestamp;
	}
}

function js_product_special_group_change(elem, group_id) {
    elem = jQuery(elem);

    if (typeof(group_id) == 'undefined')
        group_id = elem.val();

    elem.siblings('.order_by_option').removeClass('active');
    elem.addClass('active');

    var path_name = window.location.pathname + '/';
    window.location.href = 'http://' + window.location.host + path_name.match(/^\/[^\/]+\//)[0] + ((parseInt(group_id) > 0) ? 'g' + group_id + ',a' + (jQuery('select#limit').length ? ',' + jQuery('select#limit').val() : '') + '/' : '');
}

function saveAdminLanguages(){
	alert("save admin langs");
}

/**
 * @function initAutoTooltip
 */
var initAutoTooltip = function () {

	/**
	 * JAN, tento observer je brutal overkill, ktory sa pouziva iba na autodetekciu inicializacie poshytipu pri dynamickom vlozeni elementov
	 * Nemoze sa to robit takto? jQuery('body').on('mouseenter', '[data-tooltip]',  function(){ initTooltip(this); });
	 */
	if (jQuery('body.optimized_list').length) return;

	var addedTypes = [
		'childList',
		'subtree',
		'characterData'
	];
	var attrTypes = ['attributes'];
	var attrNames = [
		'data-tooltip',
		'tooltip'
	];

	if ( typeof MutationObserver === 'undefined' ) {
		return;
	}

	var observer = new MutationObserver(function (mutations) {
		var init = false;
		var mutation, index;

		for (index in mutations) {
			if (!mutations.hasOwnProperty(index)) {
				continue;
			}

			mutation = mutations[index];

			if ((!!~addedTypes.indexOf(mutation.type) && mutation.addedNodes.length) || (!!~attrTypes.indexOf(mutation.type) && !!~attrNames.indexOf(mutation.attributeName))) {
				init = true;
				break;
			}
		}

		if (init) {
			initTooltip();
		}
	});

	var observe = function () {
		var target = document.getElementById('m1');

		if (target instanceof Node) {
			observer.observe(target, {
				attributes: true,
				childList: true,
				subtree: true,
				characterData: true
			});
		} else {
			console.log(target);
		}
	};

	var disconnect = function () {
		if ( observer !== null ) {
			observer.disconnect();
		}
	};

	var initTooltip = function () {
		jQuery('[data-tooltip]').each(function () {
			var $elem = jQuery(this);
			var alignX = $elem.data('tip-x') || 'right';
			var alignY = $elem.data('tip-y') || 'center';
			var showOn = $elem.data('tip-show') || 'hover';
			var showTimeout = parseInt($elem.data('tip-timeout')) || 0;
			var offsetX = parseInt($elem.data('tip-offset-x')) || 0;
			var offsetY = parseInt($elem.data('tip-offset-y')) || 0;
			var $elemClone;

			var tipInit = $elem.attr('tip-init');

			if ( typeof tipInit !== 'undefined' ) {
				disconnect();

				$elemClone = $elem.clone();
				$elem.after($elemClone);
				$elem.remove();
				$elem = $elemClone;

				observe();
			}

			//if ( typeof console !== 'undefined' ) {
			//	console.group('Debug');
			//	console.log($elem);
			//	console.log($elem.data('tip-init'));
			//	console.log($elem.attr('tip-init'));
			//	console.groupEnd();
			//}

			//if ( typeof tipInit === 'undefined' ) {
				$elem.attr('tip-init', true);
				$elem.poshytip({
						alignX: alignX,
						alignY: alignY,
						offsetX: offsetX,
						offsetY: offsetY,
						showOn: showOn,
						showTimeout: showTimeout,
						alignTo: 'target',
						className: 'global_tooltip',
						content: '<span class="tooltip poshy-tooltip ' + ($elem.attr('class') || '') + '">' + $elem.data('tooltip') + '</span>'
					});
			//}
		});
	};

	initTooltip();
	observe();
};

/**
 * @author Martin Hucko <marzineez@gmail.com>
 * @function initLogMessages
 * @returns {Boolean}
 */
var initLogMessages = function () {
	var messages = window.logMessages;
	var priorities = [
		'debug',
		'tip',
		'info',
		'notice',
		'alert',
		'warning',
		'error',
		'critical',
		'emergency'
	];

	/**
	 * @function getHighestPriorityMessage
	 * @inner
	 * @returns {Object}
	 */
	var getHighestPriorityMessage = function () {
		var highestIndex = 0;
		var critMessage = messages[0];

		messages.forEach(function (message) {
			var index = priorities.indexOf(message.className);

			if (index > highestIndex) {
				highestIndex = index;
				critMessage = message;
			}
		});

		return critMessage;
	};

	/**
	 * @function showVex
	 * @inner
	 * @param {String} title
	 * @param {String} body
	 * @param {String} className
	 */
	var showVex = function (title, body, className) {
		vex.dialog.alert({
			message: '<span class="login-title">' + title + '</span>',
			input: body,
			className: 'vex-cs vex-log ' + className
		});
	};

	/**
	 * @function getUniqueMessages
	 * @returns {Object[]}
	 */
	var getUniqueMessages = function () {
		var newArray = [];
		var lookupObject = {};
		var i;

		for (i in messages) {
			if (messages.hasOwnProperty(i)) {
				lookupObject[messages[i].message] = messages[i];
			}
		}

		for (i in lookupObject) {
			if (lookupObject.hasOwnProperty(i)) {
				newArray.push(lookupObject[i]);
			}
		}

		return newArray;
	};
	var topMessage;

	if (!(messages instanceof Array) || js_is_empty(messages)) {
		return false;
	}

	messages = getUniqueMessages();
	messages.sort(function (a, b) {
		var aPriority = priorities.indexOf(a.className);
		var bPriority = priorities.indexOf(b.className);

		if (aPriority === bPriority) {
			return 0;
		}

		return aPriority > bPriority ? -1 : 1;
	});

	if (messages.length === 1) {
		topMessage = messages[0];

		showVex(topMessage.title, topMessage.message, topMessage.className);

		return true;
	}


	topMessage = getHighestPriorityMessage();

	showVex(topMessage.title, '<ul>' + messages.map(function (message) {
		return '<li class="' + message.className + '">' + message.message + '</li>';
	}).join('') + '</ul>', topMessage.className);

	return true;
};

/**********/
jQuery(function () {
	if (is_cs_user()) {
		console.log('%cJS INIT LOAD', 'color: #2196F3');
	} else if (typeof js_lang_we_are_hiring !== 'undefined') {
		console.log(js_lang_we_are_hiring);
	}

	//if(is_cs_user()) {
	var module_cont_nivo_slider = jQuery('.module_cont_nivo_slider');
		if(module_cont_nivo_slider.length > 0) module_cont_nivo_slider.addClass('theme-default');
	//}

	if ( typeof js_CS_Config_cs_infobar !== 'undefined' && js_CS_Config_cs_infobar == '1' ){
		js_infobar_cs('.cs_infobar');// app 946, CS_Config_cs_infobar

		if ( typeof js_Config_infowidget_countdown_timer !== 'undefined' && js_Config_infowidget_countdown_timer ) {
			var infobarElem = jQuery('.cs_infobar');
			if ( infobarElem.length > 0 && js_Config_infowidget_countdown_timer.end != '' && js_Config_infowidget_countdown_timer.start != '' ) {
				var currentTime = new Date().getTime();

				if ( js_Config_infowidget_countdown_timer.startTimestamp != '' ) {
					var startDate = js_Config_infowidget_countdown_timer.startTimestamp;
				} else {
					var startDate = Date.parse(js_Config_infowidget_countdown_timer.start.split(' ')[0].split('.').reverse().join('-') + ' ' + js_Config_infowidget_countdown_timer.start.split(' ')[1]);
				}

				//var startDate = new Date(js_Config_infowidget_countdown_timer.start.split(' ')[0].split('.').reverse().join('-') + ' ' + js_Config_infowidget_countdown_timer.start.split(' ')[1]).getTime();
				if (currentTime > startDate) {

					//infobarElem.find('.inner').append('<div class="timer"></div>');
					infobarElem.find('.text p:last-child').append('<span class="timer"></span>');
					var elem = infobarElem.find('.inner').find('.timer');
					if ( js_Config_infowidget_countdown_timer.endTimestamp != '' ) {
						var endDate = js_Config_infowidget_countdown_timer.endTimestamp;
					} else {
						var endDate = Date.parse(js_Config_infowidget_countdown_timer.end.split(' ')[0].split('.').reverse().join('-') + ' ' + js_Config_infowidget_countdown_timer.end.split(' ')[1]);
					}
					//var endDate = new Date(js_Config_infowidget_countdown_timer.end.split(' ')[0].split('.').reverse().join('-') + ' ' + js_Config_infowidget_countdown_timer.end.split(' ')[1]).getTime();
					initInfowidgetCountdownTimer(endDate, elem);
				}
			}
		}
	}

	/**
	 * Log/info/warn/error to console for cs users only
	 */
	if ( console && ( !jQuery('body').hasClass('cs_user_ip') && ( typeof js_global_is_csip === 'undefined' || !js_global_is_csip ) ) ) {
		console.log = function() {};
		console.info = function() {};
		console.warn = function() {};
		console.error = function() {};
	}

	initAutoTooltip();
	initLogMessages();

	setTimeout(function() {
		showNotificationsAfterReload()
	}, 500);
});
// example: array("1=aaa") to array(1:'aaa');
function splitArrayToKeyValue(x, splitter) {

	var obj = {};
	for (var i = 0; i < x.length; i++) {
		var split = x[i].split(splitter);
		obj[jQuery.trim(split[0])] = jQuery.trim(split[1]);
	}
	return obj;
}

function getLang(lang, def) {
	var langText = '';

	if( lang.indexOf('js_lang') === -1 ) {
		langText = window['js_lang_' + lang];
	} else {
		langText = window[lang];
	}

	if ( typeof langText !== 'undefined' ) {
		return langText;
	}

	if ( typeof def !== 'undefined' ) {
		return def;
	}

	return '';
}

function closeOutdatedBrowserAlert() {
	Cookies.set('outdatedBrowserAlertCookie', 1, { expires: 1 });
	jQuery('#outdatedBrowser').remove();
}

/*
	type - success, info, error, notice
 */
function showNotification(text, title, type, delay, autohide, options, custom_class) {

	var opts = {};
	opts.target = document.body;
	opts.title = (typeof title !== 'undefined') ?  title : false;
	opts.text = (typeof text !== 'undefined') ?  text : false;
	opts.type = (typeof type !== 'undefined') ?  type : "success";
	opts.delay = (typeof delay !== 'undefined') ?  delay : 10000;
	opts.hide = (typeof autohide !== 'undefined') ?  autohide : true;
	add_custom_class = (typeof custom_class !== 'undefined') ?  custom_class : '';
	opts.addclass = "stack-custom "+add_custom_class;

	if (typeof options === 'object') opts = jQuery.extend(true, {}, opts, options);

	// PNotify
	if (typeof PNotify !== 'undefined') {
		return new PNotify(opts);
	}

	// docasne riesenie pokym nebude nieco univerzalnejsie
	if (false && typeof CsModal !== 'undefined') {
		let csModalType = 'info';
		if (type === 'error' || type === 'warning') {
			csModalType = type;
		}

		return new CsModal()
			.setClassName('notification notification_alert')
			.setType(csModalType)
			.setTitle(opts.title)
			.setContent(opts.text)
			.hideCloseButton(false)
			.open();
	}
}

function showNotificationsAfterReload() {
	/* zobrazovanie notifikacii z localstorage */
	var notifications = localStorage.getItem('NotificationsAfterReload');
	if (notifications) {
		notifications = JSON.parse(notifications);
		if (typeof notifications === 'object') {
			showNotificationsFromList(notifications);
			localStorage.removeItem('NotificationsAfterReload');
		}
	}
}

/**
 *
 * @param notificationList {type: string, title: string, body: string}[]
 */
function showNotificationsFromList(notificationList) {

	if (typeof notificationList !== 'object' || !notificationList.length) {
		return;
	}

	notificationList.map(function(notificationData) {
		showNotification(notificationData.body, notificationData.title, notificationData.type);
	});
}

function config(_config) {
	if (typeof _config !== 'string') {
		return undefined;
	}

	if (_config.includes('.')) {
		let keys = _config.split('.');
		let obj = window;
		for (let i = 0; i < keys.length; i++) {
			obj = obj[keys[i]];
			if (typeof obj === 'undefined') {
				return undefined;
			}
		}

		return obj;
	}

	if (typeof window[_config] !== 'undefined') {
		return window[_config];
	}

	return undefined;
}

jQuery( document ).ajaxError(function(event, jqxhr, settings, thrownError) {

	if (typeof jqxhr.status !== 'undefined' && jqxhr.status == 408){

		jQuery(document).trigger('onAjaxError');
		var title = (typeof cms_js_lang_request_timeout_error_title !== 'undefined' ? cms_js_lang_request_timeout_error_title : '');
		var text = (typeof cms_js_lang_request_timeout_error !== 'undefined' ? cms_js_lang_request_timeout_error : '');
		vex.dialog.open({
			className: "vex-cs newsletter_vex",
			showCloseButton: true,
			escapeButtonCloses: true,
			message: '<span class="login-title">' + title + '</span>',
			input: text,
			buttons: [jQuery.extend({}, vex.dialog.buttons.YES, {text: "OK"})]
		});
	}
});

function js_get_gdpr_form_name(form_id) {
	switch (form_id) {
		case "1":
			return js_gdpr_watch_dog;
		case "2":
			return js_gdpr_send_to_friend;
		case "3":
			return js_gdpr_product_question;
		case "4":
			return js_gdpr_contact_form;
		case "5":
			return js_gdpr_register_form;
		case "6":
			return js_gdpr_module_newsleatter;
		case "7":
			return js_gdpr_comment;
		case "8":
			return js_gdpr_product_best_price;
		case "100":
			return js_gdpr_checkout;
		case "400":
			return 'product reservation';
		case "499":
			return js_gdpr_dt_form;
		case "500":
			return js_gdpr_module_short_contact_form;
		case "501":
			return js_gdpr_module_contest_form;
		case "505":
			return js_gdpr_contact_form + " - universal";
		case "999":
			return js_gdpr_first_login;
		default:
			return js_gdpr_unknown;
	}
}

function js_admin_user_list_gdpr_info(user_id, elem) {

	new AjaxRequest({user_id: user_id})
		.setMethod('POST')
		.setController('Customer')
		.setAction('getGdprUserData')
		.onSuccess(function (response) {
			var data = response.data['gdpr'];
			if (data === null) {
				jQuery(elem).tooltipster({
					theme        : "tooltipster-gdpr",
					trigger      : 'click',
					contentAsHTML: true,
					trackTooltip : true,
					trackOrigin  : true,
					multiple     : false,
					timer        : 3000,
					content      : js_gdpr_empty_data
				}).tooltipster('open');
				return true;
			}
			var gdpr_table_html = '<table class="adminlist gdpr_approval_table">';
			gdpr_table_html += '<thead>';
			gdpr_table_html += '<th class="title"></th>';
			gdpr_table_html += '<th class="title" title="' + js_gdpr_version_title_head + '">' + js_gdpr_version + '</th>';
			gdpr_table_html += '<th class="title" title="' + js_gdpr_cdate_title_head + '">' + js_gdpr_cdate + '</th>';
			gdpr_table_html += '<th class="title" title="' + js_gdpr_form_id_title_head + '">' + js_gdpr_form_id + '</th>';
			gdpr_table_html += '</thead>';
			gdpr_table_html += '<tbody>';
			jQuery.each(data, function(i,v){
				if (v === null) {
					jQuery(elem).tooltipster({
						theme        : "tooltipster-gdpr",
						trigger      : 'click',
						contentAsHTML: true,
						trackTooltip : true,
						trackOrigin  : true,
						multiple     : false,
						timer        : 3000,
						content      : js_gdpr_empty_data
					}).tooltipster('open');
					return true;
				}
				gdpr_table_html += '<tr>';
				gdpr_table_html += '<td class="data">' + '<span class="cs_icon csi-file-text-o" onclick="js_admin_user_list_get_gdpr_verion(' + v.version_id + ', this)" title="' + js_gdpr_copy + '"></span>' + '</td>';
				gdpr_table_html += '<td class="data" title="' + js_gdpr_version_title + '">' + v.version_id + '</td>';
				gdpr_table_html += '<td class="data">' + v.cdate + '</td>';
				gdpr_table_html += '<td class="data">' + js_get_gdpr_form_name(v.form_id) + '</td>';
				gdpr_table_html += '</tr>';
			});
			if (typeof response.data['additional_approves'] !== 'undefined') {
				jQuery.each(response.data['additional_approves'], function(i,v) {

					jQuery.each(v.tableData, function (ii, vv) {
						gdpr_table_html += '<tr>';
						gdpr_table_html += '<td class="data"> </td>';
						gdpr_table_html += '<td class="data">' + v.title + '</td>';
						jQuery.each(vv, function (iii, vvv) {
							gdpr_table_html += '<td class="data">' + vvv + '</td>';
						});
						gdpr_table_html += '</tr>';
					});

				});
			}
			gdpr_table_html += '</tbody></table>';

			vex.dialog.open({
				message: '<span class="login-title">' + js_gdpr_personal_gdpr_approval_title + '</span>',
				input: gdpr_table_html,
				buttons: [
					jQuery.extend({}, vex.dialog.buttons.NO, {
						text: 'OK'
					})
				],
				callback: function(data) {
				}
			});
		})
		.send();
}

function js_admin_user_lisg_gdpr_personal_info(user_id) {

	if (typeof user_id === 'undefined') {
		user_id = 0;
	}

	new AjaxRequest({user_id: user_id})
		.setMethod('POST')
		.setController('Customer')
		.setAction('getGdprUserPersonalInfo')
		.onSuccess(function (response) {
			var data = response.data[0];
			var gdpr_table_html = '';

			for (var index in data) {
				gdpr_table_html += '<fieldset class="gdpr_fieldset">';
				gdpr_table_html += '<legend>' + (data[index].address_type == "BT" ? js_lang_address_type_bt : js_lang_address_type_st) + '</legend>';
				gdpr_table_html += '<div class="fieldset_content">';
					gdpr_table_html += '<div class="name_cell">';
						gdpr_table_html += '<span class="title">';
							gdpr_table_html += js_lang_name;
						gdpr_table_html += '</span>';
						gdpr_table_html += '<span class="order_address_name">';
				gdpr_table_html += (data[index].first_name != null && data[index].first_name != "" ? data[index].first_name : '') + ' ' + (data[index].middle_name != null && data[index].middle_name != "" ? data[index].middle_name : '') + ' ' + (data[index].last_name != null && data[index].last_name != "" ? data[index].last_name : '');
				gdpr_table_html += '</span>';
				gdpr_table_html += '</div>';
				gdpr_table_html += '<div class="address_cell">';
				gdpr_table_html += '<span class="title">' + js_lang_address + '</span>';
				gdpr_table_html += '<span>' + data[index].address_1 + '</span>';
				gdpr_table_html += '<div class="country_name">' + data[index].zip + ' ' + data[index].city + '</div>';
				gdpr_table_html += '<div class="country_name">' + data[index].state + '</div>';
					gdpr_table_html += '</div>';
					if (data[index].phone_1 != null && data[index].phone_1 != "") {
						gdpr_table_html += '<div class="phone_cell">';
							gdpr_table_html += '<span class="order_detail_phone">';
								gdpr_table_html += '<span class="title">' + js_lang_phone + '</span>';
								gdpr_table_html += '<span class="phone_number">' + data[index].phone_1 + '</span>';
							gdpr_table_html += '</span>';
						gdpr_table_html += '</div>';
					}
					if (data[index].user_email != null && data[index].user_email != "") {
						gdpr_table_html += '<div class="email_cell">';
							gdpr_table_html += '<span class="order_detail_email">';
							gdpr_table_html += '<span class="title">E-mail:</span>';
							gdpr_table_html += '<span class="email_address">' + data[index].user_email + '</span>';
							gdpr_table_html += '</span>';
						gdpr_table_html += '</div>';
					}
				gdpr_table_html += '</div>';
			}

			gdpr_table_html += '</tbody></table>';
			vex.dialog.open({
				message: '<span class="login-title">' + js_gdpr_personal_data_title + '</span>',
				input: gdpr_table_html,
				buttons: [
					jQuery.extend({}, vex.dialog.buttons.NO, {
						text: 'OK'
					})
				],
				callback: function(data) {
				}
			});
		})
		.send();
}

function js_admin_user_list_get_gdpr_verion(version_id, elem) {

	var tmpData = '';
	new AjaxRequest({version_id: version_id})
		.setMethod('POST')
		.setController('Customer')
		.setAction('getGdprVersion')
		.setAsync(false) //asi nerobi nic
		.onSuccess(function (response) {
			tmpData = response.data[0];
		})
		.send();

	setTimeout( function () {copyTextToClipboard(tmpData, elem);}, 500);

}

/**
 * Dynamicky loadne js a css zdroje na stranku, callback vrati true alebo false oznacujuci uspesnu akciu pre vsetky url
 * @param {object} scripts Zoznam url pre loading
 * @param {function} callback Zavola po loadnuti vsetkych scriptov
 */
function csLoadScripts(scripts, callback){

	if ( typeof window.loadedScripts === 'undefined' ) window.loadedScripts = {};
	if ( typeof scripts !== 'object' ){

		if ( typeof callback === 'function' ) callback(false);
		return;
	}

	var tag;
	var _check = function(){
		var done = true;
		var ok = true;
		jQuery.each(scripts, function(c,v){
			var hash = jQuery.md5(v);
			if ( typeof window.loadedScripts[hash] === 'undefined' ){
				done = false;
				return false;
			}
			if ( !window.loadedScripts[hash] ) ok = false;
		});
		if ( done && typeof callback === 'function' ) callback(ok);
	};

	var _success = function(hash){
		window.loadedScripts[hash] = 1;
		_check();
	};

	var _error = function(hash){
		window.loadedScripts[hash] = 0;
		_check();
	};

	jQuery.each(scripts, function(c,url){

		var hash = jQuery.md5(url);
		var type = ( url.search('\\.js$') > -1 ? 'js' : (url.search('\\.css$') > -1 ? 'css' : 0) );

		if ( !type ) _error(hash);
		else if ( typeof window.loadedScripts[hash] !== 'undefined' ) _success(hash);
		else {

			if ( type == 'js' ){
				tag = document.createElement('script');
				tag.type = 'text/javascript';
				tag.src = url;
				tag.onload = function(){ _success(hash); };
				tag.onreadystatechange = function(){ _success(hash); };
			} else {
				tag = document.createElement('link');
				tag.type = 'text/css';
				tag.rel = 'stylesheet';
				tag.href = url;
				tag.onload = function(){ _success(hash); };
				tag.onreadystatechange = function(){ _success(hash); };
			}

			document.head.appendChild(tag);
		}
	});
}

function copyTextToClipboard(text, elem){

	showLoader();
	function selectElementText(element) {
		if (document.selection) {
			var range = document.body.createTextRange();
			range.moveToElementText(element);
			range.select();
		} else if (window.getSelection) {
			var range = document.createRange();
			range.selectNode(element);
			window.getSelection().removeAllRanges();
			window.getSelection().addRange(range);
		}
	}

	var element = document.createElement('DIV');
	element.innerHTML = text;
	document.body.appendChild(element);
	selectElementText(element);
	document.execCommand('copy');
	element.remove();

	hideLoader();
	jQuery(elem).tooltipster({
		theme        : "tooltipster-gdpr",
		trigger      : 'click',
		contentAsHTML: true,
		trackTooltip : true,
		trackOrigin  : true,
		multiple     : false,
		timer        : 3000,
		content      : js_gdpr_article_copy
	}).tooltipster('open');
	jQuery(elem).attr("title", js_gdpr_copy);
}

function changePositionModuleSwitch (type, name) {
	var cookie_name = 'PositionModuleSwitcher';
	var property_name = type + '_' + name;
	var class_name = 'active_switch_' + type + '_' + name;

	var cookie_value = Cookies.get(cookie_name);
	if (cookie_value == null || cookie_value == '')
		cookie_value = {};
	else
		cookie_value = JSON.parse(cookie_value);

	if (typeof cookie_value[property_name] != 'undefined') {
		delete cookie_value[property_name];
		jQuery('body').removeClass(class_name);
	} else {
		cookie_value[property_name] = 1;
		jQuery('body').addClass(class_name);
	}

	cookie_value = JSON.stringify(cookie_value);
	Cookies.set(cookie_name, cookie_value, { expires : 365, path : '/' });
}

function js_download_base64_file (name, content, type, id) {
	id = typeof(id) != 'undefined' ? '_'+id : '';
	var byteCharacters = window.atob(content);
	var byteArrays = [];
	var sliceSize = 512;
	var slice;
	var byteNumbers;

	for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
		slice = byteCharacters.slice(offset, offset + sliceSize);
		byteNumbers = new Array(slice.length);

		for (var i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}

		byteArray = new Uint8Array(byteNumbers);
		byteArrays.push(byteArray);
	}

	blob = new Blob(byteArrays, {type: type});
	var link = document.createElement('a');
	link.href = window.URL.createObjectURL(blob);
	if (type == 'application/pdf') {
		link.target = '_blank';
	} else {
		link.download = name;
	}
	link.id = 'download_base_64_file_temp_elem_id' + id;
	jQuery('body').append(link);
	link.click();
	jQuery(link).remove();
}

function js_copy_to_clipboard (text) {
	var input = jQuery('<input>').val(text).appendTo('body').trigger('select');
	document.execCommand('copy');
	input.remove();
}

if ( typeof lazySizesConfig !== "undefined" ) {
	// lazysizes CONFIGURACIA - nadstavba na lazyLoad
	window.lazySizesConfig.loadHidden = false;
}
if ( is_cs_user('lazyload_preload') && typeof lazySizesConfig !== "undefined" ) {
	window.lazySizesConfig.preloadAfterLoad = true;
}

$jQ = jQuery.noConflict();

/*
 * Checks whether the value passed to the function is numeric
 * Therefore both 0 and '0' will return true, but 'zero' will return false
 * Replacement for jQuery.isNumeric fn, which was deprecated
 *
 * @return bool
 */
function isNumeric (num) {
	return !isNaN(parseFloat(num)) && isFinite(num);
}

/*
 * Append loader/spinner on element
 * Replacement for jQuery.fancybox.showLoading();
 * @auth TL
 *
 * @param element [string] (valid jQuery selector) - element to which loader will be appended
 * @return void
 */
function showLoader (element) {
	if (typeof element === 'undefined') {
		element = 'body';
	}

	let $elem = jQuery(element).first();
	let html  = '<span class="css_graph_ajax_loader"></span>';

	if ($elem.length && !$elem.children('.css_graph_ajax_loader').length) {
		$elem.append(html);
	}
}
/*
 * Hide loader/spinner
 * Replacement for jQuery.fancybox.hideLoading();
 * @auth TL
 *
 * @param element {string} (valid jQuery selector) - element from which the loader will be removed
 * @param hideAll {bool} - if set to true, all loaders inside the element, no matter on which level, will be removed
 * @return void
 */
function hideLoader (element, hideAll) {
	if (typeof element == 'undefined') {
		element = 'body';
	}

	if (typeof hideAll == 'undefined') {
		hideAll = false;
	}

	let $elem = jQuery(element).first();

	if (hideAll) {
		$elem.find('.css_graph_ajax_loader').remove();
	} else {
		$elem.children('.css_graph_ajax_loader').remove();
	}
}

function toggleMiddleSubCategories(elem, module) {
	switch (module) {
		case 'middle_subcategories':
			jQuery(elem).closest('.module_middle_subcategories').toggleClass('show_all');
			break;
		case 'kateg':
			jQuery(elem)
				.toggleClass('open')
				.closest('ul')
				.toggleClass('open');
			break;
		case 'topten':
			jQuery(elem)
				.toggleClass('open')
				.closest('.module-topten')
				.toggleClass('open');
			break;
		default:
			return;
	}
}


function js_flypage_product_as_sqm_init() {
	if ( typeof js_Config_show_package_sqm_in_product_detail !== 'undefined' && js_Config_show_package_sqm_in_product_detail ) {
		//if(is_cs_user()) {
		var currency   = shop_currency_info[shop_vendor_currency_code],
		    focusInput = false;
		if (!jQuery('.flypage-kosik[data-packagesqm]').length) {
			return false;
		}

		jQuery('#quantity_sqm').keypress(function (e) {
			if (e.which == 46) {
				if (jQuery(this).val().indexOf('.') != -1 || jQuery(this).val().indexOf(',') != -1) {
					return false;
				}
			}
			if (e.which == 44) {
				if (jQuery(this).val().indexOf('.') != -1 || jQuery(this).val().indexOf(',') != -1) {
					return false;
				}
			}

			if (e.which != 8 && e.which != 0 && e.which != 46 && e.which != 44 && (e.which < 48 || e.which > 57)) {
				return false;
			}
		});

		jQuery('body').on('keyup mouseup', '#quantity_sqm', function () {
			//úprava JB 02-04-2020 po DR, nesprávne zaokrúhľovanie
			//nakoniec premiestniť z LOCAL.JS
			//nefunkčné zaokrúhľvoanie a podobne.. na eshope majú nastavneé 3 desatinné miesta..
			var new_value     = jQuery('#quantity_sqm').val().replace(',', '.');
			var one_package   = parseFloat(jQuery('.total_unit_price .price_unit').text().replace(',', '.'));
			var price_per_sqm = parseFloat(jQuery('#product-detail-price-value').text().replace(',', '.'));
			var new_package   = Math.ceil(new_value / one_package);
			//var quantity_sqm = (Math.round(parseFloat(new_package * one_package) * 100) / 100);
			//var new_price = (Math.round(parseFloat(quantity_sqm * price_per_sqm) * 100) / 100);
			var quantity_sqm = parseFloat(new_package * one_package);
			var new_price    = parseFloat(quantity_sqm * price_per_sqm);
			if (new_package == 1) {
				package_text = ' balenie';
			} else if (new_package > 1 && new_package < 5) {
				package_text = ' balenia';
			} else {
				package_text = ' balení';
			}
			jQuery('#quantity').val(quantity_sqm);
			jQuery('.form_info .bal').text(new_package);
			jQuery('.form_info .bal_text').text(package_text + ' (' + String(quantity_sqm).replace('.', ',') + jQuery('.quantity_per_sqm').html() + ')');
			jQuery('.form_info .price').html(js_format_Money(new_price, currency.DECIMALS, currency.SYMBOL, currency['1000_SYMBOL'], currency.DEC_SYMBOL));
		});
		jQuery('#quantity_sqm').on('focus', function () {
			jQuery(this).get(0).setSelectionRange(0, 9999);
		});
	}
}

/*
	Custom confirmation vex
    PJ
    Based on js_delete_confirm_vex(), more customizable
    options {
        getSelectedSplit
        getSelected
        actionLang
        itemLangOne, itemLangTwo, itemLangMore,
        errorTooltip,
        mainText,
        inputText1,
        inputAdditionalText1,
        inputText2,
        inputAdditionalText2,
        customInfo,
        yesButtonText
    }
 */

function vexCustomConfirm(options, callback) {
	var selected = options.getSelectedSplit;
	var total = selected.curPage + selected.otherPages;
	var title = '';

	if (total == 1) {
		// napr. produkt
		title = options.actionLang + ' ' + total + options.itemLangOne.replace('.', '');
	} else if (total < 5) {
		// napr. produkty
		title = options.actionLang + ' ' + total + options.itemLangTwo.replace('.', '');
	} else {
		// napr. produktov
		title = options.actionLang + ' ' + total + options.itemLangMore.replace('.', '');
	}

	var customOptions = jQuery.extend({
		total: selected,
		vexTitle: title
	}, options);

	js_confirm_vex(customOptions, callback);
}


/*
 * Confirmation Vex
 * @auth TL
 *
 * @param customOptions {object}
 * @param callback {function} - callback function to be executed upon successful confirmation
 * @return void
 */
function js_delete_confirm_vex(customOptions, callback) {

	// OPTIONS:
	var options = jQuery.extend({
		total: {
			count: 1
		},
		vexTitle: '',
		mainText: '',
		inputText1: '',
		inputAdditionalText1: '',
		errorTooltip: ''
	}, customOptions);

	if (typeof options.total === 'string' || typeof options.total === 'number') {
		var itemsTotal     = parseInt(options.total);
		var numberOfInputs = [1];
	} else {
		var itemsTotal     = 0;
		var numberOfInputs = Object.keys(options.total);
		for (var i = 0; i < numberOfInputs.length; i++) {
			itemsTotal += parseInt(options.total[numberOfInputs[i]]);
		}
	}

	var vexTitle = '<span class="login-title">' + options.vexTitle + '</span>';
	var vexYesButtonText = cms_js_lang_delete;
	if (typeof customOptions.yesButtonText !== 'undefined' && customOptions.yesButtonText.length > 0) {
		vexYesButtonText = customOptions.yesButtonText;
	}

	var vexContent = options.mainText;

	if (typeof customOptions.dontAddItemsTotal === 'undefined' || (typeof customOptions.dontAddItemsTotal !== 'undefined' && !customOptions.dontAddItemsTotal)) {
		vexContent += ' <strong>' + itemsTotal + '</strong>';
	}

	jQuery.each(numberOfInputs, function (index, value) {
		// if inputText is undefined, continue into another loop iteration
		if ( typeof options['inputText' + (index + 1)] === 'undefined' ) return;

		if ((typeof options.total === 'string' || typeof options.total === 'number') ? (index === 0 || options.total > 0) : (index === 0 || options.total[value] > 0)) {
			vexContent += '<br><br><span class="vex-dialog-span">' + options['inputText' + (index + 1)] + ' <strong>' + ((typeof options.total === 'string' || typeof options.total === 'number') ? options.total : options.total[value]) + '</strong> ';
			vexContent += options['inputAdditionalText' + (index + 1)] + '</span><br><br>';
			vexContent += '<input type="number" name="' + value + '" class="inputbox vex-dialog-confirm-input" placeholder="0" min="0">';
		} else {
			vexContent += '<input type="hidden" name="confirmedOtherPages" value="0">';
		}
	});

	if (typeof customOptions.customDeleteInfo !== 'undefined' && customOptions.customDeleteInfo.length > 0) {
		vexContent += customOptions.customDeleteInfo;
	}

	stop_submit_vex_enter();
	vex.dialog.confirm({
		title: vexTitle,
		vexCount: 1,
		className: 'vex-cs vex-text delete_items_vex delete_items_vex_new',
		message: vexTitle,
		input : vexContent,
		afterOpen: function(){
			stop_submit_vex_enter(this);
		},
		buttons: {
			YES: {
				text     : vexYesButtonText,
				className: "vex-dialog-button-primary",
				type     : "button",
				click    : function () {

					var $inputs = jQuery('.vex-dialog-confirm-input');
					var wrongInputs = [];
					var valuesAreEqual = true;

					$inputs.each(function (index, input) {
						input = jQuery(input);
						var nameAttr = input.prop('name');

						if (input.hasClass('error')) {
							input.removeClass('error').tooltipster('destroy');
						}

						if ( $inputs.length === 1 ) {
							if ( itemsTotal !== parseInt(input.val()) ) {
								wrongInputs.push(input);
							}
						} else {
							if ( options.total[nameAttr] !== parseInt(input.val()) ) {
								wrongInputs.push(input);
							}
						}
					});

					if ( wrongInputs.length ) {

						jQuery.each(wrongInputs, function(index, input) {
							jQuery(input).tooltipster({
								theme        : "tooltipster-gdpr",
								contentAsHTML: true,
								trackTooltip : true,
								trackOrigin  : true,
								multiple     : true,
								timer        : 5000,
								content      : options.errorTooltip
							}).tooltipster('open');

							jQuery(input).addClass('error');
						});

						return;
					}

					callback();
					vex.close();
				}
			},
			NO : {
				text     : cms_js_lang_module_copy_btn_cancel,
				className: "vex-dialog-button-secondary",
				type     : "button",
				click    : function () {
					return vex.close();
				}
			}
		}
	});
}

function js_confirm_vex(customOptions, callback) {
	// OPTIONS:
	var options = jQuery.extend({
		total: {
			count: 1
		},
		vexTitle: '',
		mainText: '',
		className: '',
		inputText1: '',
		inputAdditionalText1: '',
		errorTooltip: ''
	}, customOptions);

	var itemsTotal = 0;
	var numberOfInputs = Object.keys(options.total);
	for (var i = 0; i < numberOfInputs.length; i++) {
		itemsTotal += parseInt( options.total[numberOfInputs[i]] );
	}

	var vexTitle = '<span class="login-title">' + options.vexTitle + '</span>';

	var vexContent;
	vexContent = options.mainText + ' <strong>' + itemsTotal + '</strong>';

	jQuery.each(numberOfInputs, function (index, value) {
		// if inputText is undefined, continue into another loop iteration
		if ( typeof options['inputText' + (index + 1)] === 'undefined' ) return;

		if (index === 0 || options.total[value] > 0) {
			vexContent += '<br><br><span class="vex-dialog-span">' + options['inputText' + (index + 1)] + ' <strong>' + options.total[value] + '</strong> ';
			vexContent += options['inputAdditionalText' + (index + 1)] + '</span><br><br>';
			vexContent += '<input type="number" name="' + value + '" class="inputbox vex-dialog-confirm-input" placeholder="0" min="0">';
		} else {
			vexContent += '<input type="hidden" name="confirmedOtherPages" value="0">';
		}
	});

	if (typeof customOptions.customInfo !== 'undefined' && customOptions.customInfo.length > 0) {
		vexContent += customOptions.customInfo;
	}

	stop_submit_vex_enter();
	var confirmVex = vex.dialog.confirm({
		title: vexTitle,
		vexCount: 1,
		className: 'vex-cs vex-text ' + options.className,
		message: vexTitle,
		input : vexContent,
		afterOpen: function(){
			stop_submit_vex_enter(this);
		},
		buttons: {
			YES: {
				text     : options.yesButtonText,
				className: "vex-dialog-button-primary",
				type     : "button",
				click    : function () {

					var $inputs        = confirmVex.find('.vex-dialog-confirm-input');
					var wrongInputs    = [];

					$inputs.each(function (index, input) {
						input        = jQuery(input);
						var nameAttr = input.prop('name');

						if (input.hasClass('error')) {
							input.removeClass('error').tooltipster('destroy');
						}

						if ($inputs.length === 1) {
							if (itemsTotal !== parseInt(input.val())) {
								wrongInputs.push(input);
							}
						} else {
							if (options.total[nameAttr] !== parseInt(input.val())) {
								wrongInputs.push(input);
							}
						}
					});

					if (wrongInputs.length) {

						jQuery.each(wrongInputs, function (index, input) {
							jQuery(input).tooltipster({
								theme        : "tooltipster-gdpr",
								contentAsHTML: true,
								trackTooltip : true,
								trackOrigin  : true,
								multiple     : true,
								timer        : 5000,
								content      : options.errorTooltip
							}).tooltipster('open');

							jQuery(input).addClass('error');
						});

						return;
					}

					callback();
					vex.close();
				}
			},
			NO : {
				text     : cms_js_lang_module_copy_btn_cancel,
				className: "vex-dialog-button-secondary",
				type     : "button",
				click    : function () {
					return vex.close();
				}
			}
		}
	});
}

function google_recaptcha_add_wrap_class() {
	if ( typeof MutationObserver != 'undefined' ) {
		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mut) {
				if ( jQuery(mut.target).find('div.g-recaptcha-bubble-arrow').length > 0 ) {
					jQuery(mut.target).find('div.g-recaptcha-bubble-arrow').parent().addClass('g-recaptcha-wrap');
				}
			});
		});
		observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});
	}
}

/**
 * presunute z comments.js lebo sa ta funkcia pouziva aj v registracii [2020-03-02] - tomasL
 * Validate google recaptcha
 * @function validation_by_google_recaptcha
 *
 * @author Miro
 *
 * @return {Boolean}
 */
function validation_by_google_recaptcha()
{
	return jQuery('#g-recaptcha-response').val();
}

function js_infobar_cs(module) {
	var mod = jQuery(module);
	if ( !mod.length || ( typeof admin_view_design !== 'undefined' && typeof admin_view_design == 0 ) ) { return false; }
	var body = jQuery('body');
	var scrollTop_old = null;
	var scrollTop = null;
	body.addClass('show_banner_infobar');
	mod.find('.close').on('click',function () { //.text
		body.removeClass('show_banner_infobar');
		mod.addClass('hide');
		var time = new Date();
		Cookies.set('banner_infobar_hidden', Math.floor(time.getTime() / 1000));
		if (typeof js_infobar_content_md5 !== 'undefined') {
			Cookies.set('banner_infobar_msg', js_infobar_content_md5);
		}
		body.addClass('banner_infobar_hidden');
	});
}

function js_infobar_set_to_app_settings() {
	Cookies.set('admin.cfg_webfxtab_content-pane', '4');
}

function js_vex_show_after_registration_user_activation_2() {

	vex.dialog.open({
		message: '<h6>' + js_lang_phpshop_registration_thank_you_vex_title + '</h6>',
		input: js_lang_phpshop_registration_thank_you_vex,
		buttons: [
			jQuery.extend({}, vex.dialog.buttons.YES, { text: 'Ok'})
		],
		callback: function (data) {
			window.location = window.location.protocol + '//' + window.location.host;
		}
	});
}

function js_product_mass_bonus_assign() {
	var checkedProducts = jQuery('input:checked[name="product_id[]"][type="checkbox"]').length;
	if (checkedProducts == 0) {
		vex.dialog.alert({message: '<?php echo $VM_LANG->_PHPSHOP_MAKE_SEL_FROM_LIST_FOR_ACTION . " " . $VM_LANG->_PHPSHOP_PRODUCT_SPECIAL_GROUP_MASS_SPECIAL_ASSIGN_LBL; ?>'});
		return;	//	bez parametra !!!
	}

	jQuery.get(js_global_live_site + '/administrator/index3.php?pshop_mode=admin&page=product.product_list&option=com_shop&ajax_call=1&ajax_func=product_bonus_assign_get_groups&no_html=1&no_menu=1', {'product_count': checkedProducts}, function (res) {
		var bonusSelectHtml = JSON.parse(res);
		vex.open({
			content  : bonusSelectHtml.bonusSelectHtml,
			afterOpen: function () {
			console.log(JSON.parse(res));
			/*	start_improve_multiselect();
				var group_select_element = jQuery('.vex-content select[name="product_special_group_id[]"]:first');
				group_select_element.find('option').on('click', function () {
					js_multiple_select_option_click(jQuery(this));
				});

				jQuery('#mass_special_group_moving_container select[name="product_special_group_id[]"]')
					.prop('size', '10')
					.css('width', '100%')
					.css('height', 'auto');*/
			}
		});
	});

	return;
}

function js_product_mass_bonus_assign_save() {
	var selectedBonus        = jQuery('select[name="product_bonus_id[]"] option:selected');
	var bonusSelectedMethod = jQuery('#mass_product_bonus_select_method option:selected');
	var selectedProducts = js_getSelectedProducts();

	if ( selectedProducts.length > 0 && selectedBonus.length == 1 && bonusSelectedMethod.length == 1 ) {
		var options = {
			'productSpecialId': selectedBonus.val(),
			'selectedMethod'  : bonusSelectedMethod.val(),
			'selectedProducts': selectedProducts,
		};

		jQuery.post(js_global_live_site + '/administrator/index3.php?pshop_mode=admin&page=product.product_list&option=com_shop&ajax_call=2&ajax_func=save_mass_product_bonus&no_html=1&no_menu=1', options, function (res) {
			if (res == '0') {
				alert(cms_js_lang_products_shipping_message_error_2);
			}

			window.location.reload();
		});
	}
}

function js_set_partial_shipping(elem) {
	showLoader();
	var element = jQuery(elem);
	new AjaxRequest({ hasPartialShipping: element.is(":checked") })
		.setController("Basket")
		.setAction("setPartialShipping")
		.onSuccess(function (result) {
			hideLoader();
			window.location.reload();
		})
		.send();
}

function moduleCreativeShopSwitch(elem) {
	var $elem = jQuery(elem);

	$elem.prop('disabled',true);

	var $newContentWrapper = $elem.closest('div.video-news-page').find('div.more');

	if ($newContentWrapper.html() == '') {
		$elem.startAjaxLoader();
		new AjaxRequest()
			.setMethod('POST')
			.setController('Module')
			.setAction('moduleCreativeshopNewsAsyncLoad')
			.onSuccess(function (response) {
				$elem.prop('disabled',false);
				$newContentWrapper.html(response['data'][0]);
				$newContentWrapper.removeClass('hide');
				$newContentWrapper.removeClass('hidden');
				$elem.stopAjaxLoader();
				$elem.html($elem.data('hide'));
			})
			.onError(function (response) {
				$elem.prop('disabled',false);
				$elem.stopAjaxLoader();
				$elem.html($elem.data('show'));
			})
			.send();
	} else {

		if ($newContentWrapper.is(':visible')) {
			$newContentWrapper.hide();
			$elem.html($elem.data('show'));
		} else {
			$newContentWrapper.show();
			$elem.html($elem.data('hide'));
		}
	}
}

/**
 * Univerzalny wrapper na rendering/manipulaciu stromu z json dat
 * Pouziva ztree plugin http://www.treejs.cn/v3/api.php
 * @author IAN
 * TODO: kedze to bolo narychlo robene, treba dotiahnut niektore ficurky ako iteraciu nodov,hlasky,eventy,callbacks atd...
 */
var CsTree = function(id, options){
	var obj = this;
	obj.box = {};
	obj.tree = {};
	obj.ztree = {};
	obj.search = {};
	obj.keyword = '';
	obj.timer = 0;
	obj.index = 0;
	obj.options = {
		data: {},
		selected: [],
		setting: {
			data: {
				key: {
					name: "title",
					children: "branch",
					idKey: "id"
				}
			},
			check: {
				enable: true,
				chkboxType: {"Y": "", "N": ""}
			},
			view: {
				showTitle: false,
				expandSpeed: ''
			},
			callback: {
				onClick: function (event, treeId, treeNode) {}
			}
		}
	};
	obj.init = function (id, options) {

		obj.options = jQuery.extend(true, obj.options, options);
		obj.tree = jQuery('#'+id);

		if ( !obj.tree.length ) return;

		obj.box = obj.tree.closest('.nc_nav_master');

		if ( obj.box.length ){

			obj.search = obj.box.find('.nc_search_input');

			if ( obj.search.length ){

				obj.search.on('keyup', function (e) {
					var input = jQuery(this);
					var value = jQuery.trim(input.val());

					if (value == '' || value.length < 2) {
						obj.resetSearch();
						return;
					}

					if (obj.keyword == value) {
						return;
					}

					obj.keyword = value;

					if (obj.timer > 0) {
						return;
					}

					obj.timer = setTimeout(function () {

						clearTimeout(obj.timer);
						obj.timer = 0;
						obj.find();
					}, 300);
				});
			}
		}

		obj.ztree = jQuery.fn.zTree.init(obj.tree, obj.options.setting, obj.options.data);

		if ( obj.options.selected.length ) obj.select(obj.options.selected);
	}
	obj.select = function (selected){

		jQuery.each(selected, function (i, u) {

			var node = obj.ztree.getNodeByParam("id", u, null);
			if (node !== null) obj.ztree.checkNode(node, true, false);
		});
	}
	obj.getChecked = function(){

		var ret = [];
		var nodes = obj.ztree.getCheckedNodes(true);

		for (var i = 0; i < nodes.length; i++) {

			ret.push(nodes[i].id);
		}

		return ret;
	}
	obj.find = function(){

		if (obj.keyword == '') {

			obj.resetSearch();
			return;
		}

		obj.ztree.cancelSelectedNode();

		var keyword = obj.keyword.latinise();

		var nodes = obj.ztree.getNodesByFilter(obj.filter, false, null, keyword);

		obj.index = 0;

		if (nodes.length > 0) {

			for (var i = 0; i < nodes.length; i++) {

				if (i == 0) obj.scroll(nodes[i]);

				obj.ztree.selectNode(nodes[i], true, true);
			}
			//cscat.iterator[id].addClass('found').removeClass('notfound').text(' ' + nodes.length).attr('title', cms_js_iterate_found);
		} else {
			//cscat.iterator[id].removeClass('found').addClass('notfound').text(' ' + 0).attr('title', cms_js_iterate_notfound);
		}
	}
	obj.resetSearch = function(clearinput){

		if (clearinput) obj.search.val('');
		obj.ztree.cancelSelectedNode();
		obj.keyword = '';
		obj.index = -1;
	}
	obj.scroll = function(node){

		if (typeof node === 'undefined' || node === null) return;

		var row = obj.tree.find('#' + node.tId);

		// Node nebol otvoreny a zatial neexistuje
		if (!row.length){

			var nodes = node.getPath();
			if (nodes.length){

				for(var i=0; i<nodes.length; i++){

					obj.ztree.expandNode(nodes[i], true, true, true);
				}

				row = obj.tree.find('#' + node.tId);
			}
		} else {

			obj.ztree.expandNode(node, true, true, true);
		}

		// V strome uz nemame tento node
		if (!row.length) return;

		obj.timer = setTimeout(function () {

			clearTimeout(obj.timer);
			obj.timer = 0;
			obj.tree.stop().animate({scrollTop: row[0].offsetTop}, 300);
		}, 150);
	}
	obj.filter = function(node, keyword){

		if ( typeof node[obj.options.setting.data.key.name] === 'undefined' ) return false;
		var regex = new RegExp(keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "i");
		var label = node[obj.options.setting.data.key.name].latinise();
		return regex.test(String(label));
	}
	obj.init(id, options);
	return obj;
}

//JB globálna zmena množstva produtku.. nie je potrebné aby sme mali v systéme 4 funckie
/*
*  element, má v sebe cez data-attributes všetky hodnoty potrebné na vyhodnotenie
* */
function jsChangeProductQuantity(elem) {
	if (typeof elem !== 'undefined') {
		var jQueryBody = jQuery('body');
		var elem = jQuery(elem);
		var finalQuantity = 0;

		var params = {
			'inputSelector'     : elem.data('input_selector'),
			'parentSelector'    : elem.data('parent_selector'),
			'action'            : elem.data('action'),
			'quantity'          : elem.data('quantity'),
			'decimals'          : 0,
			'defaultValue'      : elem.data('default_value'),
		};



		//pridanie zaokrúhľovania množstva podľa potreby -> počet desatinných miest samotného quantity / forcedQuantity
		//blobo by fajn nahodiť tam : js_Config_vm_use_decimal_product_quantity, lenže to má mmoentálne zlé hodnoty, prípadne produkt môže mať menší počet desatinných miest
		if (Math.floor(params.quantity) != params.quantity) {
			params.decimals = params.quantity.toString().split(".")[1].length || 0;
		}

		var quantityInput = elem.closest(params.parentSelector).find(params.inputSelector);

		if (typeof quantityInput.data('allow_zero_quantity') !== 'undefined') {
			params.allowZeroQuantity = quantityInput.data('allow_zero_quantity');
		} else {
			params.allowZeroQuantity = 0;
		}

		//množstevné nákupy
		if ( typeof quantityInput.data('maximum_quantity') !== 'undefined') {
			params.maximumQuantity = quantityInput.data('maximum_quantity');
		} else {
			params.maximumQuantity = 0;
		}

		if ( typeof quantityInput.data('forced_quantity') !== 'undefined') {
			params.forcedQuantity = quantityInput.data('forced_quantity');

			if (Math.floor(params.forcedQuantity) !== params.forcedQuantity) {
				params.decimals = params.forcedQuantity.toString().split(".")[1].length || 0;
			}

		} else {
			params.forcedQuantity = 0;
		}

		if ( typeof quantityInput.data('minimum_quantity') !== 'undefined') {
			params.minimumQuantity = quantityInput.data('minimum_quantity');
		} else {
			params.minimumQuantity = 0;
		}

		params.floatFix = Math.pow(10, params.decimals);

		var startingQuantity = parseFloat(quantityInput.val().replace(',','.'));

		switch (params.action) {
			case 'add' :

				if (params.forcedQuantity) {
					finalQuantity = (startingQuantity + parseFloat(params.forcedQuantity) ).toFixed(params.decimals);

					if (params.minimumQuantity && (parseFloat(finalQuantity) < parseFloat(params.minimumQuantity)) && !params.allowZeroQuantity) {
						finalQuantity = params.minimumQuantity;
					} else if (params.maximumQuantity && (parseFloat(finalQuantity) > parseFloat(params.maximumQuantity))) {
						finalQuantity = params.maximumQuantity;
					}
				} else {
					finalQuantity = (startingQuantity + parseFloat(params.quantity) ).toFixed(params.decimals);
				}

				finalQuantity = parseFloat(finalQuantity).toFixed(params.decimals);

				quantityInput.val( finalQuantity ).attr('value', finalQuantity).trigger('change');

				if (quantityInput.data('refresh')) {
					quantityInput.closest('tr').find('input[name="update"]').click();
				}
				jQueryBody.trigger('jsChangeProductQuantity', [quantityInput, finalQuantity]);
				return 1;
			case 'sub' :

				if (params.forcedQuantity) {
					finalQuantity = (startingQuantity - parseFloat(params.forcedQuantity)).toFixed(params.decimals);
					if (params.minimumQuantity && (finalQuantity < params.minimumQuantity)) {

						//ak je sa nažíme pridať menšie množstvo ako je minimum a je povolené zero Quantity, setneme na 0, inak vrátime na minimum
						if (params.allowZeroQuantity) {
							finalQuantity = 0;
						} else {
							finalQuantity = params.minimumQuantity;
						}
					} else if (params.maximumQuantity && (finalQuantity > params.maximumQuantity)) {
						finalQuantity = params.maximumQuantity;
					}

					if ( !(finalQuantity > 0) ) {
						if (params.allowZeroQuantity) {
							finalQuantity = 0;
						} else {
							finalQuantity = params.forcedQuantity;
						}
					}

				} else {
					//potrebujeme si uložiť minimálne množstvo čo je buď 1 ks alebo min. množstvo
					finalQuantity = Math.ceil( (startingQuantity - parseFloat(params.quantity)).toFixed(params.decimals));

					if ( !(finalQuantity > 0) ) {
						if (params.allowZeroQuantity) {
							finalQuantity = 0;
						} else {
							finalQuantity = 1;
						}
					}
				}

				// JB 05-06-2020 maťova žiadosť -> množstvo sa nemá dostať na nulu cez buttony
				//finalQuantity = parseFloat(quantityInput.val()) - params.quantity;
				//finalQuantity = parseFloat(finalQuantity).toFixed(params.decimals);
				//TODO : defaultValue by mal byť len bool ktorý určuje či sa dostane produkt na nulu alebo nie -> takže to bude 1 / minimálne / krokové množstvo

				if ( finalQuantity === 0 ) {
					//  FIX: v riadkovom výpise sa vzdy opyta, ci user chce odstranit product z kosika
					if( !params.allowZeroQuantity || params.parentSelector === '.basket_quantity_wrapper' ) {
						vex.dialog.confirm({
							message : js_lang_shopping_cart_delete_item_confirm,
							callback: function (confirmed) {
								if ( confirmed ) {
									refreshQuantity(quantityInput, finalQuantity, true);
								} else {
									return false;
								}
							}
						});
						return false;
					}

					refreshQuantity(quantityInput, finalQuantity);
					return false;
				}

				refreshQuantity(quantityInput, finalQuantity);

				jQueryBody.trigger('jsChangeProductQuantity', [quantityInput, finalQuantity]);
				return 1;
			case 'set' :
				//úprava on blur funkciou, po každom vyplnení inputu sa spraví validácia na dané množstvo aby sedelo zadanému množstvu, ktoré používateľ zadal
				finalQuantity = parseFloat(elem.val().replace(',','.'));

				if (params.minimumQuantity && ( finalQuantity < params.minimumQuantity ) && !params.allowZeroQuantity  ) {
					finalQuantity = params.minimumQuantity;
				}
				if (params.maximumQuantity && finalQuantity > params.maximumQuantity) {
					finalQuantity = params.maximumQuantity;
				}

				if (params.forcedQuantity) {

					//je možno potrebné upraviť na cfg

					if (1 || is_cs_user()) {
						//zaokrúhli vždy k väčšiemu
						finalQuantity = (parseFloat(params.forcedQuantity) * Math.ceil( finalQuantity / parseFloat(params.forcedQuantity) )).toFixed(params.decimals);
					} else {
						//zaokrúhli dole / nahor -> podľa toho čo je bližšie
						finalQuantity = (parseFloat(params.forcedQuantity) * Math.ceil( (  finalQuantity / parseFloat(params.forcedQuantity) ).toFixed(params.decimals))).toFixed(params.decimals);
					}
				}

				if ( !(finalQuantity > 0) ) {
					if (params.allowZeroQuantity) {
						finalQuantity = 0;
					} else {
						if (params.forcedQuantity) {
							finalQuantity = params.forcedQuantity;
						} else {
							finalQuantity = 1;
						}
					}
				}

				//posledná úprava aby sa do inputu nedostala záporná hodnota, prípadne nula

				//quantityInput.val( ( finalQuantity > 0 ) ? (finalQuantity.toFixed(params.decimals).toString()) : 0).trigger('change');
				quantityInput.val( finalQuantity ).attr('value', finalQuantity).trigger('change');

				if (finalQuantity != startingQuantity) {
					quantityInput.addClass('error_inputbox_animation');
					setTimeout(function() {
						quantityInput.removeClass('error_inputbox_animation');
					}, 1000);

					var lang = js_lang_insufficient_quantity_inform;
					lang     = lang.replace('{from}', startingQuantity);
					lang     = lang.replace('{to}', finalQuantity);

					quantityInput.closest('.quantity_wrapper').tooltipster({
						theme    : 'cs_tooltipster_grey_theme tooltipster_minquantity',
						animation: 'fade',
						side     : 'top',
						delay    : 10,
						timer    : 5000
					})
						.tooltipster('content', lang)
						.tooltipster('open');
				}
				if (quantityInput.data('refresh')) {
					quantityInput.closest('tr').find('input[name="update"]').click();
				}

				jQueryBody.trigger('jsChangeProductQuantity', [quantityInput, finalQuantity]);
				return 1;
			default :
				jQueryBody.trigger('jsChangeProductQuantity', [quantityInput, finalQuantity]);
				return 1;
		}
	}
	return 0;
}

function refreshQuantity(quantityInput, quantity, forceRefresh = false) {
	quantityInput.val( quantity ).attr('value', quantity).trigger('change');

	if (quantityInput.data('refresh') || forceRefresh) {
		quantityInput.closest('tr').find('input[name="update"]').click();
	}
}

function js_checkout_thankyou_message_to_unregistered_customer (data) {
	if ( typeof data !== 'undefined' && typeof data.data !== 'undefined' && data.data != '' ) {
		vex.dialog.open({
			message  : '<h4>' + data.title + '</h4>',
			className: 'vex-cs vex-dialog-checkout-thankyou-unregistered-message',
			input    : data.data,
			buttons: [
				jQuery.extend({}, vex.dialog.buttons.YES, { text: js_lang_checkout_thankyou_unregistered_vex_confirm }),
			],
		});
	}
}

// loyalty scheme
function js_add_to_loyalty_scheme_checkbox_handler (elem) {
	elem = jQuery(elem);
	var isChecked = elem.is(':checked');
	if (isChecked) {
		jQuery.cookie('add_to_loyalty_scheme_checked', '1', {path:'/'});
	} else if (jQuery.cookie('add_to_loyalty_scheme_checked')) {
		jQuery.cookie('add_to_loyalty_scheme_checked', null, {path:'/'});
	}
}

/**
 * Toggles cstools on/off
 *
 * @return void
 */
function toggleCsTools() {
	jQuery('.pres_btn.nobg').trigger('click');
}

function initInfowidgetCountdownTimer (duration, display) {
	infowidgetInterval = setInterval(function () {
		if ( typeof js_Config_infowidget_countdown_timer.current !== 'undefined' ) {
			now = js_Config_infowidget_countdown_timer.current * 1000;
			if ( typeof infowidgetCountDownHelper == 'undefined' ) {
				infowidgetCountDownHelper = 0;
			} else {
				infowidgetCountDownHelper += 1;
				now += infowidgetCountDownHelper * 1000;
			}
		} else {
			var now = new Date().getTime();
		}

		var timeleft = duration - now;

		var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
		var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
		var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

		if ( seconds < 0 || minutes < 0 || hours < 0 || days < 0 ) {
			clearInterval(infowidgetInterval);
			display.hide();
		}

		var daysText = '';
		var hoursText = '';
		var minutesText = '';
		var secondsText = '';

		if ( days == 1 ) {
			daysText = days + ' ' + (typeof js_lang_time_day_1 !== 'undefined' ? js_lang_time_day_1 : 'day') ;
		} else if ( days > 1 && days < 5 ) {
			daysText = days + ' ' + (typeof js_lang_time_day_more !== 'undefined' ? js_lang_time_day_more : 'days') ;
		} else if ( days >= 5 ) {
			daysText = days + ' ' + (typeof js_lang_time_day_more_2 !== 'undefined' ? js_lang_time_day_more_2 : 'days' );
		}

		if ( hours == 1 ) {
			hoursText = hours + ' ' + (typeof js_lang_time_hours_1 !== 'undefined' ? js_lang_time_hours_1 : 'hours') ;
		} else if ( hours > 1 && hours < 5 ) {
			hoursText = hours + ' ' + (typeof js_lang_time_hours_2_4 !== 'undefined' ? js_lang_time_hours_2_4 : 'hours') ;
		} else if ( hours >= 5 || ( hours == 0 && days != 0 ) ) {
			hoursText = hours + ' ' + (typeof js_lang_time_hours_more !== 'undefined' ? js_lang_time_hours_more : 'hours') ;
		}

		if ( minutes == 1 ) {
			minutesText = minutes + ' ' + (typeof js_lang_time_minutes_1 !== 'undefined' ? js_lang_time_minutes_1 : 'minute') ;
		} else if ( minutes > 1 && minutes < 5 ) {
			minutesText = minutes + ' ' + (typeof js_lang_time_minutes_2_4 !== 'undefined' ? js_lang_time_minutes_2_4 : 'minutes') ;
		} else if ( minutes >= 5 || ( minutes == 0 && ( days != 0 || hours != 0 ) ) ) {
			minutesText = minutes + ' ' + (typeof js_lang_time_minutes_more !== 'undefined' ? js_lang_time_minutes_more : 'minutes') ;
		}

		if ( seconds == 1 ) {
			secondsText = seconds + ' ' + (typeof js_lang_time_seconds_1 !== 'undefined' ? js_lang_time_seconds_1 : 'second') ;
		} else if ( seconds > 1 && seconds < 5 ) {
			secondsText = seconds + ' ' + (typeof js_lang_time_seconds_2_4 !== 'undefined' ? js_lang_time_seconds_2_4 : 'seconds') ;
		} else if ( seconds >= 5 || ( seconds == 0 && ( days != 0 || hours != 0 || minutes != 0 ) ) ) {
			secondsText = seconds + ' ' + (typeof js_lang_time_seconds_more !== 'undefined' ? js_lang_time_seconds_more : 'seconds') ;
		}

		display.text(daysText + ' ' + hoursText + ' ' + minutesText + ' ' + secondsText);
	}, 1000);
}

function tempNewLoader (toggle, reload, fade) {
	var $body = jQuery('body');
	var fadeDuration = 300;

	if ( typeof loaderTimeouts === 'undefined' ) {
		loaderTimeouts = [];
	}

	var changeText = function changeText(text) { jQuery('.css_graph_ajax_loader_text').text(text); };

	if ( !toggle ) {
		if ( fade ) {
			$body.find('.css_graph_ajax_loader_wrapper').fadeOut(fadeDuration, function() {
				jQuery(this).remove();
			});
		} else {
			$body.find('.css_graph_ajax_loader_wrapper').remove();
		}

		loaderTimeouts.map(function (timeoutId) {
			clearTimeout(timeoutId);
		});
		delete loaderTimeouts;
		return;
	}

	if ($body.children('.css_graph_ajax_loader_wrapper').length) {
		return;
	}

	var loaderTexts = {
		initial: typeof js_lang_checkout_loader_initial !== 'undefined' ? js_lang_checkout_loader_initial : '',
		intermediate: typeof js_lang_checkout_loader_intermediate !== 'undefined' ? js_lang_checkout_loader_intermediate : '',
		final: typeof js_lang_checkout_loader_final !== 'undefined' ? js_lang_checkout_loader_final : ''
	};

	var html = [
		'<span class="css_graph_ajax_loader_wrapper">',
		'<span class="css_graph_ajax_loader_inner">',
		'<span class="css_graph_ajax_loader"></span>',
		'<span class="css_graph_ajax_loader_text"></span>',
		'</span>',
		'</span>'
	].join('');

	loaderTimeouts.push(setTimeout(function () {
		changeText(loaderTexts.initial);
		}, 3000));

	loaderTimeouts.push(setTimeout(function () {
		changeText(loaderTexts.intermediate);
		}, 5000));

	loaderTimeouts.push(setTimeout(function () {
		changeText(loaderTexts.final);
		}, 15000));

	if ( reload ) {
		loaderTimeouts.push(setTimeout(function() {
			window.location.reload();
		}, 30000));
	}

	if ( fade ) {
		$body.append(jQuery(html).hide().fadeIn(fadeDuration));
	} else {
		$body.append(jQuery(html));
	}
}

var CsLoader = {
	fade: false,
	fadeDuration: 300,
	reload: false,
	loaderLangs: {
		initial: typeof js_lang_checkout_loader_initial !== 'undefined' ? js_lang_checkout_loader_initial : 'Spracováva sa...',
		intermediate: typeof js_lang_checkout_loader_intermediate !== 'undefined' ? js_lang_checkout_loader_intermediate : 'Chvíľku strpenia...',
		final: typeof js_lang_checkout_loader_final !== 'undefined' ? js_lang_checkout_loader_final : 'Ešte chvíľu počkajte...',
	},
	loaderTimeoutDurations: {
		initial: 3000,
		intermediate: 5000,
		final: 15000,
		reload: 30000,
	},
	loaderTimeouts: {},
	transparentBackground: false,
	blurBackground: true,
	loaderTextSelector: '.css_graph_ajax_loader_text',
	loaderWrapperSelector: '.css_graph_ajax_loader_wrapper',
	html: [
		'<span class="css_graph_ajax_loader_wrapper">',
		'<span class="css_graph_ajax_loader_inner">',
		'<span class="css_graph_ajax_loader"></span>',
		'<span class="css_graph_ajax_loader_text"></span>',
		'</span>',
		'</span>'
	].join(''),
	htmlTransparent: [
		'<span class="css_graph_ajax_loader_wrapper" style="background:transparent;">',
		'<span class="css_graph_ajax_loader_inner">',
		'<span class="css_graph_ajax_loader"></span>',
		'<span class="css_graph_ajax_loader_text"></span>',
		'</span>',
		'</span>'
	].join(''),
	startLoader: function ( selector ) {

		if ( typeof selector !== 'string' || selector === '' ) {
			selector = 'body';
		}

		var $body = jQuery(selector);

		if ( this.isLoaderActive(selector) ) {
			return;
		}

		if ( selector === 'body' && this.blurBackground === true ) {
			$body.addClass('csloader-active');
		}

		this.loaderTimeouts[selector] = [];
		this.loaderTimeouts[selector].push(setTimeout(function () {
			CsLoader.changeText(CsLoader.loaderLangs.initial, selector);
		}, this.loaderTimeoutDurations.initial));

		this.loaderTimeouts[selector].push(setTimeout(function () {
			CsLoader.changeText(CsLoader.loaderLangs.intermediate, selector);
		}, this.loaderTimeoutDurations.intermediate));

		this.loaderTimeouts[selector].push(setTimeout(function () {
			CsLoader.changeText(CsLoader.loaderLangs.final, selector);
		}, this.loaderTimeoutDurations.final));

		if ( this.reload ) {
			this.loaderTimeouts[selector].push(setTimeout(function() {
				window.location.reload();
			}, this.loaderTimeoutDurations.reload));
		}

		if ( this.fade ) {
			if ( this.transparentBackground ) {
				$body.append(jQuery(this.htmlTransparent).hide().fadeIn(this.fadeDuration));
			} else {
				$body.append(jQuery(this.html).hide().fadeIn(this.fadeDuration));
			}
		} else {
			if ( this.transparentBackground ) {
				$body.append(jQuery(this.htmlTransparent));
			} else {
				$body.append(jQuery(this.html));
			}
		}
	},

	stopLoader: function ( selector ) {

		if ( typeof selector !== 'string' || selector === '' ) {
			selector = 'body';
		}

		if ( !this.isLoaderActive(selector) ) {
			return;
		}

		if ( this.fade ) {
			jQuery(selector).children(this.loaderWrapperSelector).fadeOut(this.fadeDuration, function() {
				jQuery(this).remove();
			});
		} else {
			jQuery(selector).children(this.loaderWrapperSelector).remove();
		}

		if ( selector === 'body' ) {
			jQuery(selector).removeClass('csloader-active');
		}

		this.clearTimeouts(selector);
	},

	clearTimeouts: function (selector) {
		CsLoader.loaderTimeouts[selector].map(function (timeoutId) {
			clearTimeout(timeoutId);
		});
		delete CsLoader.loaderTimeouts[selector];
	},

	changeText: function(text, selector) {
		jQuery(selector).children(this.loaderWrapperSelector).find(this.loaderTextSelector).html(text);
	},

	isLoaderActive: function ( selector ) {
		if ( jQuery(selector).children(this.loaderWrapperSelector).length ) {
			return true;
		}
		return false;
	},

	setLoaderText: {
		initial: function (text) {
			if ( typeof text === 'string' ) {
				CsLoader.loaderLangs.initial = text;
			}
		},
		intermediate: function (text) {
			if ( typeof text === 'string' ) {
				CsLoader.loaderLangs.intermediate = text;
			}
		},
		final: function (text) {
			if ( typeof text === 'string' ) {
				CsLoader.loaderLangs.final = text;
			}
		},
	},

	setLoaderTimeout: {
		initial: function (duration) {
			if ( typeof duration === 'number' ) {
				CsLoader.loaderTimeoutDurations.initial = duration;
			}
		},
		intermediate: function (duration) {
			if ( typeof duration === 'number' ) {
				CsLoader.loaderTimeoutDurations.intermediate = duration;
			}
		},
		final: function (duration) {
			if ( typeof duration === 'number' ) {
				CsLoader.loaderTimeoutDurations.final = duration;
			}
		},
		reload: function (duration) {
			if ( typeof duration === 'number' ) {
				CsLoader.loaderTimeoutDurations.reload = duration;
			}
		}
	},

	toggleFade: function (fade) {
		if ( typeof fade === 'boolean' ) {
			CsLoader.fade = fade;
		}
	},

	setFadeDuration: function (duration) {
		if ( typeof duration === 'number' ) {
			CsLoader.fadeDuration = duration;
		}
	},

	toggleReload: function (reload) {
		if ( typeof reload === 'boolean' ) {
			CsLoader.reload = reload;
		}
	},

	stopAll: function () {
		if ( this.fade ) {
			jQuery(this.loaderWrapperSelector).fadeOut(this.fadeDuration, function() {
				jQuery(this).remove();
			});
		} else {
			jQuery(this.loaderWrapperSelector).remove();
		}

		Object.keys(this.loaderTimeouts).map(function (selector) {
			CsLoader.clearTimeouts(selector);
		});
	},

};

function faqTableStructuredData () {
	if ( !jQuery('.banner_faq_init').length ) {
		return;
	}

	var faqArray = [];
	var tableElem = jQuery('.banner_faq_content .module_cont').find('tbody');
	if ( tableElem.length > 0 ) {
		tableElem.each( function(key, table) {
			var currentTable = jQuery(table);
			var questions = currentTable.find('tr').each( function(key, questionElem) {
				var question = jQuery(questionElem).find('td:first').find('span').text();
				if ( question == '' ) {
					question = jQuery(questionElem).find('td:first').text();
				}

				var prohibited = {
					'sk': 'NOŽE',
					'cz': 'NOŽE',
					'de': 'MESSER',
					'at': 'MESSER',
					'ro': 'CUȚITE',
					'pl': 'NOŻE',
					'si': 'NOŽI',
					'hu': 'KÉSEK',
				};

				var prohibitedWord = typeof prohibited[js_get_lang] !== 'undefined' ? prohibited[js_get_lang] : prohibited['sk'];

				if ( question.includes(prohibitedWord) ) {
					return;
				}

				var answer = jQuery(questionElem).find('td').last().text();
				if ( answer == '' ) {
					answer = jQuery(questionElem).find('td').last().find('span').text();
				}

				if ( question != '' && answer != '' ) {
					var questionGroup = {
						'@type': 'Question',
						'name': question,
						'acceptedAnswer': {
							'@type': 'Answer',
							'text' : answer
						}
					};
					faqArray.push(questionGroup);
				}
			});
		});

		if ( faqArray.length > 0 ) {
			var jsonLd = {
				"@context": "https://schema.org",
				"@type": "FAQPage",
				"mainEntity": faqArray
			};

			var script = document.createElement('script');
			script.setAttribute('type', 'application/ld+json');
			script.textContent = JSON.stringify(jsonLd);
			document.head.appendChild(script);
		}
	}
}

function isElementInView(elem) {
	var $elem = jQuery(elem);

	if ($elem.length > 0) {
		var rect = $elem[0].getBoundingClientRect();
		return rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth);
	}

	return false;
}

function lazyLoadFunction(selector, callback, callbackObject, ...params) {
	// Guard
	if (typeof callback !== 'function' && (typeof callbackObject === 'undefined' || typeof callbackObject[callback] !== 'function')) {
		if (is_cs_user()) {
			console.log('Nefunkcne spustenie optimalizovaneho lazyloadu - callback nie je funkcia');
		}

		return;
	}

	// Cant watch this element, run callback
	if (jQuery(selector).length === 0) {
		if (typeof callbackObject !== 'undefined') {
			callbackObject[callback](...params);
		} else {
			callback(...params);
		}

		if (is_cs_user()) {
			console.log('Nefunkčné spustenie optimalizovaného lazyloadu - nepodarilo sa nájsť element');
		}

		return;
	}

	// Element is in view, run callback instatly
	if (isElementInView(selector)) {
		if (typeof callbackObject !== 'undefined') {
			callbackObject[callback](...params);
		} else {
			callback(...params);
		}

		return;
	}

	// Element is not in view, run callback after 5 seconds or when user scrolls element into view
	if (typeof window.lazyLoadElements === 'undefined') {
		window.lazyLoadElements = [];
	}

	let uniqueId = window.lazyLoadElements.length;
	let eventNamespace = 'scroll.lle_' + uniqueId;
	let timeout = config('js_CS_Config_lazyLoadFunctions_pagespeed') ? 20000 : 5000;

	window.lazyLoadElements.push(selector);
	// Load after time spent
	setTimeout(function () {
		if (typeof window.lazyLoadElements[uniqueId] === 'undefined') {
			return;
		}

		window.lazyLoadElements[uniqueId] = undefined;

		if (typeof callbackObject !== 'undefined') {
			callbackObject[callback](...params);
		} else {
			callback(...params);
		}

		jQuery(window).off('.lle_' + uniqueId);
	}, timeout, uniqueId, params, callback, callbackObject);

	// Load when user scrolls element into view
	jQuery(window).on(eventNamespace, {
		uniqueId: uniqueId,
		selector: selector,
		params: params,
		callback: callback,
		callbackObject: callbackObject
	}, function (ev) {
		if (typeof window.lazyLoadElements[ev.data.uniqueId] !== 'string') {
			jQuery(window).off('.lle_' + ev.data.uniqueId);
			return;
		}

		if (!isElementInView(ev.data.selector)) {
			return;
		}

		window.lazyLoadElements[ev.data.uniqueId] = null;

		if (typeof callbackObject !== 'undefined') {
			callbackObject[callback](...params);
		} else {
			callback(...params);
		}

		jQuery(window).off('.lle_' + ev.data.uniqueId);
	});
}

function showMessageAfterAddToCart (elem) {
	var $elem = jQuery(elem);
	if ( $elem.hasClass('vex_product_is_in_spg') && typeof js_Config_show_vex_after_add_to_cart !== 'undefined' && js_Config_show_vex_after_add_to_cart && typeof CsModal !== "undefined" ) {
		var modalSettings = JSON.parse(js_Config_show_vex_after_add_to_cart);
		var buttons = "<input type=\"button\" class=\"button cs_modal_sec_button\" name=\"submit\" title=\"\" onclick=\"messageModal.close();\" value=" + js_lang_admin_media_cancel + "><input type=\"button\" name=\"login-button\" onclick=\"window.location.href='" + modalSettings.loginLink + "'\" class=\"button\" title=\"\" value=\"" + (typeof js_lang_vex_after_add_to_cart_login !== 'undefined' ? js_lang_vex_after_add_to_cart_login : 'Login') + "\">";
		var modalTitle = getLang(modalSettings.title);
		var modalContent = getLang(modalSettings.content);

		if ( modalTitle == '' ) {
			modalTitle = modalSettings.title;
		}

		if ( modalContent == '' ) {
			modalContent = modalSettings.content;
		}

		messageModal = new CsModal()
			.setClassName('type_login_required')
			.setType('info')
			.setTitle(modalTitle)
			.setContent(modalContent)
			.setButtons(buttons)
			.open();
		return false;
	}
}

function bindAutoCouponTooltip() {
	var autoAddButton = jQuery('.shop_cart_coupon_form form .tooltip-code-add');
	if (typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled) {
		window.addEventListener('DOMContentLoaded', function() {
			autoAddButton.on('click', setAutoCoupon);
		});
	} else {
		jQuery(function(){
			autoAddButton.on('click', setAutoCoupon);
		});
	}
}

function setAutoCoupon(event) {
	var autoButton = jQuery(event.target);
	var couponForm = autoButton.closest('form');
	var couponAutoCode = autoButton.parent().find('.tooltip-code').attr('data-code');

	if(typeof couponAutoCode !== 'undefined' && couponAutoCode !== '') {
		couponForm.find('input[name=do_coupon]').val('yes');
		couponForm.find('input[name=delete_coupon]').val('no');
		couponForm.find('input[name=coupon_code]').val(couponAutoCode);
		couponForm.find('input[name=unset_autoskip]').val('yes');
	}

	couponForm.find('input[type=submit]').trigger('click');
}

/**
 * @elem : .cs_rating_wrapper element
 * @rating : (Optional) to change rating value
 * @rCount : (Optional) to change count number and toggle .is_empty
 * @ratingLang : (Optional) to change rating lang value
 */
function updateRatingElement(elem, rating, rCount, ratingLang) {
	let ratingElem = jQuery(elem);

	if (typeof ratingElem === 'undefined' || !ratingElem.hasClass('cs_rating_wrapper')) {
		return;
	}

	if (typeof rating !== 'undefined' && !isNaN(rating)) {
		let ratingPercentage = Math.floor(rating * 20);
		let spaceKoef = 0;

		if (ratingPercentage > 80) {
			spaceKoef = 4;
		} else if (ratingPercentage > 60) {
			spaceKoef = 3;
		} else if (ratingPercentage > 40) {
			spaceKoef = 2;
		} else if (ratingPercentage > 10) {
			spaceKoef = -4;
		}

		ratingElem.find('.count .val').text(rating);
		ratingElem.find('.rating').attr('style', '--rating:' + ratingPercentage + '%; --space-koef:' + spaceKoef + ';')
	}

	if (typeof rCount !== 'undefined' && !isNaN(rCount)) {
		ratingElem.find('.count .total').text(rCount);

		if (rCount > 0) {
			ratingElem.removeClass('is_empty');
		} else {
			ratingElem.addClass('is_empty');
		}
	}

	if (typeof ratingLang !== 'undefined') {
		ratingElem.find('.count .count_total').text(ratingLang);
	}
}

function openModalVideo(e, url, title, admin) {
	var videoElem = '';
	var yUrl = '';
	var yTitle = '';

	if(typeof admin !== 'undefined' && admin) {
		yUrl = "https://www.youtube.com/embed/" +  url;
		yTitle = title;
	} else {
		e.preventDefault();
		e.stopPropagation();

		videoElem = jQuery(e.target).closest('.product_video').find('a');
		yUrl = "https://www.youtube.com/embed/" + videoElem.attr('data-url');
		yTitle = videoElem.attr('data-title');
	}

	var iFrame = '<iframe width="1280" height="720" src="';
	iFrame += yUrl;
	iFrame += '" title="';
	iFrame += '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';

	new CsModal()
		.setClassName('product_video')
		.setType('info')
		.setTitle(yTitle)
		.setContent(iFrame)
		.hideCloseButton(true)
		.setActionsClassName('vex-dialog-buttons')
		.open();
}

function activeImageFancyHover() {
	var $flypageImage = jQuery('.flypage-image a:first');
		$flypageImage.data('href', $flypageImage.attr('href'));
		$flypageImage.data('src', $flypageImage.children('img:first').attr('src'));
		$flypageImage.data('srcset', $flypageImage.children('img:first').attr('srcset'));

	jQuery('.product_activeimages_image_div a').on('mouseenter', function () {
		var activeImage = jQuery(this);
		var dataOptions = $flypageImage.data('options');

		if ( activeImage.data('fancybox') ) {

			$flypageImage
				.attr('href', activeImage.attr('href'))
				.data('src', activeImage.attr('href'))
				.children('img')
				.attr('src', activeImage.attr('href'));

			$flypageImage
				.data('options')

			if ($flypageImage.children('img').attr('srcset') !== 'undefined' && $flypageImage.children('img').attr('srcset') !== false) {
				$flypageImage
					.attr('href', activeImage.attr('href'))
					.children('img')
					.attr('srcset', activeImage.attr('href'));
			}
		}
	});

	jQuery('.product_activeimages_image_div a').on('mouseleave', function () {
		if (jQuery(this).data('fancybox')) {
			if ($flypageImage.data('href') && $flypageImage.data('src')) {
				$flypageImage
					.attr('href', $flypageImage.data('href'))
					.children('img')
					.attr('src', $flypageImage.data('src'));
			}
			if ($flypageImage.children('img').attr('srcset') !== 'undefined' && $flypageImage.children('img').attr('srcset') !== false && $flypageImage.data('srcset')) {
				$flypageImage
					.attr('href', $flypageImage.data('href'))
					.children('img')
					.attr('srcset', $flypageImage.data('srcset'));
			}
		}
	});
}

function initSlickSlider(wrap, slide) {
	wrap = jQuery(wrap);

	if (!wrap.length || wrap.hasClass('slick-initialized') || wrap.find(slide).length < 5) {
		return;
	}

	wrap.slick({
		slide: slide,
		centerMode: true,
		centerPadding: '64px',
		slidesToShow: 1,
		slidesToScroll: 1,
		infinite: true,
		dots: true,
		variableWidth: false,
		draggable: false,
		swipeToSlide: false,
	});
}

function bindProductActiveImageSlick() {
    jQuery('.cs_product_item .browse_active_images:not(.loaded)').closest('.cs_product_item').on('mouseenter', function () {
        var imageWrap = jQuery(this);

        if (!imageWrap.hasClass('loaded')) {
            imageWrap.find('.browse_active_images').slick({
                slide: '.active_image',
                centerMode: true,
                centerPadding: '64px',
                slidesToShow: 1,
                slidesToScroll: 1,
                infinite: true,
                dots: true,
                variableWidth: false,
                draggable: false,
                swipeToSlide: false,
            });
        }

		imageWrap.addClass('loaded');
    });
}

function loadProductTabPage(elem, tabId) {

	var element = jQuery(elem);

	if ( element.hasClass('tab-loaded') ) {
		return;
	} else {
		// Prevencia duplicitnemu nacitanie pre zmenu sirky (napr. pri otoceni zariadenia)
		element
			.closest('#tabsContainer')
			.find('label[for="' + element.attr('for') + '"]')
			.addClass('tab-loaded')
			.removeClass('is_empty');
	}

	var productId = js_product_id;

	var params = {
		productId 	: productId,
		tabId		: tabId,
	};

	jQuery('.tabPages .tabContent#page' + tabId).startAjaxLoader();

	new AjaxRequest(params)
		.setMethod('POST')
		.setController('ProductTab')
		.setAction('loadProductTab')
		.onSuccess(function (res) {
			console.log(res);
			if ( res.data.tabId !== '' ) {
				jQuery('.tabPages .tabContent#page' + res.data.tabId).stopAjaxLoader();
			}

			if ( res.data.tabId !== '' && res.data.result !== '' ) {
				var tabPageId = res.data.tabId;
				var tabPageResult = res.data.result;
				var insertMode = res.data.insertMode;
				var tabPage = jQuery('.tabPages .tabContent#page' + tabPageId);
				if ( tabPage.length > 0 && tabPageResult != '' ) {
					if ( insertMode === 'append' ) {
						tabPage.append(tabPageResult);
					} else if ( insertMode === 'prepend' ) {
						tabPage.prepend(tabPageResult);
					}

					if ( typeof afterProductTabLoad === 'function' ) {
						afterProductTabLoad(tabPageId);
					}

				}
			}
		})
		.send();
}

function afterProductTabLoad ( tabId ) {
	if ( typeof tabId === 'undefined' || tabId == '' || typeof js_Config_product_tabs_configuration === 'undefined' ) {
		return;
	}

	var tabSettings = JSON.parse(js_Config_product_tabs_configuration);

	if ( typeof tabSettings[tabId] !== 'undefined' ) {
		var currentTab = tabSettings[tabId];
		//CODE TO EXECUTE AFTER PRODUCT TAB LOAD GOES HERE
		//currentTab.elements -> elementy v aktualne nacitanom tabe

		if (currentTab.elements.includes('Product_Comments') && typeof CsRating !== 'undefined') {
			let setRatings = jQuery('.cs_rating_wrapper.set_rating .rating');
			setRatings.each(function(index, elem ) {
				new CsRating(elem);
			});
		}

		if ( typeof after_init_tab === 'function' ) {
			//Toto je funkcia ktora sa bude definovat v local.js, nie kazdy shop ju musi mat
			after_init_tab(tabId);
		}
	}
}

function js_multiselect_click_handle(element) {
	$element = jQuery(element);
	if ($element.val() == '') {
		// nemozeme manualne odselectnut "vsetky"
		if (!$element.is(':selected')) {
			$element.prop('selected', true);
		}
		$element.siblings('[selected]').prop('selected', false);
	} else {
		$element.siblings('[value=""]').prop('selected', false);
	}
}

function quantityUpdate(elem, up) {
	var quantityWrap = jQuery(elem).closest('.quantity_wrapper');
	var quantityInput = quantityWrap.find('input');
	var qVal = quantityInput.val();
	var minStep = typeof quantityInput.attr('step') !== 'undefined' ? quantityInput.attr('step') * 1 : 1;

	if (up === 1) {
		quantityInput.val(parseFloat(qVal) + parseFloat(minStep));
	} else if( qVal >= minStep) {
		quantityInput.val(parseFloat(qVal) - parseFloat(minStep));
	}

	quantityInput.trigger('change');
}

function checkQuantity(elem) {
	var quantityInput = jQuery(elem);
	var minVal = typeof quantityInput.attr('min') !== 'undefined' ? Number(quantityInput.attr('min')) : undefined;
	var maxVal = typeof quantityInput.attr('max') !== 'undefined' ? Number(quantityInput.attr('max')) : undefined;
	var val = Number(quantityInput.val());

	if(typeof minVal !== 'undefined' && minVal > val) {
		quantityInput.val(minVal);
	}

	if(typeof maxVal !== 'undefined' && maxVal < val) {
		quantityInput.val(maxVal);
	}
}

function openReservationModal(elem) {
	let element = jQuery(elem);
	let productId = element.data('product_id');
	let selectedAttribute = '';
	if ( typeof element.data('is_attribute') !== 'undefined' && element.data('is_attribute') == 1 ) {
		let productAttribute = window[`ProductVariantInstance_${js_product_id}`].selectedAttribute;
		if ( typeof productAttribute.prop.CODE !== 'undefined' && productAttribute.prop.CODE !== '' ) {
			selectedAttribute = productAttribute.prop.CODE;
		}
	}

	let menuOpen = false;
	if ( element.data('menu_open') !== 'undefined' && element.data('menu_open') === 1 ) {
		menuOpen = true;
	}

	let action = typeof js_Config_product_store_reservation !== 'undefined' && typeof js_Config_product_store_reservation.extended !== 'undefined' && js_Config_product_store_reservation.extended ? 'getModalContentExtended' : 'getModalContent';
	element.prop('disabled', true);

	new AjaxRequest({productId: productId, attribute: selectedAttribute, menuOpen: menuOpen})
	.setMethod('POST')
	.setController('ProductStoreReservation')
	.setAction(action)
	.onSuccess(function (response) {
		if ( response.data.success === false && response.data.addFailed === true ) {
			new CsModal()
			.setClassName('product_reservation_error')
			.setType('info')
			.setTitle('')
			.setContent(response.data.info_message)
			.open();

			let reservationButton = jQuery('.button.prod_reservation');
			if ( reservationButton.length > 0 ) {
				reservationButton.hide();
			}

			if ( typeof response.data.attribute !== 'undefined' && response.data.attribute != '' && typeof reservationAttributes !== 'undefined' && Object.keys(reservationAttributes).includes(response.data.attribute) ) {
				reservationAttributes[response.data.attribute] = false;
			}
		} else if (response.data.success === true) {
			var title = response.data.modalTitle;
			var content = response.data.modalContent;

			if ( typeof response.data.reservationAttributes != 'undefined' && response.data.reservationAttributes != '' ) {
				reservationAttributes = response.data.reservationAttributes;
			}

			let reservationCookie = jQuery.cookie('product_reservation_filled');
			if (reservationCookie == null) {
				jQuery.cookie('product_reservation_filled', '1', {path: '/'});
				toggleProductReservationButton();
			} else {
				updateReservationCount();
			}

			reservationModal = new CsModal()
			.setClassName('product_reservation')
			.setType('info')
			.setTitle((typeof title != 'undefined' && title != '') ? title : '')
			.setContent(content)
			.hideCloseButton(false)
			.setButtons("<input type=\"button\" name=\"reservation-confirm\" class=\"button\" title=\"\" value=\"" + response.data.modalButtonConfirm + "\"><input type=\"button change_my_store\" name=\"change_my_store\" class=\"button\" title=\"\" value=\"" + response.data.modalButtonContinue + "\"><div class=\"reservation_with_payment_obligation\">" + response.data.paymentObligationText + "</div>")
			.afterClose(function() {
				let reservationButton = jQuery('.button.prod_reservation');
				if ( reservationButton.length > 0 ) {
					reservationButton.prop('disabled', false);
				}
			})
			.afterOpen(function() {
				var quantityWrapper = jQuery('.reservation_quantity_wrapper .quantity_wrapper');
				var storeSelect = jQuery('.product_reservation_modal .store_select_wrap select');

				let fakeStoreSelect = jQuery('.attr_group_custom_select_div_wrap.attr_group');
				if (fakeStoreSelect.length > 0) {
					let fakeStoreSelect = jQuery('.attr_group_custom_select_div_wrap.attr_group');
					let fakeInputBox = fakeStoreSelect.find('.inputbox.store_custom_select');
					let fakeOptions = fakeStoreSelect.find('.stores .custom_select_item');

					fakeInputBox.on('click', function() {
						let elem = jQuery(this);
						elem.toggleClass('open');
						let options = elem.parent().find('.stores');
						if (options.length > 0) {
							//"Rozbalime" fake select
							options.toggle();
						}
					});

					fakeOptions.on('click', function() {
						let elem = jQuery(this);
						let fakeSelectedStoreId = elem.data('value');

						//Prepiseme zvolenu hodnotu selectu
						let inputBox = elem.parents('.attr_group').find('.inputbox.store_custom_select');
						if (inputBox.length > 0) {
							let inputBoxName = inputBox.find('.product_reservation_store_name');
							let inputBoxAvail = inputBox.find('.product_reservation_store_availability');
							if (inputBoxName.length > 0) {
								inputBoxName.text(elem.data('name'));
							}
							if (inputBoxAvail.length > 0) {
								if (fakeSelectedStoreId == '') {
									inputBoxAvail.text('');
								} else if (fakeSelectedStoreId != '') {
									inputBoxAvail.text('V predajni');
								}
							}
							inputBox.toggleClass('open');
						}

						//Skryjeme rozbaleny fakeSelect
						let optionsWrap = elem.parent();
						if (optionsWrap.length > 0) {
							optionsWrap.toggle();
						}

						//Odstranime aktualne active
						let options = elem.siblings();
						if (options.length > 0) {
							options.removeClass('active');
						}

						//Nastavime nove active
						elem.addClass('active');

						//Zmenime pôvodný select
						if (fakeSelectedStoreId != '') {
							storeSelect.val(fakeSelectedStoreId);
						} else {
							storeSelect.val('0');
						}

						//Triggerneme change na select a tým sa vykonajú aj nabidnované funkcionality
						storeSelect.trigger('change');
					});
				}

				jQuery('.product_reservation .reservation_customer_info input[name="name"]').on('blur', function() {
					var $this = jQuery(this);
					var inputValue = $this.val();

					if ( typeof inputValue == 'undefined' || inputValue == '' || inputValue.replace(/\s/g, "").length <= 2 || /^[a-žA-Ž ]+$/.test(inputValue) === false ) {
						$this.addClass('error');
						$this.removeClass('valid');
					} else {
						$this.addClass('valid');
						$this.removeClass('error');
					}
				});

				jQuery('.product_reservation .reservation_customer_info input[name="name"],[name="surname"]').on('blur', function() {
					var $this = jQuery(this);
					var inputValue = $this.val();

					if ( typeof inputValue == 'undefined' || inputValue == '' || inputValue.replace(/\s/g, "").length <= 2 || /^[a-žA-Ž ]+$/.test(inputValue) === false ) {
						$this.addClass('error');
						$this.removeClass('valid');
					} else {
						$this.addClass('valid');
						$this.removeClass('error');
					}
				});

				jQuery('.product_reservation .reservation_customer_info input[name="email"]').on('blur', function() {
					var $this = jQuery(this);
					var inputValue = $this.val();

					if ( typeof inputValue == 'undefined' || inputValue == '' || /\S+@\S+\.\S+/.test(inputValue) === false ) {
						$this.addClass('error');
						$this.removeClass('valid');
					} else {
						$this.addClass('valid');
						$this.removeClass('error');
					}
				});

				jQuery('.product_reservation .reservation_customer_info input[name="phone"]').on('blur', function() {
					var $this = jQuery(this);
					var inputValue = $this.val();

					if ( typeof inputValue == 'undefined' || inputValue == '' || inputValue.replace(/\s/g, "").length < 9 || inputValue.replace(/\s/g, "").length > 13 || /\d/g.test(inputValue.replace(/\s/g, "")) === false ) {
						$this.addClass('error');
						$this.removeClass('valid');
					} else {
						$this.addClass('valid');
						$this.removeClass('error');
					}
				});

				var submitButton = jQuery('.product_reservation input[name="reservation-confirm"]');
				submitButton.on('click', function () {
					var $this = jQuery(this);
					$this.prop('disabled', true);
					showLoader();
					var result = true;
					var parentElement 	= $this.parents('.product_reservation');
					var customerInfo 	= parentElement.find('.reservation_customer_info');
					var selectedStore 	= parentElement.find('.store_select').val();
					var quantity 		= parentElement.find('.quantity_wrapper input').val();
					var name 			= customerInfo.find('input[name="name"]').val();
					var surname 		= customerInfo.find('input[name="surname"]').val();
					var email 			= customerInfo.find('input[name="email"]').val();
					var phone 			= customerInfo.find('input[name="phone"]').val();
					var comment 		= customerInfo.find('textarea[name="comment"]').val();
					var productId 		= parentElement.find('.reservation_product_id').val();
					var attribute 		= parentElement.find('.reservation_attribute').val();

					var errors = {
						'name': false,
						'surname': false,
						'email': false,
						'phone': false,
						'store': false,
						'quantity': false,
						'product' : false,
					};

					if ( (typeof productId == 'undefined' || productId == '' || productId == '0') && (typeof js_Config_product_store_reservation.extended === 'undefined' || js_Config_product_store_reservation.extended !== true) ) {
						errors.product = true;
					}

					if ( typeof selectedStore == 'undefined' || selectedStore == '' || selectedStore == '0' ) {
						errors.store = true;
						parentElement.find('.store_select').addClass('error');
						parentElement.find('.inputbox.store_custom_select').addClass('error');
					}

					if ( typeof quantity == 'undefined' || quantity == '' || quantity == 0 ) {
						errors.quantity = true;
					}

					if ( (typeof name == 'undefined' || name == '' || name.replace(/\s/g, "").length <= 2 || /^[a-žA-Ž ]+$/.test(name) === false) && (typeof js_Config_product_store_reservation.extended === 'undefined' || js_Config_product_store_reservation.extended !== true) ) {
						errors.name = true;
						customerInfo.find('input[name="name"]').addClass('error');
					}

					if ( (typeof surname == 'undefined' || surname == '' || surname.replace(/\s/g, "").length <= 2 || /^[a-žA-Ž ]+$/.test(surname) === false) && (typeof js_Config_product_store_reservation.extended === 'undefined' || js_Config_product_store_reservation.extended !== true) ) {
						errors.surname = true;
						customerInfo.find('input[name="surname"]').addClass('error');
					}

					if ( (typeof email == 'undefined' || email == '' || /\S+@\S+\.\S+/.test(email) === false) && (typeof js_Config_product_store_reservation.extended === 'undefined' || js_Config_product_store_reservation.extended !== true) ) {
						errors.email = true;
						customerInfo.find('input[name="email"]').addClass('error');
					}

					if ( (typeof phone == 'undefined' || phone == '' || phone.replace(/\s/g, "").length < 9 || phone.replace(/\s/g, "").length > 13 || /\d/g.test(phone.replace(/\s/g, "")) === false) && (typeof js_Config_product_store_reservation.extended === 'undefined' || js_Config_product_store_reservation.extended !== true) ) {
						errors.phone = true;
						customerInfo.find('input[name="phone"]').addClass('error');
					}


					Object.values(errors).forEach(function (error) {
						if ( error === true) {
							result = false;
						}
					});

					if ( result === true && typeof js_Config_product_store_reservation.extended !== 'undefined' && js_Config_product_store_reservation.extended === true ) {

						//Kontaktne udaje zakaznika vypnute, kedze su tu zbytocne
						/* var controllerData = {
							'first_name'	: name,
							'last_name'		: surname,
							'email'			: email,
							'phone_1'		: phone,
						}; */

						let setDefaultStoreCbx = jQuery('.product_reservation_modal #set_as_my_store_cbx');
						let setDefaultStore = false;
						if ( setDefaultStoreCbx.length > 0 ) {
							setDefaultStore = setDefaultStoreCbx.is(':checked');
						}

						new AjaxRequest()
						.setMethod('POST')
						.setController('ProductStoreReservation')
						.setAction('checkCartItems')
						.onSuccess(function (response) {
							if (response.data.success === true && response.data.cartEmpty == true) {
								new AjaxRequest({data: {'selectedStore': selectedStore, 'setDefaultStore': setDefaultStore}})
								.setMethod('POST')
								.setController('ProductStoreReservation')
								.setAction('fillCartReservation')
								.onSuccess(function (response) {
									if (response.data.success === true && response.data.checkout_redirect_url != '' ) {

										if ( typeof response.data.checkout_form_data !== 'undefined' && response.data.checkout_form_data != '' ) {
											let checkoutFormData = response.data.checkout_form_data;
											let currentFormData = jQuery.cookie('checkout_form_data');

											if ( currentFormData !== null ) {
												currentFormData = JSON.parse(currentFormData);
												checkoutFormData = Object.assign(currentFormData, checkoutFormData);
											}

											jQuery.cookie('checkout_form_data', JSON.stringify(checkoutFormData), {path: '/'});
											jQuery.cookie('product_reservation_active', 1, {path: '/'});
										}

										window.location.replace(response.data.checkout_redirect_url);
									}
								})
								.send();
							} else {
								cartReservationModalConfirm = new CsModal()
								.setClassName('cart_reservation_fill_confirm')
								.setType('info')
								.setTitle('')
								.setContent(js_lang_checkout_product_reservation.fillModalMessage)
								.hideCloseButton(true)
								.setButtons("<input type=\"button\" name=\"reservation-fill-confirm\" class=\"button\" title=\"\" value=\"" + js_lang_checkout_product_reservation.confirm + "\"><input type=\"button\" name=\"reservatil-fill-cancel\" onclick=\"cartReservationModalConfirm.close();\" class=\"button\" title=\"\" value=\"" + js_lang_checkout_product_reservation.cancel + "\">")
								.afterOpen(function() {
									let reservationFillModal = jQuery('.cart_reservation_fill_confirm');
									if (reservationFillModal.length > 0) {
										let fillConfirmButton = reservationFillModal.find('input[name="reservation-fill-confirm"]');
										if (fillConfirmButton.length > 0) {
											fillConfirmButton.on('click', function() {
												if (typeof selectedStore !== 'undefined' && typeof setDefaultStore !== 'undefined') {
													new AjaxRequest({data: {'selectedStore': selectedStore, 'setDefaultStore': setDefaultStore}})
													.setMethod('POST')
													.setController('ProductStoreReservation')
													.setAction('fillCartReservation')
													.onSuccess(function (response) {
														if (response.data.success === true && response.data.checkout_redirect_url != '' ) {

															if ( typeof response.data.checkout_form_data !== 'undefined' && response.data.checkout_form_data != '' ) {
																let checkoutFormData = response.data.checkout_form_data;
																let currentFormData = jQuery.cookie('checkout_form_data');

																if ( currentFormData !== null ) {
																	currentFormData = JSON.parse(currentFormData);
																	checkoutFormData = Object.assign(currentFormData, checkoutFormData);
																}

																jQuery.cookie('checkout_form_data', JSON.stringify(checkoutFormData), {path: '/'});
																jQuery.cookie('product_reservation_active', 1, {path: '/'});
															}

															window.location.replace(response.data.checkout_redirect_url);
														}
													})
													.send();
												} else {
													console.log('Variables are not defined');
												}
											});
										}
									}
								})
								.open();
							}
						})
						.send();
					}

					if ( result === true && (typeof js_Config_product_store_reservation.extended === 'undefined' || js_Config_product_store_reservation.extended !== true ) ) {

						var controllerData = {
							'store'		: selectedStore,
							'quantity'	: quantity,
							'name'		: name,
							'surname'	: surname,
							'email'		: email,
							'phone'		: phone,
							'comment'	: comment,
							'product'	: productId,
						};

						if ( typeof attribute !== 'undefined' && attribute != '' ) {
							controllerData.attribute = attribute;
						}

						new AjaxRequest({data: controllerData,})
						.setMethod('POST')
						.setController('ProductStoreReservation')
						.setAction('processReservation')
						.onSuccess(function (response) {
							if (response.data.success === true) {
								if ( typeof reservationModal === 'undefined' ) {
									hideLoader();
									return;
								}

								var newContent = response.data.modalUpdate.content;
								var newButton  =  response.data.modalUpdate.button;

								//var reservationNumber = response.data.reservationNumber;
								reservationModal.setContent(newContent);
								var button = jQuery('.product_reservation .vex-dialog-buttons input');
								if ( button.length > 0 ) {
									button.replaceWith(newButton);
								}
								hideLoader();
							} else {
								jQuery('.product_reservation input[name="reservation-confirm"]').prop('disabled', false);
								hideLoader();
							}
						}).send();
					} else {
						$this.prop('disabled', false);
						hideLoader();
					}
				});

				let changeStoreButton = jQuery('.product_reservation input[name="change_my_store"]');
				if ( changeStoreButton.length > 0 ) {
					changeStoreButton.on('click', function () {
						let button = jQuery(this);
						button.prop('disabled', true);
						let storeSelect = jQuery('.product_reservation_modal .store_select_wrap select');
						if ( storeSelect.length > 0 ) {
							var selectedStore = storeSelect.val();
						}

						if ( typeof selectedStore === 'undefined' || selectedStore == '' || selectedStore == '0' ) {
							reservationModal.close();
							return;
						}

						let preventStoreUpdate = jQuery('.product_reservation_modal #my_store_active');
						preventStoreUpdate = preventStoreUpdate.length > 0 && preventStoreUpdate.val() == 1;

						let setDefaultStoreCbx = jQuery('.product_reservation_modal #set_as_my_store_cbx');
						var setDefaultStore = false;
						if ( setDefaultStoreCbx.length > 0 ) {
							setDefaultStore = setDefaultStoreCbx.is(':checked');
							let storeTooltip = jQuery('.store_reservation span.my_store.tooltipstered');
							if ( setDefaultStore === true && storeTooltip.length > 0 ) {
								storeTooltip.tooltipster('destroy');
							}
						}

						if ( preventStoreUpdate === false || setDefaultStore === true ) {
							new AjaxRequest({'storeId': selectedStore, 'myStore': setDefaultStore})
							.setMethod('POST')
							.setController('ProductStoreReservation')
							.setAction('updateStore')
							.onSuccess(function (response) {
								if ( response.data.success === true ) {
									reservationModal.close();
									if (typeof setDefaultStore !== 'undefined' && setDefaultStore === true && jQuery('body').hasClass('shop_page_class_shop_browse')) {
										js_reload_current_page();
									} else if (typeof setDefaultStore !== 'undefined' && setDefaultStore === true && jQuery('body').hasClass('shop_page_class_shop_product_details')) {
										let availabilityWrapper = jQuery('.product_store_availability_wrapper');
										if (availabilityWrapper.length > 0) {
											detailActiveStoreIcon = availabilityWrapper.find('.active_store_icon');
											if (detailActiveStoreIcon.length > 0) {
												detailActiveStoreIcon.remove();
											}
											newDetailActive = availabilityWrapper.find('div[data-store-id="' + selectedStore + '"]');
											if (newDetailActive.length > 0) {
												newDetailActive.find('.store_title').find('span').after('<span class="active_store_icon"></span>');
											}
										}
									}
								} else {
									let changeStoreButton = jQuery('.product_reservation input[name="change_my_store"]');
									if ( changeStoreButton.length > 0 ) {
										changeStoreButton.prop('disabled', false);
									}
								}
							}).send();
						} else {
							reservationModal.close();
						}
					});
				}

				var totalMaximumQuantity = 0;
				storeSelect.find('option').each(function () {
					var storeMaximum = jQuery(this).data('quantity');
					if ( typeof storeMaximum === 'object' ) {
						Object.values(storeMaximum).forEach( function (quantity) {
							if ( quantity > totalMaximumQuantity ) {
								totalMaximumQuantity = quantity;
							}
						});
					} else if ( typeof storeMaximum !== 'undefined' && storeMaximum > totalMaximumQuantity ) {
						totalMaximumQuantity = storeMaximum;
					}
				});

				var quantityInput = quantityWrapper.find('input');
				if ( typeof quantityInput.data('forced_quantity') === 'undefined' ) {
					quantityInput.data('forced_quantity', 1);
				}

				if ( typeof totalMaximumQuantity !== 'undefined' ) {
					quantityInput.data('maximum_quantity', totalMaximumQuantity);
					storeSelect.find('option[value="0"]').data('quantity', totalMaximumQuantity);
				}

				quantityInput.on('change', function (evt) {
					let element = jQuery(this);

					if ( typeof evt.isTrigger === 'undefined' || element.prop('disabled') == true ) {
						return;
					}

					/* let priceWrapper =  element.parents('.reservation_snapshot').find('.price_wrapper');
					let unitPrice = priceWrapper.find('.price_per_unit').data('unit_price').replace(',', '.');
					if ( typeof unitPrice !== 'undefined' ) {
						let newPrice = element.val() * unitPrice;
						priceWrapper.find('.total_price').html('<b>' + csFormatPrice(newPrice) + '</b>');
					} */

					let totalPrice = element.parents('.product_reservation_modal').find('.reservation_total .total_price');
					if ( totalPrice.length > 0 ) {
						let reservationTotal = 0;
						jQuery('.reservation_snapshot').each(function(){
							let elem = jQuery(this);
							let unit_price = elem.find('.price_per_unit').data('unit_price');
							let quantity = elem.find('.quantity_wrapper').find('input').val();
							reservationTotal += parseFloat(unit_price.replace(',','.')) * quantity;
						});
						totalPrice.html('<b>' + reservationTotal.toFixed(shop_currency_info[shop_vendor_currency_code].DECIMALS).replace('.',',') + ' ' + shop_currency_info[shop_vendor_currency_code].SYMBOL + ' ' + cms_js_lang_product_form_price_gross_label + '</b>');
					}

					let productId = element.parents('.reservation_quantity_wrapper').data('prod_id');
					let productAttribute = element.parents('.reservation_quantity_wrapper').data('prod_attr_code');

					if ( typeof productId !== 'undefined' && productId != '' ) {
						let quantityData = {
							productId: productId,
							attribute: (typeof productAttribute !== 'undefined' && productAttribute != '' ? productAttribute : ''),
							quantity: element.val(),
						};

						element.prop('disabled', true);

						new AjaxRequest(quantityData)
							.setMethod('POST')
							.setController('ProductStoreReservation')
							.setAction('updateQuantity')
							.onSuccess(function (response) {
								element.prop('disabled', false);
								updateReservationCount();
							}).send();
					}
				});

				//Bindovanie odstranenia produktu z rezervacie
				let removeButtons = jQuery('.product_reservation .remove_product span[name="delete"]');
				removeButtons.on('click', function () {
					let element = jQuery(this);
					let productId = element.parent().siblings('.reservation_quantity_wrapper').data('prod_id');

					if ( typeof productId !== 'undefined' && productId != '' ) {
						let removeProductOptions = {
							productId: productId,
						};

						let attrCode = element.parent().siblings('.reservation_quantity_wrapper').data('prod_attr_code');
						if ( typeof attrCode !== 'undefined' && attrCode != '' ) {
							removeProductOptions.attribute = attrCode;
						}

						new AjaxRequest(removeProductOptions)
							.setMethod('POST')
							.setController('ProductStoreReservation')
							.setAction('removeProduct')
							.onSuccess(function (response) {
								if ( response.data.success === true && response.data.product_id != '' ) {

									if ( response.data.reservation_empty === true ) {
										let reservationCookie = jQuery.cookie('product_reservation_filled');
										if (reservationCookie != null) {
											Cookies.remove('product_reservation_filled');
											toggleProductReservationButton();
										} else {
											updateReservationCount();
										}
										reservationModal.close();
										return;
									} else {
										updateReservationCount();
									}

									if ( typeof response.data.reservationAttributes != 'undefined' && response.data.reservationAttributes != '' && typeof js_product_id != 'undefined' && js_product_id == response.data.product_id ) {
										reservationAttributes = response.data.reservationAttributes;
									}

									if ( typeof response.data.updated_stores === 'object' && Object.keys(response.data.updated_stores).length > 0 ) {
										let storeSelect = jQuery('.product_reservation_modal .store_select_wrap select');
										let storeOptions = storeSelect.find('option:not(:first)');
										storeOptions.remove();
										let newOptions = '';
										Object.entries(response.data.updated_stores).forEach( entry => {
											let newStore = entry[1];
											newOptions += '<option value="' + newStore.store_id + '" data-quantity="' + newStore.quantity + '"' + (typeof newStore.selected !== 'undefined' && newStore.selected === true ? ' selected' : '') + '>' + newStore.store + '</option>';
										});

										storeSelect.append(newOptions);
										storeSelect.trigger('change');
									}

									if ( typeof response.data.store_json !== 'undefined' && response.data.store_json != '' ) {
										storeReservationJson = JSON.parse(response.data.store_json);
									}

									let isAttribute = typeof response.data.attribute !== 'undefined' && response.data.attribute != '' ? true : false;
									let productElement = jQuery('.product_reservation_modal .reservation_quantity_wrapper.prod_id_' + response.data.product_id + ( isAttribute === true ? '[data-prod_attr_code="' + response.data.attribute + '"]' : ''));
									if ( productElement.length > 0 ) {
										productElement = productElement.parents('.reservation_snapshot');
										if ( productElement.length > 0 ) {
											productElement.slideUp(150, function () {
												this.remove();

												let totalPrice = jQuery('.product_reservation_modal .reservation_total .total_price');
												if ( totalPrice.length > 0 ) {
													let reservationTotal = 0;
													jQuery('.reservation_snapshot').each(function(){
														let elem = jQuery(this);
														let unit_price = elem.find('.price_per_unit').data('unit_price');
														let quantity = elem.find('.quantity_wrapper').find('input').val();
														reservationTotal += parseFloat(unit_price.replace(',','.')) * quantity;
													});
													totalPrice.html('<b>' + reservationTotal.toFixed(shop_currency_info[shop_vendor_currency_code].DECIMALS).replace('.',',') + ' ' + shop_currency_info[shop_vendor_currency_code].SYMBOL + '</b>');
												}

												let reservationPrices = jQuery('.product_reservation_modal .reservation_snapshot .price_per_unit');
												if (reservationPrices.length > 0) {
													let hidePriceInfo = true;

													reservationPrices.each(function() {
														if (jQuery(this).css('display') != 'none') {
															hidePriceInfo = false;
															return false;
														}
													});

													if (hidePriceInfo === true) {
														let priceInfo = jQuery('.product_reservation_modal .reservation_discounted_price_info');
														if (priceInfo.length > 0) {
															priceInfo.hide();
														}
													}
												}
											});
										}
									}
								}
							}).send();
					}
				});

				if ( storeSelect.length > 0 ) {
					storeSelect.on('change', function(){
						var element = jQuery(this);
						var selected = element.find('option:selected');

						if ( selected.length == 0 ) {
							return;
						}
						var maximumQuantity = selected.data('quantity');

						if ( typeof maximumQuantity === 'object' ) {
							Object.entries(maximumQuantity).forEach( entry => {
								let productId = entry[0];
								let quantity = entry[1];
								let quantityInput = element.parents('.product_reservation_modal').find('.reservation_quantity_wrapper[data-prod_attr_code="' + productId + '"] input'); //Najskor hladaj variant

								if ( quantityInput.length == 0 ) {
									quantityInput = element.parents('.product_reservation_modal').find('.reservation_quantity_wrapper.prod_id_' + productId + ' input');//Ak sa nenajde variant tak podla prod_id
								}

								if ( quantityInput.length > 0 ) {
									quantityInput.data('maximum_quantity', quantity);
									if ( parseInt(quantityInput.val()) > parseInt(quantity) ) {
										quantityInput.trigger('blur');
									}
								}
							});
						} else {
							let quantityInput = element.parents('.product_reservation_modal').find('.quantity_wrapper input');

							if ( quantityInput.length == 0 ) {
								return;
							}

							quantityInput.data('maximum_quantity', maximumQuantity);
							quantityInput.trigger('blur');
						}

						//Tu konci zmena quantity a zacina info o predajni
						var storeId = selected.val();
						if ( typeof storeReservationJson !== 'undefined' && typeof storeReservationJson[storeId] !== 'undefined' ) {
							element.removeClass('error');
							let temFakeSelect = element.siblings('.attr_group_custom_select_div_wrap.attr_group');
							if (temFakeSelect.length > 0) {
								temFakeSelect.find('.inputbox.store_custom_select').removeClass('error');
							}
							var storeInfo = element.parents('.store_select_wrap').find('.selected_store_info');
							storeInfo.find('.address').html(storeReservationJson[storeId].street + ', ' + storeReservationJson[storeId].city);
							let hoursHtml = '';
							if ( typeof storeReservationJson[storeId].hours !== 'undefined' && storeReservationJson[storeId].hours != '' ) {
								let openingHours = storeReservationJson[storeId].hours;
								Object.entries(openingHours).forEach( entry => {
									hoursHtml += '<div class="hours_row">' + entry[0] + ': ' + entry[1] + '</div>';
								});
							}

							storeInfo.find('.phone_contact').html(storeReservationJson[storeId].phone);
							storeInfo.find('.email_contact').html(storeReservationJson[storeId].mail);
							storeInfo.find('.opening_hours').html(hoursHtml);
							storeInfo.show();

							let preventStoreUpdate = jQuery('.product_reservation_modal #my_store_active');
							if ( typeof preventStoreUpdate == 'undefined' || preventStoreUpdate.length == 0 || preventStoreUpdate.val() != 1 ) {
								new AjaxRequest({'storeId': storeId})
								.setMethod('POST')
								.setController('ProductStoreReservation')
								.setAction('updateStore')
								.send();
							}
						} else {
							element.parents('.store_select_wrap').find('.selected_store_info').hide();
						}
					});
				}
				storeSelect.trigger('change');
			})
			.setActionsClassName('vex-dialog-buttons')
			.open();
		}
	}).send();
}

function updateReservationCount() {
	let reservationCookie = jQuery.cookie('product_reservation_filled');
	if (reservationCookie == null) {
		return;
	}

	new AjaxRequest()
	.setMethod('POST')
	.setController('ProductStoreReservation')
	.setAction('getProductCount')
	.onSuccess(function (response) {
		let reservationcountElem = jQuery(".store_reservation span.prod_reservation .count");
		if (response.data.success === true && typeof response.data.count !== 'undefined' && reservationcountElem.length > 0) {
			reservationcountElem.text(response.data.count > 0 ? response.data.count : '');
		} else if (reservationcountElem.length > 0) {
			reservationcountElem.text('');
		}
	}).send();
}

function resetReservationFilter() {
	let sphfResetButton = jQuery('.fp_active_reset');
	if (sphfResetButton.length > 0) {
		sphfResetButton.trigger('click');
	}
}

function toggleProductReservationButton() {
	let reservationButton = jQuery(".store_reservation span.prod_reservation");
	if (reservationButton.length == 0) {
		return;
	}

	let reservationCookie = jQuery.cookie('product_reservation_filled');
	if (reservationCookie == null || reservationCookie != 1) {
		reservationButton.hide();
		return;
	}

	updateReservationCount();

	reservationButton.show();
	return;
}

function openMyStoreTooltip(element){
	let elem = jQuery(element);

	if ( elem.hasClass('tooltipstered') ) {
		return false;
	}

	elem.prop('disabled', true);

	new AjaxRequest()
		.setMethod('POST')
		.setController('ProductStoreReservation')
		.setAction('getTooltipContent')
		.onSuccess(function (response) {
			if ( response.data.success === true ) {
				elem.tooltipster({
					theme        	: "cs_tooltipster_grey_theme store-tooltip",
					contentAsHTML	: true,
					position	 	: 'bottom',
					content      	: response.data.tooltipContent,
					interactive		: true,
				}).tooltipster('open');
				elem.prop('disabled', false);
			}
		}).send();
}

function resetMyStore(){
	let button = jQuery(this);
	if ( button.length > 0 ) {
		button.prop('disabed', true);
	}

	new AjaxRequest()
	.setMethod('POST')
	.setController('ProductStoreReservation')
	.setAction('cancelSelectedStore')
	.onSuccess(function (response) {
		if ( response.data.success === true ) {
			if (jQuery('body').hasClass('shop_page_class_shop_browse')) {
				//Ak sme v kategorii tak klikneme na reset filtra
				resetReservationFilter();
			} else if (jQuery('body').hasClass('shop_page_class_shop_product_details')) {
				//Ak sme v detaile tak odstranime ikonku domceku
				let availabilityWrapper = jQuery('.product_store_availability_wrapper');
				if (availabilityWrapper.length > 0) {
					detailActiveStoreIcon = availabilityWrapper.find('.active_store_icon');
					if (detailActiveStoreIcon.length > 0) {
						detailActiveStoreIcon.remove();
					}
				}
			}

			jQuery('.store_reservation span.my_store.tooltipstered').tooltipster('destroy');
		}
	}).send();
}

function openMyStore(element){
	var element = jQuery(element);
	element.prop('disabled', true);

	new AjaxRequest()
		.setMethod('POST')
		.setController('ProductStoreReservation')
		.setAction('getStoreModal')
		.onSuccess(function (response) {
			if ( response.data.success === true ) {
				let storeTooltip = jQuery('.store_reservation span.my_store.tooltipstered');
				if ( storeTooltip.length > 0 && storeTooltip.hasClass('tooltipstered') ) {
					storeTooltip.tooltipster('hide');
				}

				let content = response.data.modalContent;
				let title = response.data.modalTitle;

				myStoreModal = new CsModal()
				.setClassName('my_store')
				.setType('info')
				.setTitle(title)
				.setContent(content)
				.setButtons("<input type=\"button\" name=\"my_store_confirm\" class=\"button\" title=\"\" value=\"" + response.data.modalButton + "\">")
				.afterClose(function() {
					let myStoreButton = jQuery('.button.my_store');
					if ( myStoreButton.length > 0 ) {
						myStoreButton.prop('disabled', false);
					}
				})
				.afterOpen(function() {

					let storeConfirmButton = jQuery('.cs_modal.my_store input[name="my_store_confirm"]');
					if ( storeConfirmButton.length > 0) {
						storeConfirmButton.on('click', function() {
							let confirmButton = jQuery(this);
							confirmButton.prop('disabled', true);
							let selectedStoreId = confirmButton.parents('.my_store').find('input[name="store_select_radio"]:checked').val();
							if ( selectedStoreId != '' ) {
								new AjaxRequest({'storeId': selectedStoreId, 'myStore': true})
								.setMethod('POST')
								.setController('ProductStoreReservation')
								.setAction('updateStore')
								.onSuccess(function (response) {
									if ( response.data.success === true ) {
										jQuery('.store_reservation span.my_store.tooltipstered').tooltipster('destroy');
										if (jQuery('body').hasClass('shop_page_class_shop_browse')) {
											js_reload_current_page();
										} else if (jQuery('body').hasClass('shop_page_class_shop_product_details')) {
											let availabilityWrapper = jQuery('.product_store_availability_wrapper');
											if (availabilityWrapper.length > 0) {
												detailActiveStoreIcon = availabilityWrapper.find('.active_store_icon');
												if (detailActiveStoreIcon.length > 0) {
													detailActiveStoreIcon.remove();
												}
												newDetailActive = availabilityWrapper.find('div[data-store-id="' + selectedStoreId + '"]');
												if (newDetailActive.length > 0) {
													newDetailActive.find('.store_title').find('span').after('<span class="active_store_icon"></span>');
												}
											}
										}

										myStoreModal.close();
									} else {
										let storeConfirmButton = jQuery('.cs_modal.my_store input[name="my_store_confirm"]');
										if ( storeConfirmButton.length > 0 ) {
											storeConfirmButton.prop('disabled', false);
										}
									}
								}).send();
							} else {
								confirmButton.prop('disabled', true);
							}
						});
					}

					let storeCitySelect = jQuery('.cs_modal.my_store select.city_select');
					if ( storeCitySelect.length > 0 ) {
						storeCitySelect.on('change', function () {
							let citySelect = jQuery(this);
							let selected = citySelect.find('option:selected');
							let stores = selected.data('stores');

							if ( typeof stores !== 'undefined' && stores.length > 0 ) {
								let allStores = citySelect.parents('.my_store_modal').find('input[name="store_select_radio"]');
								if ( allStores.length > 0 ) {
									allStores.each(function() {
										let store = jQuery(this);
										if ( stores.includes(store.val()) ) {
											store.parents('.other_store_row').show();
										} else {
											store.parents('.other_store_row').hide();
										}
									});
								}
							} else {
								citySelect.parents('.my_store_modal').find('.other_store_row').show();
							}
						});
					}

					let storesRadio = jQuery('.cs_modal.my_store input[name="store_select_radio"]');
					if ( storesRadio.length > 0 ) {
						storesRadio.on('change', function() {
							let storeRow = jQuery(this).parents('.other_store_row');
							storeRow.siblings('.active').removeClass('active');
							storeRow.addClass('active');
						});
					}
				})
				.open();
			}
		}).send();
}

function js_shopcart_reserve_product_submit(elem) {
	let element = jQuery(elem);
	let productId = element.data('product_id');
	let productName = element.data('product_name');
	let reservationModal = '';

	new AjaxRequest({productId: productId, productName: productName})
		.setMethod('POST')
		.setController('ProductRental')
		.setAction('getModalContent')
		.onSuccess(function (response) {

			reservationModal = new CsModal()
				.setClassName('product_mode_reservation')
				.setType('info')
				.setTitle(productName)
				.setContent(response.data.content)
				.setButtons("<button type='button' class='close_button close_reservation_mode_modal'>"+ cms_js_lang_close +"</button><button type='button' class='button submit_product_mode_reservation'>"+ js_lang_dynamic_attributes_lm_btn +"</button>")
				.afterOpen(function () {
					let sendEmailButton = jQuery('.submit_product_mode_reservation');
					let reservationInfo = sendEmailButton.parents().find('.reservation_mode_customer_info');

					sendEmailButton.on('click', function () {
						sendEmailButton.prop('disabled', true);
						let result = true;

						let nameElem = reservationInfo.find('input[name="name"]');
						let surnameElem = reservationInfo.find('input[name="surname"]');
						let emailElem = reservationInfo.find('input[name="email"]');
						let phoneElem = reservationInfo.find('input[name="phone"]');
						let commentElem = reservationInfo.find('textarea[name="comment"]');
						let dateFromElem = reservationInfo.find('input[name="dateFrom"]');
						let dateToElem = reservationInfo.find('input[name="dateTo"]');

						let name = nameElem.val();
						let surname = surnameElem.val();
						let email = emailElem.val();
						let phone = phoneElem.val();
						let comment = commentElem.val();
						let dateFrom = dateFromElem.val();
						let dateTo = dateToElem.val();

						let errors = {
							'name': false,
							'surname': false,
							'email': false,
							'phone': false,
							'product': false,
							'dateFrom': false,
							'dateTo': false,
						};

						if (typeof productId == 'undefined' || productId === '' || productId === '0') {
							errors.product = true;
						}

						if (typeof name == 'undefined' || name === '' || name.replace(/\s/g, "").length <= 2 || /^[a-žA-Ž ]+$/.test(name) === false) {
							errors.name = true;
							nameElem.addClass('error');
							nameElem.after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + nameElem.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>');
						}

						if (typeof surname == 'undefined' || surname === '' || surname.replace(/\s/g, "").length <= 2 || /^[a-žA-Ž ]+$/.test(surname) === false) {
							errors.surname = true;
							surnameElem.addClass('error');
							surnameElem.after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + surnameElem.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>');
						}

						if (typeof email == 'undefined' || email === '' || /\S+@\S+\.\S+/.test(email) === false) {
							errors.email = true;
							if (emailElem.siblings('.error_box').length === 0) {
								emailElem.after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + emailElem.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>');
								emailElem.addClass('error');
							}
						}

						if (typeof phone == 'undefined' || phone === '' || phone.replace(/\s/g, "").length < 9 || (phone.replace(/\s/g, "").length > 13 || /\d/g.test(phone.replace(/\s/g, "")) === false)) {
							errors.phone = true;
							if (phoneElem.siblings('.error_box').length === 0) {
								phoneElem.after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + phoneElem.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>');
								phoneElem.addClass('error');
							}
						}

						if (typeof dateFrom == 'undefined' || dateFrom === '' || /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](20|21)\d\d/.test(dateFrom) === false) {
							errors.dateFrom = true;
							errors.phone = true;
							if (dateFromElem.siblings('.error_box').length === 0) {
								dateFromElem.after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + dateFromElem.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>');
								dateFromElem.addClass('error');
							}
						}

						if (typeof dateTo == 'undefined' || dateTo === '' || /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](20|21)\d\d/.test(dateTo) === false) {
							errors.dateTo = true;
							if (dateToElem.siblings('.error_box').length === 0) {
								dateToElem.after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + dateToElem.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>');
								dateToElem.addClass('error');
							}
						}

						if (dateFrom !== '' && dateTo !== '') {
							let dateFrom2 = dateFrom.split(".");
							let dateTo2 = dateTo.split(".");
							let now = new Date();
							now.setHours(0, 0, 0, 0);

							dateFrom2 = new Date(parseInt(dateFrom2[2], 10),
								parseInt(dateFrom2[1], 10) - 1,
								parseInt(dateFrom2[0], 10));

							dateTo2 = new Date(parseInt(dateTo2[2], 10),
								parseInt(dateTo2[1], 10) - 1,
								parseInt(dateTo2[0], 10));

							if (isNaN(dateFrom2.getDate())) {
								errors.dateFrom = true;
								dateFromElem.removeClass('valid');
								dateFromElem.after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_incorrect_format_date_error + '</div>');
							}

							if (isNaN(dateTo2.getDate())) {
								errors.dateTo = true;
								dateToElem.removeClass('valid');
								dateToElem.after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_incorrect_format_date_error + '</div>');
							}

							if (dateFrom2 > dateTo2) {
								errors.dateFrom = true;
								dateFromElem.removeClass('valid');
								dateToElem.removeClass('valid');
								dateToElem.removeClass('error_box');
								dateFromElem.addClass('error');
								dateToElem.addClass('error');
								dateToElem.after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_predate_error + '</div>');
								dateFromElem.after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_predate_error + '</div>');
							}

							if (dateFrom2 < now) {
								errors.dateFrom = true;
								dateFromElem.removeClass('valid');
								dateFromElem.addClass('error');
								dateFromElem.after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_current_date_error + '</div>');
							}

							if (dateTo2 < now) {
								errors.dateTo = true;
								dateToElem.removeClass('valid');
								dateToElem.addClass('error');
								dateToElem.after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_current_date_error + '</div>');
							}
						}


						Object.values(errors).forEach(function (error) {
							if (error === true) {
								result = false;
							}
						});

						if (result === true) {
							let emailData = {
								name: name,
								surname: surname,
								email: email,
								phone: phone,
								comment: comment,
								productId: productId,
								productName: productName,
								dateFrom: dateFrom,
								dateTo: dateTo,
							};

							new AjaxRequest({data: emailData})
								.setMethod('POST')
								.setController('ProductRental')
								.setAction('sendEmail')
								.onSuccess(function (response) {
									if (response.data.message === 'success') {
										reservationModal.close();
										vex.dialog.alert(cms_js_lang_reservation_mode_email_sent + '. ' + cms_js_lang_reservation_mode_email_sent_contact);
									} else {
										reservationModal.close();
										vex.dialog.alert(cms_js_lang_reservation_mode_email_not_sent);
									}
								}).send();

						} else {
							sendEmailButton.prop('disabled', false);
						}
					})

					reservationInfo.on("focusout", "input, textarea", function () {
						var $this = jQuery(this);
						let elemValue = $this.val();
						var valid = typeof elemValue !== 'undefined' && elemValue !== '';
						let elemName = $this.attr('name');
						let message = '<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + $this.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>';

						if (elemName === 'dateTo' || elemName === 'dateFrom') {
							return;
						}

						if (elemName === 'email' && elemValue.length > 0 && /\S+@\S+\.\S+/.test(elemValue) === false) {
							valid = false;
							message = '<div class="cleaner"></div><div class="error_box">' + js_lang_nsu_lm_wrong_email + '</div>';
						}

						if (elemName === 'phone' && elemValue.length > 0 && (elemValue === '' || elemValue.replace(/\s/g, "").length < 9 || elemValue.replace(/\s/g, "").length > 13 || /\d/g.test(elemValue.replace(/\s/g, "")) === false)) {
							valid = false;
							message = '<div class="cleaner"></div><div class="error_box">' + cms_js_lang_is_not_numeric + '</div>';
						}

						if (valid) {
							if ($this.hasClass('required')) {
								$this.addClass('valid');
								$this.removeClass('error');
								$this.siblings('.error_box').remove();
								$this.siblings('.cleaner').remove();
							}
							$this.addClass('filled');

						} else {
							$this.siblings('.error_box').remove();
							$this.siblings('.cleaner').remove();
							if ($this.hasClass('required')) {
								$this.removeClass('valid');
								$this.addClass('error');
								$this.after(message);
							}
							if (elemValue.length > 0) {
								$this.addClass('filled');
							} else {
								$this.removeClass('filled');
							}
						}
					});

					reservationInfo.on("change", ".date", function () {
						var $this = jQuery(this);
						let elemValue = $this.val();
						var valid = typeof elemValue !== 'undefined' && elemValue !== '';
						let elemName = $this.attr('name');
						let currentDateInput = elemValue.split(".");
						currentDateInput = new Date(parseInt(currentDateInput[2], 10),
							parseInt(currentDateInput[1], 10) - 1,
							parseInt(currentDateInput[0], 10));
						let now = new Date();
						now.setHours(0, 0, 0, 0);

						if (elemName === 'dateTo' || elemName === 'dateFrom') {
							let message = '<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' ' + $this.parent().find("label").html() + ' ' + js_lang_new_form_nesessery + '</div>';

							if (isNaN(currentDateInput.getDate()) || elemValue !== '' && /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](20|21)\d\d/.test(elemValue) === false) {
								valid = false;
								message = '<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_incorrect_format_date_error + '</div>';
							}

							if (elemValue !== '' && currentDateInput < now) {
								valid = false;
								message = '<div class="cleaner"></div><div class="error_box">' + cms_js_lang_reservation_mode_current_date_error + '</div>';
							}

							if (valid) {
								if ($this.hasClass('required')) {
									$this.addClass('valid');
									$this.removeClass('error');
									$this.siblings('.error_box').remove();
									$this.siblings('.cleaner').remove();
								}
								$this.addClass('filled');

							} else {
								$this.siblings('.error_box').remove();
								$this.siblings('.cleaner').remove();

								$this.removeClass('valid');
								$this.addClass('error');
								$this.after(message);
								if (elemValue !== '') {
									$this.addClass('filled');
								} else {
									$this.removeClass('filled');
								}
							}
						}

						if (elemName === 'dateFrom') {
							let reservationInfo = jQuery('.submit_product_mode_reservation').parents().find('.reservation_mode_customer_info');
							let dateTo2 = reservationInfo.find('input[name="dateTo"]');

							dateTo2.datepicker('option', 'minDate', new Date(currentDateInput));
						}
					});

					let options = {minDate: new Date()};
					reservationInfo = jQuery('.submit_product_mode_reservation').parents().find('.reservation_mode_customer_info');
					reservationInfo.find('input[name="dateFrom"]').datepicker(options);
					reservationInfo.find('input[name="dateTo"]').datepicker(options);
					jQuery('#ui-datepicker-div').addClass('material_design');
				})
				.open();
		}).send();
}

function triggerClickOn(selector)
{
	jQuery(selector).trigger('click');
	return false;
}

/**
 * Funkcia vymeni svoj obsah s cielovym elementom
 * @param {object} elem DocumentElement
 * @param {string} target Cielovy element
 * @param {string} func Spusti funkciu na konci ak je to vyzadovane
 */
function ghostContent(elem, target,  func){
	let src = jQuery(elem);
	let trg = jQuery(target).not('.ghost_content');

	if (trg.length) {
		let from = src.closest('.ghost_content');
		let class_to = jQuery(trg).removeClass('ghost_content').attr('class');
		let ghost_to = jQuery(trg).clone();

		from.attr('class', class_to + ' ghost_content');
        let ghost_from = from.clone();
        jQuery(trg).replaceWith(ghost_from);
        from.replaceWith(ghost_to);

		// Doplnkove inicializacie
		if (typeof func !== 'undefined' && typeof window[func] === 'function') {
			window[func](src);
		}
	}
}

function ghostSearchContent(src){
	js_mod_vm_search_ajax_search_ini();
	let selector = jQuery('#shop_search_field');
	if (selector.length) {
		let caret = selector.val().length;
		selector.focus();
		selector[0].setSelectionRange(caret,caret);
	}
}

function getProductDetailSelectedVariant(selector = 'body')
{
	const mainSelector = jQuery(selector);
	let selectedVariantElem = undefined;

	// stare varianty - select
	selectedVariantElem = mainSelector.find('.prod_adv_attrib_select select.main_attr_select');

	if (!selectedVariantElem.length) {
		// stare varianty - radio
		selectedVariantElem = mainSelector.find('.prod_adv_attrib_radio input[type="radio"]:checked');
	}
	if (!selectedVariantElem.length) {
		// stare varianty - adv. select
		selectedVariantElem = mainSelector.find('.prod_adv_attrib_select');
	}
	if (typeof window.js_product_id !== 'undefined' && Number(window.js_product_id) && typeof window['ProductVariantInstance_' + window.js_product_id] !== 'undefined') {
		// nove varianty
		let selectedAttr = window['ProductVariantInstance_' + window.js_product_id].getSelectedAttribute();
		return {
			select: undefined,
			value: selectedAttr?.source,
			parsedValue: vmExplodeProductVariant(selectedAttr?.source),
			variantInstance: selectedAttr
		}
	}

	if (selectedVariantElem.length) {
		return {
			select: selectedVariantElem.attr('name'),
			value: selectedVariantElem.val(),
			parsedValue: vmExplodeProductVariant(selectedVariantElem.val()),
		};
	}

	return undefined;
}

function switchLangWyisiwyg(element) {
	var elm = jQuery(element);

	if (elm.hasClass('cs_flag_active')) {
		return;
	}

	var parentElm = elm.closest('.wysiwyg_editor');
	var lang = elm.attr('data-lang');

	parentElm.find('.cs_flag_active').removeClass('cs_flag_active');
	parentElm.find('.active').removeClass('active').hide();

	elm.addClass('cs_flag_active');
	parentElm.find('.wysiwyg_container[data-lang="'+lang+'"]').addClass('active').show();
}

function initWysiwygEditor(element) {
	element = jQuery(element);
	let textArea = element.is('textarea') ? element : element.find('textarea');

	textArea
		.ckeditor( function() {
			element
				.find('.wysiwyg_container:not(.active)')
				.hide();
		}, cs_ckeditor_default_cfg);
}

/**
 * If someone or something (third-party script, etc.) tries to overwrite jQuery, it won't let it
 */
if ( typeof js_Config_stop_jquery_overwrites !== 'undefined' && js_Config_stop_jquery_overwrites ) {
	(function() {
		var jQueryClone = window.jQuery;

		Object.defineProperty(window, 'jQuery', {
			configurable: true,
			set: function(value) {},
			get: function() {
				return jQueryClone;
			}
		});
	})();
}


/* ========================================
 FILE: /includes/js/vex/vex.2.2.1.min.js
 ==================== */

/*! vex.js, vex.dialog.js 2.3.3 */
(function(){var a;a=function(a){var b,c;return b=!1,a(function(){var d;return d=(document.body||document.documentElement).style,b=void 0!==d.animation||void 0!==d.WebkitAnimation||void 0!==d.MozAnimation||void 0!==d.MsAnimation||void 0!==d.OAnimation,a(window).bind("keyup.vex",function(a){return 27===a.keyCode?c.closeByEscape():void 0})}),c={globalID:1,animationEndEvent:"animationend webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend",baseClassNames:{vex:"vex",content:"vex-content",overlay:"vex-overlay",close:"vex-close",closing:"vex-closing",open:"vex-open"},defaultOptions:{content:"",showCloseButton:!0,escapeButtonCloses:!0,overlayClosesOnClick:!0,appendLocation:"body",className:"vex-cs",css:{},overlayClassName:"",overlayCSS:{},contentClassName:"",contentCSS:{},closeClassName:"",closeCSS:{}},open:function(b){return b=a.extend({},c.defaultOptions,b),b.id=c.globalID,c.globalID+=1,b.$vex=a("<div>").addClass(c.baseClassNames.vex).addClass(b.className).css(b.css).data({vex:b}),b.$vexOverlay=a("<div>").addClass(c.baseClassNames.overlay).addClass(b.overlayClassName).css(b.overlayCSS).data({vex:b}),b.overlayClosesOnClick&&b.$vexOverlay.bind("click.vex",function(b){return b.target===this?c.close(a(this).data().vex.id):void 0}),b.$vex.append(b.$vexOverlay),b.$vexContent=a("<div>").addClass(c.baseClassNames.content).addClass(b.contentClassName).css(b.contentCSS).append(b.content).data({vex:b}),b.$vex.append(b.$vexContent),b.showCloseButton&&(b.$closeButton=a("<div>").addClass(c.baseClassNames.close).addClass(b.closeClassName).css(b.closeCSS).data({vex:b}).bind("click.vex",function(){return c.close(a(this).data().vex.id)}),b.$vexContent.append(b.$closeButton)),a(b.appendLocation).append(b.$vex),c.setupBodyClassName(b.$vex),b.afterOpen&&b.afterOpen(b.$vexContent,b),setTimeout(function(){return b.$vexContent.trigger("vexOpen",b)},0),b.$vexContent},getSelectorFromBaseClass:function(a){return"."+a.split(" ").join(".")},getAllVexes:function(){return a("."+c.baseClassNames.vex+':not(".'+c.baseClassNames.closing+'") '+c.getSelectorFromBaseClass(c.baseClassNames.content))},getVexByID:function(b){return c.getAllVexes().filter(function(){return a(this).data().vex.id===b})},close:function(a){var b;if(!a){if(b=c.getAllVexes().last(),!b.length)return!1;a=b.data().vex.id}return c.closeByID(a)},closeAll:function(){var b;return b=c.getAllVexes().map(function(){return a(this).data().vex.id}).toArray(),(null!=b?b.length:void 0)?(a.each(b.reverse(),function(a,b){return c.closeByID(b)}),!0):!1},closeByID:function(d){var e,f,g,h,i,j;return f=c.getVexByID(d),f.length?(e=f.data().vex.$vex,j=a.extend({},f.data().vex),g=function(){return j.beforeClose?j.beforeClose(f,j):void 0},h=function(){return f.trigger("vexClose",j),e.remove(),a("body").trigger("vexAfterClose",j),j.afterClose?j.afterClose(f,j):void 0},i="none"!==f.css("animationName")&&"0s"!==f.css("animationDuration"),b&&i?g()!==!1&&e.unbind(c.animationEndEvent).bind(c.animationEndEvent,function(){return h()}).addClass(c.baseClassNames.closing):g()!==!1&&h(),!0):void 0},closeByEscape:function(){var b,d,e;return e=c.getAllVexes().map(function(){return a(this).data().vex.id}).toArray(),(null!=e?e.length:void 0)?(d=Math.max.apply(Math,e),b=c.getVexByID(d),b.data().vex.escapeButtonCloses!==!0?!1:c.closeByID(d)):!1},setupBodyClassName:function(b){return a("body").bind("vexOpen.vex",function(){return a("body").addClass(c.baseClassNames.open)}).bind("vexAfterClose.vex",function(){return c.getAllVexes().length?void 0:a("body").removeClass(c.baseClassNames.open)})},hideLoading:function(){return a(".vex-loading-spinner").remove()},showLoading:function(){return c.hideLoading(),a("body").append('<div class="vex-loading-spinner '+c.defaultOptions.className+'"></div>')}}},"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a(require("jquery")):window.vex=a(jQuery)}).call(this),function(){var a;a=function(a,b){var c,d;return null==b?a.error("Vex is required to use vex.dialog"):(c=function(b){var c;return c={},a.each(b.serializeArray(),function(){return c[this.name]?(c[this.name].push||(c[this.name]=[c[this.name]]),c[this.name].push(this.value||"")):c[this.name]=this.value||""}),c},d={},d.buttons={YES:{text:"OK",type:"submit",className:"vex-dialog-button-primary"},NO:{text:"Cancel",type:"button",className:"vex-dialog-button-secondary",click:function(a,c){return a.data().vex.value=!1,b.close(a.data().vex.id)}}},d.defaultOptions={callback:function(a){},afterOpen:function(){},message:"Message",input:'<input name="vex" type="hidden" value="_vex-empty-value" />',value:!1,buttons:[d.buttons.YES,d.buttons.NO],showCloseButton:!1,onSubmit:function(e){var f,g;return f=a(this),g=f.parent(),e.preventDefault(),e.stopPropagation(),g.data().vex.value=d.getFormValueOnSubmit(c(f)),b.close(g.data().vex.id)},focusFirstInput:!0},d.defaultAlertOptions={message:"Alert",buttons:[d.buttons.YES]},d.defaultConfirmOptions={message:"Confirm"},d.open=function(c){var e,f;return c=a.extend({},b.defaultOptions,d.defaultOptions,c),c.content=d.buildDialogForm(c),f=c.beforeClose,c.beforeClose=function(a,b){return c.callback(b.value),"function"==typeof f?f(a,b):void 0},e=b.open(c),c.focusFirstInput&&e.find('button[type="submit"], button[type="button"], input[type="submit"], input[type="button"], textarea, input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="email"], input[type="month"], input[type="number"], input[type="password"], input[type="search"], input[type="tel"], input[type="text"], input[type="time"], input[type="url"], input[type="week"]').first().focus(),e},d.alert=function(b){return"string"==typeof b&&(b={message:b}),b=a.extend({},d.defaultAlertOptions,b),d.open(b)},d.confirm=function(b){return"string"==typeof b?a.error("dialog.confirm(options) requires options.callback."):(b=a.extend({},d.defaultConfirmOptions,b),d.open(b))},d.prompt=function(b){var c;return"string"==typeof b?a.error("dialog.prompt(options) requires options.callback."):(c={message:'<label for="vex">'+(b.label||"Prompt:")+"</label>",input:'<input name="vex" type="text" class="vex-dialog-prompt-input" placeholder="'+(b.placeholder||"")+'"  value="'+(b.value||"")+'" />'},b=a.extend({},c,b),d.open(b))},d.buildDialogForm=function(b){var c,e,f;return c=a('<form class="vex-dialog-form" />'),f=a('<div class="vex-dialog-message" />'),e=a('<div class="vex-dialog-input" />'),c.append(f.append(b.message)).append(e.append(b.input)).append(d.buttonsToDOM(b.buttons)).bind("submit.vex",b.onSubmit),c},d.getFormValueOnSubmit=function(a){return a.vex||""===a.vex?"_vex-empty-value"===a.vex?!0:a.vex:a},d.buttonsToDOM=function(c){var d;return d=a('<div class="vex-dialog-buttons" />'),a.each(c,function(e,f){var g;return g=a('<button type="'+f.type+'"></button>').text(f.text).addClass(f.className+" vex-dialog-button "+(0===e?"vex-first ":"")+(e===c.length-1?"vex-last ":"")).bind("click.vex",function(c){return f.click?f.click(a(this).parents(b.getSelectorFromBaseClass(b.baseClassNames.content)),c):void 0}),g.appendTo(d)}),d},d)},"function"==typeof define&&define.amd?define(["jquery","vex"],a):"object"==typeof exports?module.exports=a(require("jquery"),require("./vex.js")):window.vex.dialog=a(window.jQuery,window.vex)}.call(this);

//Funkcia capitalize
String.prototype.capitalize = function() {
	return this.charAt(0).toUpperCase() + this.slice(1);
}

jQuery(function() {
	var body = jQuery('body');
		
	vex.defaultOptions.beforeClose = function() {
		body.addClass('vex_closing');
	};
	
	vex.defaultOptions.afterClose = function() {
		body.removeClass('vex_closing');
	};


	/** GLOBALNE NASTAVENIA **/
	
	//Nastavenie confirm dialogov 
	vex.dialog.defaultConfirmOptions = {
		className: 'vex-cs confirm',
		overlayClosesOnClick: false,
		showCloseButton: true,
		buttons:{
			NO:{
				text:cms_js_lang_no.capitalize(),  //Cancel -> Nie
				className:"vex-dialog-button-secondary",
				type:"button",
				click: function() {
						return vex.close();
				}
			},
			YES:{
				text:cms_js_lang_yes.capitalize(), //OK -> Ano
				className:"vex-dialog-button-primary",
				type:"submit"
			}
		}
	};
		
	//Nastavenie alert dialogov 
	vex.dialog.defaultAlertOptions = {
		className: 'vex-cs confirm alert',
		overlayClosesOnClick: false,
		showCloseButton: true,
		buttons:{
			YES:{
				text:'OK',
				className:"vex-dialog-button-primary",
				type:"submit"
			}
		}
	};
//if ( is_cs_user() ) {
//	// Dusan kontrola vexu a jeho elementov, ak sa tam nenachadza input, checkbox, select, link a button iny ako primary a secondary
//	// v pripade chyb povedzte
//	jQuery(window).keypress(function (e) {
//		if (e.key === ' ' || e.key === 'Spacebar') {
//			var inputs     = '';
//			var links      = '';
//			var checkboxes = '';
//			jQuery('.vex-content').each(function () {
//				inputs     = jQuery(this).find(':input').not('.vex-dialog-button-primary').not('.vex-dialog-button-secondary');
//				checkboxes = jQuery(this).find('[type=checkbox]');
//				links      = jQuery(this).find('a');
//				//console.log(inputs);
//				//console.log(links);
//				//console.log(checkboxes);
//				//<-- Should return all input elements in that specific form.
//				if (inputs.length || checkboxes.length || links.length > 0) {
//					console.log('Stlacil si space, ale nakolko sa nachadza vo vexe input, select, checkbox, link tak sa to nepotvrdilo');
//				}
//				else {
//					// ak sa nenachadza vo vexe ziadny input, checkbox, select, link a button iny ako primary, secondary
//					// bude spacebar funkcny na odkliknutie
//					// ' ' is standard, 'Spacebar' was used by IE9 and Firefox < 37
//					jQuery( ".vex-dialog-button-primary" ).click();
//					console.log('Stlacil si space, potvrdili sme vex');
//				}
//			});
//		}
//	});
//}
	// po stlaceni space sa potvrdi vex okno
	//jQuery(window).keypress(function (e) {
	//	if (e.key === ' ' || e.key === 'Spacebar') {
	//		// ' ' is standard, 'Spacebar' was used by IE9 and Firefox < 37
	//		jQuery( ".vex-dialog-button-primary" ).click();
	//
	//	}
	//});
});

/** Vlastne funkcie **/

function close_vex_spacebar() {
	//funkcia pre vypnutie vexu pomocou medzernika
	jQuery(window).on('keypress', function (e) {
			if (e.key === ' ' || e.key === 'Spacebar') {
				// ' ' is standard, 'Spacebar' was used by IE9 and Firefox < 37
				jQuery( ".vex-dialog-button-primary" ).click();

			}
		});
}
function submit_vex_enter() {
	//funkcia pre potvrdenie vexu s enterom
	jQuery(window).on('keypress', function (e) {
		if (e.which == 13) {
			jQuery( ".vex-dialog-button-primary" ).click();
		}
	});
}
function stop_submit_vex_enter(jqo) {
	//funkcia pre nepotvrdenie vexu s enterom
	jQuery(window).on('keypress', function (e) {
		if (e.which == 13) {
			e.preventDefault();
			//jQuery( ".vex-dialog-button-primary" ).click();
		}
	});
}
function js_confirm(elem, message){
	close_vex_spacebar();
	var url = jQuery(elem).prop('href');
	vex.dialog.confirm({
		message:message,
		callback: function(value){
			if (value) {
				window.location = url;
			};
		}
	});
	return false;
	
}


 /**********************
 * PRIKLADY POUZITIA:  *
 ***********************

//Alert:
vex.dialog.alert({ 
	message:'Are you absolutely sure you want to destroy the alien planet?'
});

//Confirm:
vex.dialog.confirm({ 
	message:'Are you absolutely sure you want to destroy the alien planet?',
	callback: function(value){
		return (value ? true : false);
	}
});

//Confirm na onclick:
<a href="/index.php?option=logout" title="Kliknutím sa odhlásite z administrácie" onclick="javascript:return js_confirm(this,'Prajete si odhlásiť sa z administrácie?');">Odhlásiť</a>
	

//Vseobecne:
vex.open({ content: 'Hello World!!!' });

vex.open({
	showCloseButton: true, 
	className: 'vex-cs vex-cs-login', 
	content: '<form class="vex-dialog-form vex-login-form" onsubmit="event.preventDefault()">' + 
				'<div class="vex-dialog-message">' + 
					'<b><?php echo _CMS_ADMINLANG_LOGIN_DIALOG_MESSAGE_ADMINISTRATOR ?></b>' +
				'</div>' +
				
				'<div class="vex-dialog-input" style="padding: 21px;">' +
					'<div class="vex-login-username-group">' +
						'<label><?php echo _CMS_ADMINLANG_LOGIN_DIALOG_USERNAME_LABEL ?></label>' + 
						'<input type="text" class="vex-login-username" placeholder="<?php echo _CMS_ADMINLANG_LOGIN_DIALOG_USERNAME_PLACEHOLDER ?>" name="username">' + 
					'</div>' +
					'<div class="vex-login-password-group">' +
						'<label><?php echo _CMS_ADMINLANG_LOGIN_DIALOG_PASSWORD_LABEL ?></label>' + 
						'<input type="password" class="vex-login-password" placeholder="<?php echo _CMS_ADMINLANG_LOGIN_DIALOG_PASSWORD_PLACEHOLDER ?>" name="password">' +
					'</div>' +	
				'</div>' +
				
				'<div class="vex-dialog-buttons">' + 
					'<div class="vex-dialog-err"></div>' + 
					'<button class="vex-login-submit vex-dialog-button-primary vex-dialog-button vex-first vex-last" type="submit"><?php echo _CMS_ADMINLANG_LOGIN_DIALOG_SUBMITBTN_TEXT ?></button>' +
				'</div>' +
			 '</form>'
});

***********************************************************************/

/* ========================================
 FILE: /includes/product_offer/product_offer.js
 ==================== */

/**
 * Creativesites s.r.o
 * Produkt offers
 * http://wiki.creativesites.sk/doku.php?id=product_offer
 * v.2.4
 *
 *
 *  -------------------------------------------------------------------------------------------------
 * |                                                                                                 |
 * |                                  !!!! POZOR !!!!                                                |
 * | Upravuje sa stale subor product_offer_dev.js a obsah sa skopiruje nasledne do product_offer.js  |
 * |                                                     											 |
 * |							  nasledne sync frontend.js											 |
 *  -------------------------------------------------------------------------------------------------
 *
 */
var prof={version:"2.4",debug:!1,set_plugin:0,box:{},wrap:{},body:{},currency:{},browse:0,detail:0,offers:{},verified:[],prepared:0,uninterested:0,variantpicked:1,forcedcount:0,selection:{},availability:{},product_id:0,nocheck:0,product_variant:"",options:{detailopen:"hover",categoryopen:"hover",morebutton:1,buyontop:0,checknoclose:0,mandatoryoffer:0,fadespeed:250,availability:0,scrollToElem:"",scrollToOffset:15},init:function(o){var e;prof.debug=is_cs_user("profdev"),prof.debug&&(console.log("Product offers [v."+prof.version+"]"),csstack("init")),prof.body=jQuery("body"),prof.browse=prof.body.hasClass("shop_page_class_shop_browse")?1:0,prof.detail=prof.body.hasClass("shop_page_class_shop_product_details")?1:0,prof.set_plugin=0<prof.body.find(".prod_add_to_cart.set_add").length,void 0!==o&&(prof.options=jQuery.extend(prof.options,o)),prof.detail&&(prof.box=jQuery(".pof_dt_box"),prof.wrap=jQuery(".pof_dt_overbox"),prof.morebtn=jQuery(".show_more_btn"),prof.product_id=parseInt(jQuery('input[name="product_id"]').val()),prof.set_plugin&&prof.box.addClass("pof_set"),prof.body.on("change",".main_attr_select",function(){var o=jQuery(this);prof.product_variant=o.val(),o.removeClass("pof_var_warn")}),void 0!==prof.box&&0<prof.box.length&&(e=prof.box.find(".pof_dt_offer_wrap").length,prof.wrap.addClass("has_offers"),prof.options.morebutton&&0<e-prof.options.morebutton&&(prof.morebtn.show(),prof.morebtn.on("click",function(){prof.box.hasClass("open")?prof.box.removeClass("open"):prof.box.addClass("open")})),prof.options.buyontop&&prof.box.find(".pof_dt_form").insertAfter(".pof_dt_offer_title"),prof.body.on("change",'select[name="pof_variant"]',function(){prof.refreshPrices(this),0==prof.noCheck&&prof.autoCheck(this),1==prof.options.availability&&prof.setAvailability(this),jQuery(this).trigger("blur")}),prof.body.on("focus",'select[name="pof_variant"]',function(){prof.box.addClass("select-opened")}),prof.body.on("blur",'select[name="pof_variant"]',function(){prof.box.removeClass("select-opened")}),prof.body.on("mouseleave",'select[name="pof_variant"]',function(){}),prof.body.on("click",'.select-opened select[name="pof_variant"] option',function(){jQuery(this).trigger("blur")}),prof.body.on("change",'input[name="pof_buy_this"]',function(){var o=jQuery(this),e=o.closest("li");"radio"==o.attr("type")&&o.closest("ul").find("li").removeClass("pof_picked"),o.is(":checked")?e.addClass("pof_picked"):e.removeClass("pof_picked").find(".main_attr_select").val(e.find(".main_attr_select option:first").val()),"click"!=prof.options.detailopen||prof.box.hasClass("open")||prof.morebtn.trigger("click")}),"hover"==prof.options.detailopen?(prof.body.on("mouseenter",".pof_dt_box",function(){prof.box.addClass("open").addClass("mouse-in")}),prof.body.on("mouseleave",".pof_dt_box",function(){prof.box.removeClass("mouse-in"),0<jQuery(".vex").length&&prof.box.hasClass("forcedopen")||prof.options.checknoclose&&prof.box.find('input[name="pof_buy_this"]:checked').length||prof.box.hasClass("select-opened")||prof.box.removeClass("open").removeClass("forcedopen")})):prof.options.detailopen,prof.body.on("click",'.pof_dt_box a[rel="vex"]',function(){prof.box.addClass("forcedopen")}),prof.box.find('[name="pof_variant"]').each(function(){prof.refreshPrices(this)}),prof.wrap.fadeIn(prof.options.fadespeed).addClass("initialized"),"function"==typeof prof.options.onDetailInit&&prof.options.onDetailInit())),prof.browse&&(prof.getOffers(),e="click"===prof.options.categoryopen?"click":"mouseover",prof.body.on(e,".product_offer_fly",function(){prof.show(this)}),"click"===prof.options.categoryopen&&prof.body.on("click",function(o){void 0!==o.target&&jQuery(o.target).closest("div").hasClass("product_offer_fly")||jQuery(".poshy-up").poshytip("hide").removeClass("poshy-up")}))},autoCheck:function(o){prof.debug&&csstack("autoCheck");var e=jQuery(o),o=e.closest("li");(""!==e.val()?o.find('input[name="pof_buy_this"]').attr("checked","checked").prop("checked",!0):o.find('input[name="pof_buy_this"]').removeAttr("checked").prop("checked",!1)).trigger("change")},setAvailability:function(o){var e,r,t,a;prof.debug&&csstack("setAvailability"),"function"==typeof setProductAvailabilityTime&&(a=prof.getHighestAvail(),"undefined"==typeof need_days_variable&&(window.need_days_variable=0),need_days_variable=a,setProductAvailabilityTime(),e=0,r="",t=jQuery(o).closest(".pof_dt_offer_wrap"),a=parseInt(t.find('input[name="pof_buy_this"]').val()),(o=t.find('[name="pof_variant"]')).length&&(o=o.val(),void 0!==prof.availability[a].variant[o]&&(e=parseInt(prof.availability[a].variant[o].id),r=prof.availability[a].variant[o].name)),0==e&&void 0!==prof.availability[a].product&&(e=parseInt(prof.availability[a].product.id),r=prof.availability[a].product.name),""!==r&&void 0!==r&&(prof.debug&&console.log("    Seting availability text: ",r),t.find(".shop_product_availability_value").attr("class","").addClass("shop_product_availability_value").addClass("attr_avail_"+e).html(r)))},getHighestAvail:function(){prof.debug&&csstack("getHighestAvail");var t=0;return prof.box.find("li").each(function(){var o=jQuery(this),e=parseInt(o.find('input[name="pof_buy_this"]').val()),r=o.find('[name="pof_variant"]');if(void 0===prof.availability[e])return!1;o=0;r.length&&(r=r.val(),void 0!==prof.availability[e].variant[r]&&(o=parseInt(prof.availability[e].variant[r].day))),0==o&&(o=parseInt(prof.availability[e].product.day)),t<o&&(prof.debug&&console.log("    Setting availability day: ",o),t=o)}),t},resetVariantSelect:function(){prof.debug&&csstack("resetVariantSelect"),prof.nocheck=1,prof.box.find('select[name="pof_variant"]').each(function(){var o=jQuery(this);o.val(o.find("option:first").val()).trigger("change")}),prof.nocheck=0},show:function(o){prof.debug&&csstack("show");var e=jQuery(o),r=parseInt(e.find("input").val()),t="",a="",i="",p=e.hasClass("poshy-up");if("click"===prof.options.categoryopen&&(jQuery(".poshy-up").each(function(){jQuery(this).poshytip("hide").removeClass("poshy-up")}),p))return!1;if(void 0!==prof.offers[r]){var o='<div class="pof_pt_box">',s=[];jQuery.each(prof.offers[r],function(o,e){s.push(e)});for(var f=s.sort(function(o,e){return void 0===o.offer_ordering||void 0===e.offer_ordering?0:parseInt(o.offer_ordering)-parseInt(e.offer_ordering)}),n=0;n<f.length;n++)a=f[n].product_credit,i=f[n].product_name,t+='<div class="pof_pt_offer_wrap">',t+='<a class="pof_pt_offer_thumb" href="'+f[n].offer_url+'"><img src="'+f[n].offer_thumb+'" alt="'+f[n].offer_name+'" /></a>',t+='<div class="pof_pt_offer_name"><a href="'+f[n].offer_url+'">'+f[n].offer_name+"</a></div>",t+='<div class="pof_pt_offer_save">'+f[n].offer_discount_text+"</div>",t+='<div class="pof_pt_offer_old">'+f[n].offer_standard_price_text+" "+f[n].offer_save_price_text+"</div>",t+='<div class="pof_pt_offer_pay">'+f[n].offer_new_price_text+"</div>",t+="</div>";o+=i,o+=t,o+=a,o+="</div>",null==e.data("poshytip")?(e.poshytip({className:"tip-yellow",content:o,alignTo:"target",alignX:"center",showOn:"click"===prof.options.categoryopen?"none":"hover",offsetX:0,offsetY:-1,fade:!0,slide:!0,showTimeout:100,hideTimeout:is_cs_user("offer_block")?400000009:100}),e.poshytip("show").addClass("poshy-up")):"click"===prof.options.categoryopen?p?e.poshytip("hide").removeClass("poshy-up"):e.poshytip("show").addClass("poshy-up"):e.poshytip("show")}},getOffers:function(){prof.debug&&csstack("getOffers");var o={action:"getOffers"};o.selection=prof.getProducts(),0!=o.selection.length&&jQuery.post(js_global_live_site+"/includes/product_offer/product_offer_ajax.php",o,function(r){r=csJsonParse(r)||{};prof.debug&&console.log(r),void 0!==r.offers&&(prof.offers=jQuery.extend(!0,prof.offers,r.offers),jQuery.each(o.selection,function(o,e){void 0===r.offers[e]?jQuery(".product_id_"+e).find(".product_offer_fly").remove():jQuery(".product_id_"+e).find(".product_offer_fly").show()}))})},getProducts:function(){prof.debug&&csstack("getProducts");var r=[];return prof.body.find(".product_offer_fly").each(function(){var o=jQuery(this),e=parseInt(o.find('input[name="product_offer_id"]').val());void 0===prof.offers[e]&&prof.verified.indexOf(e)<0&&(o.hide(),r.push(e),prof.verified.push(e))}),r},highlight:function(){prof.debug&&csstack("highlight"),o=""!==prof.options.scrollToElem?jQuery(""+prof.options.scrollToElem):prof.box;var o=parseInt(o.offset().top,10)-prof.options.scrollToOffset;o<0&&(o=0),jQuery("body,html").animate({scrollTop:o},1e3),prof.box.addClass("open"),prof.box.effect("highlight",{},800)},refreshPrices:function(o){prof.debug&&csstack("refreshPrices");var e=parseInt(prof.currency.currency_display.nbDecimal),r=jQuery(o),t=r.closest(".pof_dt_offer_wrap"),a=parseFloat(t.find('input[name="raw_discount"]').val()),i=parseInt(t.find('input[name="raw_discount_type"]').val());"-0-"!=r.val()&&r.removeClass("error"),r.trigger("blur");o=r.find("option:selected");""==o.val()&&(o=r.find("option[data-price]:first"));r=parseFloat(o.attr("data-price")),o=0,o=0==i?prof._round(parseFloat(a/100*r),e):1==i?r-a:a;t.find(".akcia-cena").html(js_format_Money(r,e,prof.currency.currency_display.symbol,prof.currency.currency_display.decimal)),t.find(".pof_dt_offer_save .pof_sv span").html(js_format_Money(o,e,prof.currency.currency_display.symbol,prof.currency.currency_display.decimal)),e=0<r-o?js_format_Money(r-o,e,prof.currency.currency_display.symbol,prof.currency.currency_display.decimal):"undefined"!=typeof js_lang_prof_free?js_lang_prof_free:"Free",t.find(".pof_dt_offer_pay").html(e)},showWarning:function(e){prof.debug&&csstack("showWarning");var r="",o=e.closest(".products_wrap"),t="",a=new RegExp("pof_par_"),i=e.closest(".product_cont").attr("class").split(" ");if(jQuery.each(i,function(o,e){-1!=e.search(a)&&(t=parseInt(e.replace("pof_par_","")))}),o.find(".pof_ref_"+t).each(function(){var o=jQuery(this);r+='<div class="pof_to_del">',r+='<div class="pof_del_img">'+o.find(".cajx_image").html()+"</div>",r+='<div class="pof_del_name">'+o.find(".cajx_name").html()+"</div>",r+='<div class="pof_del_attr">'+o.find(".cajx_attr").html()+"</div>",r+='<div class="pof_del_price">'+o.find(".cajx_price").html()+"</div>",r+="</div>"}),""==r)return!0;o="";return o+='<div class="pof_del_wrap">',o+='<div class="pof_del_q">'+("undefined"!=typeof js_lang_prof_del_warn?js_lang_prof_del_warn:"Along with this product, the following special offers will removed.")+"</div>",o+='<div class="pof_to_del_prods">'+r+"</div>",o+='<div class="pof_del_c">'+("undefined"!=typeof js_lang_prof_del_conf?js_lang_prof_del_conf:"Do you want to continue?")+"</div>",vex.dialog.confirm({message:o,callback:function(o){o&&e.addClass("pof_del_confirmed").trigger("click")}}),!1},prepare:function(){if(prof.debug&&csstack("prepare"),prof.getChecked(),!prof.uninterested&&jQuery.isEmptyObject(prof.selection))return vex.dialog.alert({message:js_lang_prof_select_offer}),prof.prepared=0,!1;if("undefined"!=typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED&&1==js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED&&!prof.uninterested&&!prof.variantpicked)return vex.dialog.alert({message:js_lang_prof_select_variant}),!1;if(prof.uninterested){prof.prepared=1;var o=prof.body.find(".prod_add_to_cart");return o.hasClass("set_add")||o.trigger("click"),!0}if(prof.set_plugin)return prof.prepared=1,!0;var e=prof.getParentVariant(),o={action:"pof_check_cart"};o.selection=JSON.stringify(prof.selection),o.product_id=prof.product_id,o.product_variant=0==e||e<-1?"":e,jQuery.post(js_global_live_site+"/includes/product_offer/product_offer_ajax.php",o,function(o){if(1==(o=csJsonParse(o)||{}).status){prof.debug&&console.log("    Parent is in cart, can add offers..."),prof.prepared=1;var e={update_res:{},log_params:[]};e.update_res.success=1,e.log_params.push(o.product_id),e.log_params.push("+"),e.log_params.push(o.product_qty),e.log_params.push({select_value:o.product_variant}),prof.add(e)}else if(2==o.status){if(prof.debug&&console.log("    Parent is in cart, quantity missing, adding another parent to cart..."),0===prof.getParentVariant(!0))return!1;prof.prepared=1;var r=prof.body.find(".prod_add_to_cart");if(prof.set_plugin)return!0;r.trigger("click")}else{if(prof.debug&&console.log("    Parent not in cart, adding parent to cart..."),0===prof.getParentVariant(!0))return!1;prof.prepared=1;r=prof.body.find(".prod_add_to_cart");if(prof.set_plugin)return!0;r.trigger("click")}})},getParentVariant:function(o){var e,r=-1;return"undefined"==typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED||1!=js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED||0<(e=jQuery("select.main_attr_select")).length&&(r=""==e.val()?(o&&(e.addClass("pof_var_warn"),vex.dialog.alert({message:js_lang_prof_select_main_variant})),0):e.val()),r},add:function(e){if(prof.debug&&csstack("add"),void 0===e.update_res||void 0===e.update_res.success||1!=e.update_res.success)return prof.prepared=0,prof.uninterested=0,!1;if(!prof.prepared)return!1;if(prof.uninterested)return prof.prepared=0,prof.uninterested=0,!1;var o={action:"pof_cart_add"};o.selection=JSON.stringify(prof.selection),o.product_id=e.log_params[0],o.product_qty=e.log_params[2],void 0!==e.log_params[3]&&"string"==typeof e.log_params[3].select_value&&(o.product_variant=e.log_params[3].select_value),jQuery.post(js_global_live_site+"/includes/product_offer/product_offer_ajax.php",o,function(o){o=csJsonParse(o)||{};prof.set_plugin||(prof.uncheckAll(),prof.resetVariantSelect()),1==o.status?(prof.debug&&console.log("    Success..."),e.html_products=o.html_products,e.html_cart_values=o.html_cart_values,js_ajax_cart_container_init(e),js_add_to_cart_form_ajax_cart_bind(),"function"==typeof js_ajax_cart_update_after_init&&js_ajax_cart_update_after_init()):(prof.debug&&console.log("    Error..."),void 0!==o.html_products&&(e.html_products=o.html_products,e.html_cart_values=o.html_cart_values,js_ajax_cart_container_init(e),js_add_to_cart_form_ajax_cart_bind(),"function"==typeof js_ajax_cart_update_after_init&&js_ajax_cart_update_after_init()),void 0!==o.not_added&&jQuery.each(o.not_added,function(o,e){jQuery(".pof_pid_"+e).addClass("pof_highlight")}),prof.box.append(o.status),setTimeout(function(){jQuery(".shop_tip, .shop_warning").remove()},6e3)),prof.prepared=0,prof.uninterested=0})},uncheckAll:function(){prof.debug&&csstack("uncheckAll"),jQuery('input[name="pof_buy_this"]').prop("checked",!1)},getChecked:function(){prof.debug&&csstack("getChecked"),prof.selection={},prof.variantpicked=1,prof.box.find('input[name="pof_buy_this"]:checked').each(function(){var o,e=jQuery(this),r=parseInt(e.val(),10),t=0;if(0==r)return prof.uninterested=1,{};e.hasClass("pof_variants")&&(o=void 0!==(t=e.closest(".pof_dt_offer_wrap").find('select[name="pof_variant"] option:selected').val())&&"-0-"!=t&&""!=t,prof.variantpicked=prof.variantpicked&&o,o?e.closest(".pof_dt_offer_wrap").find('select[name="pof_variant"]').removeClass("error"):e.closest(".pof_dt_offer_wrap").find('select[name="pof_variant"]').addClass("error")),prof.selection[r]=t}),prof.box.find('input[name="pof_buy_forced"]').each(function(){var o=jQuery(this),o=parseInt(o.val(),10);prof.selection[o]=0,prof.forcedcount++}),jQuery.isEmptyObject(prof.selection)&&prof.box.hasClass("pof_type_1")&&(prof.uninterested=1)},sortCart:function(r){prof.debug&&csstack("sortCart"),void 0===r&&(r=jQuery(".cart_ajax_container"));var t={};r.find(".pof_child").each(function(){var o=jQuery(this),e=new RegExp("pof_ref_(\\d+)","g").exec(o.attr("class"));null!==e&&void 0!==e[1]&&(void 0===t[e[1]]?t[e[1]]=1:t[e[1]]++,o.addClass("pof_sort_"+t[e[1]]),r.find(".pof_par_"+e[1]).after(o))}),jQuery.each(t,function(o,e){r.find(".pof_ref_"+o+".pof_sort_1").addClass("pof_child_last")})},_round:function(o,e){void 0===e&&(e=0);e=Math.pow(10,e),o*=e;return Math.round(o)/e}};

/* ========================================
 FILE: /includes/js/jquery/mCustomScrollbar-3.1.7/jquery.mCustomScrollbar.concat.min.js
 ==================== */

/* == jquery mousewheel plugin == Version: 3.1.13, License: MIT License (MIT) */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});
/* == malihu jquery custom scrollbar plugin == Version: 3.1.7, License: MIT License (MIT) */
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"undefined"!=typeof module&&module.exports?module.exports=e:e(jQuery,window,document)}(function(e){var t,o,a,n,i,r,l,s,c,d,u,f,m,h,p,g,v,x,S,_,w,C,b,y,B,T,k,M,O,I,D,E,W,R,A,L,z,P,H,U,F,q,j,Y,X,N,V,Q,G,J,K,Z,$,ee,te,oe,ae,ne;oe="function"==typeof define&&define.amd,ae="undefined"!=typeof module&&module.exports,ne="https:"==document.location.protocol?"https:":"http:",oe||(ae?require("jquery-mousewheel")(e):e.event.special.mousewheel||e("head").append(decodeURI("%3Cscript src="+ne+"//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js%3E%3C/script%3E"))),o="mCustomScrollbar",a={setTop:0,setLeft:0,axis:"y",scrollbarPosition:"inside",scrollInertia:950,autoDraggerLength:!0,alwaysShowScrollbar:0,snapOffset:0,mouseWheel:{enable:!0,scrollAmount:"auto",axis:"y",deltaFactor:"auto",disableOver:["select","option","keygen","datalist","textarea"]},scrollButtons:{scrollType:"stepless",scrollAmount:"auto"},keyboard:{enable:!0,scrollType:"stepless",scrollAmount:"auto"},contentTouchScroll:25,documentTouchScroll:!0,advanced:{autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",updateOnContentResize:!0,updateOnImageLoad:"auto",autoUpdateTimeout:60},theme:"light",callbacks:{onTotalScrollOffset:0,onTotalScrollBackOffset:0,alwaysTriggerOffsets:!0}},n=0,i={},r=window.attachEvent&&!window.addEventListener?1:0,l=!1,s=["mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar","mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer","mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight"],c={init:function(t){var t=e.extend(!0,{},a,t),o=d.call(this);if(t.live){var r=t.liveSelector||this.selector||".mCustomScrollbar",l=e(r);if("off"===t.live)return void f(r);i[r]=setTimeout(function(){l.mCustomScrollbar(t),"once"===t.live&&l.length&&f(r)},500)}else f(r);return t.setWidth=t.set_width?t.set_width:t.setWidth,t.setHeight=t.set_height?t.set_height:t.setHeight,t.axis=t.horizontalScroll?"x":m(t.axis),t.scrollInertia=t.scrollInertia>0&&t.scrollInertia<17?17:t.scrollInertia,"object"!=typeof t.mouseWheel&&1==t.mouseWheel&&(t.mouseWheel={enable:!0,scrollAmount:"auto",axis:"y",preventDefault:!1,deltaFactor:"auto",normalizeDelta:!1,invert:!1}),t.mouseWheel.scrollAmount=t.mouseWheelPixels?t.mouseWheelPixels:t.mouseWheel.scrollAmount,t.mouseWheel.normalizeDelta=t.advanced.normalizeMouseWheelDelta?t.advanced.normalizeMouseWheelDelta:t.mouseWheel.normalizeDelta,t.scrollButtons.scrollType=h(t.scrollButtons.scrollType),u(t),e(o).each(function(){var o=e(this);if(!o.data("mCS")){o.data("mCS",{idx:++n,opt:t,scrollRatio:{y:null,x:null},overflowed:null,contentReset:{y:null,x:null},bindEvents:!1,tweenRunning:!1,sequential:{},langDir:o.css("direction"),cbOffsets:null,trigger:null,poll:{size:{o:0,n:0},img:{o:0,n:0},change:{o:0,n:0}}});var a=o.data("mCS"),i=a.opt,r=o.data("mcs-axis"),l=o.data("mcs-scrollbar-position"),d=o.data("mcs-theme");r&&(i.axis=r),l&&(i.scrollbarPosition=l),d&&(i.theme=d,u(i)),p.call(this),a&&i.callbacks.onCreate&&"function"==typeof i.callbacks.onCreate&&i.callbacks.onCreate.call(this),e("#mCSB_"+a.idx+"_container img:not(."+s[2]+")").addClass(s[2]),c.update.call(null,o)}})},update:function(t,o){var a=t||d.call(this);return e(a).each(function(){var t=e(this);if(t.data("mCS")){var a=t.data("mCS"),n=a.opt,i=e("#mCSB_"+a.idx+"_container"),r=e("#mCSB_"+a.idx),l=[e("#mCSB_"+a.idx+"_dragger_vertical"),e("#mCSB_"+a.idx+"_dragger_horizontal")];if(!i.length)return;a.tweenRunning&&X(t),o&&a&&n.callbacks.onBeforeUpdate&&"function"==typeof n.callbacks.onBeforeUpdate&&n.callbacks.onBeforeUpdate.call(this),t.hasClass(s[3])&&t.removeClass(s[3]),t.hasClass(s[4])&&t.removeClass(s[4]),r.css("max-height","none"),r.height()!==t.height()&&r.css("max-height",t.height()),v.call(this),"y"===n.axis||n.advanced.autoExpandHorizontalScroll||i.css("width",g(i)),a.overflowed=C.call(this),T.call(this),n.autoDraggerLength&&S.call(this),_.call(this),y.call(this);var c=[Math.abs(i[0].offsetTop),Math.abs(i[0].offsetLeft)];"x"!==n.axis&&(a.overflowed[0]?l[0].height()>l[0].parent().height()?b.call(this):(N(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}),a.contentReset.y=null):(b.call(this),"y"===n.axis?B.call(this):"yx"===n.axis&&a.overflowed[1]&&N(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}))),"y"!==n.axis&&(a.overflowed[1]?l[1].width()>l[1].parent().width()?b.call(this):(N(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}),a.contentReset.x=null):(b.call(this),"x"===n.axis?B.call(this):"yx"===n.axis&&a.overflowed[0]&&N(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}))),o&&a&&(2===o&&n.callbacks.onImageLoad&&"function"==typeof n.callbacks.onImageLoad?n.callbacks.onImageLoad.call(this):3===o&&n.callbacks.onSelectorChange&&"function"==typeof n.callbacks.onSelectorChange?n.callbacks.onSelectorChange.call(this):n.callbacks.onUpdate&&"function"==typeof n.callbacks.onUpdate&&n.callbacks.onUpdate.call(this)),Y.call(this)}})},scrollTo:function(t,o){if(void 0!==t&&null!=t){var a=d.call(this);return e(a).each(function(){var a=e(this);if(a.data("mCS")){var n=a.data("mCS"),i=n.opt,r={trigger:"external",scrollInertia:i.scrollInertia,scrollEasing:"mcsEaseInOut",moveDragger:!1,timeout:60,callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},l=e.extend(!0,{},r,o),s=q.call(this,t),c=l.scrollInertia>0&&l.scrollInertia<17?17:l.scrollInertia;s[0]=j.call(this,s[0],"y"),s[1]=j.call(this,s[1],"x"),l.moveDragger&&(s[0]*=n.scrollRatio.y,s[1]*=n.scrollRatio.x),l.dur=te()?0:c,setTimeout(function(){null!==s[0]&&void 0!==s[0]&&"x"!==i.axis&&n.overflowed[0]&&(l.dir="y",l.overwrite="all",N(a,s[0].toString(),l)),null!==s[1]&&void 0!==s[1]&&"y"!==i.axis&&n.overflowed[1]&&(l.dir="x",l.overwrite="none",N(a,s[1].toString(),l))},l.timeout)}})}},stop:function(){var t=d.call(this);return e(t).each(function(){var t=e(this);t.data("mCS")&&X(t)})},disable:function(t){var o=d.call(this);return e(o).each(function(){var o=e(this);o.data("mCS")&&(o.data("mCS"),Y.call(this,"remove"),B.call(this),t&&b.call(this),T.call(this,!0),o.addClass(s[3]))})},destroy:function(){var t=d.call(this);return e(t).each(function(){var a=e(this);if(a.data("mCS")){var n=a.data("mCS"),i=n.opt,r=e("#mCSB_"+n.idx),l=e("#mCSB_"+n.idx+"_container"),c=e(".mCSB_"+n.idx+"_scrollbar");i.live&&f(i.liveSelector||e(t).selector),Y.call(this,"remove"),B.call(this),b.call(this),a.removeData("mCS"),J(this,"mcs"),c.remove(),l.find("img."+s[2]).removeClass(s[2]),r.replaceWith(l.contents()),a.removeClass(o+" _mCS_"+n.idx+" "+s[6]+" "+s[7]+" "+s[5]+" "+s[3]).addClass(s[4])}})}},d=function(){return"object"!=typeof e(this)||e(this).length<1?".mCustomScrollbar":this},u=function(t){t.autoDraggerLength=!(e.inArray(t.theme,["rounded","rounded-dark","rounded-dots","rounded-dots-dark"])>-1)&&t.autoDraggerLength,t.autoExpandScrollbar=!(e.inArray(t.theme,["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"])>-1)&&t.autoExpandScrollbar,t.scrollButtons.enable=!(e.inArray(t.theme,["minimal","minimal-dark"])>-1)&&t.scrollButtons.enable,t.autoHideScrollbar=e.inArray(t.theme,["minimal","minimal-dark"])>-1||t.autoHideScrollbar,t.scrollbarPosition=e.inArray(t.theme,["minimal","minimal-dark"])>-1?"outside":t.scrollbarPosition},f=function(e){i[e]&&(clearTimeout(i[e]),J(i,e))},m=function(e){return"yx"===e||"xy"===e||"auto"===e?"yx":"x"===e||"horizontal"===e?"x":"y"},h=function(e){return"stepped"===e||"pixels"===e||"step"===e||"click"===e?"stepped":"stepless"},p=function(){var t=e(this),a=t.data("mCS"),n=a.opt,i=n.autoExpandScrollbar?" "+s[1]+"_expand":"",r=["<div id='mCSB_"+a.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+a.idx+"_scrollbar mCS-"+n.theme+" mCSB_scrollTools_vertical"+i+"'><div class='"+s[12]+"'><div id='mCSB_"+a.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div></div><div class='mCSB_draggerRail' /></div>","<div id='mCSB_"+a.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+a.idx+"_scrollbar mCS-"+n.theme+" mCSB_scrollTools_horizontal"+i+"'><div class='"+s[12]+"'><div id='mCSB_"+a.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div></div><div class='mCSB_draggerRail' /></div>"],l="yx"===n.axis?"mCSB_vertical_horizontal":"x"===n.axis?"mCSB_horizontal":"mCSB_vertical",c="yx"===n.axis?r[0]+r[1]:"x"===n.axis?r[1]:r[0],d="yx"===n.axis?"<div id='mCSB_"+a.idx+"_container_wrapper' class='mCSB_container_wrapper' />":"",u=n.autoHideScrollbar?" "+s[6]:"",f="x"!==n.axis&&"rtl"===a.langDir?" "+s[7]:"";n.setWidth&&t.css("width",n.setWidth),n.setHeight&&t.css("height",n.setHeight),n.setLeft="y"!==n.axis&&"rtl"===a.langDir?"989999px":n.setLeft,t.addClass(o+" _mCS_"+a.idx+u+f).wrapInner("<div id='mCSB_"+a.idx+"' class='mCustomScrollBox mCS-"+n.theme+" "+l+"'><div id='mCSB_"+a.idx+"_container' class='mCSB_container' style='position:relative; top:"+n.setTop+"; left:"+n.setLeft+";' dir='"+a.langDir+"' /></div>");var m=e("#mCSB_"+a.idx),h=e("#mCSB_"+a.idx+"_container");"y"===n.axis||n.advanced.autoExpandHorizontalScroll||h.css("width",g(h)),"outside"===n.scrollbarPosition?("static"===t.css("position")&&t.css("position","relative"),t.css("overflow","visible"),m.addClass("mCSB_outside").after(c)):(m.addClass("mCSB_inside").append(c),h.wrap(d)),x.call(this);var p=[e("#mCSB_"+a.idx+"_dragger_vertical"),e("#mCSB_"+a.idx+"_dragger_horizontal")];p[0].css("min-height",p[0].height()),p[1].css("min-width",p[1].width())},g=function(t){var o=[t[0].scrollWidth,Math.max.apply(Math,t.children().map(function(){return e(this).outerWidth(!0)}).get())],a=t.parent().width();return o[0]>a?o[0]:o[1]>a?o[1]:"100%"},v=function(){var t=e(this),o=t.data("mCS"),a=o.opt,n=e("#mCSB_"+o.idx+"_container");if(a.advanced.autoExpandHorizontalScroll&&"y"!==a.axis){n.css({width:"auto","min-width":0,"overflow-x":"scroll"});var i=Math.ceil(n[0].scrollWidth);3===a.advanced.autoExpandHorizontalScroll||2!==a.advanced.autoExpandHorizontalScroll&&i>n.parent().width()?n.css({width:i,"min-width":"100%","overflow-x":"inherit"}):n.css({"overflow-x":"inherit",position:"absolute"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:Math.ceil(n[0].getBoundingClientRect().right+.4)-Math.floor(n[0].getBoundingClientRect().left),"min-width":"100%",position:"relative"}).unwrap()}},x=function(){var t=e(this),o=t.data("mCS"),a=o.opt,n=e(".mCSB_"+o.idx+"_scrollbar:first"),i=$(a.scrollButtons.tabindex)?"tabindex='"+a.scrollButtons.tabindex+"'":"",r=["<a href='#' class='"+s[13]+"' "+i+" />","<a href='#' class='"+s[14]+"' "+i+" />","<a href='#' class='"+s[15]+"' "+i+" />","<a href='#' class='"+s[16]+"' "+i+" />"],l=["x"===a.axis?r[2]:r[0],"x"===a.axis?r[3]:r[1],r[2],r[3]];a.scrollButtons.enable&&n.prepend(l[0]).append(l[1]).next(".mCSB_scrollTools").prepend(l[2]).append(l[3])},S=function(){var t=e(this),o=t.data("mCS"),a=e("#mCSB_"+o.idx),n=e("#mCSB_"+o.idx+"_container"),i=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[a.height()/n.outerHeight(!1),a.width()/n.outerWidth(!1)],s=[parseInt(i[0].css("min-height")),Math.round(l[0]*i[0].parent().height()),parseInt(i[1].css("min-width")),Math.round(l[1]*i[1].parent().width())],c=r&&s[1]<s[0]?s[0]:s[1],d=r&&s[3]<s[2]?s[2]:s[3];i[0].css({height:c,"max-height":i[0].parent().height()-10}).find(".mCSB_dragger_bar").css({"line-height":s[0]+"px"}),i[1].css({width:d,"max-width":i[1].parent().width()-10})},_=function(){var t=e(this),o=t.data("mCS"),a=e("#mCSB_"+o.idx),n=e("#mCSB_"+o.idx+"_container"),i=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],r=[n.outerHeight(!1)-a.height(),n.outerWidth(!1)-a.width()],l=[r[0]/(i[0].parent().height()-i[0].height()),r[1]/(i[1].parent().width()-i[1].width())];o.scrollRatio={y:l[0],x:l[1]}},w=function(e,t,o){var a=o?s[0]+"_expanded":"",n=e.closest(".mCSB_scrollTools");"active"===t?(e.toggleClass(s[0]+" "+a),n.toggleClass(s[1]),e[0]._draggable=e[0]._draggable?0:1):e[0]._draggable||("hide"===t?(e.removeClass(s[0]),n.removeClass(s[1])):(e.addClass(s[0]),n.addClass(s[1])))},C=function(){var t=e(this),o=t.data("mCS"),a=e("#mCSB_"+o.idx),n=e("#mCSB_"+o.idx+"_container"),i=null==o.overflowed?n.height():n.outerHeight(!1),r=null==o.overflowed?n.width():n.outerWidth(!1),l=n[0].scrollHeight,s=n[0].scrollWidth;return l>i&&(i=l),s>r&&(r=s),[i>a.height(),r>a.width()]},b=function(){var t,o,a=e(this),n=a.data("mCS"),i=n.opt,r=e("#mCSB_"+n.idx),l=e("#mCSB_"+n.idx+"_container"),s=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];X(a),("x"!==i.axis&&!n.overflowed[0]||"y"===i.axis&&n.overflowed[0])&&(s[0].add(l).css("top",0),N(a,"_resetY")),("y"!==i.axis&&!n.overflowed[1]||"x"===i.axis&&n.overflowed[1])&&(t=o=0,"rtl"===n.langDir&&(t=r.width()-l.outerWidth(!1),o=Math.abs(t/n.scrollRatio.x)),l.css("left",t),s[1].css("left",o),N(a,"_resetX"))},y=function(){var t=e(this),o=t.data("mCS"),a=o.opt;if(!o.bindEvents){var n;if(M.call(this),a.contentTouchScroll&&O.call(this),I.call(this),a.mouseWheel.enable)!function o(){n=setTimeout(function(){e.event.special.mousewheel?(clearTimeout(n),D.call(t[0])):o()},100)}();L.call(this),P.call(this),a.advanced.autoScrollOnFocus&&z.call(this),a.scrollButtons.enable&&H.call(this),a.keyboard.enable&&U.call(this),o.bindEvents=!0}},B=function(){var t=e(this),o=t.data("mCS"),a=o.opt,n="mCS_"+o.idx,i=".mCSB_"+o.idx+"_scrollbar",r=e("#mCSB_"+o.idx+",#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,"+i+" ."+s[12]+",#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal,"+i+">a"),l=e("#mCSB_"+o.idx+"_container");if(a.advanced.releaseDraggableSelectors&&r.add(e(a.advanced.releaseDraggableSelectors)),a.advanced.extraDraggableSelectors&&r.add(e(a.advanced.extraDraggableSelectors)),o.bindEvents){var c=W()?top.document:document;e(document).add(e(c)).unbind("."+n),r.each(function(){e(this).unbind("."+n)}),clearTimeout(t[0]._focusTimeout),J(t[0],"_focusTimeout"),clearTimeout(o.sequential.step),J(o.sequential,"step"),clearTimeout(l[0].onCompleteTimeout),J(l[0],"onCompleteTimeout"),o.bindEvents=!1}},T=function(t){var o=e(this),a=o.data("mCS"),n=a.opt,i=e("#mCSB_"+a.idx+"_container_wrapper"),r=i.length?i:e("#mCSB_"+a.idx+"_container"),l=[e("#mCSB_"+a.idx+"_scrollbar_vertical"),e("#mCSB_"+a.idx+"_scrollbar_horizontal")],c=[l[0].find(".mCSB_dragger"),l[1].find(".mCSB_dragger")];"x"!==n.axis&&(a.overflowed[0]&&!t?(l[0].add(c[0]).add(l[0].children("a")).css("display","block"),r.removeClass(s[8]+" "+s[10])):(n.alwaysShowScrollbar?(2!==n.alwaysShowScrollbar&&c[0].css("display","none"),r.removeClass(s[10])):(l[0].css("display","none"),r.addClass(s[10])),r.addClass(s[8]))),"y"!==n.axis&&(a.overflowed[1]&&!t?(l[1].add(c[1]).add(l[1].children("a")).css("display","block"),r.removeClass(s[9]+" "+s[11])):(n.alwaysShowScrollbar?(2!==n.alwaysShowScrollbar&&c[1].css("display","none"),r.removeClass(s[11])):(l[1].css("display","none"),r.addClass(s[11])),r.addClass(s[9]))),a.overflowed[0]||a.overflowed[1]?o.removeClass(s[5]):o.addClass(s[5])},k=function(t){var o=t.type,a=t.target.ownerDocument!==document&&null!==frameElement?[e(frameElement).offset().top,e(frameElement).offset().left]:null,n=W()&&t.target.ownerDocument!==top.document&&null!==frameElement?[e(t.view.frameElement).offset().top,e(t.view.frameElement).offset().left]:[0,0];switch(o){case"pointerdown":case"MSPointerDown":case"pointermove":case"MSPointerMove":case"pointerup":case"MSPointerUp":return a?[t.originalEvent.pageY-a[0]+n[0],t.originalEvent.pageX-a[1]+n[1],!1]:[t.originalEvent.pageY,t.originalEvent.pageX,!1];case"touchstart":case"touchmove":case"touchend":var i=t.originalEvent.touches[0]||t.originalEvent.changedTouches[0],r=t.originalEvent.touches.length||t.originalEvent.changedTouches.length;return t.target.ownerDocument!==document?[i.screenY,i.screenX,r>1]:[i.pageY,i.pageX,r>1];default:return a?[t.pageY-a[0]+n[0],t.pageX-a[1]+n[1],!1]:[t.pageY,t.pageX,!1]}},M=function(){var t,o,a,n=e(this),i=n.data("mCS"),s=i.opt,c="mCS_"+i.idx,d=["mCSB_"+i.idx+"_dragger_vertical","mCSB_"+i.idx+"_dragger_horizontal"],u=e("#mCSB_"+i.idx+"_container"),f=e("#"+d[0]+",#"+d[1]),m=s.advanced.releaseDraggableSelectors?f.add(e(s.advanced.releaseDraggableSelectors)):f,h=W()?top.document:document,p=s.advanced.extraDraggableSelectors?e(h).add(e(s.advanced.extraDraggableSelectors)):e(h);function g(e,o,a,r){if(u[0].idleTimer=s.scrollInertia<233?250:0,t.attr("id")===d[1])var l="x",c=(t[0].offsetLeft-o+r)*i.scrollRatio.x;else var l="y",c=(t[0].offsetTop-e+a)*i.scrollRatio.y;N(n,c.toString(),{dir:l,drag:!0})}f.bind("contextmenu."+c,function(e){e.preventDefault()}).bind("mousedown."+c+" touchstart."+c+" pointerdown."+c+" MSPointerDown."+c,function(i){if(i.stopImmediatePropagation(),i.preventDefault(),K(i)){l=!0,r&&(document.onselectstart=function(){return!1}),R.call(u,!1),X(n);var c=(t=e(this)).offset(),d=k(i)[0]-c.top,f=k(i)[1]-c.left,m=t.height()+c.top,h=t.width()+c.left;d<m&&d>0&&f<h&&f>0&&(o=d,a=f),w(t,"active",s.autoExpandScrollbar)}}).bind("touchmove."+c,function(e){e.stopImmediatePropagation(),e.preventDefault();var n=t.offset(),i=k(e)[0]-n.top,r=k(e)[1]-n.left;g(o,a,i,r)}),e(document).add(p).bind("mousemove."+c+" pointermove."+c+" MSPointerMove."+c,function(e){if(t){var n=t.offset(),i=k(e)[0]-n.top,r=k(e)[1]-n.left;if(o===i&&a===r)return;g(o,a,i,r)}}).add(m).bind("mouseup."+c+" touchend."+c+" pointerup."+c+" MSPointerUp."+c,function(e){t&&(w(t,"active",s.autoExpandScrollbar),t=null),l=!1,r&&(document.onselectstart=null),R.call(u,!0)})},O=function(){var o,a,n,i,r,s,c,d,u,f,m,h,p,g,v=e(this),x=v.data("mCS"),S=x.opt,_="mCS_"+x.idx,w=e("#mCSB_"+x.idx),C=e("#mCSB_"+x.idx+"_container"),b=[e("#mCSB_"+x.idx+"_dragger_vertical"),e("#mCSB_"+x.idx+"_dragger_horizontal")],y=[],B=[],T=0,M="yx"===S.axis?"none":"all",O=[],I=C.find("iframe"),D=["touchstart."+_+" pointerdown."+_+" MSPointerDown."+_,"touchmove."+_+" pointermove."+_+" MSPointerMove."+_,"touchend."+_+" pointerup."+_+" MSPointerUp."+_],E=void 0!==document.body.style.touchAction&&""!==document.body.style.touchAction;function R(e){if(!Z(e)||l||k(e)[2])t=0;else{t=1,p=0,g=0,o=1,v.removeClass("mCS_touch_action");var i=C.offset();a=k(e)[0]-i.top,n=k(e)[1]-i.left,O=[k(e)[0],k(e)[1]]}}function A(e){if(Z(e)&&!l&&!k(e)[2]&&(S.documentTouchScroll||e.preventDefault(),e.stopImmediatePropagation(),(!g||p)&&o)){c=Q();var t=w.offset(),i=k(e)[0]-t.top,r=k(e)[1]-t.left;if(y.push(i),B.push(r),O[2]=Math.abs(k(e)[0]-O[0]),O[3]=Math.abs(k(e)[1]-O[1]),x.overflowed[0])var s=b[0].parent().height()-b[0].height(),d=a-i>0&&i-a>-s*x.scrollRatio.y&&(2*O[3]<O[2]||"yx"===S.axis);if(x.overflowed[1])var u=b[1].parent().width()-b[1].width(),f=n-r>0&&r-n>-u*x.scrollRatio.x&&(2*O[2]<O[3]||"yx"===S.axis);d||f?(E||e.preventDefault(),p=1):(g=1,v.addClass("mCS_touch_action")),E&&e.preventDefault(),m="yx"===S.axis?[a-i,n-r]:"x"===S.axis?[null,n-r]:[a-i,null],C[0].idleTimer=250,x.overflowed[0]&&H(m[0],T,"mcsLinearOut","y","all",!0),x.overflowed[1]&&H(m[1],T,"mcsLinearOut","x",M,!0)}}function L(e){if(!Z(e)||l||k(e)[2])t=0;else{t=1,e.stopImmediatePropagation(),X(v),s=Q();var o=w.offset();i=k(e)[0]-o.top,r=k(e)[1]-o.left,y=[],B=[]}}function z(e){if(Z(e)&&!l&&!k(e)[2]){o=0,e.stopImmediatePropagation(),p=0,g=0,d=Q();var t=w.offset(),a=k(e)[0]-t.top,n=k(e)[1]-t.left;if(!(d-c>30)){var v=(f=1e3/(d-s))<2.5,_=v?[y[y.length-2],B[B.length-2]]:[0,0];u=v?[a-_[0],n-_[1]]:[a-i,n-r];var b=[Math.abs(u[0]),Math.abs(u[1])];f=v?[Math.abs(u[0]/4),Math.abs(u[1]/4)]:[f,f];var T=[Math.abs(C[0].offsetTop)-u[0]*P(b[0]/f[0],f[0]),Math.abs(C[0].offsetLeft)-u[1]*P(b[1]/f[1],f[1])];m="yx"===S.axis?[T[0],T[1]]:"x"===S.axis?[null,T[1]]:[T[0],null],h=[4*b[0]+S.scrollInertia,4*b[1]+S.scrollInertia];var O=parseInt(S.contentTouchScroll)||0;m[0]=b[0]>O?m[0]:0,m[1]=b[1]>O?m[1]:0,x.overflowed[0]&&H(m[0],h[0],"mcsEaseOut","y",M,!1),x.overflowed[1]&&H(m[1],h[1],"mcsEaseOut","x",M,!1)}}}function P(e,t){var o=[1.5*t,2*t,t/1.5,t/2];return e>90?t>4?o[0]:o[3]:e>60?t>3?o[3]:o[2]:e>30?t>8?o[1]:t>6?o[0]:t>4?t:o[2]:t>8?t:o[3]}function H(e,t,o,a,n,i){e&&N(v,e.toString(),{dur:t,scrollEasing:o,dir:a,overwrite:n,drag:i})}C.bind(D[0],function(e){R(e)}).bind(D[1],function(e){A(e)}),w.bind(D[0],function(e){L(e)}).bind(D[2],function(e){z(e)}),I.length&&I.each(function(){e(this).bind("load",function(){W(this)&&e(this.contentDocument||this.contentWindow.document).bind(D[0],function(e){R(e),L(e)}).bind(D[1],function(e){A(e)}).bind(D[2],function(e){z(e)})})})},I=function(){var o,a=e(this),n=a.data("mCS"),i=n.opt,r=n.sequential,s="mCS_"+n.idx,c=e("#mCSB_"+n.idx+"_container"),d=c.parent();function u(e,t,n){r.type=n&&o?"stepped":"stepless",r.scrollAmount=10,F(a,e,t,"mcsLinearOut",n?60:null)}c.bind("mousedown."+s,function(e){t||o||(o=1,l=!0)}).add(document).bind("mousemove."+s,function(e){if(!t&&o&&(window.getSelection?window.getSelection().toString():document.selection&&"Control"!=document.selection.type&&document.selection.createRange().text)){var a=c.offset(),l=k(e)[0]-a.top+c[0].offsetTop,s=k(e)[1]-a.left+c[0].offsetLeft;l>0&&l<d.height()&&s>0&&s<d.width()?r.step&&u("off",null,"stepped"):("x"!==i.axis&&n.overflowed[0]&&(l<0?u("on",38):l>d.height()&&u("on",40)),"y"!==i.axis&&n.overflowed[1]&&(s<0?u("on",37):s>d.width()&&u("on",39)))}}).bind("mouseup."+s+" dragend."+s,function(e){t||(o&&(o=0,u("off",null)),l=!1)})},D=function(){if(e(this).data("mCS")){var t=e(this),o=t.data("mCS"),a=o.opt,n="mCS_"+o.idx,i=e("#mCSB_"+o.idx),l=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],s=e("#mCSB_"+o.idx+"_container").find("iframe");s.length&&s.each(function(){e(this).bind("load",function(){W(this)&&e(this.contentDocument||this.contentWindow.document).bind("mousewheel."+n,function(e,t){c(e,t)})})}),i.bind("mousewheel."+n,function(e,t){c(e,t)})}function c(n,s){if(X(t),!A(t,n.target)){var c="auto"!==a.mouseWheel.deltaFactor?parseInt(a.mouseWheel.deltaFactor):r&&n.deltaFactor<100?100:n.deltaFactor||100,d=a.scrollInertia;if("x"===a.axis||"x"===a.mouseWheel.axis)var u="x",f=[Math.round(c*o.scrollRatio.x),parseInt(a.mouseWheel.scrollAmount)],m="auto"!==a.mouseWheel.scrollAmount?f[1]:f[0]>=i.width()?.9*i.width():f[0],h=Math.abs(e("#mCSB_"+o.idx+"_container")[0].offsetLeft),p=l[1][0].offsetLeft,g=l[1].parent().width()-l[1].width(),v="y"===a.mouseWheel.axis?n.deltaY||s:n.deltaX;else var u="y",f=[Math.round(c*o.scrollRatio.y),parseInt(a.mouseWheel.scrollAmount)],m="auto"!==a.mouseWheel.scrollAmount?f[1]:f[0]>=i.height()?.9*i.height():f[0],h=Math.abs(e("#mCSB_"+o.idx+"_container")[0].offsetTop),p=l[0][0].offsetTop,g=l[0].parent().height()-l[0].height(),v=n.deltaY||s;"y"===u&&!o.overflowed[0]||"x"===u&&!o.overflowed[1]||((a.mouseWheel.invert||n.webkitDirectionInvertedFromDevice)&&(v=-v),a.mouseWheel.normalizeDelta&&(v=v<0?-1:1),(v>0&&0!==p||v<0&&p!==g||a.mouseWheel.preventDefault)&&(n.stopImmediatePropagation(),n.preventDefault()),n.deltaFactor<5&&!a.mouseWheel.normalizeDelta&&(m=n.deltaFactor,d=17),N(t,(h-v*m).toString(),{dir:u,dur:d}))}}},E=new Object,W=function(t){var o=!1,a=!1,n=null;if(void 0===t?a="#empty":void 0!==e(t).attr("id")&&(a=e(t).attr("id")),!1!==a&&void 0!==E[a])return E[a];if(t){try{var i=t.contentDocument||t.contentWindow.document;n=i.body.innerHTML}catch(e){}o=null!==n}else{try{var i=top.document;n=i.body.innerHTML}catch(e){}o=null!==n}return!1!==a&&(E[a]=o),o},R=function(e){var t=this.find("iframe");if(t.length){var o=e?"auto":"none";t.css("pointer-events",o)}},A=function(t,o){var a=o.nodeName.toLowerCase(),n=t.data("mCS").opt.mouseWheel.disableOver;return e.inArray(a,n)>-1&&!(e.inArray(a,["select","textarea"])>-1&&!e(o).is(":focus"))},L=function(){var t,o=e(this),a=o.data("mCS"),n="mCS_"+a.idx,i=e("#mCSB_"+a.idx+"_container"),r=i.parent(),c=e(".mCSB_"+a.idx+"_scrollbar ."+s[12]);c.bind("mousedown."+n+" touchstart."+n+" pointerdown."+n+" MSPointerDown."+n,function(o){l=!0,e(o.target).hasClass("mCSB_dragger")||(t=1)}).bind("touchend."+n+" pointerup."+n+" MSPointerUp."+n,function(e){l=!1}).bind("click."+n,function(n){if(t&&(t=0,e(n.target).hasClass(s[12])||e(n.target).hasClass("mCSB_draggerRail"))){X(o);var l=e(this),c=l.find(".mCSB_dragger");if(l.parent(".mCSB_scrollTools_horizontal").length>0){if(!a.overflowed[1])return;var d="x",u=n.pageX>c.offset().left?-1:1,f=Math.abs(i[0].offsetLeft)-u*(.9*r.width())}else{if(!a.overflowed[0])return;var d="y",u=n.pageY>c.offset().top?-1:1,f=Math.abs(i[0].offsetTop)-u*(.9*r.height())}N(o,f.toString(),{dir:d,scrollEasing:"mcsEaseInOut"})}})},z=function(){var t=e(this),o=t.data("mCS"),a=o.opt,n="mCS_"+o.idx,i=e("#mCSB_"+o.idx+"_container"),r=i.parent();i.bind("focusin."+n,function(o){var n=e(document.activeElement),l=i.find(".mCustomScrollBox").length;n.is(a.advanced.autoScrollOnFocus)&&(X(t),clearTimeout(t[0]._focusTimeout),t[0]._focusTimer=l?17*l:0,t[0]._focusTimeout=setTimeout(function(){var e=[ee(n)[0],ee(n)[1]],o=[i[0].offsetTop,i[0].offsetLeft],l=[o[0]+e[0]>=0&&o[0]+e[0]<r.height()-n.outerHeight(!1),o[1]+e[1]>=0&&o[0]+e[1]<r.width()-n.outerWidth(!1)],s="yx"!==a.axis||l[0]||l[1]?"all":"none";"x"===a.axis||l[0]||N(t,e[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:s,dur:0}),"y"===a.axis||l[1]||N(t,e[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:s,dur:0})},t[0]._focusTimer))})},P=function(){var t=e(this),o=t.data("mCS"),a="mCS_"+o.idx,n=e("#mCSB_"+o.idx+"_container").parent();n.bind("scroll."+a,function(t){0===n.scrollTop()&&0===n.scrollLeft()||e(".mCSB_"+o.idx+"_scrollbar").css("visibility","hidden")})},H=function(){var t=e(this),o=t.data("mCS"),a=o.opt,n=o.sequential,i="mCS_"+o.idx,r=".mCSB_"+o.idx+"_scrollbar",s=e(r+">a");s.bind("contextmenu."+i,function(e){e.preventDefault()}).bind("mousedown."+i+" touchstart."+i+" pointerdown."+i+" MSPointerDown."+i+" mouseup."+i+" touchend."+i+" pointerup."+i+" MSPointerUp."+i+" mouseout."+i+" pointerout."+i+" MSPointerOut."+i+" click."+i,function(i){if(i.preventDefault(),K(i)){var r=e(this).attr("class");switch(n.type=a.scrollButtons.scrollType,i.type){case"mousedown":case"touchstart":case"pointerdown":case"MSPointerDown":if("stepped"===n.type)return;l=!0,o.tweenRunning=!1,s("on",r);break;case"mouseup":case"touchend":case"pointerup":case"MSPointerUp":case"mouseout":case"pointerout":case"MSPointerOut":if("stepped"===n.type)return;l=!1,n.dir&&s("off",r);break;case"click":if("stepped"!==n.type||o.tweenRunning)return;s("on",r)}}function s(e,o){n.scrollAmount=a.scrollButtons.scrollAmount,F(t,e,o)}})},U=function(){var t=e(this),o=t.data("mCS"),a=o.opt,n=o.sequential,i="mCS_"+o.idx,r=e("#mCSB_"+o.idx),l=e("#mCSB_"+o.idx+"_container"),s=l.parent(),c="input,textarea,select,datalist,keygen,[contenteditable='true']",d=l.find("iframe"),u=["blur."+i+" keydown."+i+" keyup."+i];function f(i){switch(i.type){case"blur":o.tweenRunning&&n.dir&&h("off",null);break;case"keydown":case"keyup":var r=i.keyCode?i.keyCode:i.which,d="on";if("x"!==a.axis&&(38===r||40===r)||"y"!==a.axis&&(37===r||39===r)){if((38===r||40===r)&&!o.overflowed[0]||(37===r||39===r)&&!o.overflowed[1])return;"keyup"===i.type&&(d="off"),e(document.activeElement).is(c)||(i.preventDefault(),i.stopImmediatePropagation(),h(d,r))}else if(33===r||34===r){if((o.overflowed[0]||o.overflowed[1])&&(i.preventDefault(),i.stopImmediatePropagation()),"keyup"===i.type){X(t);var u=34===r?-1:1;if("x"===a.axis||"yx"===a.axis&&o.overflowed[1]&&!o.overflowed[0])var f="x",m=Math.abs(l[0].offsetLeft)-u*(.9*s.width());else var f="y",m=Math.abs(l[0].offsetTop)-u*(.9*s.height());N(t,m.toString(),{dir:f,scrollEasing:"mcsEaseInOut"})}}else if((35===r||36===r)&&!e(document.activeElement).is(c)&&((o.overflowed[0]||o.overflowed[1])&&(i.preventDefault(),i.stopImmediatePropagation()),"keyup"===i.type)){if("x"===a.axis||"yx"===a.axis&&o.overflowed[1]&&!o.overflowed[0])var f="x",m=35===r?Math.abs(s.width()-l.outerWidth(!1)):0;else var f="y",m=35===r?Math.abs(s.height()-l.outerHeight(!1)):0;N(t,m.toString(),{dir:f,scrollEasing:"mcsEaseInOut"})}}function h(e,i){n.type=a.keyboard.scrollType,n.scrollAmount=a.keyboard.scrollAmount,"stepped"===n.type&&o.tweenRunning||F(t,e,i)}}d.length&&d.each(function(){e(this).bind("load",function(){W(this)&&e(this.contentDocument||this.contentWindow.document).bind(u[0],function(e){f(e)})})}),r.attr("tabindex","0").bind(u[0],function(e){f(e)})},F=function(t,o,a,n,i){var r=t.data("mCS"),l=r.opt,c=r.sequential,d=e("#mCSB_"+r.idx+"_container"),u="stepped"===c.type,f=l.scrollInertia<26?26:l.scrollInertia,m=l.scrollInertia<1?17:l.scrollInertia;switch(o){case"on":if(c.dir=[a===s[16]||a===s[15]||39===a||37===a?"x":"y",a===s[13]||a===s[15]||38===a||37===a?-1:1],X(t),$(a)&&"stepped"===c.type)return;h(u);break;case"off":clearTimeout(c.step),J(c,"step"),X(t),(u||r.tweenRunning&&c.dir)&&h(!0)}function h(e){l.snapAmount&&(c.scrollAmount=l.snapAmount instanceof Array?"x"===c.dir[0]?l.snapAmount[1]:l.snapAmount[0]:l.snapAmount);var o="stepped"!==c.type,a=i||(e?o?f/1.5:m:1e3/60),s=e?o?7.5:40:2.5,u=[Math.abs(d[0].offsetTop),Math.abs(d[0].offsetLeft)],p=[r.scrollRatio.y>10?10:r.scrollRatio.y,r.scrollRatio.x>10?10:r.scrollRatio.x],g="x"===c.dir[0]?u[1]+c.dir[1]*(p[1]*s):u[0]+c.dir[1]*(p[0]*s),v="x"===c.dir[0]?u[1]+c.dir[1]*parseInt(c.scrollAmount):u[0]+c.dir[1]*parseInt(c.scrollAmount),x="auto"!==c.scrollAmount?v:g,S=n||(e?o?"mcsLinearOut":"mcsEaseInOut":"mcsLinear"),_=!!e;e&&a<17&&(x="x"===c.dir[0]?u[1]:u[0]),N(t,x.toString(),{dir:c.dir[0],scrollEasing:S,dur:a,onComplete:_}),e?c.dir=!1:(clearTimeout(c.step),c.step=setTimeout(function(){h()},a))}},q=function(t){var o=e(this).data("mCS").opt,a=[];return"function"==typeof t&&(t=t()),t instanceof Array?a=t.length>1?[t[0],t[1]]:"x"===o.axis?[null,t[0]]:[t[0],null]:(a[0]=t.y?t.y:t.x||"x"===o.axis?null:t,a[1]=t.x?t.x:t.y||"y"===o.axis?null:t),"function"==typeof a[0]&&(a[0]=a[0]()),"function"==typeof a[1]&&(a[1]=a[1]()),a},j=function(t,o){if(null!=t&&void 0!==t){var a=e(this),n=a.data("mCS"),i=n.opt,r=e("#mCSB_"+n.idx+"_container"),l=r.parent(),s=typeof t;o||(o="x"===i.axis?"x":"y");var d="x"===o?r.outerWidth(!1)-l.width():r.outerHeight(!1)-l.height(),u="x"===o?r[0].offsetLeft:r[0].offsetTop,f="x"===o?"left":"top";switch(s){case"function":return t();case"object":var m=t.jquery?t:e(t);if(!m.length)return;return"x"===o?ee(m)[1]:ee(m)[0];case"string":case"number":if($(t))return Math.abs(t);if(-1!==t.indexOf("%"))return Math.abs(d*parseInt(t)/100);if(-1!==t.indexOf("-="))return Math.abs(u-parseInt(t.split("-=")[1]));if(-1!==t.indexOf("+=")){var h=u+parseInt(t.split("+=")[1]);return h>=0?0:Math.abs(h)}if(-1!==t.indexOf("px")&&$(t.split("px")[0]))return Math.abs(t.split("px")[0]);if("top"===t||"left"===t)return 0;if("bottom"===t)return Math.abs(l.height()-r.outerHeight(!1));if("right"===t)return Math.abs(l.width()-r.outerWidth(!1));if("first"===t||"last"===t){var m=r.find(":"+t);return"x"===o?ee(m)[1]:ee(m)[0]}return e(t).length?"x"===o?ee(e(t))[1]:ee(e(t))[0]:(r.css(f,t),void c.update.call(null,a[0]))}}},Y=function(t){var o=e(this),a=o.data("mCS"),n=a.opt,i=e("#mCSB_"+a.idx+"_container");if(t)return clearTimeout(i[0].autoUpdate),void J(i[0],"autoUpdate");function r(e){clearTimeout(i[0].autoUpdate),c.update.call(null,o[0],e)}!function t(){clearTimeout(i[0].autoUpdate),0!==o.parents("html").length?i[0].autoUpdate=setTimeout(function(){return n.advanced.updateOnSelectorChange&&(a.poll.change.n=function(){!0===n.advanced.updateOnSelectorChange&&(n.advanced.updateOnSelectorChange="*");var e=0,t=i.find(n.advanced.updateOnSelectorChange);return n.advanced.updateOnSelectorChange&&t.length>0&&t.each(function(){e+=this.offsetHeight+this.offsetWidth}),e}(),a.poll.change.n!==a.poll.change.o)?(a.poll.change.o=a.poll.change.n,void r(3)):n.advanced.updateOnContentResize&&(a.poll.size.n=o[0].scrollHeight+o[0].scrollWidth+i[0].offsetHeight+o[0].offsetHeight+o[0].offsetWidth,a.poll.size.n!==a.poll.size.o)?(a.poll.size.o=a.poll.size.n,void r(1)):!n.advanced.updateOnImageLoad||"auto"===n.advanced.updateOnImageLoad&&"y"===n.axis||(a.poll.img.n=i.find("img").length,a.poll.img.n===a.poll.img.o)?void((n.advanced.updateOnSelectorChange||n.advanced.updateOnContentResize||n.advanced.updateOnImageLoad)&&t()):(a.poll.img.o=a.poll.img.n,void i.find("img").each(function(){!function(t){if(e(t).hasClass(s[2]))r();else{var o,a,n=new Image;n.onload=(o=n,a=function(){this.onload=null,e(t).addClass(s[2]),r(2)},function(){return a.apply(o,arguments)}),n.src=t.src}}(this)}))},n.advanced.autoUpdateTimeout):o=null}()},X=function(t){var o=t.data("mCS"),a=e("#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal");a.each(function(){G.call(this)})},N=function(t,o,a){var n=t.data("mCS"),i=n.opt,r={trigger:"internal",dir:"y",scrollEasing:"mcsEaseOut",drag:!1,dur:i.scrollInertia,overwrite:"all",callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},a=e.extend(r,a),l=[a.dur,a.drag?0:a.dur],s=e("#mCSB_"+n.idx),c=e("#mCSB_"+n.idx+"_container"),d=c.parent(),u=i.callbacks.onTotalScrollOffset?q.call(t,i.callbacks.onTotalScrollOffset):[0,0],f=i.callbacks.onTotalScrollBackOffset?q.call(t,i.callbacks.onTotalScrollBackOffset):[0,0];if(n.trigger=a.trigger,0===d.scrollTop()&&0===d.scrollLeft()||(e(".mCSB_"+n.idx+"_scrollbar").css("visibility","visible"),d.scrollTop(0).scrollLeft(0)),"_resetY"!==o||n.contentReset.y||(y("onOverflowYNone")&&i.callbacks.onOverflowYNone.call(t[0]),n.contentReset.y=1),"_resetX"!==o||n.contentReset.x||(y("onOverflowXNone")&&i.callbacks.onOverflowXNone.call(t[0]),n.contentReset.x=1),"_resetY"!==o&&"_resetX"!==o){if(!n.contentReset.y&&t[0].mcs||!n.overflowed[0]||(y("onOverflowY")&&i.callbacks.onOverflowY.call(t[0]),n.contentReset.x=null),!n.contentReset.x&&t[0].mcs||!n.overflowed[1]||(y("onOverflowX")&&i.callbacks.onOverflowX.call(t[0]),n.contentReset.x=null),i.snapAmount){var m=i.snapAmount instanceof Array?"x"===a.dir?i.snapAmount[1]:i.snapAmount[0]:i.snapAmount;o=function(e,t,o){return Math.round(e/t)*t-o}(o,m,i.snapOffset)}switch(a.dir){case"x":var h=e("#mCSB_"+n.idx+"_dragger_horizontal"),p="left",g=c[0].offsetLeft,v=[s.width()-c.outerWidth(!1),h.parent().width()-h.width()],x=[o,0===o?0:o/n.scrollRatio.x],S=u[1],_=f[1],C=S>0?S/n.scrollRatio.x:0,b=_>0?_/n.scrollRatio.x:0;break;case"y":var h=e("#mCSB_"+n.idx+"_dragger_vertical"),p="top",g=c[0].offsetTop,v=[s.height()-c.outerHeight(!1),h.parent().height()-h.height()],x=[o,0===o?0:o/n.scrollRatio.y],S=u[0],_=f[0],C=S>0?S/n.scrollRatio.y:0,b=_>0?_/n.scrollRatio.y:0}x[1]<0||0===x[0]&&0===x[1]?x=[0,0]:x[1]>=v[1]?x=[v[0],v[1]]:x[0]=-x[0],t[0].mcs||(B(),y("onInit")&&i.callbacks.onInit.call(t[0])),clearTimeout(c[0].onCompleteTimeout),V(h[0],p,Math.round(x[1]),l[1],a.scrollEasing),!n.tweenRunning&&(0===g&&x[0]>=0||g===v[0]&&x[0]<=v[0])||V(c[0],p,Math.round(x[0]),l[0],a.scrollEasing,a.overwrite,{onStart:function(){a.callbacks&&a.onStart&&!n.tweenRunning&&(y("onScrollStart")&&(B(),i.callbacks.onScrollStart.call(t[0])),n.tweenRunning=!0,w(h),n.cbOffsets=[i.callbacks.alwaysTriggerOffsets||g>=v[0]+S,i.callbacks.alwaysTriggerOffsets||g<=-_])},onUpdate:function(){a.callbacks&&a.onUpdate&&y("whileScrolling")&&(B(),i.callbacks.whileScrolling.call(t[0]))},onComplete:function(){if(a.callbacks&&a.onComplete){"yx"===i.axis&&clearTimeout(c[0].onCompleteTimeout);var e=c[0].idleTimer||0;c[0].onCompleteTimeout=setTimeout(function(){y("onScroll")&&(B(),i.callbacks.onScroll.call(t[0])),y("onTotalScroll")&&x[1]>=v[1]-C&&n.cbOffsets[0]&&(B(),i.callbacks.onTotalScroll.call(t[0])),y("onTotalScrollBack")&&x[1]<=b&&n.cbOffsets[1]&&(B(),i.callbacks.onTotalScrollBack.call(t[0])),n.tweenRunning=!1,c[0].idleTimer=0,w(h,"hide")},e)}}})}function y(e){return n&&i.callbacks[e]&&"function"==typeof i.callbacks[e]}function B(){var e=[c[0].offsetTop,c[0].offsetLeft],o=[h[0].offsetTop,h[0].offsetLeft],n=[c.outerHeight(!1),c.outerWidth(!1)],i=[s.height(),s.width()];t[0].mcs={content:c,top:e[0],left:e[1],draggerTop:o[0],draggerLeft:o[1],topPct:Math.round(100*Math.abs(e[0])/(Math.abs(n[0])-i[0])),leftPct:Math.round(100*Math.abs(e[1])/(Math.abs(n[1])-i[1])),direction:a.dir}}},V=function(e,t,o,a,n,i,r){e._mTween||(e._mTween={top:{},left:{}});var l,s,r=r||{},c=r.onStart||function(){},d=r.onUpdate||function(){},u=r.onComplete||function(){},f=Q(),m=0,h=e.offsetTop,p=e.style,g=e._mTween[t];"left"===t&&(h=e.offsetLeft);var v=o-h;function x(){g.stop||(m||c.call(),m=Q()-f,S(),m>=g.time&&(g.time=m>g.time?m+l-(m-g.time):m+l-1,g.time<m+1&&(g.time=m+1)),g.time<a?g.id=s(x):u.call())}function S(){a>0?(g.currVal=function(e,t,o,a,n){switch(n){case"linear":case"mcsLinear":return o*e/a+t;case"mcsLinearOut":return e/=a,e--,o*Math.sqrt(1-e*e)+t;case"easeInOutSmooth":return(e/=a/2)<1?o/2*e*e+t:-o/2*(--e*(e-2)-1)+t;case"easeInOutStrong":return(e/=a/2)<1?o/2*Math.pow(2,10*(e-1))+t:(e--,o/2*(2-Math.pow(2,-10*e))+t);case"easeInOut":case"mcsEaseInOut":return(e/=a/2)<1?o/2*e*e*e+t:o/2*((e-=2)*e*e+2)+t;case"easeOutSmooth":return e/=a,-o*(--e*e*e*e-1)+t;case"easeOutStrong":return o*(1-Math.pow(2,-10*e/a))+t;case"easeOut":case"mcsEaseOut":default:var i=(e/=a)*e,r=i*e;return t+o*(.499999999999997*r*i+-2.5*i*i+5.5*r+-6.5*i+4*e)}}(g.time,h,v,a,n),p[t]=Math.round(g.currVal)+"px"):p[t]=o+"px",d.call()}g.stop=0,"none"!==i&&null!=g.id&&(window.requestAnimationFrame?window.cancelAnimationFrame(g.id):clearTimeout(g.id),g.id=null),l=1e3/60,g.time=m+l,s=window.requestAnimationFrame?window.requestAnimationFrame:function(e){return S(),setTimeout(e,.01)},g.id=s(x)},Q=function(){return window.performance&&window.performance.now?window.performance.now():window.performance&&window.performance.webkitNow?window.performance.webkitNow():Date.now?Date.now():(new Date).getTime()},G=function(){var e=this;e._mTween||(e._mTween={top:{},left:{}});for(var t=["top","left"],o=0;o<t.length;o++){var a=t[o];e._mTween[a].id&&(window.requestAnimationFrame?window.cancelAnimationFrame(e._mTween[a].id):clearTimeout(e._mTween[a].id),e._mTween[a].id=null,e._mTween[a].stop=1)}},J=function(e,t){try{delete e[t]}catch(o){e[t]=null}},K=function(e){return!(e.which&&1!==e.which)},Z=function(e){var t=e.originalEvent.pointerType;return!(t&&"touch"!==t&&2!==t)},$=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},ee=function(e){var t=e.parents(".mCSB_container");return[e.offset().top-t.offset().top,e.offset().left-t.offset().left]},te=function(){var e=function(){var e=["webkit","moz","ms","o"];if("hidden"in document)return"hidden";for(var t=0;t<e.length;t++)if(e[t]+"Hidden"in document)return e[t]+"Hidden";return null}();return!!e&&document[e]},e.fn[o]=function(t){return c[t]?c[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):c.init.apply(this,arguments)},e[o]=function(t){return c[t]?c[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):c.init.apply(this,arguments)},e[o].defaults=a,window[o]=!0,e(window).bind("load",function(){e(".mCustomScrollbar")[o](),e.extend(e.expr[":"],{mcsInView:e.expr[":"].mcsInView||function(t){var o,a,n=e(t),i=n.parents(".mCSB_container");if(i.length)return o=i.parent(),(a=[i[0].offsetTop,i[0].offsetLeft])[0]+ee(n)[0]>=0&&a[0]+ee(n)[0]<o.height()-n.outerHeight(!1)&&a[1]+ee(n)[1]>=0&&a[1]+ee(n)[1]<o.width()-n.outerWidth(!1)},mcsInSight:e.expr[":"].mcsInSight||function(t,o,a){var n,i,r,l,s=e(t),c=s.parents(".mCSB_container"),d="exact"===a[3]?[[1,0],[1,0]]:[[.9,.1],[.6,.4]];if(c.length)return n=[s.outerHeight(!1),s.outerWidth(!1)],r=[c[0].offsetTop+ee(s)[0],c[0].offsetLeft+ee(s)[1]],i=[c.parent()[0].offsetHeight,c.parent()[0].offsetWidth],r[0]-i[0]*(l=[n[0]<i[0]?d[0]:d[1],n[1]<i[1]?d[0]:d[1]])[0][0]<0&&r[0]+n[0]-i[0]*l[0][1]>=0&&r[1]-i[1]*l[1][0]<0&&r[1]+n[1]-i[1]*l[1][1]>=0},mcsOverflow:e.expr[":"].mcsOverflow||function(t){var o=e(t).data("mCS");if(o)return o.overflowed[0]||o.overflowed[1]}})})});

/* ========================================
 FILE: /includes/js/jquery.touchpunch.min.js
 ==================== */

//jQuery UI Touch Punch 0.2.3
/*
!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d);}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"));},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"));},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1);},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b);},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b);};}}(jQuery);
*/
/*!
 * jQuery UI Touch Punch 1.0.8 as modified by RWAP Software
 * based on original touchpunch v0.2.3 which has not been updated since 2014
 *
 * Updates by RWAP Software to take account of various suggested changes on the original code issues
 *
 * Original: https://github.com/furf/jquery-ui-touch-punch
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Fork: https://github.com/RWAP/jquery-ui-touch-punch
 *
 * Depends:
 * jquery.ui.widget.js
 * jquery.ui.mouse.js
 */
!function(t){"function"==typeof define&&define.amd?define(["jquery","jquery.ui"],t):t(jQuery)}(function(t){function o(t){return{x:t.originalEvent.changedTouches[0].pageX,y:t.originalEvent.changedTouches[0].pageY}}function e(t,o){if(!(t.originalEvent.touches.length>1)){t.cancelable&&t.preventDefault();var e=t.originalEvent.changedTouches[0],n=document.createEvent("MouseEvents");n.initMouseEvent(o,!0,!0,window,1,e.screenX,e.screenY,e.clientX,e.clientY,!1,!1,!1,!1,0,null),t.target.dispatchEvent(n)}}if(t.support.mspointer=window.navigator.msPointerEnabled,t.support.touch="ontouchstart"in document||"ontouchstart"in window||window.TouchEvent||window.DocumentTouch&&document instanceof DocumentTouch||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,(t.support.touch||t.support.mspointer)&&t.ui.mouse){var n,u=t.ui.mouse.prototype,c=u._mouseInit,i=u._mouseDestroy;u._touchStart=function(t){var u=this;this._startedMove=t.timeStamp,u._startPos=o(t),!n&&u._mouseCapture(t.originalEvent.changedTouches[0])&&(n=!0,u._touchMoved=!1,e(t,"mouseover"),e(t,"mousemove"),e(t,"mousedown"))},u._touchMove=function(t){n&&(this._touchMoved=!0,e(t,"mousemove"))},u._touchEnd=function(t){if(n){e(t,"mouseup"),e(t,"mouseout");var u=t.timeStamp-this._startedMove;if(!this._touchMoved||500>u)e(t,"click");else{var c=o(t);Math.abs(c.x-this._startPos.x)<10&&Math.abs(c.y-this._startPos.y)<10&&(this._touchMoved&&"stylus"!==t.originalEvent.changedTouches[0].touchType||e(t,"click"))}this._touchMoved=!1,n=!1}},u._mouseInit=function(){var o=this;t.support.mspointer&&(o.element[0].style.msTouchAction="none"),o.element.on({touchstart:t.proxy(o,"_touchStart"),touchmove:t.proxy(o,"_touchMove"),touchend:t.proxy(o,"_touchEnd")}),c.call(o)},u._mouseDestroy=function(){var o=this;o.element.off({touchstart:t.proxy(o,"_touchStart"),touchmove:t.proxy(o,"_touchMove"),touchend:t.proxy(o,"_touchEnd")}),i.call(o)}}});

/* ========================================
 FILE: /templates/js/template.js
 ==================== */

var script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};

//	contact.html.php
if( typeof script_manage_params.contact_chkas !== 'undefined' && script_manage_params.contact_chkas == '1' ){
	function checkAntispam() {
		if (document.emailForm.cs_as_v.value!='' && !isNaN(document.emailForm.cs_as_v.value)) {
			return validate();
		} else {
			if ( typeof script_manage_params.as_nan !== 'undefined' ) {
				alert(script_manage_params.as_nan);
			}

			document.emailForm.cs_as_v.trigger('focus');
			return false;
		}
	}
}

//	shop.cart.php
if( typeof script_manage_params['shop.cart_h2'] !== 'undefined' && script_manage_params['shop.cart_h2'] == '1' ) {
	function shop_cart_quantity_input_onkeydown( event, form_obj ) {
		var ret_val = false;
		if ( event.keyCode == 13 ) {
			if (form_obj.getAttribute('onsubmit')!='') ret_val = form_obj.onsubmit();

			//bonus system (nedovol pridat polozku ktora by prekrocila vysku nazbieraneho bonusu)
			// string 'Ym9udXM=' znamena 'bonus' len je zakodovany v base64
			if (Cookies.get('bonusShoppingMode') == 'Ym9udXM=' && jQuery('.bonus-system-cart-wrapper').length > 0) {

				var cart_id             = jQuery(form_obj).find('input[name=idx]').val();
				var actualBonusAmount   = jQuery('.bonus-system-cart-wrapper .bonus-amount-lbl strong').html().split(' ')[0];
				var originalQty         = js_cart_items[cart_id].quantity;
				var actualQty           = jQuery(form_obj).find('input[name=quantity]').val();

				if (actualBonusAmount < (actualQty - originalQty) * js_cart_items[cart_id].product_price) {
					vex.dialog.alert(js_lang_bonus_system_not_enough_credit);
					event.preventDefault();
					ret_val = false;
				}
			}

			if (ret_val) form_obj.submit();
		}
		return ret_val;
	}
}

//	shop.product_details, ps_product_attribute.php
if( typeof script_manage_params['shop.product_details_ps_pa'] !== 'undefined' && script_manage_params['shop.product_details_ps_pa'] == '1' ){
	function js_custom_attribute_submit_addtocart() {
		var isvalid = true;
		if (typeof script_manage_params.rr == 'object') {
			for (var i in script_manage_params.rr) {
				var ref_required1 = script_manage_params.rr[i];
					if ( (typeof document.getElementById('addtocart')[ref_required1] === 'undefined' || document.getElementById('addtocart')[ref_required1].value == "") && (document.getElementById(ref_required1 +'_field').value == "") ) {
						if ( isDesignTools()){
							jQuery('#'+ ref_required1 + '_field').parents('.product-custom-attribute:first').addClass('error');
						}else{
							document.getElementById(ref_required1 + '_label_div').style.color   = "red";
							document.getElementById(ref_required1 + '_field').style.borderColor = "red";
						}
						isvalid                                                             = false;
					} else {
						if ( isDesignTools()){
							jQuery('#'+ ref_required1 + '_field').parents('.product-custom-attribute:first').removeClass('error');
						} else {
							document.getElementById(ref_required1 + '_label_div').style.color   = "";
							document.getElementById(ref_required1 + '_field').style.borderColor = "";
						}
					}
			}
		}
		if (!isvalid && typeof script_manage_params.vml_wchffv !== 'undefined') {
			jQuery('#addtocart').addClass('custom_attribute_submit_error');
			if (isDesignTools()) {
				vex.dialog.alert({message: '', input: script_manage_params.vml_wchffv});
			} else {
				alert(script_manage_params.vml_wchffv);
			}
		}
		return isvalid;
	}
}
if (typeof script_manage_params.dcid !== 'undefined' && script_manage_params.dcid) {
	var displayed_category_id = script_manage_params.dcid;
}
//	shop.browse
if (typeof script_manage_params['shop.browse_desc_ord_by'] !== 'undefined' && script_manage_params['shop.browse_desc_ord_by'] == '1') {
	function js_DescOrderBy_click( DescOrderBy_value, elem ) {
		elem = jQuery(elem);
		if (elem.hasClass('orderby_price')) {
			Cookies.set('shop_browse_orderby_price_asc_desc', DescOrderBy_value, {path: '/'});
		} else {
			Cookies.remove('shop_browse_orderby_price_asc_desc', {path: '/'});
		}

		document.order.DescOrderBy.value = DescOrderBy_value;
		document.order.submit();
	}
}

if ( typeof script_manage_params['shop.browse_mf_filt_ch'] !== 'undefined' && script_manage_params['shop.browse_mf_filt_ch'] == '1' ) {
	function js_product_manufacturer_shop_browse_filter_changed( o ) {
		$o = jQuery(o);
		if ($o.parents('.module-param-filter:first').length) {
			js_pexf_load();
			return;
		}
		document.location.href = o.value;

	}
}

if ( typeof script_manage_params['shop.browse_globals'] !== 'undefined' && script_manage_params['shop.browse_globals'] == '1') {

	var script_manage_params_vml = typeof script_manage_params.vml !== 'undefined' ? script_manage_params.vml : '';
	//var Fscript_manage_params_vml = typeof script_manage_params.vml !== 'undefined' ? script_manage_params.vml : '';
	js_global_live_site = typeof script_manage_params.ls !== 'undefined' ? script_manage_params.ls : '';
	js_global_VM_LANG_PEAR_LOG_INFO     = typeof script_manage_params_vml.pli !== 'undefined' ? script_manage_params_vml.pli : '';
	js_global_VM_LANG_PEAR_LOG_ERR      = typeof script_manage_params_vml.ple !== 'undefined' ? script_manage_params_vml.ple : '';
	js_global_VM_LANG_PEAR_LOG_WARNING  = typeof script_manage_params_vml.plw !== 'undefined' ? script_manage_params_vml.plw : '';
	js_global_VM_LANG_PHPSHOP_VALUES_UPDATED_SUCCESSFULLY = typeof script_manage_params_vml.pvus !== 'undefined' ? script_manage_params_vml.pvus : '';
	var tax_rates = [];

	if ( typeof script_manage_params.tr === 'object' ){
		for(var i in script_manage_params.tr) {
			var tax_rate = script_manage_params.tr[i];
			tax_rates[tax_rate.tax_rate_id] = tax_rate.tax_rate;
		}
	}
}

//	template.php, #418
if (typeof script_manage_params.lt !== 'undefined' && script_manage_params.lt != null) {
	var js_itemid               = typeof script_manage_params.lt.iid !== 'undefined' ? script_manage_params.lt.iid : '';
	var js_url                  = typeof script_manage_params.lt.u !== 'undefined' ? script_manage_params.lt.u : '';
	var js_server_request_uri   = typeof script_manage_params.lt.sru !== 'undefined' ? script_manage_params.lt.sru : '';
	if( typeof script_manage_params.lt.pid !== 'undefined' && script_manage_params.lt.pid > 0 ) var js_product_id = script_manage_params.lt.pid;
}

//	template.php, #538
if ( typeof script_manage_params.gac !== 'undefined' && script_manage_params.gac != '') {
	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', script_manage_params.gac]);
	_gaq.push(['_trackPageview']);
	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
}

//	template.php, #974
if ( typeof script_manage_params.onr !== 'undefined' && script_manage_params.onr ) {
	// on ready
	if ( typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled ) {
		jQuery(window).on('load', function () {
			js_add_class_to_last_module( jQuery('#subheader') );
			js_add_class_to_last_module( jQuery('#middle_top') );
			js_add_class_to_last_module( jQuery('#middle_bot') );
			js_add_class_to_last_module( jQuery('#footer_top') );
			js_add_class_to_last_module( jQuery('#pre_footer') );
		});
	} else {
		jQuery(function() {
			js_add_class_to_last_module( jQuery('#subheader') );
			js_add_class_to_last_module( jQuery('#middle_top') );
			js_add_class_to_last_module( jQuery('#middle_bot') );
			js_add_class_to_last_module( jQuery('#footer_top') );
			js_add_class_to_last_module( jQuery('#pre_footer') );
		});
	}

	if( typeof script_manage_params.msl !== 'undefined' && script_manage_params.msl != '' ) {
		var sublvl_t = 0;

		function sort_submenu(menu_rows, cell_width) {
			if(!(jQuery("#tab-menu-tools").length && Cookies.get('admin_view_design') == '0')) {
				jQuery(".mainlevel-nav>li>ul").each(function(){
					var new_menu_html="";
					var total_cells=jQuery(this).find("li").length;
					var menu_cols=Math.ceil(total_cells/menu_rows);
					var curr_cell=1;

					//insert invisible li's to achieve vertical ordering
					for(curr_cell; curr_cell<=menu_rows; curr_cell++)
					{
						for(var i=0; i<menu_cols; i++)
						{
							var tmp_val=i*menu_rows+curr_cell;
							if(i==0 && tmp_val>total_cells)break;
							if(jQuery(this).find("li:nth-child("+tmp_val+")").length)
							{
								new_menu_html= new_menu_html+"<li>"+jQuery(this).find("li:nth-child("+tmp_val+")").html()+"</li>";
							}
							else new_menu_html= new_menu_html+"<li class=\"empty_li\"></li>";
						}
					}
					jQuery(this).html(new_menu_html).wrap('<span class="sublevel-span">');

					//width for the whole ul
					jQuery(this).css({
							'overflow':'hidden',
							'width': (total_cells<=menu_rows) ? (cell_width+1)+'px' : Math.ceil(total_cells/menu_rows)*cell_width+'px'
					});
				});
			}
		}
	}
}

jQuery(function() {
	if ( typeof js_Config_registration_company_skip_email_show_thank_you_vex !== 'undefined' && js_Config_registration_company_skip_email_show_thank_you_vex && typeof URLSearchParams !== 'undefined' ) {
		var urlParams = new URLSearchParams(window.location.search);
		if (urlParams.get('execFunction')) {
			var executeFunction = urlParams.get('execFunction');
			if (typeof window[executeFunction] === 'function') {
				window[executeFunction]();
			}
		}
	}
});
if (is_cs_user()) {
	function js_product_detail_quick_view(productSku) {
		if (typeof productSku !== 'undefined') {
			new AjaxRequest({'productSku' : productSku})
				.setController('Product')
				.setAction('quickViewProduct')
				.onSuccess(function(res){
					console.log(res.data.script);
					console.log(jQuery(res.data.script).html());
					if (typeof jQuery(res.data.script).html() != 'undefined') {
						eval(jQuery(res.data.script).html());
						console.log('eval');
					}
					vex.dialog.open({
						message: 'RÝCHLY NÁHĽAD PRODUKTU',
						input: res.data.html,
						className: 'vex-cs vex-product-quick-view',
						showCloseButton: false
					});
				})
				.send();
		}
	}
}

/* ========================================
 FILE: /includes/js/shop/ps_product_attribute_prod_detail_imgs.js
 ==================== */

(function(){
	script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};
	var params = {
		'ccic': typeof script_manage_params.ccic !== 'undefined' && script_manage_params.ccic
	};

	// pouziej sa metoda zmeny hl. obrazka cez local.js
	if (!params.ccic) {
		//Hide all alternate images that are referenced by attributes
		jQuery(function () {
			main_image_href       = jQuery('.flypage-lightbox-image-a').attr('href');
			main_image_thumb_href = jQuery('.flypage-lightbox-image-a>img').attr('src');
			//Fixes problem when main image is not defined
			if (typeof (main_image_href) != 'undefined') {
				product_image_base = main_image_href.split('/');
				product_image_base = product_image_base[product_image_base.length - 1].split('.');
				delete product_image_base[product_image_base.length - 1];
				product_image_base = product_image_base.join('');
			}
			if (typeof js_prevent_hiding_active_images == 'undefined') {
				jQuery('.product_activeimages_image_div').each(function () {
					var alternate_product_image = jQuery(this).find('a');
					if (!alternate_product_image.length) {
						return true;
					}
					var alternate_product_image_base = alternate_product_image.attr('href').split('/');
					alternate_product_image_base     = alternate_product_image_base[alternate_product_image_base.length - 1].split('.');
					delete alternate_product_image_base[alternate_product_image_base.length - 1];
					alternate_product_image_base = alternate_product_image_base.join('');
					var alternate_attr_val       = alternate_product_image_base.split('_');
					if (alternate_attr_val.length > 1 && typeof ref_attr_value !== 'undefined') {
						alternate_attr_val = alternate_attr_val[alternate_attr_val.length - 1];
						for (attr_val in ref_attr_value) {
							if (ref_attr_value.hasOwnProperty(attr_val)) {
								if ((ref_attr_value[attr_val].toLowerCase() == alternate_attr_val.toLowerCase() || ref_attr_value[attr_val].toLowerCase().replace(/ /gi, '-') == alternate_attr_val.toLowerCase()) && ref_attr_value[attr_val].indexOf('/') == -1) {
									attr_val                     = attr_val.latinise();
									new_ref_attr_value[attr_val] = jQuery(this).find('a').attr('href');
									jQuery(this).hide();
								}
							}
						}
					}
				});
			}
			jQuery('.attr_group_sel_div a').each(function () {
				if (typeof (jQuery(this).attr('id')) == 'undefined') {
					return;
				}
				var attr_val = decodeURIComponent(jQuery(this).attr('id').replace(/--/gi, '%')).split("__");
				if (typeof new_ref_attr_value !== 'undefined' && typeof (new_ref_attr_value[attr_val[1]]) != 'undefined') {
					hover_attr = attr_val[0];
				}
			});
			if (!jQuery('.product_activeimages_image_div img:visible').length) {
				jQuery('.active-images').hide();
			}
		});
		if (typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled) {
			jQuery(window).on('load', function () {
				js_main_img_change_enable();
			});
		} else {
			jQuery(function () {
				js_main_img_change_enable();
			});
		}
	} // end CS_Config_product_attrib_new_display_enabled
	// MAIN CODE --------------------------------------------------
	//set the right product image
	jQuery(function () {
		if (typeof selected_arr == 'undefined') {
			selected_arr = [];
		}

		for (key in selected_arr) {
			if (typeof (new_ref_attr_value[selected_arr[key]]) != 'undefined') {
				jQuery('.flypage-image>a').attr('href', new_ref_attr_value[selected_arr[key]]);
				jQuery('.flypage-image>a>img').attr('src', new_ref_attr_value[selected_arr[key]]);
				break;
			} else {
				jQuery('.flypage-image>a').attr('href', main_image_href);
				jQuery('.flypage-image>a>img').attr('src', main_image_thumb_href);
			}
		}
		// JAN Product last pieces : count quantity on page load
		if (typeof js_last_pieces_html_box == 'function') {
			js_last_pieces_html_box(0);
		}
	});
})();

//function that handles frontend display of attributes
function select_attribute(elem) {
	var first_selected_item = jQuery('.attr_group_sel_div a:first');
	// kontrola, ci nebol hodeny error na varianty ak bol, sa zrusi
	if (first_selected_item.hasClass('tooltipstered')) {
		first_selected_item.tooltipster('destroy');
	}
	if (jQuery('.attr_group_sel_div').length != '0') {
		jQuery('.attr_group_sel_div a').each(function () {
			if (jQuery(this).hasClass('please_choose_variant')) {
				jQuery(this).removeClass('please_choose_variant');
			}
		});
	}
	//get the attr_name:attr_value from current element
	if (typeof (jQuery(elem).attr('id')) == 'undefined') {
		return;
	}
	if (js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED == '') {
		if (jQuery(elem).hasClass('out_of_stock')) {
			jQuery(elem).closest('div.attr_group_sel_div').find('a:not(.disabled_attr):first').click();
			return;
		}
		var tmp_arr = decodeURIComponent(jQuery(elem).attr('id').replace(/--/gi, '%')).split("__");
		//var tmp_arr = decodeURIComponent(jQuery(elem).closest('div.attr_group_sel_div').find('a:not(.disabled_attr):first').attr('id').replace(/--/gi, '%')).split("__");
		//jQuery(elem).closest('div.attr_group_sel_div').find('a:not(.disabled_attr):first').addClass('selected_attr');
	} else {
		var tmp_arr = decodeURIComponent(jQuery(elem).attr('id').replace(/--/gi, '%')).split("__");
	}
	var url = window.location.href;
	if (typeof js_Config_disable_product_variant_hashtag_in_url != 'undefined') {
	} else {
		if (url.indexOf('#') == -1) {
			history.replaceState({}, '', url + '#' + tmp_arr[1].toLowerCase());
		} else {
			history.replaceState({}, '', url.substring(0, url.indexOf('#')) + '#' + tmp_arr[1].toLowerCase());
		}
	}
	//decision based on class of current element
	if (jQuery(elem).hasClass('disabled_attr')) {
		var alert_lang = js_lang_product_attribute_unavailable;
		alert_lang     = alert_lang.replace(/{variant}/g, tmp_arr[0]);
		alert_lang     = alert_lang.replace(/{value}/g, tmp_arr[1]);
		return;
		//selected_arr=[];
	} else if (jQuery(elem).hasClass('out_of_stock')) {
		alert(js_lang_product_attribute_unavailable_2);
		//selected_arr=[];
		return;
	} else if (jQuery(elem).hasClass('not_selectable_attr')) {
		if (jQuery(elem).hasClass('selected_attr')) {
			delete selected_arr[tmp_arr[0]];
		}
		jQuery('.prod_adv_attribs_div:first').find('span.hover_color').remove();	// 4mama color mouseover
		jQuery('.attr_group_sel_label:first span:first').removeAttr('style');
		var clicked        = jQuery(elem).parent().prev().html().replace(/<span>(.*?)<\/span>/g, '') + jQuery(elem).find('span').html();
		var clicked_parent = jQuery(elem).parent().prev().html().replace('<span>', '').replace('</span>', '');
		var other_attribs  = '';
		jQuery('.prod_adv_attribs_div:first .attr_group_sel_label').each(function () {
			var tmp = jQuery(this).html().replace('<span>', '').replace('</span>', '');
			if (tmp != clicked_parent) {
				other_attribs += tmp + ',';
			}
		});
		// 							if (typeof(console) != 'undefined') console.log('"' + other_attribs.substring(0, other_attribs.length-1).split(':')[1] + '"');
		// 							var r=confirm('This attribute combination is not available. Do you want to select this attribute anyway?');
		if (is_cs_user('separate_js')) {
			console.log(1);
			console.log(other_attribs);
		}
		if ((typeof (js_not_selectable_attr_confirm_disable) == 'undefined' || js_not_selectable_attr_confirm_disable != 1) && other_attribs.substring(0, other_attribs.length - 1).split(':')[1].length != 0 && other_attribs.substring(0, other_attribs.length - 1).split(':')[1] != ' ') {
			var conf_text = js_lang_product_attribute_unavailable_3;
			conf_text     = conf_text.replace(/{clicked}/g, clicked);
			conf_text     = conf_text.replace(/{other_attribs}/g, other_attribs.substring(0, other_attribs.length - 1));
			var r         = confirm(conf_text);
			if (r == false) {
				return;
			}
		}
		selected_arr = [];
	}
	selected_arr[tmp_arr[0]] = tmp_arr[1];
	tmp_arr = [];
	//put the available attribute permutations in tmp_arr
	for (arr in ref_array) {
		if (ref_array.hasOwnProperty(arr)) {
			var show_attr = 1;
			for (attr in selected_arr)
				if (typeof (ref_array[arr][attr]) == 'undefined' || ref_array[arr][attr] != selected_arr[attr]) {
					show_attr = 0;
				}
			if (show_attr == 1) {
				tmp_arr.push(ref_array[arr]);
			}
		}
	}
	//this is to make sure that in  tmp_arr is just one entry and it's not out of stock
	var x = [];
	for (arr in tmp_arr) {
		if (tmp_arr[arr].option_unique_id != 'out_of_stock') {
			x.push(tmp_arr[arr]);
			break;
		}
	}
	tmp_arr = [];
	if (x.length > 0) {
		tmp_arr.push(x[0]);
	}
	var plus_one_arr = []; //array for storing attr permutations which can be accessed by changing one value
	for (arr in tmp_arr) {
		jQuery.each(ref_array, function (ref_sub_arr_key, ref_sub_arr) {
			var diff_count = 0;
			jQuery.each(ref_sub_arr, function (ref_attrib_key, ref_attrib) {
				if (typeof (tmp_arr[arr][ref_attrib_key]) == 'undefined' || tmp_arr[arr][ref_attrib_key] != ref_array[ref_sub_arr_key][ref_attrib_key]) {
					diff_count++;
				}
			});
			if (diff_count == 2)//1+1(unique identificator)
			{
				plus_one_arr.push(ref_sub_arr);
			}
		});
	}
	//this is to make sure that in  tmp_arr is just one entry and it's not out of stock
	if (tmp_arr.length == 0) {
		tmp_arr.push(plus_one_arr[0]);
	}
	for (key in tmp_arr[0]) {
		if (tmp_arr[0].hasOwnProperty(key)) {
			if (key != 'option_unique_id' && key != 'availability') {
				selected_arr[key] = tmp_arr[0][key];
			}
		}
	}
	var permutation_found = 0;
	//determine class for each element based on current element clicked
	jQuery('.prod_adv_attribs_div:first .attr_group_sel_div a.attr_sel_a').each(function () {
		if (typeof (jQuery(this).attr('id')) == 'undefined') {
			return;
		}
		if ((typeof js_CS_Config_prod_detail_attribute_img_variant_fix !== 'undefined' && js_CS_Config_prod_detail_attribute_img_variant_fix == 1)) {
			var attr_val = decodeURIComponent(jQuery(this).attr('id').replace(/--/gi, '%')).replace('&amp;', '&').split("__");
		} else {
			var attr_val = decodeURIComponent(jQuery(this).attr('id').replace(/--/gi, '%')).split("__");
		}
		var got_arr = 0;
		//search for selected element
		for (arr in tmp_arr) {
			var got_vals = 1;
			for (key in tmp_arr[arr])
				if (tmp_arr[arr].hasOwnProperty(key)) {
					if (key == attr_val[0] && tmp_arr[arr][key] != attr_val[1]) {
						got_vals = 0;
					}
				}
			if (got_vals == 1) {
				got_arr = 1;
				break;
			}
		}
		//search for 'plus one' elements
		for (arr in plus_one_arr) {
			got_vals = 1;
			for (key in plus_one_arr[arr])
				if (plus_one_arr[arr].hasOwnProperty(key)) {
					if (key == attr_val[0] && plus_one_arr[arr][key] != attr_val[1]) {
						got_vals = 0;
					}
				}
			if (got_vals == 1 && got_arr != 1) {
				got_arr = 2;
			}
		}
		var is_in_glob_arr  = 0;
		var is_out_of_stock = 1;
		//checking if attr permutation is inn ref_array
		for (arr in ref_array)
			if (ref_array.hasOwnProperty(arr)) {
				for (key in ref_array[arr])
					if (ref_array[arr].hasOwnProperty(key)) {
						if (key == attr_val[0] && ref_array[arr][key] == attr_val[1] && ref_array[arr].option_unique_id != 'out_of_stock') {
							is_in_glob_arr = 1;
						}
					}
			}
		//control out of stock for global array
		if (got_arr != 2) {
			for (arr in ref_array)
				if (ref_array.hasOwnProperty(arr)) {
					for (key in ref_array[arr])
						if (ref_array[arr].hasOwnProperty(key)) {
							if (key == attr_val[0] && ref_array[arr][key] == attr_val[1] && ref_array[arr].option_unique_id != 'out_of_stock') {
								is_out_of_stock = 0;
							}
						}
				}
		}
		//control out of stock for plus one array
		if (got_arr == 2) {
			plus_one_arr.push(tmp_arr[0]);
			for (arr in plus_one_arr)
				for (key in plus_one_arr[arr])
					if (plus_one_arr[arr][attr_val[0]] == attr_val[1] && plus_one_arr[arr].option_unique_id != 'out_of_stock') {
						is_out_of_stock = 0;
					}
		}
		if (is_out_of_stock == 1) {
			if (is_in_glob_arr == 0) {
				jQuery(this).addClass('disabled_attr');
			}
			jQuery(this).addClass('out_of_stock');
			jQuery(this).removeClass('not_selectable_attr selected_attr');
		} else {
			jQuery(this).removeClass('out_of_stock');
			if (got_arr == 1) {
				jQuery(this).removeClass('not_selectable_attr');
				jQuery(this).addClass('selected_attr');
				if (!jQuery(this).parents('.attr_group_sel_div').prev().find('span').length) {
					jQuery(this).parents('.attr_group_sel_div').prev().append(' <span>' + attr_val[1] + '</span>');
				} else {
					jQuery(this).parents('.attr_group_sel_div').prev().find('span').html(attr_val[1]);
				}
			} else if (got_arr == 0) {
				jQuery(this).removeClass('selected_attr');
				jQuery(this).addClass('not_selectable_attr');
			} else if (got_arr == 2) {
				jQuery(this).removeClass('selected_attr not_selectable_attr');
			}
		}
	});
	if (typeof (tmp_arr[0]) != 'undefined' && typeof (tmp_arr[0].option_unique_id) != 'undefined') {
		var flypage = jQuery(elem).parents('.flypage1');
		if (flypage.length > 0) {
			flypage.find('.prod_adv_attribs_div:first .attr_select_hidden').val(jQuery('#' + tmp_arr[0].option_unique_id).val()).trigger('change');
			var shop_product_availability_value_elem = flypage.find('.shop_product_availability_value').not(flypage.find('div.flypage-related').find('.shop_product_availability_value')); // .not() exclude pre related products

			if ( (typeof(js_CS_Config_attrib_style_button_change_stoc_avail_fix) !== 'undefined' && js_CS_Config_attrib_style_button_change_stoc_avail_fix == '1') ) {
				shop_product_availability_value_elem.html(ref_array_avail[tmp_arr[0].option_unique_id]).show();
			} else {
				shop_product_availability_value_elem.html(ref_array_avail[tmp_arr[0].option_unique_id]);
			}
			//flypage.find('.shop_product_availability_value').html(ref_array_avail[tmp_arr[0].option_unique_id]);
		} else { // pre pripadne stare shopy kde flypage1 nieje
			jQuery('.prod_adv_attribs_div:first .attr_select_hidden').val(jQuery('#' + tmp_arr[0].option_unique_id).val()).trigger('change');
			jQuery('.shop_product_availability_value').html(ref_array_avail[tmp_arr[0].option_unique_id]);
		}
		//jQuery('.prod_adv_attribs_div:first .attr_select_hidden').val(jQuery('#' + tmp_arr[0]['option_unique_id']).val()).trigger('change');
		//jQuery('.shop_product_availability_value').html(ref_array_avail[tmp_arr[0]['option_unique_id']]);
	}
	// JAN product last pieces html box
	if (typeof js_last_pieces_html_box == 'function') {
		js_last_pieces_html_box(elem);
	}
	return false;
}

function js_main_img_change_enable() {
	var flypage_image = jQuery('.flypage-image>a>img');
	if (js_global_is_csu) {
		if (typeof (console) != 'undefined') {
			console.log('FN: js_main_img_change_enable');
		}
	}

	if (typeof hover_attr == 'undefined') {
		hover_attr = '';
	}

	jQuery('.attr_group_sel_div a[id^="' + hover_attr + '"], .attr_group_sel_div_test a[id^="' + hover_attr + '"]').each(function () {
		if (typeof (jQuery(this).attr('id')) == 'undefined') {
			return;
		}
		var attr_val = decodeURIComponent(jQuery(this).attr('id').replace(/--/gi, '%')).split("__");
		jQuery('.flypage-image>a>img').on('load', function () {
			if (flypage_image.width() != curr_width || flypage_image.height() != curr_height) {
				//console.log(curr_width,jQuery('.flypage-image>a>img').width());
				curr_width  = flypage_image.width();
				curr_height = flypage_image.height();
				if (curr_width > curr_height) {
					jQuery('.flypage-image>a>img').width(main_image_width + 'px');
				} else {
					jQuery('.flypage-image>a>img').height(main_image_height + 'px');
				}
			}
		});
		jQuery(this)
			.on('mouseover', function () {
				// check active image array exists
				var index = null;
				for (color in new_ref_attr_value) {
					if (attr_val[1].toLowerCase().latinise() == color.toLowerCase().latinise()) {
						index = color;
						break;
					}
				}
				if (index != null) {
					jQuery('.flypage-image>a').attr('href', new_ref_attr_value[index]);
					flypage_image.attr('src', new_ref_attr_value[index]);
					flypage_image.on('load', function () {
						//make sure the width/height of product image is correct
						if (flypage_image.width() != curr_width || flypage_image.height() != curr_height) {
							curr_width  = flypage_image.width();
							curr_height = flypage_image.height();
							if (curr_width > curr_height) {
								jQuery('.flypage-image>a>img').width(main_image_width + 'px');
							} else {
								jQuery('.flypage-image>a>img').height(main_image_height + 'px');
							}
						}
					});
				} else {
					jQuery('.flypage-image>a').attr('href', main_image_href);
					jQuery('.flypage-image>a>img').attr('src', main_image_thumb_href);
				}
				jQuery(this).addClass('main_attr_hover');
			})
			.on('mouseout', function () {
				for (key in selected_arr) {
					// check active image array exists
					var index = null;
					for (color in new_ref_attr_value) {
						if (attr_val[1].toLowerCase().latinise() == color.toLowerCase().latinise()) {
							index = color;
							break;
						}
					}
					if (index != null) {
						jQuery('.flypage-image>a').attr('href', new_ref_attr_value[index]);
						jQuery('.flypage-image>a>img').attr('src', new_ref_attr_value[index]);
						break;
					} else {
						jQuery('.flypage-image>a').attr('href', main_image_href);
						jQuery('.flypage-image>a>img').attr('src', main_image_thumb_href);
					}
				}
				jQuery(this).removeClass('main_attr_hover');
			});
	});

	if (typeof js_Config_variant_select_after_load_fix !== 'undefined' && js_Config_variant_select_after_load_fix) {
		var init_elem;
		var variantSelection = jQuery('.attr_group_sel_div');

		if (window.location.href.indexOf('#') > 0) {
			var urlVariant = decodeURIComponent(window.location.href.substr(window.location.href.indexOf('#') + 1)).toLowerCase();

			variantSelection.find('a.attr_sel_a').each(function (index, value) {
				if (decodeURIComponent(jQuery(value).attr('id').replace(/--/gi, '%')).split('__')[1].toLowerCase() === urlVariant) {
					init_elem = jQuery(value);
				}
			});

			init_elem = (typeof init_elem === 'undefined') ? variantSelection.find('.selected_attr') : init_elem;
		} else {
			init_elem = jQuery('.attr_group_sel_div').find('.selected_attr');
		}
	} else {
		var init_elem = jQuery('.attr_group_sel_div').find('.selected_attr');
	}
	select_attribute(init_elem);
}

/* ========================================
 FILE: /includes/js/shop/ps_product_attribute_prod_detail_avail_and_custom.js
 ==================== */

if (typeof originalProductSkuValue === 'undefined') {
	var originalProductSkuValue = [];
}

script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};
var attributeChangeCustomParams = {
	'sil'                 : typeof script_manage_params.sil !== 'undefined' && (script_manage_params.sil == 'true' || script_manage_params.sil == true),
	'VM_PRODUCT_OLD_PRICE': typeof script_manage_params.VM_PRODUCT_OLD_PRICE !== 'undefined' ? script_manage_params.VM_PRODUCT_OLD_PRICE : ''
};

window.addEventListener('DOMContentLoaded', function () {
	attribute_change_custom();
});

function attribute_change_custom() {
	var price_by_product_attribute = typeof js_CS_Config_set_price_by_product_attribute !== 'undefined' && js_CS_Config_set_price_by_product_attribute;

	if (!price_by_product_attribute || ( typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED !== 'undefined' && js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED === 0 ) ) {

		if (typeof js_custom_variant_init_script === 'undefined') {
			if (typeof js_Config_do_not_encode_attribute !== 'undefined' && js_Config_do_not_encode_attribute) {
				var hash = decodeURIComponent(window.location.hash.replace('#', ''));
			} else {
				var hash = encodeURIComponent(window.location.hash.replace('#', ''));
			}

			if (hash === '') {
				let searchUrlParams = new URLSearchParams(window.location.search);

				hash = searchUrlParams.get('var');
			}

			if (hash !== null && hash != '') {
				var select  = jQuery('.prod_adv_attrib_select:first select:first');
				var options = select.find('option');
				var radio = false;

				if (options.length == 0) {
					options = jQuery('.prod_adv_attrib_radio .shop_addtocart_advanced_attribute_buy input');
					radio   = true;
				}
				if (options.length > 0) {
					jQuery.each(options, function (index, option) {
						let $option = jQuery(option);
						var attributes = $option.val();
						if (attributes.includes('[')) {
							attributes = attributes.split('[')[0];
						}
						if (attributes.includes('{')) {
							attributes = attributes.split('{')[0];
						}
						attributes = attributes.split('-');
						if (attributes != '') {
							var key = '';
							jQuery.each(attributes, function (v_index, attribute) {
								if (attribute != '') {
									var attr;
									if (attribute.includes('[')) {
										attr = attribute.split(':')[1].split('[')[0];
									} else if (attribute.includes('{')) {
										attr = attribute.split(':')[1].split('{')[0];
									} else {
										attr = attribute.split(':')[1];
									}
									key += (key != '' ? '-' : '') + attr;
								}
							});

							//key = key.toLowerCase();

							key = key.normalize('NFD').replace(/[\u0300-\u036f]/g, "");

							if (typeof js_Config_do_not_encode_attribute === 'undefined' || !js_Config_do_not_encode_attribute) {
								key = encodeURIComponent(key);
							}

							if (key == hash || (hash.replace(/\+/g, '_').toLowerCase() === key.toLowerCase())) {

								if ( typeof js_Config_product_attribute_settings !== 'undefined' ) {
									var template = js_Config_product_attribute_settings.template || '';
									var selector = js_Config_product_attribute_settings.selector || '';
									var activeAttrClass = js_Config_product_attribute_settings.activeAttrClass || '';

									var $attributeBtn;
									var variants;

									if (template === 'table') {
										$option.prop('selected', true);
										$option.parent().trigger('change');

										if ( $option.val().indexOf('{D=3}') >= 0 ) {
											jQuery('body').addClass('flypage_variant_is_out_of_stock');
										} else {
											jQuery('body').removeClass('flypage_variant_is_out_of_stock');
										}

										$attributeBtn = jQuery('.' + selector + '[value^="' + $option.val() + '"]');

										if (!$attributeBtn.length) {
											let optionClasses = $option.attr('class').split(' ');

											if (optionClasses.length) {
												optionClasses.forEach(function (optionClass) {
													$attributeBtn = jQuery('.' + selector + '.' + optionClass);
													if ($attributeBtn.length) {
														return false;
													}
												});
											}
										}

										if ($attributeBtn.length) {
											$attributeBtn.trigger('click');
											$attributeBtn.closest('[class*="shop_addtocart_advanced_attribute_row_"]').addClass(activeAttrClass);
										}

										js_set_shop_product_detail_avail_value_from_attrib_comb(select);
										customVariantSelectChange(select);
									} else if (template === 'links') {
										if ( selector !== '' && jQuery('.' + selector).length ) {
											var varId = encodeURIComponent($option.html().replace(': ', '__')).replace(/%/g, '--');
											$attributeBtn = jQuery('[id="' + varId + '"]');

											if ($attributeBtn.length > 0) {
												$attributeBtn.trigger('click');
												// TODO - pridat aktivnu classu pre links template
												//$attributeBtn.closest('[class*="shop_addtocart_advanced_attribute_row_"]').addClass('active custom_active');
											}
										}
									} else if (template === 'radio') {
										if (radio) {
											$option.prop('checked', true);
											$option.trigger('click');
										} else {
											$option.prop('selected', true);
										}
									}
								} else if (jQuery('.attr_group_sel_div').length > 0) {
									var var_id = encodeURIComponent($option.html().replace(': ', '__')).replace(/%/g, '--');
									var $varId = jQuery('[id="' + var_id + '"]');

									if ($varId.length > 0) {
										$varId.trigger('click');
									} else {
										if (radio) {
											$option.prop('checked', true);
											$option.trigger('click');
										} else {
											$option.prop('selected', true);
										}
									}
								} else {
									if (radio) {
										$option.prop('checked', true);
										$option.trigger('click');
									} else {
										$option.prop('selected', true);

										$option.closest('select').trigger('change');
									}
								}
							} else {
								if (radio) {
									$option.prop('checked', false);
								} else {
									$option.prop('selected', false);
								}
							}
						}
					});

				}
			} else {
				if ( typeof js_CS_Config_disable_defer_select_attribute === 'undefined' ) {
					if ( typeof js_CS_Config_lighthouse6_opt === 'undefined' ) {
						var refreshIntervalId = setInterval(function () {
							var select = jQuery('.prod_adv_attrib_select:first select:first');
							var radio  = jQuery('.prod_adv_attrib_radio .shop_addtocart_advanced_attribute_buy input:checked');
							//if ( is_cs_user() ) {
							if (typeof js_CS_Config_display_min_max_variant_price === 'undefined') {
								if (select.length > 0) {
									select.trigger('click').trigger('change');
									clearInterval(refreshIntervalId);
								}
								if (radio.length > 0) {
									radio.trigger('click').trigger('change');
									clearInterval(refreshIntervalId);
								}
							}
						}, 100);
					}
				}
			}
		}
	}
	// JAN Product last pieces : count quantity on page load
	if (typeof js_last_pieces_html_box == 'function') {
		js_last_pieces_html_box(0);
	}
	// !!! this function is defined for non_cs_user
	if (typeof js_template_flypage == 'function') {
		js_template_flypage();
	}
	// hook for cs_user and non_cs_user
	if (typeof js_template_flypage2 == 'function') {
		js_template_flypage2();
	}
}

function js_set_shop_product_detail_avail_value_from_attrib_comb(select_element) {
	var doNotRunInBrowse = typeof js_CS_Config_run_script_only_in_product_detail !== 'undefined' && js_CS_Config_run_script_only_in_product_detail && jQuery('.flypage-top').length === 0;

	if ((typeof js_config_set_shop_product_detail_avail_value_from_attrib_comb_disable != 'undefined' && js_config_set_shop_product_detail_avail_value_from_attrib_comb_disable > 0) || doNotRunInBrowse) {
		return false;
	}

	select_element       = jQuery(select_element);
	var attrib_comb_name = '';
	var attrib_position  = '';
	var attrib_comb_id;

	if (select_element.children('option').length != 0 || select_element.attr('type') == 'radio') {
		if (select_element.attr('type') == 'radio') {
			attrib_comb_id   = /attrib_comb_([0-9]+)(\s|$)/.exec(select_element.attr('class'));
			attrib_comb_name = select_element.val().match(/^(.+?)(\{|\[|$)/)[1];
		} else {
			attrib_comb_id   = /attrib_comb_([0-9]+)(\s|$)/.exec(select_element.children('option:selected').attr('class'));
			attrib_comb_name = select_element.children('option:selected').html();

			var $showAttrButtons = jQuery('.show_attr_buttons');
			if ($showAttrButtons.find('span.flypage_attr_button').length > 0) {
				$showAttrButtons.find('span.flypage_attr_button').each(function (k, v) {
					if (jQuery(this).hasClass('active')) {
						attrib_position = k;
					}
				});
			}
			if (attrib_comb_id == null) {
				attrib_comb_id = /attr_id_([0-9]+)(\s|$)/.exec(select_element.children('option:selected').attr('id'));
			}
		}
	} else {
		attrib_comb_id   = /attrib_comb_([0-9]+)(\s|$)/.exec(select_element.attr('class'));
		attrib_comb_name = '';
		select_element.parents('tr:first').find('.shop_addtocart_advanced_attribute_name:first').children('span:first').each(function () {
			jQuery(this).children(':visible').each(function () {
				attrib_comb_name += jQuery(this).text();
			});
		});
	}

	if ( typeof attrib_comb_name === 'undefined' ) {
		attrib_comb_name = '';
	}

	// HOTFIX var product_avail_value_element = jQuery('.flypage1 .flypage-avail .shop_product_availability_value:first');
	var product_avail_value_element, product_in_stock_not_available_element, product_in_stock_available_from_element, product_in_stock_value_element, product_custom_text_element;
	if ( is_cs_user('kc-7949') && jQuery('.vex-product-quick-view .flypage1 .flypage-avail').length > 0 ) {
		var quickViewFlypage = jQuery('.vex-product-quick-view .flypage1');

		product_avail_value_element             = quickViewFlypage.find('.flypage-avail:first .shop_product_availability_value');
		attrib_comb_name                        = attrib_comb_name.replace(/\([^\(*]*$/, '').replace(/\&nbsp;/g, ' ').replace(/_/g, ' ');
		product_in_stock_not_available_element  = quickViewFlypage.find('.flypage-avail:first .prod_in_stock_not_available');
		product_in_stock_available_from_element = quickViewFlypage.find('.flypage-avail:first .prod_in_stock_available_from');
		product_in_stock_value_element          = quickViewFlypage.find('.flypage-avail:first .prod_in_stock_info');
		product_custom_text_element             = quickViewFlypage.find('.flypage-avail:first .flypage-custom-text');
	} else if (jQuery('.flypage1 .flypage-avail').length > 0) {
		product_avail_value_element             = jQuery('.flypage1 .flypage-avail .shop_product_availability_value:first');
		attrib_comb_name                        = attrib_comb_name.replace(/\([^\(*]*$/, '').replace(/\&nbsp;/g, ' ').replace(/_/g, ' ');
		product_in_stock_not_available_element  = jQuery('#middle_content_inner .flypage-avail .prod_in_stock_not_available:first');
		product_in_stock_available_from_element = jQuery('#middle_content_inner .flypage-avail .prod_in_stock_available_from:first');
		product_in_stock_value_element          = jQuery('#middle_content_inner .flypage-avail .prod_in_stock_info:first');
		product_custom_text_element             = jQuery('#middle_content_inner .flypage-avail .flypage-custom-text:first');
	} else {
		product_avail_value_element             = jQuery('.flypage1 .shop_product_availability_value:first');
		attrib_comb_name                        = attrib_comb_name.replace(/\([^\(*]*$/, '').replace(/\&nbsp;/g, ' ').replace(/_/g, ' ');
		product_in_stock_not_available_element  = jQuery('#middle_content_inner .prod_in_stock_not_available:first');
		product_in_stock_available_from_element = jQuery('#middle_content_inner .prod_in_stock_available_from:first');
		product_in_stock_value_element          = jQuery('#middle_content_inner .prod_in_stock_info:first');
		product_custom_text_element             = jQuery('#middle_content_inner .flypage-custom-text:first');
	}

	product_avail_value_element.show();
	product_avail_value_element.prev().show();
	product_in_stock_not_available_element.hide();
	product_in_stock_value_element.hide();

	if (typeof js_CS_Config_vm_product_attributes_use_available_from === 'undefined') {
		product_in_stock_available_from_element.hide();
	}

	if (product_custom_text_element.length != 0) {
		product_custom_text_element.hide();
	}

	if (typeof (attrib_comb_id) !== 'undefined' && attrib_comb_id != null) {
		attrib_comb_id = parseInt(attrib_comb_id[1]);
		// gangstagroup fix pri vybere variantu to davalo hodnotu dostupnosti o jednu vyssiu
		// fix prebehol v ps_product_attribute.php:2810
		// ak by sa zle zobrazovali dostupnosti treba pozriet ci nieje toto navine
		// zmena classy attr_avail_xx
		if (typeof attrib_position !== 'undefined' && attrib_position !== '') {
			attrib_comb_id = parseInt(attrib_position);
		}

		if ( typeof shop_product_details_avail_list !== 'undefined' ) {
			var newAvailId = shop_product_details_avail_list[attrib_comb_id];
		}

		var availClass = product_avail_value_element.attr('class');
		if (typeof availClass !== 'undefined' && typeof newAvailId !== 'undefined' && newAvailId != '') {
			if (availClass.match(/attr_avail_[0-9]+/) == null) {
				newAvailClass = availClass + ' attr_avail_' + newAvailId;
			} else {
				newAvailClass = availClass.replace(/attr_avail_[0-9]+/, 'attr_avail_' + newAvailId);
			}
			product_avail_value_element.attr('class', newAvailClass).show();
		}

		if (typeof (shop_product_details_avail_names_list) != 'undefined' && typeof (shop_product_details_avail_names_list[attrib_comb_id]) != 'undefined' && shop_product_details_avail_names_list[attrib_comb_id] != '') {
			var avail_name = shop_product_details_avail_names_list[attrib_comb_id];

			if ( (typeof(js_CS_Config_prod_details_variant_change_avail_count_fix) !== 'undefined' && js_CS_Config_prod_details_variant_change_avail_count_fix == '1') ) { //variant_change_fix , pozriet related product moze robit problem
				if (jQuery('.flypage1 .flypage-avail').length > 0) {
					jQuery('.flypage1 .flypage-avail .shop_product_availability_value').attr('title',avail_name).html(avail_name);
				} else {
					jQuery('.flypage1 .shop_product_availability_value').not(jQuery('.flypage1').find('div.flypage-related').find('.shop_product_availability_value'));
				}
			} else {
				product_avail_value_element.attr('title', avail_name).html(avail_name);
			}
			jQuery('span.sw_shop_product_availability_value').remove();
			jQuery('span.sw_prod_availability_heading2').remove();
			if (typeof (sw_shop_product_details_avail_names_list) != 'undefined' && typeof (sw_shop_product_details_avail_names_list[attrib_comb_id]) != 'undefined' && sw_shop_product_details_avail_names_list[attrib_comb_id] != '') {
				if (typeof sw_shop_product_details_avail_id_list[attrib_comb_id] !== 'undefined') {
					sw_availClass = 'attr_avail_' + sw_shop_product_details_avail_id_list[attrib_comb_id];
				} else {
					sw_availClass = '';
				}

				console.log(sw_availClass);
				product_avail_value_element.after('<span class="shop_product_availability_value sw_shop_product_availability_value ' + sw_availClass + '">' + sw_shop_product_details_avail_names_list[attrib_comb_id] + '</span>');
				product_avail_value_element.after('<span class="sw_prod_availability_heading2">' + js_lang_availability + ' ' + CS_Config_prod_info_from_switched_db_label + ': </span>');
			}
			if (typeof setProductAvailabilityTime === 'function' && typeof shop_product_details_avail_names_list[attrib_comb_id] !== 'undefined') {
				need_days_variable = parseInt(shop_product_details_avail_days_list[attrib_comb_id]);
				setProductAvailabilityTime();
			}
		} else {  // default

			// JAN poziadavka od TK ak mamedostupnost u variantoch a nic nie je zvolene nema sa zobrazovat dostupnost zakladna nastavena u produktu
			var variant_avails = (typeof shop_product_details_avail_names_list === 'object' && shop_product_details_avail_names_list.length);

			if (!variant_avails && typeof (shop_product_details_avail) != 'undefined' && shop_product_details_avail != '') {
				product_avail_value_element.html(shop_product_details_avail);
			} else {
				product_avail_value_element.hide();
				product_avail_value_element.prev().hide();
			}
		}

		var $prodInStockValue = jQuery('.flypage-avail .prod-in-stock .prod_in_stock_value');
		var prod_in_stock_value_selector;
		if (typeof js_product_in_stock_show_amount !== 'undefined' && js_product_in_stock_show_amount && $prodInStockValue.length > 0) {
			prod_in_stock_value_selector = $prodInStockValue;
		} else {
			$prodInStockValue = jQuery('.flypage1 .prod_in_stock_value');
			if ($prodInStockValue.length > 0 && product_in_stock_value_element.length == 0) {
				prod_in_stock_value_selector = $prodInStockValue;
			} else {
				prod_in_stock_value_selector = product_in_stock_value_element.children('.prod_in_stock_value');
			}
		}

		if (typeof (shop_product_details_in_stock_list) != 'undefined' && typeof (shop_product_details_in_stock_list[attrib_comb_id]) != 'undefined') {
			var in_stock = parseInt(shop_product_details_in_stock_list[attrib_comb_id]);
			var text;
			if (in_stock > 0) {
				text = (typeof (js_prod_detail_stock_text_mode) != 'undefined' && js_prod_detail_stock_text_mode == '1') ? cms_js_lang_yes : in_stock;
				text = typeof (js_lang_prod_detail_in_stock_text_value) != 'undefined' && js_lang_prod_detail_in_stock_text_value != '' ? js_lang_prod_detail_in_stock_text_value : text;
				// palo
				if (isDesignTools()) {
					var ph_product_in_stock             = '';
					var ph_product_in_stock_lang_define = '0';
					if (in_stock == 1) {
						if (typeof (js_lang_product_in_stock_1) != 'undefined') {
							ph_product_in_stock = js_lang_product_in_stock_1;
						} else {
							ph_product_in_stock_lang_define = '1';
						}
					} else if (in_stock < 5) {
						if (typeof (js_lang_product_in_stock_2) != 'undefined') {
							ph_product_in_stock = js_lang_product_in_stock_2;
						} else {
							ph_product_in_stock_lang_define = '1';
						}
					} else {
						if (typeof (js_lang_product_in_stock_5) != 'undefined') {
							ph_product_in_stock = js_lang_product_in_stock_5;
						} else {
							ph_product_in_stock_lang_define = '1';
						}
					}
					if (ph_product_in_stock_lang_define == '0') {
						var phtext;
						if (typeof js_is_color_stock_pieces !== 'undefined' && js_is_color_stock_pieces) {
							phtext = '<span class="amount_val" style="color:red;">' + text + ' </span><span class="amount_text"> ' + ph_product_in_stock + '</span>';
						} else {
							phtext = '<span class="amount_val">' + text + ' </span><span class="amount_text"> ' + ph_product_in_stock + '</span>';
						}
						prod_in_stock_value_selector.html(phtext);
					} else {
						prod_in_stock_value_selector.text(text);
					}
				} else {
					prod_in_stock_value_selector.text(text);
				}

				// pridanie poctu kusov k dostupnosti
				if (typeof js_product_avail_with_stock !== 'undefined' && typeof newAvailId !== 'undefined' && jQuery.inArray(newAvailId, js_product_avail_with_stock) != -1) {
					jQuery('.flypage-avail span.shop_product_availability_value:first').append(' ' + in_stock + ' ' + ph_product_in_stock);
				}

				product_in_stock_value_element.show();
			} else if (typeof js_Config_show_main_stock_instead_of_empty_variant_stock !== 'undefined' && js_Config_show_main_stock_instead_of_empty_variant_stock && isNaN(in_stock) && typeof product_main_stock !== 'undefined') {
				text = product_main_stock;
				prod_in_stock_value_selector.text(text);
			} else {
				text = (typeof (js_prod_detail_stock_text_mode) != 'undefined' && js_prod_detail_stock_text_mode == '1') ? cms_js_lang_no : '0';
				prod_in_stock_value_selector.text(text);
			}

			var $swProdInStockInfo = jQuery('.sw_prod_in_stock_info');

			if ($swProdInStockInfo.length) {
				$swProdInStockInfo.remove();
			}

			if (typeof sw_product_in_stock != 'undefined' && sw_product_in_stock.length && typeof sw_product_in_stock[attrib_comb_id] != 'undefined') {
				if (sw_product_in_stock[attrib_comb_id] < 2) {
					amountText = js_lang_product_in_stock_1;
				} else if (sw_product_in_stock[attrib_comb_id] < 5) {
					amountText = js_lang_product_in_stock_2;
				} else {
					amountText = js_lang_product_in_stock_5;
				}

				jQuery('.flypage-avail .prod_in_stock_info').after('<div class="sw_prod_in_stock_info"></div>');
				$swProdInStockInfo.html('<span class="prod_in_stock_info_lbl" style="font-weight:bold;">' + cms_js_lang_product_detail_in_stock_label + ' ' + CS_Config_prod_info_from_switched_db_label + ': </span><span class="prod_in_stock_value"><span class="amount_val">' + sw_product_in_stock[attrib_comb_id] + ' </span><span class="amount_text"> ' + amountText + '</span><span class="attrib_name"> </span></span>');
			}

			if (attributeChangeCustomParams.sil) {
				var $browseAvail = jQuery('.browse-avail');
				var jqo_stock_info_label = $browseAvail.find('.stock_info_label');
				if (jqo_stock_info_label.length < 1) {
					$browseAvail.append('<div class="stock_info_label"/>');
					jqo_stock_info_label = $browseAvail.find('.stock_info_label');
				}

				if (in_stock > 0) {
					jqo_stock_info_label.text(js_global_PHPSHOP_PRODUCT_FORM_IN_STOCK).addClass('in_stock').removeClass('not_in_stock');
				} else {
					jqo_stock_info_label.text(js_global_PHPSHOP_PRODUCT_FORM_NOT_IN_STOCK).addClass('not_in_stock').removeClass('in_stock');
				}
			}

			var js_cs_config_product_details_do_not_set_first_attrib_to_stock_label = typeof js_cs_config_product_details_do_not_set_first_attrib_to_stock_label !== 'undefined' ? js_cs_config_product_details_do_not_set_first_attrib_to_stock_label : false;
			var product_in_stock_value_text = cms_js_lang_product_detail_in_stock_label;

			if (typeof CS_Config_prod_info_from_switched_db_curShopStockPostLabel !== 'undefined') {
				product_in_stock_value_text += ' ' + CS_Config_prod_info_from_switched_db_curShopStockPostLabel;
			}

			product_in_stock_value_element.children('span:first').text(product_in_stock_value_text + ': ');
			if (attrib_comb_name != '' && !js_cs_config_product_details_do_not_set_first_attrib_to_stock_label) {
				if (typeof js_show_attrib_in_stock_info !== 'undefined' && js_show_attrib_in_stock_info) {
					var append = jQuery('.flypage-avail .prod_in_stock_info_lbl').text().replace(':', ' <span class="attrib_name"> (' + attrib_comb_name + ')</span>:');
					jQuery('.flypage-avail. prod_in_stock_info_lbl').html(append);
				} else {
					product_in_stock_value_element.children('.prod_in_stock_value').append('<span class="attrib_name"> (' + attrib_comb_name + ')</span>');
				}
			}
		}

		if (product_custom_text_element.length != 0 && typeof (shop_product_details_custom_text) != 'undefined' && typeof (shop_product_details_custom_text[attrib_comb_id]) != 'undefined') {
			product_custom_text_element.html(shop_product_details_custom_text[attrib_comb_id]);
			product_custom_text_element.show();
		}
	} else {
		product_avail_value_element.hide();
		product_avail_value_element.prev().hide();
	}

	// custom after load
	if (typeof js_set_shop_product_detail_avail_value_from_attrib_comb_after_init == 'function') {
		js_set_shop_product_detail_avail_value_from_attrib_comb_after_init(select_element);
	}

	if (typeof js_custom_delivery_date == 'function') {
		js_custom_delivery_date(newAvailId);
	}

	if (typeof js_CS_Config_product_lowest_price !== 'undefined') {
		let selected_elm = select_element.is('select') ? select_element.children('option:selected') : select_element;
		let lowest_price = selected_elm.data('lowest-price');
		let lowest_price_elm = jQuery('.lowest_price');

		if (lowest_price && lowest_price_elm.length) {
			lowest_price_elm.find('.lp_val').html(lowest_price.val);

			let lpDiscountPercent = ( lowest_price.perc > 0 ? '+' : '' ) + lowest_price.perc;
			lowest_price_elm.find('.lp_perc').html('(' + lpDiscountPercent + ' %)');

			lowest_price_elm.show();
		} else if (selected_elm.val() !== '') {
			lowest_price_elm.hide();
		}
	}

	var $productAvailability = jQuery('[name="product_availability"]');
	if ($productAvailability.length > 0) {
		var avail_text = jQuery('.flypage-avail .shop_product_availability_value').html();
		if (avail_text != '' && avail_text != null) {
			$productAvailability.val(avail_text);
		}
	}
}

function customVariantSelectChange(select) {
	select = jQuery(select);
	var variantName = select.find(":selected").val().split('[')[0];
	var variantName = variantName.replace(/_/g, ' ');

	if (typeof variantsCustomStocks !== 'undefined') {
		for (var key in variantsCustomStocks[variantName]) {
			customStockNumber = key.replace('S','stock');

			var customStockValue = jQuery('.availability_custom_stocks .'+customStockNumber+' .custom_stock_value');

			customStockValue.text(variantsCustomStocks[variantName][key]['text']);
			customStockValue.removeClass('available_in_custom_stock');
			customStockValue.removeClass('unavailable_in_custom_stock');


			if(variantsCustomStocks[variantName][key]['count'] > 0) {
				jQuery('.availability_custom_stocks .'+customStockNumber+' .custom_stock_value').addClass('available_in_custom_stock');
			} else {
				jQuery('.availability_custom_stocks .'+customStockNumber+' .custom_stock_value').addClass('unavailable_in_custom_stock');
			}
		}
	}
}

function js_set_others_params(selectbox) {
	var $selectbox = jQuery(selectbox);

	if ($selectbox.val() == null) {
		return false;
	}

	if (typeof (set_actual_variant_main_image) != 'undefined' && set_actual_variant_main_image == '1') {
		js_set_actual_variant_main_image($selectbox);
	} // zobrazenie aktuia

	// definovane v local.js
	if (typeof (js_custom_variant_change_function) == 'function') {
		js_custom_variant_change_function($selectbox);
	}

	js_custom_credit_change_function($selectbox);	// zmena kreditu
	js_handle_variant_code_changed($selectbox);	//	zmena CODE
	js_handle_variant_old_price_changed($selectbox);	//	zmena beznej ceny
	js_save_price_changed($selectbox);// zmena usetrite v detaile produktu
	js_set_product_weight($selectbox);	// zmena vahy
	js_set_attribute_info_price_with_coupon_sale($selectbox);
}

function js_set_product_weight(selectbox) {
	if (selectbox.val().indexOf('{W=') == -1) {
		return;
	}

	var variant_weight = selectbox.val().match(/\{W=([^\}]+)\}/)[1] || '';
	if (!js_is_empty(variant_weight)) {
		jQuery('.product_weight_number').html(variant_weight);
	}
}

function js_set_attribute_info_price_with_coupon_sale(selectbox) {
	let attr = selectbox.val().replace(/_/gi, ' ').match(/^[^\[\{]+/);

	if (!attr) {
		return;
	}

	attr = attr[0];

	if (!config('js_attribute_info_price_with_coupon_sale.'+attr+'.product_coupon_discount_price')) {
		return;
	}

	jQuery('.coupon-notlogged-price-value').text(js_attribute_info_price_with_coupon_sale[attr]['product_coupon_discount_price']);
	jQuery('#coupon-notlogged-coupon-code').text(js_attribute_info_price_with_coupon_sale[attr]['coupon_code']);
}

function js_save_price_changed(selectbox) {
	var $savePrice = jQuery('.flypage-cena .save_val');
	var savevalboth = $savePrice.hasClass('type_both');
	var save_val_element = '';
	var old_price_bdph = '';
	var old_price_sdph = '';
	var $oldPrice = jQuery('.flypage-old-price .old-price');

	var $oldPriceWithoutTax = jQuery('.flypage-old-price .old-price-bdph');
	if ($oldPriceWithoutTax.length > 0) {
		old_price_bdph = $oldPriceWithoutTax.text();
	}

	var $oldPriceWithTax = jQuery('.flypage-old-price .old-price-sdph');
	if ($oldPriceWithTax.length > 0) {
		old_price_sdph = $oldPriceWithTax.text();
	}

	var old_price = '';

	if ($oldPrice.length) {
		old_price = $oldPrice.text();
	} else {
		$oldPrice = jQuery('.flypage-prices .old-price');
		if ($oldPrice.length) {
			old_price = $oldPrice.text();
		}
	}

	if ($savePrice.length) {
		save_val_element = '.flypage-cena .save_val';
	} else if (jQuery('.image_container .save_val').length) {
		save_val_element = '.image_container .save_val';
	} else if (jQuery('.flypage-image .flypage-saving-price').length) {
		save_val_element = '.flypage-image .flypage-saving-price';
	} else if ( jQuery('.flypage-right .flypage-saving-price .save_val').length ) {
		save_val_element = '.flypage-right .flypage-saving-price .save_val';
	} else if ( jQuery('.flypage-right .flypage-saving-price').length ) {
		save_val_element = '.flypage-right .flypage-saving-price';
	}

	$savePrice = jQuery(save_val_element);

	if (typeof (a) == 'undefined' || typeof js_old_price_values === 'undefined') {
		js_old_price_values = {
			save_val      : $savePrice.html(),
			old_price     : old_price,
			old_price_sdph: old_price_sdph,
			old_price_bdph: old_price_bdph
		};
	}

	var $actionPriceWithoutTax = jQuery('.akcia-cena-bdph').first();

	if (js_old_price_values.old_price_bdph != '' && $actionPriceWithoutTax.is(':visible') && $oldPriceWithTax.length > 0) {
		js_old_price_values.old_price = js_old_price_values.old_price_bdph;
		$oldPriceWithTax.show();
		$oldPriceWithoutTax.show();
	} else if (js_old_price_values.old_price_bdph != '' && $actionPriceWithoutTax.not(':visible') && $oldPriceWithTax.length > 0) {
		js_old_price_values.old_price = js_old_price_values.old_price_sdph;
		$oldPriceWithTax.show();
		$oldPriceWithoutTax.hide();
	}

	// Variant ma beznu cenu
	var has_old_price   = selectbox.val().indexOf('{OP=') > -1;

	// Niekedy toto nie je definovane (cookiebot?) a pouziva sa to vsade
	if ( typeof shop_currency_info === 'undefined' || typeof shop_currency_info[shop_vendor_currency_code] === 'undefined' ) return;

	var current_curency = shop_currency_info[shop_vendor_currency_code];

	// Aktualna cena
	variant_price = '';
	if (jQuery('.prod_adv_attrib_radio tr').hasClass('active')) {
		var variant_price_text = jQuery('.prod_adv_attrib_radio tr.active .shop_addtocart_advanced_attribute_price').clone().find('.attr_old_price').remove().end().text();
		variant_price = parseFloat(variant_price_text.replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.').replace(/[^\d\.\,]+/g, ''));
		//variant_price = parseFloat(variant_price_text.split(' ')[0].replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.').replace(/[^\d\.\,]+/g, ''));
	} else {
		if (js_old_price_values.old_price_bdph != '' && $actionPriceWithoutTax.is(':visible')) {
			variant_price = parseFloat($actionPriceWithoutTax.text().replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.').replace(/[^\d\.\,]+/g, ''));
		} else {
			if (jQuery('.prod_adv_attribs_div .attr_group_sel_div').length > 0) {
				var s       = jQuery(selectbox).val();
				var regExp  = /\[=([^)]+)\]/;
				var matches = regExp.exec(s);
				if (matches != null && typeof matches[1] !== 'undefined' && matches[1] != '') {
					variant_price = matches[1];

					if (typeof js_global_VM_PRODUCT_ATTRIB_PRICE_VALUES_WITH_TAX != 'undefined' && js_global_VM_PRODUCT_ATTRIB_PRICE_VALUES_WITH_TAX == '') {
						// ak ma shop nastavene ceny variantov bez dph

						if ( typeof js_Config_fix_prices_for_variants != 'undefined' && js_Config_fix_prices_for_variants) {
							//cena získaná zo selectu nie je správna -> v prípade, že mena nesedí , preto cenu vždy predelíme currency
							//shop_vendor_currency_code -> to by mal byť kurz ktorý má zśakazník

							var vendor_currency = 1;

							if (typeof shop_currency_info[shop_vendor_currency_code] != 'undefined') {
								vendor_currency = shop_currency_info[shop_vendor_currency_code]['RATE'];
							}

							variant_price = variant_price * js_product_tax_rate * (current_curency.RATE / vendor_currency);
						} else {
							variant_price = variant_price * js_product_tax_rate * current_curency.RATE;
						}
					}

					//janB fix pre eshopist nenaťahovalo sa správne nastavenie cien pre iné

					if (typeof js_Config_fix_variant_price_not_default_currency != 'undefined' && js_Config_fix_variant_price_not_default_currency) {
						variant_price *= current_curency.RATE;
					}

					/*else {
						variant_price *= current_curency.RATE;
					}*/
					variant_price_text = js_format_Money(variant_price, current_curency.DECIMALS, current_curency.SYMBOL, current_curency['1000_SYMBOL'], current_curency.DEC_SYMBOL);
				} else {
					variant_price = parseFloat(jQuery('#product-detail-price-value').text().replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.').replace(/[^\d\.\,]+/g, ''));
				}
			} else {
				variant_price = parseFloat(jQuery('#product-detail-price-value').text().replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.').replace(/[^\d\.\,]+/g, ''));
			}
		}
	}

	if (typeof js_dual_price_config !== 'undefined') {
		var dualPriceVal = Math.round(variant_price * js_dual_price_config.rate * 100) / 100;

		jQuery('.dual-price-value').html(dualPriceVal + ' ' + js_dual_price_config.symbol);
	}

	// Bezna cena
	var variant_old_price = selectbox.val() != '' && has_old_price ? parseFloat(selectbox.val().match(/\{OP\=([-+]?[0-9]*\.?[0-9]*)\}/)[1]) : (!js_is_empty(js_old_price_values.old_price) ? parseFloat(js_old_price_values.old_price.replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.')) : '');	//	/\{OP\=([-+]?[0-9]*\.?[0-9]*)\}(\s|$)/
	// vyzera to tak, ze v OP su data tahane z db a tak nemaju . a , zamenenu

	var variant_old_price_wo_vat = variant_old_price;

	if (typeof js_global_VM_PRODUCT_ATTRIB_PRICE_VALUES_WITH_TAX !== 'undefined' && js_global_VM_PRODUCT_ATTRIB_PRICE_VALUES_WITH_TAX == '' && typeof js_product_tax_rate !== 'undefined' && has_old_price) {
		variant_old_price = variant_old_price * js_product_tax_rate * parseFloat(current_curency.RATE);
	}

	if (isNaN(variant_old_price) && js_old_price_values.old_price != '' ){
		// pridane kvoli thestreets.sk lebo nemaju nastavenu old price na variantoch ale na produktoch
		variant_old_price = parseFloat(js_old_price_values.old_price.replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.').replace(/[^\d\.\,]+/g, ''));
	}

	if (isNaN(variant_old_price) && !jQuery('.prod_adv_attribs_div .attr_group_sel_div').length) {
		if ( jQuery('.flypage-old-price').length ) {
			var oldPriceWTaxEl  = jQuery('.flypage-old-price').find('.old-price-sdph');
			var oldPriceWoTaxEl = jQuery('.flypage-old-price').find('.old-price-bdph');

			if (oldPriceWoTaxEl.length || oldPriceWTaxEl.length) {
				var showWithTax = js_global_VM_PRODUCT_ATTRIB_PRICE_VALUES_WITH_TAX;
				if (showWithTax) {
					variant_old_price = parseFloat(oldPriceWTaxEl.text().replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.'));
				} else {
					variant_old_price = parseFloat(oldPriceWoTaxEl.text().replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.'));
				}
			} else {
				variant_old_price = parseFloat(jQuery('.flypage-old-price').text().replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.').replace(/[^\d\.\,]+/g, ''));
			}
		}
	}

	// zaokruhlenie na 2 desatine miesta, kedze vznikaju ceny ako 11.750000000000039 co nieje 11.75
	if (config('js_Config_save_price_round_variant_old_price')) {
		variant_old_price = +(Math.round(variant_old_price + "e+2")  + "e-2");
	}

	var showSavingPriceBothSeparately = typeof js_Config_show_saving_price_both_values_separately !== 'undefined';

	var savePriceSumValue = jQuery('.saving_price_value');
	var savePricePercentValue = jQuery('.saving_price_percent');

	var savingPriceValue = 0;
	var savingPricePercent = 0;

	if (variant_old_price > variant_price) {
		savingPriceValue = variant_old_price - variant_price;
		savingPricePercent = savingPriceValue / variant_old_price * 100;
	}

	if (savingPriceValue > 0) {
		if (has_old_price && variant_old_price > variant_price) {
			// variant ma vlastnu beznu cenu
			$oldPrice.html(js_format_Money(variant_old_price, current_curency.DECIMALS, current_curency.SYMBOL, current_curency['1000_SYMBOL'], current_curency.DEC_SYMBOL));
			$oldPriceWithoutTax.html(js_format_Money(variant_old_price_wo_vat, current_curency.DECIMALS, current_curency.SYMBOL, current_curency['1000_SYMBOL'], current_curency.DEC_SYMBOL));
		}

		$savePrice.show();
		jQuery('.flypage-old-price').show();

		var mena, save_value, percentage;

		if (savevalboth || showSavingPriceBothSeparately) {
			var save_html  = '';

			mena = js_old_price_values.old_price.split(' ')[1];

			if(!mena) {
				mena = current_curency.SYMBOL;
			}

			save_value = savingPriceValue.toFixed(2).replace('.', ',');
			percentage = savingPricePercent.toFixed(0).replace('.', ',');

			if (showSavingPriceBothSeparately && savePriceSumValue.length && savePricePercentValue.length) {
				savePriceSumValue.text(save_value + ' ' + mena).show();
				savePricePercentValue.text(percentage + ' %').show();
			} else {
				save_html += '<span class="save_val_sum">' + save_value + ' ' + mena + '</span>';
				save_html += '<span class="save_val_perc">' + percentage + ' %</span>';
				$savePrice.html(save_html);
			}
		} else {
			if (attributeChangeCustomParams.VM_PRODUCT_OLD_PRICE == '3') {
				save_value = js_format_Money(savingPriceValue, current_curency.DECIMALS, current_curency.SYMBOL, current_curency['1000_SYMBOL'], current_curency.DEC_SYMBOL);
				$savePrice.html('<span class="save_lbl">' + js_lang_saving_price_label + ':</span> <span class="save_val">' + save_value + '</span>');
			} else {
				// Usetrite percenta
				percentage = savingPricePercent.toFixed(0).replace('.', ',');

				if (typeof (js_CS_Config_prod_detail_save_price_disp_old_variant) != 'undefined' && js_CS_Config_prod_detail_save_price_disp_old_variant) {
					var save_html_perc = '<span class="save_val">' + percentage + ' %</span>';
					$savePrice.html(save_html_perc);
				}else {
					if ($savePrice.hasClass('save_val')) {
						$savePrice.text(percentage + ' %');
					} else {
						var additionalContent = '';
						var contentElement = $savePrice.find('.save_cstm_string');

						if (contentElement.length) {
							additionalContent = contentElement.prop('outerHTML');
						}

						var save_html_perc = '<span class="save_val">' + percentage + ' %' + additionalContent + '</span>';

						$savePrice.html(save_html_perc);
					}
				}
			}
		}
	} else {
		$savePrice.hide();
		jQuery('.flypage-old-price').hide();

		if (showSavingPriceBothSeparately && savePriceSumValue.length && savePricePercentValue.length) {
			savePriceSumValue.hide();
			savePricePercentValue.hide();
		}
	}

	if (variant_price_text != '') {
		jQuery('#product-detail-price-value').html(variant_price_text);

		if (typeof variant_old_price != 'undefined' && variant_old_price) {
			var variant_old_price_text = js_format_Money(variant_old_price, current_curency.DECIMALS, current_curency.SYMBOL, current_curency['1000_SYMBOL'], current_curency.DEC_SYMBOL);

			jQuery('.flypage-cena span.old-price-sdph').html(variant_old_price_text);
		}
	} else {
		jQuery('.flypage-saving-price, .flypage-old-price').html(jQuery('.prod_adv_attrib_radio tr.active .shop_addtocart_advanced_attribute_price').text().split(' ')[0].replace('.', '').replace(',', '.'));
	}
}

function js_handle_variant_code_changed(jso) {
	if (typeof js_attr_table_mod !== 'undefined' && js_attr_table_mod) {
		return;
	}

	if (typeof (js_handle_variant_code_changed_disabled) != 'undefined' && js_handle_variant_code_changed_disabled) {
		return false;
	}

	// ak ma viariant nastavene zobrazovanie kodu produktu a aj kodu variantu
	if (jQuery('.flypage_variant_sku').length != 0) {
		return;
	}
	if (jQuery('.flypage_sku .product_sku_value_old').length == 0) {
		jQuery('.flypage_sku').append('<span class="product_sku_value_old hide">' + jQuery('.product_sku_value').text() + '</span>');
	}
	var jqo                   = jQuery(jso);
	var jqo_product_sku_value = jQuery('#middle .flypage1 .product_sku_value');
	originalProductSkuValue.push(jqo_product_sku_value);
	if (jqo_product_sku_value.length > 0) {
		if (jqo.data('orig_product_sku_value') == null) {
			jqo.data('orig_product_sku_value', jqo_product_sku_value.html());
		}
		var curr_val  = jqo.val();
		var curr_code = '';
		if (curr_val != '' && curr_val !== null) {
			var curr_code_matches = curr_val.match(/\{CODE\=([^\}]+)\}/);
			if (curr_code_matches != null) {
				curr_code = curr_code_matches[1];
			}
		}
		if (curr_code == '') {
			curr_code = jqo.data('orig_product_sku_value');
		}
		curr_code = curr_code.replace('_', ' ');
		jqo_product_sku_value.html(curr_code);
	}
}

function js_handle_variant_old_price_changed(jso) {
	if (typeof (js_prod_attr_old_price) === 'undefined' || !js_prod_attr_old_price) {
		return;
	}
	var jqo                         = jQuery(jso);
	var jqo_product_old_price_value = jQuery('#middle .flypage1 .flypage-cena .old-price');
	if (jqo_product_old_price_value.length < 1) {
		jqo_product_old_price_value = jQuery('#middle .flypage1 .flypage-prices').find('.old-price');
	}

	if (jqo_product_old_price_value.length > 0) {
		if (jqo.data('orig_product_old_price_value') == null) {
			jqo.data('orig_product_old_price_value', jqo_product_old_price_value.html());
		}

		curr_code = jqo.data('orig_product_old_price_value');

		if (typeof (js_op_list) != 'undefined' && js_op_list != null && typeof (js_list) != 'undefined' && js_list != null) {
			//	ak je to select ktory ma 1. polozku len vyberovu (prazdnu) a zaroven je vybrana ina ako tato vyberova (prazdna)
			//	vtedy musime odpocitavat poziciu
			var sel_opt_offset = jqo.children('option:first').val() == '' && jqo.get(0).selectedIndex > 0 ? 1 : 0;
			var current_curency = shop_currency_info[shop_vendor_currency_code];

			var price1;
			if (typeof js_op_list[jqo.get(0).selectedIndex - sel_opt_offset] !== 'undefined') {
				price1 = parseFloat(js_op_list[jqo.get(0).selectedIndex - sel_opt_offset].replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.'));
			} else {
				price1 = '';
			}

			var price2;
			if (typeof js_list[jqo.get(0).selectedIndex - sel_opt_offset] !== 'undefined') {
				price2 = parseFloat(js_list[jqo.get(0).selectedIndex - sel_opt_offset].replace(current_curency['1000_SYMBOL'], '').replace(current_curency.DEC_SYMBOL, '.'));
			} else {
				price2 = '';
			}

			if (jqo.get(0).selectedIndex <= js_op_list.length && js_op_list[jqo.get(0).selectedIndex - sel_opt_offset] != '' && jqo.get(0).selectedIndex <= js_list.length && js_list[jqo.get(0).selectedIndex - sel_opt_offset] != '' && price1 > price2) {
				//curr_code = jqo.get(0).selectedIndex-sel_opt_offset;
				curr_code = js_op_list[jqo.get(0).selectedIndex - sel_opt_offset];
				//curr_code = js_op_list[jqo.get(0).selectedIndex-sel_opt_offset].replace(current_curency['1000_SYMBOL'],'').replace(current_curency['DEC_SYMBOL'],'.');
			}
		}

		if (curr_code == '') {
			curr_code = jqo.data('orig_product_old_price_value');
		}

		jqo_product_old_price_value.html(curr_code);
	}
}

function js_custom_credit_change_function(selectbox) {
	var $selectbox = jQuery(selectbox);
	if (typeof (js_global_product_credit_value) == 'undefined' || typeof (js_global_product_variants_credit_json) == 'undefined' || jQuery('.credit_val').length == 0) {
		return false;
	}
	var credit_value = js_global_product_credit_value;
	var credit_index = $selectbox.val().replace(/_/gi, ' ').match(/^[^\[\{]+/) || '';
// 	if (typeof(console) != 'undefined') console.log('credit_index', credit_index);
	if (credit_index != '' && typeof credit_index !== 'object' && typeof (js_global_product_variants_credit_json[credit_index]) && typeof (js_global_product_variants_credit_json[credit_index].credit_value) != 'undefined') {
		credit_value = js_global_product_variants_credit_json[credit_index].credit_value;
	}
	var credit_text = '';
	if (credit_value < 1 || credit_value > 4) {
		credit_text = js_global_PHPSHOP_PRODUCT_INCR_CREDIT_BY_PURCHASE_TEXT;
	}
	if (credit_value > 1 && credit_value < 5) {
		credit_text = js_global_PHPSHOP_PRODUCT_INCR_CREDIT_BY_PURCHASE_TEXT_5;
	}
	if (credit_value == '1') {
		credit_text = js_global_PHPSHOP_PRODUCT_INCR_CREDIT_BY_PURCHASE_TEXT_1;
	}
	if (credit_text == '') {
		if (typeof (console) != 'undefined') {
			console.log('ERR: credit_text');
		}
		return false;
	}
	jQuery('.product_credit_amount').html(credit_text.replace('%s', credit_value));
}

function js_set_actual_variant_main_image(selectbox) {
	selectbox     = jQuery(selectbox);
	var img_index     = selectbox.find('option:selected').attr('id');
	var flypage_img_a = jQuery('.flypage-image a');
	var flypage_img   = jQuery('.flypage-image a img');
	if (selectbox.data('main_flypage_image_src') == null) {
		selectbox.data('main_flypage_image_src', flypage_img.attr('src'));
	}
	if (selectbox.data('main_flypage_a_href') == null) {
		selectbox.data('main_flypage_a_href', flypage_img.parents('a:first').attr('href'));
	}
	if (typeof (img_index) != 'undefined' && typeof (ref_array_imgs) != 'undefined' && typeof (ref_array_imgs[img_index]) != 'undefined' && ref_array_imgs[img_index] != '') {
		// isset variant image
		flypage_img_a.attr('href', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index]);
		if ( typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled ) {
			flypage_img.attr('src', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index].replace('(', '%28').replace(')', '%29'));
		} else {
			flypage_img.attr('src', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index]);
		}
		main_image_href = main_image_thumb_href = js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index];
		flypage_img_a.data({href: main_image_href, src: main_image_href});
		// fancybox option je potrebne zmenit, lebo je tam nastaveny povodny img produktu
		if (typeof flypage_img_a.attr('data-fancybox') !== 'undefined') {
			var data_options = {
				'thumb': main_image_href,
				'src'  : main_image_href,
				'type' : 'image'
			};
			flypage_img_a.attr('data-options', JSON.stringify(data_options));
			flypage_img_a.data().options = JSON.stringify(data_options);
		}
		if (typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled) {
			if ( typeof flypage_img[0] !== 'undefined' && flypage_img[0].hasAttribute('data-srcset') ) {
				flypage_img.attr('data-srcset', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index].replace('%', '%25'));
				flypage_img.attr('srcset', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index].replace('%', '%25'));
				if ( (is_cs_user('js_opts') || is_cs_user('csu-parser')) ) {
					if ( jQuery('.product_activeimages_attr.' + img_index).length ) {
						var attrId = Number(img_index.match(/attr_id_([0-9])/)[1]) + 1;
						flypage_img.parent('a[data-fancybox^="gallery"]').attr('data-fancybox', 'gallery' + attrId);
					} else {
						flypage_img.parent('a[data-fancybox^="gallery"]').attr('data-fancybox', 'gallery');
					}
				}
			} else if ( typeof flypage_img[0] !== 'undefined' && flypage_img[0].hasAttribute('longdesc') ) {

				flypage_img.attr('longdesc', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index]);
			}
		} else {
			if ( typeof flypage_img[0] !== 'undefined' && flypage_img[0].hasAttribute('data-srcset') ) {
				flypage_img.attr('data-srcset', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index]);
				flypage_img.attr('srcset', js_global_skvelyweb_site + '/images/shop-active-images/' + ref_array_imgs[img_index]);
			}
		}
	} else {
		// set the default product thumb image
		flypage_img_a.attr('href', selectbox.data('main_flypage_a_href'));
		flypage_img.attr('src', selectbox.data('main_flypage_image_src'));
	}
}

function js_set_variant_into_url(selectbox) {
	let $selectbox = jQuery(selectbox);
	let variant = decodeURIComponent($selectbox.val()).split('{')[0].split(':');
	let url = window.location.href;

	if (typeof variant === 'undefined' || typeof variant[1] === 'undefined') {
		return false;
	}

	// fix ak ma variant cenu
	if (variant[1]) {
		variant[1] = variant[1].split('[')[0];
	}

	//hash predstavoval lovercase a ten nechceme
	if (url.indexOf('#') == -1) {
		history.replaceState({}, '', url + '#' + variant[1]);
	} else {
		history.replaceState({}, '', url.substring(0, url.indexOf('#')) + '#' + variant[1]);
	}
}

function setVariantUrlParam(selectbox) {
	let $selectbox = jQuery(selectbox);
	let variant = decodeURIComponent($selectbox.val()).split('{')[0].split(':');
	let href = window.location.origin + window.location.pathname;
	let urlSearchParams = new URLSearchParams(window.location.search);

	if (typeof variant === 'undefined' || typeof variant[1] === 'undefined') {
		return false;
	}

	if (variant[1]) {
		variant[1] = variant[1].split('[')[0];
	}

	urlSearchParams.set('var', variant[1]);
	history.replaceState({}, '', href + '?' + urlSearchParams.toString() + window.location.hash);
}


/* ========================================
 FILE: /includes/js/jquery/slick/slick.min.js
 ==================== */

/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/

 Version: 1.6.0
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues

 */
!function(i){"use strict";"function"==typeof define&&define.amd?define(["jquery"],i):"undefined"!=typeof exports?module.exports=i(require("jquery")):i(jQuery)}(function(i){"use strict";var e=window.Slick||{};e=function(){function e(e,o){var s,n=this;n.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:i(e),appendDots:i(e),arrows:!0,asNavFor:null,prevArrow:'<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">Previous</button>',nextArrow:'<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">Next</button>',autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(e,t){return i('<button type="button" data-role="none" role="button" tabindex="0" />').text(t+1)},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",mobileFirst:!1,pauseOnHover:!0,pauseOnFocus:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rows:1,rtl:!1,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,useTransform:!0,variableWidth:!1,vertical:!1,verticalSwiping:!1,waitForAnimate:!0,zIndex:1e3},n.initials={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:!1,slideOffset:0,swipeLeft:null,$list:null,touchObject:{},transformsEnabled:!1,unslicked:!1},i.extend(n,n.initials),n.activeBreakpoint=null,n.animType=null,n.animProp=null,n.breakpoints=[],n.breakpointSettings=[],n.cssTransitions=!1,n.focussed=!1,n.interrupted=!1,n.hidden="hidden",n.paused=!0,n.positionProp=null,n.respondTo=null,n.rowCount=1,n.shouldClick=!0,n.$slider=i(e),n.$slidesCache=null,n.transformType=null,n.transitionType=null,n.visibilityChange="visibilitychange",n.windowWidth=0,n.windowTimer=null,s=i(e).data("slick")||{},n.options=i.extend({},n.defaults,o,s),n.currentSlide=n.options.initialSlide,n.originalSettings=n.options,"undefined"!=typeof document.mozHidden?(n.hidden="mozHidden",n.visibilityChange="mozvisibilitychange"):"undefined"!=typeof document.webkitHidden&&(n.hidden="webkitHidden",n.visibilityChange="webkitvisibilitychange"),n.autoPlay=i.proxy(n.autoPlay,n),n.autoPlayClear=i.proxy(n.autoPlayClear,n),n.autoPlayIterator=i.proxy(n.autoPlayIterator,n),n.changeSlide=i.proxy(n.changeSlide,n),n.clickHandler=i.proxy(n.clickHandler,n),n.selectHandler=i.proxy(n.selectHandler,n),n.setPosition=i.proxy(n.setPosition,n),n.swipeHandler=i.proxy(n.swipeHandler,n),n.dragHandler=i.proxy(n.dragHandler,n),n.keyHandler=i.proxy(n.keyHandler,n),n.instanceUid=t++,n.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,n.registerBreakpoints(),n.init(!0)}var t=0;return e}(),e.prototype.activateADA=function(){var i=this;null!==i.$slideTrack&&i.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},e.prototype.addSlide=e.prototype.slickAdd=function(e,t,o){var s=this;if("boolean"==typeof t)o=t,t=null;else if(0>t||t>=s.slideCount)return!1;s.unload(),"number"==typeof t?0===t&&0===s.$slides.length?i(e).appendTo(s.$slideTrack):o?i(e).insertBefore(s.$slides.eq(t)):i(e).insertAfter(s.$slides.eq(t)):o===!0?i(e).prependTo(s.$slideTrack):i(e).appendTo(s.$slideTrack),s.$slides=s.$slideTrack.children(this.options.slide),s.$slideTrack.children(this.options.slide).detach(),s.$slideTrack.append(s.$slides),s.$slides.each(function(e,t){i(t).attr("data-slick-index",e)}),s.$slidesCache=s.$slides,s.reinit()},e.prototype.animateHeight=function(){var i=this;if(1===i.options.slidesToShow&&i.options.adaptiveHeight===!0&&i.options.vertical===!1){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.animate({height:e},i.options.speed)}},e.prototype.animateSlide=function(e,t){var o={},s=this;s.animateHeight(),s.options.rtl===!0&&s.options.vertical===!1&&(e=-e),s.transformsEnabled===!1?s.options.vertical===!1?s.$slideTrack.animate({left:e},s.options.speed,s.options.easing,t):s.$slideTrack.animate({top:e},s.options.speed,s.options.easing,t):s.cssTransitions===!1?(s.options.rtl===!0&&(s.currentLeft=-s.currentLeft),i({animStart:s.currentLeft}).animate({animStart:e},{duration:s.options.speed,easing:s.options.easing,step:function(i){i=Math.ceil(i),s.options.vertical===!1?(o[s.animType]="translate("+i+"px, 0px)",s.$slideTrack.css(o)):(o[s.animType]="translate(0px,"+i+"px)",s.$slideTrack.css(o))},complete:function(){t&&t.call()}})):(s.applyTransition(),e=Math.ceil(e),s.options.vertical===!1?o[s.animType]="translate3d("+e+"px, 0px, 0px)":o[s.animType]="translate3d(0px,"+e+"px, 0px)",s.$slideTrack.css(o),t&&setTimeout(function(){s.disableTransition(),t.call()},s.options.speed))},e.prototype.getNavTarget=function(){var e=this,t=e.options.asNavFor;return t&&null!==t&&(t=i(t).not(e.$slider)),t},e.prototype.asNavFor=function(e){var t=this,o=t.getNavTarget();null!==o&&"object"==typeof o&&o.each(function(){var t=i(this).slick("getSlick");t.unslicked||t.slideHandler(e,!0)})},e.prototype.applyTransition=function(i){var e=this,t={};e.options.fade===!1?t[e.transitionType]=e.transformType+" "+e.options.speed+"ms "+e.options.cssEase:t[e.transitionType]="opacity "+e.options.speed+"ms "+e.options.cssEase,e.options.fade===!1?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.autoPlay=function(){var i=this;i.autoPlayClear(),i.slideCount>i.options.slidesToShow&&(i.autoPlayTimer=setInterval(i.autoPlayIterator,i.options.autoplaySpeed))},e.prototype.autoPlayClear=function(){var i=this;i.autoPlayTimer&&clearInterval(i.autoPlayTimer)},e.prototype.autoPlayIterator=function(){var i=this,e=i.currentSlide+i.options.slidesToScroll;i.paused||i.interrupted||i.focussed||(i.options.infinite===!1&&(1===i.direction&&i.currentSlide+1===i.slideCount-1?i.direction=0:0===i.direction&&(e=i.currentSlide-i.options.slidesToScroll,i.currentSlide-1===0&&(i.direction=1))),i.slideHandler(e))},e.prototype.buildArrows=function(){var e=this;e.options.arrows===!0&&(e.$prevArrow=i(e.options.prevArrow).addClass("slick-arrow"),e.$nextArrow=i(e.options.nextArrow).addClass("slick-arrow"),e.slideCount>e.options.slidesToShow?(e.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.prependTo(e.options.appendArrows),e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.appendTo(e.options.appendArrows),e.options.infinite!==!0&&e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):e.$prevArrow.add(e.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},e.prototype.buildDots=function(){var e,t,o=this;if(o.options.dots===!0&&o.slideCount>o.options.slidesToShow){for(o.$slider.addClass("slick-dotted"),t=i("<ul />").addClass(o.options.dotsClass),e=0;e<=o.getDotCount();e+=1)t.append(i("<li />").append(o.options.customPaging.call(this,o,e)));o.$dots=t.appendTo(o.options.appendDots),o.$dots.find("li").first().addClass("slick-active").attr("aria-hidden","false")}},e.prototype.buildOut=function(){var e=this;e.$slides=e.$slider.children(e.options.slide+":not(.slick-cloned)").addClass("slick-slide"),e.slideCount=e.$slides.length,e.$slides.each(function(e,t){i(t).attr("data-slick-index",e).data("originalStyling",i(t).attr("style")||"")}),e.$slider.addClass("slick-slider"),e.$slideTrack=0===e.slideCount?i('<div class="slick-track"/>').appendTo(e.$slider):e.$slides.wrapAll('<div class="slick-track"/>').parent(),e.$list=e.$slideTrack.wrap('<div aria-live="polite" class="slick-list"/>').parent(),e.$slideTrack.css("opacity",0),(e.options.centerMode===!0||e.options.swipeToSlide===!0)&&(e.options.slidesToScroll=1),i("img[data-lazy]",e.$slider).not("[src]").addClass("slick-loading"),e.setupInfinite(),e.buildArrows(),e.buildDots(),e.updateDots(),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.options.draggable===!0&&e.$list.addClass("draggable")},e.prototype.buildRows=function(){var i,e,t,o,s,n,r,l=this;if(o=document.createDocumentFragment(),n=l.$slider.children(),l.options.rows>1){for(r=l.options.slidesPerRow*l.options.rows,s=Math.ceil(n.length/r),i=0;s>i;i++){var a=document.createElement("div");for(e=0;e<l.options.rows;e++){var d=document.createElement("div");for(t=0;t<l.options.slidesPerRow;t++){var c=i*r+(e*l.options.slidesPerRow+t);n.get(c)&&d.appendChild(n.get(c))}a.appendChild(d)}o.appendChild(a)}l.$slider.empty().append(o),l.$slider.children().children().children().css({width:100/l.options.slidesPerRow+"%",display:"inline-block"})}},e.prototype.checkResponsive=function(e,t){var o,s,n,r=this,l=!1,a=r.$slider.width(),d=window.innerWidth||i(window).width();if("window"===r.respondTo?n=d:"slider"===r.respondTo?n=a:"min"===r.respondTo&&(n=Math.min(d,a)),r.options.responsive&&r.options.responsive.length&&null!==r.options.responsive){s=null;for(o in r.breakpoints)r.breakpoints.hasOwnProperty(o)&&(r.originalSettings.mobileFirst===!1?n<r.breakpoints[o]&&(s=r.breakpoints[o]):n>r.breakpoints[o]&&(s=r.breakpoints[o]));null!==s?null!==r.activeBreakpoint?(s!==r.activeBreakpoint||t)&&(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),e===!0&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),e===!0&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):null!==r.activeBreakpoint&&(r.activeBreakpoint=null,r.options=r.originalSettings,e===!0&&(r.currentSlide=r.options.initialSlide),r.refresh(e),l=s),e||l===!1||r.$slider.trigger("breakpoint",[r,l])}},e.prototype.changeSlide=function(e,t){var o,s,n,r=this,l=i(e.currentTarget);switch(l.is("a")&&e.preventDefault(),l.is("li")||(l=l.closest("li")),n=r.slideCount%r.options.slidesToScroll!==0,o=n?0:(r.slideCount-r.currentSlide)%r.options.slidesToScroll,e.data.message){case"previous":s=0===o?r.options.slidesToScroll:r.options.slidesToShow-o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide-s,!1,t);break;case"next":s=0===o?r.options.slidesToScroll:o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide+s,!1,t);break;case"index":var a=0===e.data.index?0:e.data.index||l.index()*r.options.slidesToScroll;r.slideHandler(r.checkNavigable(a),!1,t),l.children().trigger("focus");break;default:return}},e.prototype.checkNavigable=function(i){var e,t,o=this;if(e=o.getNavigableIndexes(),t=0,i>e[e.length-1])i=e[e.length-1];else for(var s in e){if(i<e[s]){i=t;break}t=e[s]}return i},e.prototype.cleanUpEvents=function(){var e=this;e.options.dots&&null!==e.$dots&&i("li",e.$dots).off("click.slick",e.changeSlide).off("mouseenter.slick",i.proxy(e.interrupt,e,!0)).off("mouseleave.slick",i.proxy(e.interrupt,e,!1)),e.$slider.off("focus.slick blur.slick"),e.options.arrows===!0&&e.slideCount>e.options.slidesToShow&&(e.$prevArrow&&e.$prevArrow.off("click.slick",e.changeSlide),e.$nextArrow&&e.$nextArrow.off("click.slick",e.changeSlide)),e.$list.off("touchstart.slick mousedown.slick",e.swipeHandler),e.$list.off("touchmove.slick mousemove.slick",e.swipeHandler),e.$list.off("touchend.slick mouseup.slick",e.swipeHandler),e.$list.off("touchcancel.slick mouseleave.slick",e.swipeHandler),e.$list.off("click.slick",e.clickHandler),i(document).off(e.visibilityChange,e.visibility),e.cleanUpSlideEvents(),e.options.accessibility===!0&&e.$list.off("keydown.slick",e.keyHandler),e.options.focusOnSelect===!0&&i(e.$slideTrack).children().off("click.slick",e.selectHandler),i(window).off("orientationchange.slick.slick-"+e.instanceUid,e.orientationChange),i(window).off("resize.slick.slick-"+e.instanceUid,e.resize),i("[draggable!=true]",e.$slideTrack).off("dragstart",e.preventDefault),i(window).off("load.slick.slick-"+e.instanceUid,e.setPosition),i(document).off("ready.slick.slick-"+e.instanceUid,e.setPosition)},e.prototype.cleanUpSlideEvents=function(){var e=this;e.$list.off("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.off("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.cleanUpRows=function(){var i,e=this;e.options.rows>1&&(i=e.$slides.children().children(),i.removeAttr("style"),e.$slider.empty().append(i))},e.prototype.clickHandler=function(i){var e=this;e.shouldClick===!1&&(i.stopImmediatePropagation(),i.stopPropagation(),i.preventDefault())},e.prototype.destroy=function(e){var t=this;t.autoPlayClear(),t.touchObject={},t.cleanUpEvents(),i(".slick-cloned",t.$slider).detach(),t.$dots&&t.$dots.remove(),t.$prevArrow&&t.$prevArrow.length&&(t.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.prevArrow)&&t.$prevArrow.remove()),t.$nextArrow&&t.$nextArrow.length&&(t.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.nextArrow)&&t.$nextArrow.remove()),t.$slides&&(t.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){i(this).attr("style",i(this).data("originalStyling"))}),t.$slideTrack.children(this.options.slide).detach(),t.$slideTrack.detach(),t.$list.detach(),t.$slider.append(t.$slides)),t.cleanUpRows(),t.$slider.removeClass("slick-slider"),t.$slider.removeClass("slick-initialized"),t.$slider.removeClass("slick-dotted"),t.unslicked=!0,e||t.$slider.trigger("destroy",[t])},e.prototype.disableTransition=function(i){var e=this,t={};t[e.transitionType]="",e.options.fade===!1?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.fadeSlide=function(i,e){var t=this;t.cssTransitions===!1?(t.$slides.eq(i).css({zIndex:t.options.zIndex}),t.$slides.eq(i).animate({opacity:1},t.options.speed,t.options.easing,e)):(t.applyTransition(i),t.$slides.eq(i).css({opacity:1,zIndex:t.options.zIndex}),e&&setTimeout(function(){t.disableTransition(i),e.call()},t.options.speed))},e.prototype.fadeSlideOut=function(i){var e=this;e.cssTransitions===!1?e.$slides.eq(i).animate({opacity:0,zIndex:e.options.zIndex-2},e.options.speed,e.options.easing):(e.applyTransition(i),e.$slides.eq(i).css({opacity:0,zIndex:e.options.zIndex-2}))},e.prototype.filterSlides=e.prototype.slickFilter=function(i){var e=this;null!==i&&(e.$slidesCache=e.$slides,e.unload(),e.$slideTrack.children(this.options.slide).detach(),e.$slidesCache.filter(i).appendTo(e.$slideTrack),e.reinit())},e.prototype.focusHandler=function(){var e=this;e.$slider.off("focus.slick blur.slick").on("focus.slick blur.slick","*:not(.slick-arrow)",function(t){t.stopImmediatePropagation();var o=i(this);setTimeout(function(){e.options.pauseOnFocus&&(e.focussed=o.is(":focus"),e.autoPlay())},0)})},e.prototype.getCurrent=e.prototype.slickCurrentSlide=function(){var i=this;return i.currentSlide},e.prototype.getDotCount=function(){var i=this,e=0,t=0,o=0;if(i.options.infinite===!0)for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else if(i.options.centerMode===!0)o=i.slideCount;else if(i.options.asNavFor)for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else o=1+Math.ceil((i.slideCount-i.options.slidesToShow)/i.options.slidesToScroll);return o-1},e.prototype.getLeft=function(i){var e,t,o,s=this,n=0;return s.slideOffset=0,t=s.$slides.first().outerHeight(!0),s.options.infinite===!0?(s.slideCount>s.options.slidesToShow&&(s.slideOffset=s.slideWidth*s.options.slidesToShow*-1,n=t*s.options.slidesToShow*-1),s.slideCount%s.options.slidesToScroll!==0&&i+s.options.slidesToScroll>s.slideCount&&s.slideCount>s.options.slidesToShow&&(i>s.slideCount?(s.slideOffset=(s.options.slidesToShow-(i-s.slideCount))*s.slideWidth*-1,n=(s.options.slidesToShow-(i-s.slideCount))*t*-1):(s.slideOffset=s.slideCount%s.options.slidesToScroll*s.slideWidth*-1,n=s.slideCount%s.options.slidesToScroll*t*-1))):i+s.options.slidesToShow>s.slideCount&&(s.slideOffset=(i+s.options.slidesToShow-s.slideCount)*s.slideWidth,n=(i+s.options.slidesToShow-s.slideCount)*t),s.slideCount<=s.options.slidesToShow&&(s.slideOffset=0,n=0),s.options.centerMode===!0&&s.options.infinite===!0?s.slideOffset+=s.slideWidth*Math.floor(s.options.slidesToShow/2)-s.slideWidth:s.options.centerMode===!0&&(s.slideOffset=0,s.slideOffset+=s.slideWidth*Math.floor(s.options.slidesToShow/2)),e=s.options.vertical===!1?i*s.slideWidth*-1+s.slideOffset:i*t*-1+n,s.options.variableWidth===!0&&(o=s.slideCount<=s.options.slidesToShow||s.options.infinite===!1?s.$slideTrack.children(".slick-slide").eq(i):s.$slideTrack.children(".slick-slide").eq(i+s.options.slidesToShow),e=s.options.rtl===!0?o[0]?-1*(s.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,s.options.centerMode===!0&&(o=s.slideCount<=s.options.slidesToShow||s.options.infinite===!1?s.$slideTrack.children(".slick-slide").eq(i):s.$slideTrack.children(".slick-slide").eq(i+s.options.slidesToShow+1),e=s.options.rtl===!0?o[0]?-1*(s.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,e+=(s.$list.width()-o.outerWidth())/2)),e},e.prototype.getOption=e.prototype.slickGetOption=function(i){var e=this;return e.options[i]},e.prototype.getNavigableIndexes=function(){var i,e=this,t=0,o=0,s=[];for(e.options.infinite===!1?i=e.slideCount:(t=-1*e.options.slidesToScroll,o=-1*e.options.slidesToScroll,i=2*e.slideCount);i>t;)s.push(t),t=o+e.options.slidesToScroll,o+=e.options.slidesToScroll<=e.options.slidesToShow?e.options.slidesToScroll:e.options.slidesToShow;return s},e.prototype.getSlick=function(){return this},e.prototype.getSlideCount=function(){var e,t,o,s=this;return o=s.options.centerMode===!0?s.slideWidth*Math.floor(s.options.slidesToShow/2):0,s.options.swipeToSlide===!0?(s.$slideTrack.find(".slick-slide").each(function(e,n){return n.offsetLeft-o+i(n).outerWidth()/2>-1*s.swipeLeft?(t=n,!1):void 0}),e=Math.abs(i(t).attr("data-slick-index")-s.currentSlide)||1):s.options.slidesToScroll},e.prototype.goTo=e.prototype.slickGoTo=function(i,e){var t=this;t.changeSlide({data:{message:"index",index:parseInt(i)}},e)},e.prototype.init=function(e){var t=this;i(t.$slider).hasClass("slick-initialized")||(i(t.$slider).addClass("slick-initialized"),t.buildRows(),t.buildOut(),t.setProps(),t.startLoad(),t.loadSlider(),t.initializeEvents(),t.updateArrows(),t.updateDots(),t.checkResponsive(!0),t.focusHandler()),e&&t.$slider.trigger("init",[t]),t.options.accessibility===!0&&t.initADA(),t.options.autoplay&&(t.paused=!1,t.autoPlay())},e.prototype.initADA=function(){var e=this;null!==e.$slides&&e.$slides.add(e.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),null!==e.$slideTrack&&e.$slideTrack.attr("role","listbox"),null!==e.$slides&&e.$slides.not(e.$slideTrack.find(".slick-cloned")).each(function(t){i(this).attr({role:"option","aria-describedby":"slick-slide"+e.instanceUid+t})}),null!==e.$dots&&e.$dots.attr("role","tablist").find("li").each(function(t){i(this).attr({role:"presentation","aria-selected":"false","aria-controls":"navigation"+e.instanceUid+t,id:"slick-slide"+e.instanceUid+t})}).first().attr("aria-selected","true").end().find("button").attr("role","button").end().closest("div").attr("role","toolbar"),e.activateADA()},e.prototype.initArrowEvents=function(){var i=this;i.options.arrows===!0&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.off("click.slick").on("click.slick",{message:"previous"},i.changeSlide),i.$nextArrow.off("click.slick").on("click.slick",{message:"next"},i.changeSlide))},e.prototype.initDotEvents=function(){var e=this;e.options.dots===!0&&e.slideCount>e.options.slidesToShow&&i("li",e.$dots).on("click.slick",{message:"index"},e.changeSlide),e.options.dots===!0&&e.options.pauseOnDotsHover===!0&&i("li",e.$dots).on("mouseenter.slick",i.proxy(e.interrupt,e,!0)).on("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.initSlideEvents=function(){var e=this;e.options.pauseOnHover&&(e.$list.on("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.on("mouseleave.slick",i.proxy(e.interrupt,e,!1)))},e.prototype.initializeEvents=function(){var e=this;e.initArrowEvents(),e.initDotEvents(),e.initSlideEvents(),e.$list.on("touchstart.slick mousedown.slick",{action:"start"},e.swipeHandler),e.$list.on("touchmove.slick mousemove.slick",{action:"move"},e.swipeHandler),e.$list.on("touchend.slick mouseup.slick",{action:"end"},e.swipeHandler),e.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},e.swipeHandler),e.$list.on("click.slick",e.clickHandler),i(document).on(e.visibilityChange,i.proxy(e.visibility,e)),e.options.accessibility===!0&&e.$list.on("keydown.slick",e.keyHandler),e.options.focusOnSelect===!0&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),i(window).on("orientationchange.slick.slick-"+e.instanceUid,i.proxy(e.orientationChange,e)),i(window).on("resize.slick.slick-"+e.instanceUid,i.proxy(e.resize,e)),i("[draggable!=true]",e.$slideTrack).on("dragstart",e.preventDefault),i(window).on("load.slick.slick-"+e.instanceUid,e.setPosition),i(document).on("ready.slick.slick-"+e.instanceUid,e.setPosition)},e.prototype.initUI=function(){var i=this;i.options.arrows===!0&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.show(),i.$nextArrow.show()),i.options.dots===!0&&i.slideCount>i.options.slidesToShow&&i.$dots.show()},e.prototype.keyHandler=function(i){var e=this;i.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===i.keyCode&&e.options.accessibility===!0?e.changeSlide({data:{message:e.options.rtl===!0?"next":"previous"}}):39===i.keyCode&&e.options.accessibility===!0&&e.changeSlide({data:{message:e.options.rtl===!0?"previous":"next"}}))},e.prototype.lazyLoad=function(){function e(e){i("img[data-lazy]",e).each(function(){var e=i(this),t=i(this).attr("data-lazy"),o=document.createElement("img");o.onload=function(){e.animate({opacity:0},100,function(){e.attr("src",t).animate({opacity:1},200,function(){e.removeAttr("data-lazy").removeClass("slick-loading")}),r.$slider.trigger("lazyLoaded",[r,e,t])})},o.onerror=function(){e.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),r.$slider.trigger("lazyLoadError",[r,e,t])},o.src=t})}var t,o,s,n,r=this;r.options.centerMode===!0?r.options.infinite===!0?(s=r.currentSlide+(r.options.slidesToShow/2+1),n=s+r.options.slidesToShow+2):(s=Math.max(0,r.currentSlide-(r.options.slidesToShow/2+1)),n=2+(r.options.slidesToShow/2+1)+r.currentSlide):(s=r.options.infinite?r.options.slidesToShow+r.currentSlide:r.currentSlide,n=Math.ceil(s+r.options.slidesToShow),r.options.fade===!0&&(s>0&&s--,n<=r.slideCount&&n++)),t=r.$slider.find(".slick-slide").slice(s,n),e(t),r.slideCount<=r.options.slidesToShow?(o=r.$slider.find(".slick-slide"),e(o)):r.currentSlide>=r.slideCount-r.options.slidesToShow?(o=r.$slider.find(".slick-cloned").slice(0,r.options.slidesToShow),e(o)):0===r.currentSlide&&(o=r.$slider.find(".slick-cloned").slice(-1*r.options.slidesToShow),e(o))},e.prototype.loadSlider=function(){var i=this;i.setPosition(),i.$slideTrack.css({opacity:1}),i.$slider.removeClass("slick-loading"),i.initUI(),"progressive"===i.options.lazyLoad&&i.progressiveLazyLoad()},e.prototype.next=e.prototype.slickNext=function(){var i=this;i.changeSlide({data:{message:"next"}})},e.prototype.orientationChange=function(){var i=this;i.checkResponsive(),i.setPosition()},e.prototype.pause=e.prototype.slickPause=function(){var i=this;i.autoPlayClear(),i.paused=!0},e.prototype.play=e.prototype.slickPlay=function(){var i=this;i.autoPlay(),i.options.autoplay=!0,i.paused=!1,i.focussed=!1,i.interrupted=!1},e.prototype.postSlide=function(i){var e=this;e.unslicked||(e.$slider.trigger("afterChange",[e,i]),e.animating=!1,e.setPosition(),e.swipeLeft=null,e.options.autoplay&&e.autoPlay(),e.options.accessibility===!0&&e.initADA())},e.prototype.prev=e.prototype.slickPrev=function(){var i=this;i.changeSlide({data:{message:"previous"}})},e.prototype.preventDefault=function(i){i.preventDefault()},e.prototype.progressiveLazyLoad=function(e){e=e||1;var t,o,s,n=this,r=i("img[data-lazy]",n.$slider);r.length?(t=r.first(),o=t.attr("data-lazy"),s=document.createElement("img"),s.onload=function(){t.attr("src",o).removeAttr("data-lazy").removeClass("slick-loading"),n.options.adaptiveHeight===!0&&n.setPosition(),n.$slider.trigger("lazyLoaded",[n,t,o]),n.progressiveLazyLoad()},s.onerror=function(){3>e?setTimeout(function(){n.progressiveLazyLoad(e+1)},500):(t.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),n.$slider.trigger("lazyLoadError",[n,t,o]),n.progressiveLazyLoad())},s.src=o):n.$slider.trigger("allImagesLoaded",[n])},e.prototype.refresh=function(e){var t,o,s=this;o=s.slideCount-s.options.slidesToShow,!s.options.infinite&&s.currentSlide>o&&(s.currentSlide=o),s.slideCount<=s.options.slidesToShow&&(s.currentSlide=0),t=s.currentSlide,s.destroy(!0),i.extend(s,s.initials,{currentSlide:t}),s.init(),e||s.changeSlide({data:{message:"index",index:t}},!1)},e.prototype.registerBreakpoints=function(){var e,t,o,s=this,n=s.options.responsive||null;if("array"===i.type(n)&&n.length){s.respondTo=s.options.respondTo||"window";for(e in n)if(o=s.breakpoints.length-1,t=n[e].breakpoint,n.hasOwnProperty(e)){for(;o>=0;)s.breakpoints[o]&&s.breakpoints[o]===t&&s.breakpoints.splice(o,1),o--;s.breakpoints.push(t),s.breakpointSettings[t]=n[e].settings}s.breakpoints.sort(function(i,e){return s.options.mobileFirst?i-e:e-i})}},e.prototype.reinit=function(){var e=this;e.$slides=e.$slideTrack.children(e.options.slide).addClass("slick-slide"),e.slideCount=e.$slides.length,e.currentSlide>=e.slideCount&&0!==e.currentSlide&&(e.currentSlide=e.currentSlide-e.options.slidesToScroll),e.slideCount<=e.options.slidesToShow&&(e.currentSlide=0),e.registerBreakpoints(),e.setProps(),e.setupInfinite(),e.buildArrows(),e.updateArrows(),e.initArrowEvents(),e.buildDots(),e.updateDots(),e.initDotEvents(),e.cleanUpSlideEvents(),e.initSlideEvents(),e.checkResponsive(!1,!0),e.options.focusOnSelect===!0&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.setPosition(),e.focusHandler(),e.paused=!e.options.autoplay,e.autoPlay(),e.$slider.trigger("reInit",[e])},e.prototype.resize=function(){var e=this;i(window).width()!==e.windowWidth&&(clearTimeout(e.windowDelay),e.windowDelay=window.setTimeout(function(){e.windowWidth=i(window).width(),e.checkResponsive(),e.unslicked||e.setPosition()},50))},e.prototype.removeSlide=e.prototype.slickRemove=function(i,e,t){var o=this;return"boolean"==typeof i?(e=i,i=e===!0?0:o.slideCount-1):i=e===!0?--i:i,o.slideCount<1||0>i||i>o.slideCount-1?!1:(o.unload(),t===!0?o.$slideTrack.children().remove():o.$slideTrack.children(this.options.slide).eq(i).remove(),o.$slides=o.$slideTrack.children(this.options.slide),o.$slideTrack.children(this.options.slide).detach(),o.$slideTrack.append(o.$slides),o.$slidesCache=o.$slides,void o.reinit())},e.prototype.setCSS=function(i){var e,t,o=this,s={};o.options.rtl===!0&&(i=-i),e="left"==o.positionProp?Math.ceil(i)+"px":"0px",t="top"==o.positionProp?Math.ceil(i)+"px":"0px",s[o.positionProp]=i,o.transformsEnabled===!1?o.$slideTrack.css(s):(s={},o.cssTransitions===!1?(s[o.animType]="translate("+e+", "+t+")",o.$slideTrack.css(s)):(s[o.animType]="translate3d("+e+", "+t+", 0px)",o.$slideTrack.css(s)))},e.prototype.setDimensions=function(){var i=this;i.options.vertical===!1?i.options.centerMode===!0&&i.$list.css({padding:"0px "+i.options.centerPadding}):(i.$list.height(i.$slides.first().outerHeight(!0)*i.options.slidesToShow),i.options.centerMode===!0&&i.$list.css({padding:i.options.centerPadding+" 0px"})),i.listWidth=i.$list.width(),i.listHeight=i.$list.height(),i.options.vertical===!1&&i.options.variableWidth===!1?(i.slideWidth=Math.ceil(i.listWidth/i.options.slidesToShow),i.$slideTrack.width(Math.ceil(i.slideWidth*i.$slideTrack.children(".slick-slide").length))):i.options.variableWidth===!0?i.$slideTrack.width(5e3*i.slideCount):(i.slideWidth=Math.ceil(i.listWidth),i.$slideTrack.height(Math.ceil(i.$slides.first().outerHeight(!0)*i.$slideTrack.children(".slick-slide").length)));var e=i.$slides.first().outerWidth(!0)-i.$slides.first().width();i.options.variableWidth===!1&&i.$slideTrack.children(".slick-slide").width(i.slideWidth-e)},e.prototype.setFade=function(){var e,t=this;t.$slides.each(function(o,s){e=t.slideWidth*o*-1,t.options.rtl===!0?i(s).css({position:"relative",right:e,top:0,zIndex:t.options.zIndex-2,opacity:0}):i(s).css({position:"relative",left:e,top:0,zIndex:t.options.zIndex-2,opacity:0})}),t.$slides.eq(t.currentSlide).css({zIndex:t.options.zIndex-1,opacity:1})},e.prototype.setHeight=function(){var i=this;if(1===i.options.slidesToShow&&i.options.adaptiveHeight===!0&&i.options.vertical===!1){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.css("height",e)}},e.prototype.setOption=e.prototype.slickSetOption=function(){var e,t,o,s,n,r=this,l=!1;if("object"===i.type(arguments[0])?(o=arguments[0],l=arguments[1],n="multiple"):"string"===i.type(arguments[0])&&(o=arguments[0],s=arguments[1],l=arguments[2],"responsive"===arguments[0]&&"array"===i.type(arguments[1])?n="responsive":"undefined"!=typeof arguments[1]&&(n="single")),"single"===n)r.options[o]=s;else if("multiple"===n)i.each(o,function(i,e){r.options[i]=e});else if("responsive"===n)for(t in s)if("array"!==i.type(r.options.responsive))r.options.responsive=[s[t]];else{for(e=r.options.responsive.length-1;e>=0;)r.options.responsive[e].breakpoint===s[t].breakpoint&&r.options.responsive.splice(e,1),e--;r.options.responsive.push(s[t])}l&&(r.unload(),r.reinit())},e.prototype.setPosition=function(){var i=this;i.setDimensions(),i.setHeight(),i.options.fade===!1?i.setCSS(i.getLeft(i.currentSlide)):i.setFade(),i.$slider.trigger("setPosition",[i])},e.prototype.setProps=function(){var i=this,e=document.body.style;i.positionProp=i.options.vertical===!0?"top":"left","top"===i.positionProp?i.$slider.addClass("slick-vertical"):i.$slider.removeClass("slick-vertical"),(void 0!==e.WebkitTransition||void 0!==e.MozTransition||void 0!==e.msTransition)&&i.options.useCSS===!0&&(i.cssTransitions=!0),i.options.fade&&("number"==typeof i.options.zIndex?i.options.zIndex<3&&(i.options.zIndex=3):i.options.zIndex=i.defaults.zIndex),void 0!==e.OTransform&&(i.animType="OTransform",i.transformType="-o-transform",i.transitionType="OTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.MozTransform&&(i.animType="MozTransform",i.transformType="-moz-transform",i.transitionType="MozTransition",void 0===e.perspectiveProperty&&void 0===e.MozPerspective&&(i.animType=!1)),void 0!==e.webkitTransform&&(i.animType="webkitTransform",i.transformType="-webkit-transform",i.transitionType="webkitTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.msTransform&&(i.animType="msTransform",i.transformType="-ms-transform",i.transitionType="msTransition",void 0===e.msTransform&&(i.animType=!1)),void 0!==e.transform&&i.animType!==!1&&(i.animType="transform",i.transformType="transform",i.transitionType="transition"),i.transformsEnabled=i.options.useTransform&&null!==i.animType&&i.animType!==!1},e.prototype.setSlideClasses=function(i){var e,t,o,s,n=this;t=n.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),n.$slides.eq(i).addClass("slick-current"),n.options.centerMode===!0?(e=Math.floor(n.options.slidesToShow/2),n.options.infinite===!0&&(i>=e&&i<=n.slideCount-1-e?n.$slides.slice(i-e,i+e+1).addClass("slick-active").attr("aria-hidden","false"):(o=n.options.slidesToShow+i,
t.slice(o-e+1,o+e+2).addClass("slick-active").attr("aria-hidden","false")),0===i?t.eq(t.length-1-n.options.slidesToShow).addClass("slick-center"):i===n.slideCount-1&&t.eq(n.options.slidesToShow).addClass("slick-center")),n.$slides.eq(i).addClass("slick-center")):i>=0&&i<=n.slideCount-n.options.slidesToShow?n.$slides.slice(i,i+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):t.length<=n.options.slidesToShow?t.addClass("slick-active").attr("aria-hidden","false"):(s=n.slideCount%n.options.slidesToShow,o=n.options.infinite===!0?n.options.slidesToShow+i:i,n.options.slidesToShow==n.options.slidesToScroll&&n.slideCount-i<n.options.slidesToShow?t.slice(o-(n.options.slidesToShow-s),o+s).addClass("slick-active").attr("aria-hidden","false"):t.slice(o,o+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false")),"ondemand"===n.options.lazyLoad&&n.lazyLoad()},e.prototype.setupInfinite=function(){var e,t,o,s=this;if(s.options.fade===!0&&(s.options.centerMode=!1),s.options.infinite===!0&&s.options.fade===!1&&(t=null,s.slideCount>s.options.slidesToShow)){for(o=s.options.centerMode===!0?s.options.slidesToShow+1:s.options.slidesToShow,e=s.slideCount;e>s.slideCount-o;e-=1)t=e-1,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t-s.slideCount).prependTo(s.$slideTrack).addClass("slick-cloned");for(e=0;o>e;e+=1)t=e,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t+s.slideCount).appendTo(s.$slideTrack).addClass("slick-cloned");s.$slideTrack.find(".slick-cloned").find("[id]").each(function(){i(this).attr("id","")})}},e.prototype.interrupt=function(i){var e=this;i||e.autoPlay(),e.interrupted=i},e.prototype.selectHandler=function(e){var t=this,o=i(e.target).is(".slick-slide")?i(e.target):i(e.target).parents(".slick-slide"),s=parseInt(o.attr("data-slick-index"));return s||(s=0),t.slideCount<=t.options.slidesToShow?(t.setSlideClasses(s),void t.asNavFor(s)):void t.slideHandler(s)},e.prototype.slideHandler=function(i,e,t){var o,s,n,r,l,a=null,d=this;return e=e||!1,d.animating===!0&&d.options.waitForAnimate===!0||d.options.fade===!0&&d.currentSlide===i||d.slideCount<=d.options.slidesToShow?void 0:(e===!1&&d.asNavFor(i),o=i,a=d.getLeft(o),r=d.getLeft(d.currentSlide),d.currentLeft=null===d.swipeLeft?r:d.swipeLeft,d.options.infinite===!1&&d.options.centerMode===!1&&(0>i||i>d.getDotCount()*d.options.slidesToScroll)?void(d.options.fade===!1&&(o=d.currentSlide,t!==!0?d.animateSlide(r,function(){d.postSlide(o)}):d.postSlide(o))):d.options.infinite===!1&&d.options.centerMode===!0&&(0>i||i>d.slideCount-d.options.slidesToScroll)?void(d.options.fade===!1&&(o=d.currentSlide,t!==!0?d.animateSlide(r,function(){d.postSlide(o)}):d.postSlide(o))):(d.options.autoplay&&clearInterval(d.autoPlayTimer),s=0>o?d.slideCount%d.options.slidesToScroll!==0?d.slideCount-d.slideCount%d.options.slidesToScroll:d.slideCount+o:o>=d.slideCount?d.slideCount%d.options.slidesToScroll!==0?0:o-d.slideCount:o,d.animating=!0,d.$slider.trigger("beforeChange",[d,d.currentSlide,s]),n=d.currentSlide,d.currentSlide=s,d.setSlideClasses(d.currentSlide),d.options.asNavFor&&(l=d.getNavTarget(),l=l.slick("getSlick"),l.slideCount<=l.options.slidesToShow&&l.setSlideClasses(d.currentSlide)),d.updateDots(),d.updateArrows(),d.options.fade===!0?(t!==!0?(d.fadeSlideOut(n),d.fadeSlide(s,function(){d.postSlide(s)})):d.postSlide(s),void d.animateHeight()):void(t!==!0?d.animateSlide(a,function(){d.postSlide(s)}):d.postSlide(s))))},e.prototype.startLoad=function(){var i=this;i.options.arrows===!0&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.hide(),i.$nextArrow.hide()),i.options.dots===!0&&i.slideCount>i.options.slidesToShow&&i.$dots.hide(),i.$slider.addClass("slick-loading")},e.prototype.swipeDirection=function(){var i,e,t,o,s=this;return i=s.touchObject.startX-s.touchObject.curX,e=s.touchObject.startY-s.touchObject.curY,t=Math.atan2(e,i),o=Math.round(180*t/Math.PI),0>o&&(o=360-Math.abs(o)),45>=o&&o>=0?s.options.rtl===!1?"left":"right":360>=o&&o>=315?s.options.rtl===!1?"left":"right":o>=135&&225>=o?s.options.rtl===!1?"right":"left":s.options.verticalSwiping===!0?o>=35&&135>=o?"down":"up":"vertical"},e.prototype.swipeEnd=function(i){var e,t,o=this;if(o.dragging=!1,o.interrupted=!1,o.shouldClick=o.touchObject.swipeLength>10?!1:!0,void 0===o.touchObject.curX)return!1;if(o.touchObject.edgeHit===!0&&o.$slider.trigger("edge",[o,o.swipeDirection()]),o.touchObject.swipeLength>=o.touchObject.minSwipe){switch(t=o.swipeDirection()){case"left":case"down":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide+o.getSlideCount()):o.currentSlide+o.getSlideCount(),o.currentDirection=0;break;case"right":case"up":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide-o.getSlideCount()):o.currentSlide-o.getSlideCount(),o.currentDirection=1}"vertical"!=t&&(o.slideHandler(e),o.touchObject={},o.$slider.trigger("swipe",[o,t]))}else o.touchObject.startX!==o.touchObject.curX&&(o.slideHandler(o.currentSlide),o.touchObject={})},e.prototype.swipeHandler=function(i){var e=this;if(!(e.options.swipe===!1||"ontouchend"in document&&e.options.swipe===!1||e.options.draggable===!1&&-1!==i.type.indexOf("mouse")))switch(e.touchObject.fingerCount=i.originalEvent&&void 0!==i.originalEvent.touches?i.originalEvent.touches.length:1,e.touchObject.minSwipe=e.listWidth/e.options.touchThreshold,e.options.verticalSwiping===!0&&(e.touchObject.minSwipe=e.listHeight/e.options.touchThreshold),i.data.action){case"start":e.swipeStart(i);break;case"move":e.swipeMove(i);break;case"end":e.swipeEnd(i)}},e.prototype.swipeMove=function(i){var e,t,o,s,n,r=this;return n=void 0!==i.originalEvent?i.originalEvent.touches:null,!r.dragging||n&&1!==n.length?!1:(e=r.getLeft(r.currentSlide),r.touchObject.curX=void 0!==n?n[0].pageX:i.clientX,r.touchObject.curY=void 0!==n?n[0].pageY:i.clientY,r.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(r.touchObject.curX-r.touchObject.startX,2))),r.options.verticalSwiping===!0&&(r.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(r.touchObject.curY-r.touchObject.startY,2)))),t=r.swipeDirection(),"vertical"!==t?(void 0!==i.originalEvent&&r.touchObject.swipeLength>4&&i.preventDefault(),s=(r.options.rtl===!1?1:-1)*(r.touchObject.curX>r.touchObject.startX?1:-1),r.options.verticalSwiping===!0&&(s=r.touchObject.curY>r.touchObject.startY?1:-1),o=r.touchObject.swipeLength,r.touchObject.edgeHit=!1,r.options.infinite===!1&&(0===r.currentSlide&&"right"===t||r.currentSlide>=r.getDotCount()&&"left"===t)&&(o=r.touchObject.swipeLength*r.options.edgeFriction,r.touchObject.edgeHit=!0),r.options.vertical===!1?r.swipeLeft=e+o*s:r.swipeLeft=e+o*(r.$list.height()/r.listWidth)*s,r.options.verticalSwiping===!0&&(r.swipeLeft=e+o*s),r.options.fade===!0||r.options.touchMove===!1?!1:r.animating===!0?(r.swipeLeft=null,!1):void r.setCSS(r.swipeLeft)):void 0)},e.prototype.swipeStart=function(i){var e,t=this;return t.interrupted=!0,1!==t.touchObject.fingerCount||t.slideCount<=t.options.slidesToShow?(t.touchObject={},!1):(void 0!==i.originalEvent&&void 0!==i.originalEvent.touches&&(e=i.originalEvent.touches[0]),t.touchObject.startX=t.touchObject.curX=void 0!==e?e.pageX:i.clientX,t.touchObject.startY=t.touchObject.curY=void 0!==e?e.pageY:i.clientY,void(t.dragging=!0))},e.prototype.unfilterSlides=e.prototype.slickUnfilter=function(){var i=this;null!==i.$slidesCache&&(i.unload(),i.$slideTrack.children(this.options.slide).detach(),i.$slidesCache.appendTo(i.$slideTrack),i.reinit())},e.prototype.unload=function(){var e=this;i(".slick-cloned",e.$slider).remove(),e.$dots&&e.$dots.remove(),e.$prevArrow&&e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.remove(),e.$nextArrow&&e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.remove(),e.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},e.prototype.unslick=function(i){var e=this;e.$slider.trigger("unslick",[e,i]),e.destroy()},e.prototype.updateArrows=function(){var i,e=this;i=Math.floor(e.options.slidesToShow/2),e.options.arrows===!0&&e.slideCount>e.options.slidesToShow&&!e.options.infinite&&(e.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),e.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===e.currentSlide?(e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),e.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):e.currentSlide>=e.slideCount-e.options.slidesToShow&&e.options.centerMode===!1?(e.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),e.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):e.currentSlide>=e.slideCount-1&&e.options.centerMode===!0&&(e.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),e.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},e.prototype.updateDots=function(){var i=this;null!==i.$dots&&(i.$dots.find("li").removeClass("slick-active").attr("aria-hidden","true"),i.$dots.find("li").eq(Math.floor(i.currentSlide/i.options.slidesToScroll)).addClass("slick-active").attr("aria-hidden","false"))},e.prototype.visibility=function(){var i=this;i.options.autoplay&&(document[i.hidden]?i.interrupted=!0:i.interrupted=!1)},i.fn.slick=function(){var i,t,o=this,s=arguments[0],n=Array.prototype.slice.call(arguments,1),r=o.length;for(i=0;r>i;i++)if("object"==typeof s||"undefined"==typeof s?o[i].slick=new e(o[i],s):t=o[i].slick[s].apply(o[i].slick,n),"undefined"!=typeof t)return t;return o}});

/* ========================================
 FILE: /includes/js/jquery/slick/cs-slick.js
 ==================== */

if ( typeof js_Config_reenable_plugins_for_pagespeed === 'undefined' && typeof js_CS_Config_lighthouse6_opt !== 'undefined' && js_CS_Config_lighthouse6_opt ) {
	jQuery.fn.slick = function() {};
}

/* ========================================
 FILE: /modules/js/mod_shop_search.js
 ==================== */

var script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};
var script_manage_params_ssfv = typeof script_manage_params.ssfv !== 'undefined' ? script_manage_params.ssfv : '';
var script_manage_params_dst = typeof script_manage_params.dst !== 'undefined' ? script_manage_params.dst : '';
var script_manage_params_vlpim3 = typeof script_manage_params.vlpim3 !== 'undefined' ? script_manage_params.vlpim3 : '';
var script_manage_params_vlpim3cr = typeof script_manage_params.vlpim3cr !== 'undefined' ? script_manage_params.vlpim3cr : '';
var script_manage_params_sm = typeof script_manage_params.sm !== 'undefined' ? script_manage_params.sm : '';
var script_manage_params_fau = typeof script_manage_params.fau !== 'undefined' ? script_manage_params.fau : '';
var script_manage_params_aacwpi = typeof script_manage_params.aacwpi !== 'undefined' ? script_manage_params.aacwpi : '';
var script_manage_params_ls = typeof script_manage_params.ls !== 'undefined' ? script_manage_params.ls : '';
var script_manage_params_csq = typeof script_manage_params.csq !== 'undefined' ? script_manage_params.csq : '';

window.currentRequest = null;
if ( !is_cs_user('separate_js') ) {
	jQuery('#shop_search_field').on('focusout', function(event) {

		if(event.relatedTarget == null || (event.relatedTarget.id != 'show_more_found_cats' && event.relatedTarget.id != 'show_more_found_comps')) {
			setTimeout(function() {
				jQuery('.autocompleter_with_cats_and_companies_div').hide();
			},250);
		}
	});
}

function js_default_search_title(js_action) {
	var shop_search_field = document.getElementById('shop_search_field');
	var shop_search_field_prop = document.getElementById('keyword_props') || null;
	var sendAlsoShopSearchFieldProp = (shop_search_field_prop && shop_search_field_prop.value != '') ? shop_search_field_prop.value + '/' : '';

	switch ( js_action ) {
		case 'blur':
			if ( shop_search_field.value == '' && !isDesignTools() ) {
// 				shop_search_field.style.color = script_manage_params_cd;
				shop_search_field.value=script_manage_params_ssfv;
			}
			break;

		case 'focus':
			if ( shop_search_field.value == script_manage_params_ssfv ) {
// 				shop_search_field.style.color = script_manage_params_ct;
				if (shop_search_field.value == script_manage_params_dst)
					shop_search_field.value = '';
			}
			break;

		case 'submit':

			var $searchField = jQuery('#shop_search_field');
			ssf_val = $searchField.val();
			$searchField.val(ssf_val);
			ssf_val = encodeURIComponent(ssf_val);
			var default_val = encodeURIComponent($searchField[0].defaultValue);

			if ( shop_search_field.value == script_manage_params_dst ) {
// 				shop_search_field.style.color = script_manage_params_ct;
				jQuery(shop_search_field).trigger('focus');
				//shop_search_field.trigger('focus');
				return false;
			}
			if ( isDesignTools() && shop_search_field.value.length == 0 ) {
				jQuery(shop_search_field).trigger('focus');
				//shop_search_field.trigger('focus');
				return false;
			}
			if (shop_search_field.value.length < (typeof script_manage_params_vlpim3 !== 'undefined' ? script_manage_params_vlpim3 : 3 ) ) {
				alert(script_manage_params_vlpim3cr);
				return false;
			}
			if ( (script_manage_params_sm == '1' ? '1' : '0') && shop_search_field.value!='') {
				var jqo_form = jQuery(shop_search_field).parents('form:first');
				if (jqo_form.find('input[type="hidden"][name="search_tree_category_id"]').length > 0) {
					Cookies.set('search_tree_category_id', jqo_form.find('input[type="hidden"][name="search_tree_category_id"]').val(), { path: '/' });
				}
				// Dušan bol ostraneny replace(/\//g, ' ') na ziadost sakyho
				var search = js_vm_search_encodeURIchars(shop_search_field.value.replace(/ {2}/g, ' '));

				if (typeof script_manage_params_csq !== 'undefined' && script_manage_params_csq != '') {
					document.location.href = script_manage_params_fau + '?' + script_manage_params_csq + '=' + js_vm_search_encodeURIchars(search);
				} else {
					document.location.href = script_manage_params_fau + js_vm_search_encodeURIchars(search) + '/' + sendAlsoShopSearchFieldProp;
				}

				return false;
			}
			return true;
	}
}

if ( typeof script_manage_params_aacwpi !== 'undefined' && script_manage_params_aacwpi != '') {

	function js_mod_vm_search_ajax_search_ini() {
		let options = {};
		if (typeof modularSystem !== 'undefined') {
			options = modularSystem.getSetting('modules.search', null, {});
		}

		if ( typeof script_manage_params_aacwpi.ow !== 'undefined' ) {
			options.width = script_manage_params_aacwpi.ow;
		}
		if ( typeof script_manage_params_aacwpi.om !== 'undefined' ) {
			options.max = script_manage_params_aacwpi.om;
		}
		if ( typeof script_manage_params_aacwpi.olipcc !== 'undefined' ) {
			options.listItemPostCreateCallback = script_manage_params_aacwpi.olipcc;
		}
		if ( typeof script_manage_params_aacwpi.os !== 'undefined' ) {
			options.scroll = script_manage_params_aacwpi.os.toLowerCase() === 'true';
		}
		if ( typeof script_manage_params_aacwpi.ahtrd !== 'undefined' ) {
			options.appendHtmlToResultsDiv = script_manage_params_aacwpi.ahtrd;
		}
		if ( typeof script_manage_params_aacwpi.loff !== 'undefined' ) {
			options.leftOffset = script_manage_params_aacwpi.loff;
		}
		if ( typeof script_manage_params_aacwpi.toff !== 'undefined' ) {
			options.topOffset = script_manage_params_aacwpi.toff;
		}
		if ( typeof script_manage_params_aacwpi.minChars !== 'undefined' ) {
			options.minChars = script_manage_params_aacwpi.minChars;
		}
		if ( typeof script_manage_params_aacwpi.uacl !== 'undefined' ) {
			options.acLimit = script_manage_params_aacwpi.uacl;
		}
		if ( typeof script_manage_params_aacwpi.ofwrd !== 'undefined' ) {
			options.onlyFirstWord = script_manage_params_aacwpi.ofwrd;
		}

		// skripty hod na koniec resultBoxu a nie do 1. polozky
		options.formatItem = function(row, i, n) {
			var value = row[0];

			var script_start = value.indexOf('<script');
			var script_end = value.indexOf('</script>');
			if(script_start > -1 && script_end > -1) {
				script_end += 9;
				var scriptTag = value.substr(script_start, script_end);
				var scriptVal = value.substring(script_start, script_end);

				value = value.replace(scriptVal, '');

				var resultBox = jQuery('.ac_results');
				resultBox.find('script').remove();
				resultBox.append(scriptVal);
			}

			return ( value != '' ) ? value : false;
		};

		options.resultsClass = "ac_main ac_results";

		var $searchField = jQuery('input#shop_search_field[name="keyword"]');
		if ( typeof js_Config_parser_enabled === 'undefined' ) {
			$searchField.autocomplete();
			if ( is_cs_user('separate_js') ) {
				jQuery(document).on('click', function(event) {
					jQuery('.ac_results').hide();
					jQuery('.autocompleter_with_cats_and_companies_div').hide();
				}).on('click', '.ac_results, .moduletable-search, .autocompleter_with_cats_and_companies_div', function(event) {
					event.stopPropagation();
				});
			}
		}

		if (typeof script_manage_params_aacwpi.cats_and_companies !== 'undefined' ) {
			jQuery('input#shop_search_field').on('keyup', function(event) {

				if(window.currentRequest !== null &&  window.currentRequest.readyState != 4) {
					window.currentRequest.abort();
					window.currentRequest = null;
				}

				if ( !(typeof js_Config_ajax_search_allow_moving_with_arrows !== 'undefined' && js_Config_ajax_search_allow_moving_with_arrows) ) {
					var keyCode = event.keyCode;
					if (keyCode == '37' || keyCode == '38' || keyCode == '39' || keyCode == '40') { //sipky
						return;
					}
				}

				event.preventDefault();

				if ( typeof js_Config_ajax_search_allow_moving_with_arrows !== 'undefined' && js_Config_ajax_search_allow_moving_with_arrows ) {
					var isArrow = event.keyCode;
					if (isArrow == '37' || isArrow == '38' || isArrow == '39' || isArrow == '40') { //sipky
						return;
					}
				}


				var elem = jQuery(this);
				var acq = jQuery(this).val();


				if(acq.length > 2) {
					window.currentRequest = jQuery.ajax({
						type: 'POST',
						data: 'acq=' + acq,
						url: '/modules/ajax/mod_shop_search_ajax.php?ajax_call=1&ajax_func=get_autocompleter_with_cats_and_companies',
						beforeSend : function(request) {
							if(window.currentRequest != null &&  window.currentRequest.readyState != 4) {
								window.currentRequest.abort();
							} else {
								var resdiv = jQuery('div.autocompleter_with_cats_and_companies_div');
								if (resdiv.length){
									resdiv.html('<div class="ac_loader"><span class="featureprod_ajax_loader"></span></div>').show();
								} else {
									elem.after('<div class="autocompleter_with_cats_and_companies_div"><div class="ac_loader"><span class="featureprod_ajax_loader"></span></div></div>');
									jQuery('div.autocompleter_with_cats_and_companies_div').show();
								}
							}
						}
					}).done(function(result) {
						var resdiv = jQuery('div.autocompleter_with_cats_and_companies_div');

						resdiv.remove();
						elem.after(result);
						resdiv.hide();
						resdiv.show();

						if ( typeof(js_after_init_search_autocompleter) !== 'undefined'){ js_after_init_search_autocompleter(); }
						if (typeof(js_mod_vm_search_ajax_search_after_ini) !== 'undefined') {
							js_mod_vm_search_ajax_search_after_ini();
						}
					});

				} else {
					jQuery('div.autocompleter_with_cats_and_companies_div').remove();
				}
			});
		} else {
			if ( typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled ) {
				var minLength;

				if ( typeof script_manage_params_aacwpi.minChars !== 'undefined' ) {
					minLength = script_manage_params_aacwpi.minChars; // TODO: premenovat parametre
				}

				if ( typeof jQuery.ui === 'undefined' ) { return; }

				var auto_class = {};
				if ($searchField.is('#shop_search_field')) {
					if ( is_cs_user('separate_js') ) {
						auto_class = {'ui-autocomplete': 'ac_main'};
					} else {
						auto_class = {'ui-autocomplete': 'ac_header'};
					}
				}

				let modularOptions = {};
				if (typeof modularSystem !== 'undefined') {
					modularOptions = modularSystem.getSetting('modules.search', null, {});
				}
				
				var csoptions = jQuery.extend(true, {}, modularOptions);

				if (typeof csoptions.minLength === 'undefined') {
					csoptions.minLength = typeof options.minChars !== 'undefined' ? options.minChars : 1;
				}
				if (typeof csoptions.html === 'undefined') {
					csoptions.html = true;
				}
				if (typeof csoptions.classes === 'undefined') {
					csoptions.classes = auto_class;
				}
				csoptions.source = function (request, response) {
					var searchTerm = '&acq=' + encodeURIComponent(request.term);
					var searchLimit = typeof script_manage_params_aacwpi.uacl !== 'undefined' && script_manage_params_aacwpi != '' ? '&aclimit=' + script_manage_params_aacwpi.uacl : '';
					var getParams   = window.location.search.replace('?', '&');
					var url         = script_manage_params_ls + '/modules/ajax/mod_shop_search_ajax.php?ajax_call=1&ajax_func=get_autocompleter_with_img_list' + searchTerm + searchLimit + getParams;
					jQuery.get(url, function (res) {
						var parsedJson = csJsonParse(res);
						if (parsedJson === null) {
							response([cms_js_iterate_notfound]);
							return;
						}
						response(parsedJson);
						jQuery('.ui-menu-item:odd').addClass('ac_odd');
						jQuery('.ui-menu-item:even').addClass('ac_even');
						jQuery('.ui-menu-item')
							.on('mouseover', function () {
								jQuery(this).addClass('ac_over');
								jQuery(this).find('.ui-menu-item-wrapper');
							})
							.on('mouseleave', function () {
								jQuery(this).removeClass('ac_over');
							});
					});
				};
				csoptions.select = function (event, ui) {
					event.preventDefault();
					if (typeof ui.item.value !== 'undefined' && ui.item.value.indexOf('http') > -1) {
						location.href = ui.item.value;
					}
				};
				csoptions.focus = function(event, ui) {
					event.preventDefault();

					var $focusedElem = jQuery('.ui-state-active').parent();
					if ( $focusedElem.length ) {
						jQuery('.ui-menu-item').removeClass('ac_over');
						$focusedElem.addClass('ac_over');
					}
				};

				$searchField.csautocomplete(csoptions).off('blur');
			} else {
				$searchField.autocomplete(script_manage_params_ls + '/modules/ajax/mod_shop_search_ajax.php?ajax_call=1&ajax_func=get_autocompleter_with_img_list' + (typeof script_manage_params_aacwpi.uacl !== 'undefined' && script_manage_params_aacwpi != '' ? '&aclimit=' + script_manage_params_aacwpi.uacl : ''), options);
			}
		}
		if (typeof $searchField.result === 'function') {
			$searchField.result(function (event, data, formatted) {
				if (data && data[1] && data[2]) {
					$searchField.val(data[1]);
					jQuery('#ac_res_product_name').val(data[1]);
					jQuery('#ac_res_product_id').val(data[2]);
					// click on product -> go to product detail page
					if (formatted.indexOf('acwil_url') > -1) {
						var url = jQuery('<div/>').html(formatted).find('.acwil_url').text();
						if (!js_is_empty(url)) {
							window.location.href = url;
							return false;
						}
					}
					$searchField.parents('form:first').trigger('submit');
				}
			});
		}
	}
	function js_mod_vm_search_ajax_search_ok() {
		return jQuery('#ac_res_product_id').val() > '0' && jQuery('#ac_res_product_name').val() == jQuery('input#shop_search_field[name="keyword"]').val();
	}
	if (typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled) {
		jQuery(window).on('load', function () {
			jQuery('input#shop_search_field[name="keyword"]').after('<input name="ac_res_product_id" id="ac_res_product_id" type="hidden" value="" /><input name="ac_res_product_name" id="ac_res_product_name" type="hidden" value="" />');
			js_mod_vm_search_ajax_search_ini();
		});
	} else {
		jQuery(function () {
			jQuery('input#shop_search_field[name="keyword"]').after('<input name="ac_res_product_id" id="ac_res_product_id" type="hidden" value="" /><input name="ac_res_product_name" id="ac_res_product_name" type="hidden" value="" />');
			js_mod_vm_search_ajax_search_ini();
		});
	}
}
function js_vm_search_encodeURIchars(text) {
	//	funkcia zakoduje text, ktory sa ma pouzit ako parameter v URL
	return encodeURIComponent(text).replace('~', '%7E').replace('!', '%21').replace('*', '%2A').replace('(', '%28').replace(')', '%29').replace('\'', '%27');
}

jQuery(document).on('click','#show_more_found_cats',function() {
	var categories = jQuery('div.autocompleter_categories ul');
	var manus = jQuery('div.autocompleter_manufacturers');
	var categH;

	if ( manus.find('li').length ) {
		categH = categories.outerHeight() + jQuery(this).outerHeight();
	} else {
		categH = jQuery('.autocompleter_products').outerHeight() - jQuery('.autocompleter_categories_title').outerHeight(true) - manus.outerHeight(true);
	}

	categories.find('li.hidden_cats').removeClass('hidden_cats');
	categories.removeClass('categories_show_default');
	categories.addClass('categories_show_all');

	// categories.height( categH );

	jQuery('#show_more_found_cats').remove();
	jQuery('#shop_search_field').focus();
});

jQuery(document).on('click','#show_more_found_comps',function() {
	var manufacturers = jQuery('div.autocompleter_manufacturers ul');
	var categories = jQuery('div.autocompleter_categories');
	var manuH;

	if ( categories.find('li').length ) {
		manuH = manufacturers.outerHeight() + jQuery(this).outerHeight();
	} else {
		manuH = jQuery('.autocompleter_products').outerHeight() - jQuery('.autocompleter_manufacturers_title').outerHeight(true) - categories.outerHeight(true);
	}

	manufacturers.find('li.hidden_comps').removeClass('hidden_comps');
	manufacturers.removeClass('manufacturers_show_default');
	manufacturers.addClass('manufacturers_show_all');

	// manufacturers.height( manuH );

	jQuery('#show_more_found_comps').remove();
	jQuery('#shop_search_field').focus();
});


/* ========================================
 FILE: /modules/js/mod_lettermansubscribe.js
 ==================== */

var script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};
var script_manage_params_u = typeof script_manage_params.u !== 'undefined' ? script_manage_params.u : '';
var script_manage_params_ch = typeof script_manage_params.ch !== 'undefined' ? script_manage_params.ch : '';
var script_manage_params_lmfne = typeof script_manage_params.lmfne !== 'undefined' ? script_manage_params.lmfne : '';
var script_manage_params_chl = typeof script_manage_params.chl !== 'undefined' ? script_manage_params.chl : '';
var script_manage_params_hnf = typeof script_manage_params.hnf !== 'undefined' ? script_manage_params.hnf : '';
var script_manage_params_lmfsn = typeof script_manage_params.lmfsn !== 'undefined' ? script_manage_params.lmfsn : '';
var script_manage_params_lmfnn = typeof script_manage_params.lmfnn !== 'undefined' ? script_manage_params.lmfnn : '';

// mod_lettermansubscribe.php
var script_manage_params_use_google_recaptcha = typeof script_manage_params.use_google_recaptcha !== 'undefined' ? script_manage_params.use_google_recaptcha : '';
var script_manage_params_user_geoip = typeof script_manage_params.user_geoip !== 'undefined' ? script_manage_params.user_geoip : '';
var script_manage_params_LM_submit = typeof script_manage_params.LM_submit !== 'undefined' ? script_manage_params.LM_submit : '';
var script_manage_params_LM_unsubscribe = typeof script_manage_params.LM_unsubscribe !== 'undefined' ? script_manage_params.LM_unsubscribe : '';
var script_manage_params_LM_subscribe = typeof script_manage_params.LM_subscribe !== 'undefined' ? script_manage_params.LM_subscribe : '';
var script_manage_params_uname = typeof script_manage_params.uname !== 'undefined' ? script_manage_params.uname : '';
var script_manage_params_uid = typeof script_manage_params.uid !== 'undefined' ? script_manage_params.uid : '';
var script_manage_params_vex_input_ok = typeof script_manage_params.vex_input_ok !== 'undefined' ? script_manage_params.vex_input_ok : '';
var script_manage_params_newsletter_vex_submit_vex_input = typeof script_manage_params.newsletter_vex_submit_vex_input !== 'undefined' ? script_manage_params.newsletter_vex_submit_vex_input : false;
var script_manage_params_newsletter_vex_submit_LM_subscribe = typeof script_manage_params.newsletter_vex_submit_LM_subscribe !== 'undefined' ? script_manage_params.newsletter_vex_submit_LM_subscribe : false;
var script_manage_params_newsletter_vex_submit_vex_input_ok = typeof script_manage_params.newsletter_vex_submit_vex_input_ok !== 'undefined' ? script_manage_params.newsletter_vex_submit_vex_input_ok : false;
var script_manage_params_moduleVisibilityArray = typeof script_manage_params.moduleVisibilityArray !== 'undefined' ? script_manage_params.moduleVisibilityArray : {};
var script_manage_params_ppContent = typeof script_manage_params.ppContent !== 'undefined' ? script_manage_params.ppContent : {};
var script_manage_params_delayParam = typeof script_manage_params.delayParam !== 'undefined' ? script_manage_params.delayParam : {};

// code
var script_manage_params_code_js_newsletter_vex_submit = typeof script_manage_params.code_js_newsletter_vex_submit !== 'undefined' ? script_manage_params.code_js_newsletter_vex_submit : false;
var script_manage_params_code_moduleVisibility = typeof script_manage_params.code_moduleVisibility !== 'undefined' ? script_manage_params.code_moduleVisibility : false;
var script_manage_params_code_letterman_timer = typeof script_manage_params.code_letterman_timer !== 'undefined' ? script_manage_params.code_letterman_timer : false;


function generateMessage(msg, suc) {
	if(msg != null) {
		if(suc == 0)
			var cls = 'msg_alert';
		else
			var cls = 'msg_success';

		var msg = '<div class="msg_wrap"><div class="msg_box" data-time="5000"><div class="' + cls + '"><div class="' + cls + '_img"></div>'+ msg +'</div></div></div>';

		// Skontroluj spravy a aktivuj messengera
		if (typeof messenger != 'undefined') messenger.check(msg);
	}
}

function ajaxTask() {

	if(jQuery('div.newsletter_inputs').find('#g-recaptcha-response').length) {
		if(!validation_by_google_recaptcha()) {
			return false;
		}
	}

	var options = {};

	jQuery('form[name=lettermanMod] input[name]').each(function() {
			if(jQuery(this).attr('type') == 'radio' && !jQuery(this).prop('checked')) return;
			options[jQuery(this).attr('name')] = jQuery(this).val();
	});

	options.function = 'ajax_letterman';
	options.ajax_call = '1';

	jQuery.post( "/includes/frontend_ajax.php", options, function( data ) {
		var json = JSON.parse(data);

		generateMessage(json.content, json.success);
	});
}

function unsubscribeConfirm() {
	var r = confirm(script_manage_params_u);

	if(r) {
		ajaxTask();
	}

	return false;
}

// (miro) - validacia google recaptchou na formulare odoslane ajaxom
function validation_by_google_recaptcha() {
	return jQuery('#g-recaptcha-response').val();
}

function js_show_re_captcha(){
	if((typeof js_CS_Config_two_newsletters !== 'undefined' && js_CS_Config_two_newsletters == 1)){
		var input = jQuery('.lm_email');
	}else {
		var input = jQuery('#lm_email');
	}
	input.on('change paste keyup', function(e) {
		var txt = jQuery(this).val();

		var email = input.val();
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		if ( emailReg.test( email ) && '' != email ) {
			input.next('.g-recaptcha').addClass('show');
		} else {
			input.next('.g-recaptcha').removeClass('show');
		}
	});
	input.on('blur', function() {
		var txt = jQuery(this).val();
		input.val( txt );
		var email = input.val();
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		if( !emailReg.test( email ) ) {
			input.trigger('focus');
			input.next('.g-recaptcha').removeClass('show');
		}
	});
}

/**
 * @deprecated
 * @returns {boolean}
 */
function changeTask() {

	//(miro) ak je zapnuta recaptcha by google, urobi sa validacia
	if(jQuery('div.newsletter_inputs').find('#g-recaptcha-response').length) {

		if(!validation_by_google_recaptcha()) {
			return false;
		} else {
			setTimeout(function() {
				jQuery('#lm_email').next('.g-recaptcha').removeClass('show');
			},1500);
		}
	}


	var name = document.lettermanMod.subscriber_name.value;
	var email;
	var max_length = script_manage_params_ch;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

	if (filter.test(document.lettermanMod.email.value)) {
		email = document.lettermanMod.email.value;
		var a = true;
	} else {
		if(is_cs_user()) {
			generateMessage(script_manage_params_lmfne, 0);
		} else {
			alert(script_manage_params_lmfne);
		}

		var a = true; return false;
	}
	try {
	    if( typeof script_manage_params_chl == 'string' && script_manage_params_chl != '' && script_manage_params_hnf == "0" ) {
			if(document.lettermanMod.subscriber_name.length > max_length) {
				if(is_cs_user()) {
					generateMessage(script_manage_params_lmfsn, 0);
				} else {
					alert(script_manage_params_lmfsn);
				}
				return false;
			}
	    }
	    if( typeof script_manage_params_hnf == 'string' && script_manage_params_hnf == "0" ) {
			if(document.lettermanMod.subscriber_name.length < 1) {
				if(is_cs_user()) {
					generateMessage(script_manage_params_lmfnn, 0);
				} else {
					alert(script_manage_params_lmfnn);
				}
				return false;
			}
	    }
	}
	catch(e) {}

	ajaxTask();

	return false;


	//return true;
}

// -------------------------------------------------------------
// mod_lettermansubscribe.php
// -------------------------------------------------------------

if( script_manage_params_code_js_newsletter_vex_submit ){
	//Cookies.set('newsletterToVex', 'show', {expires: 365});
	Cookies.set('newsletterToVex2d', 'show', {expires: 2});
	var is_ok = 0;
	vex.dialog.open({
		showCloseButton     : true,
		escapeButtonCloses  : false,
		overlayClosesOnClick: false,
		className           : 'vex-cs newsletter_vex',
		zIndex              : 8,
		input               : script_manage_params_newsletter_vex_submit_vex_input,
		buttons             : [jQuery.extend({}, vex.dialog.buttons.YES, {text: script_manage_params_newsletter_vex_submit_LM_subscribe})],
		afterOpen           : function (data) {
			jQuery(data).find('.vex-dialog-message').css('display', 'none');
			jQuery(data).find('[type="submit"]').attr("onClick", "subscribe_tooltip(this, 'vex')");
		},
		onSubmit            : function (e) {
			e.preventDefault();
		}
	});

	function js_newsletter_vex_submit(elem) {
		var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		var email = jQuery(elem).parents('.vex-dialog-form').find('[name="email"]').val();

		if (filter.test(email)) {
			options = {
				email: email,
				ajax_fnc: 'subscribe_from_vex'//'confirm'
			};

			jQuery.ajaxSetup({async: false});
			jQuery.post(js_global_live_site+'/modules/mod_lettermansubscribe.php', options, function(r) {
				if (r == 'OK') is_ok = 1;
			});

			if (is_ok == 1) {
				var newsletterVexElm = jQuery('.newsletter_vex');
				newsletterVexElm.find('.vex-dialog-input').html(script_manage_params_newsletter_vex_submit_vex_input_ok);
				newsletterVexElm.find('.vex-dialog-buttons').hide();
				return false;
			}

			generateMessage(LM_SAME_EMAIL_TWICE, 0);
			return false;
		}

		generateMessage(LM_FORM_NOEMAIL, 0);
		return false;
	}
}

if( script_manage_params_code_moduleVisibility ) {
//zisti id stranky
	var actual_page = 0;
	var moduleVisibilityArray = script_manage_params_moduleVisibilityArray;
	;
	var url = js_server_request_uri.match(/(&|;|\?)page\=([^&]+)/);
	var man = js_server_request_uri.match(/(&|;|\?)pc_manufacturer_id\=([^&]+)/);
	if (url != null && typeof(url[2]) != 'undefined') {
		if (url[2] == 'shop.browse' || url[2] == 'shop.product_details') {
			if (js_category_id != null && typeof(js_category_id) != "undefined" && js_category_id != '0') {
				actual_page = -js_category_id;
			}
			else if (man != null && typeof(man[2]) != 'undefined') {
				actual_page = -100000 - man[2];
			}
		}
		else actual_page = url[2];
	}
	else if (js_itemid != null && typeof(js_itemid) != 'undefined') {
		actual_page = js_itemid;
	}

//skrytie modulu ak sa na stranke nema nachadzat
	jQuery(function () {
		if (jQuery.inArray(actual_page, moduleVisibilityArray) < 0 && jQuery.inArray('0', moduleVisibilityArray) < 0) {
			jQuery('.mp_id43').hide();
		}
	});
}

if( script_manage_params_code_letterman_timer ){
	var ppCounter = 0;
	var ppContent = script_manage_params_ppContent;
	var delayParam = script_manage_params_delayParam;
	var myInterval;

	jQuery(function () {

		if (ppCounter < 1) {

			//casovac
			myInterval = setInterval(function () {
				Cookies.set('letterman_timer', Number(Cookies.get('letterman_timer')) + 500, {path: '/'});
			}, 500);

			delayParam = delayParam - Number(Cookies.get('letterman_timer'));

			setTimeout(function () {
				js_pp_confirm(ppContent, '', '', {'width': 400, 'useVex': true});
				Cookies.set('show_letterman', '1', {path: '/'});
				Cookies.set('letterman_timer', '0', {path: '/'});
				clearInterval(myInterval);
			}, delayParam);
		}
		ppCounter++;
	});
}

function show_vex(text) {
	vex.dialog.open({
		className: 'vex-cs newsletter_vex newsletter_confirm',
		message: '',
		input: text,
		buttons: [jQuery.extend({}, vex.dialog.buttons.YES)],
		afterClose: function () {
			window.location = window.location.href.split("?")[0];
		}
	});
}

var onloadCallback = function() {
	grecaptcha.render('html_element', {
		'sitekey' : typeof script_manage_params.use_google_recaptcha !== 'undefined' ? script_manage_params.use_google_recaptcha : '',
		'callback' : correctCaptcha
	});
};

var correctCaptcha = function(response) {
	if(response != ''){
		jQuery('#g-recaptcha-response').val(response);
		jQuery('.g-recaptcha').removeClass('show');
		googleRecaptchaResponse = true;
		if ( typeof js_Config_use_google_recaptcha === 'undefined' ) {
			subscribe_tooltip(this, '', true);
		}
	} else {
		googleRecaptchaResponse = false;
	}
};

jQuery(function () {
	// kontrola kluca pre pridanie / odstranenie emailu z noviniek
	var email_sub_key = location.search.split('email_subscribe=')[1];

	if (typeof email_sub_key != 'undefined') {
		new AjaxRequest({'email_key': email_sub_key})
			.setController("Subscribe")
			.setAction('confirmEmail')
			.onSuccess(function (jsonData) {
				if (jsonData.data.response == 'added') {
					show_vex(GDPR_EMAIL_ADDED);

					if (jsonData.data.subscriber_id != '') {
						new AjaxRequest({'subscriber_id': jsonData.data.subscriber_id})
							.setController("Subscribe")
							.setAction('sendNewsletterCoupon')
							.onSuccess(function (jsonData) {
							})
							.send();
					}
				} else if (jsonData.data.response == 'deleted') {
					show_vex(GDPR_EMAIL_REMOVED);
				} else if (jsonData.data.response == 'error' || jsonData.data.response == 'no subscriber' ) {
					window.location = window.location.href.split("?")[0];
				}
			})
			.send();
	}
});

function tool_email(content, where1, where2,elem) {

	var zIndex = 2;
	var tooltipsterElem = jQuery(where1);
	var tooltipsterElem2 = jQuery(where2);

	if ( typeof js_CS_Config_two_newsletters !== 'undefined' && js_CS_Config_two_newsletters == 1 ) {
		zIndex = 9999999;
		tooltipsterElem = elem.find(where1);
	}

	var text = "<b>" + ( (content == "no") ? GDPR_NO_EMAIL : ACC_VOUCHER_EMAIL_NOT_VALID ) + "</b>";

	if ( tooltipsterElem.hasClass('tooltipstered') ) {
		tooltipsterElem.tooltipster('destroy');
	}

	tooltipsterElem.tooltipster({
		theme: "tooltipster-gdpr",
		contentAsHTML: true,
		trackTooltip: true,
		trackOrigin: true,
		multiple: true,
		zIndex : zIndex,
		timer: 5000,
		content: text
	}).tooltipster('open');

	tooltipsterElem2.addClass('error');
}

function close_gdpr() {
	jQuery(".tooltipster-base").css("display", "none");
}


function subscribe_tooltip(elem, content, g_validate) {
	var elemObjLetr, email, where1, where2, where3;
	elemObjLetr = email = where1 = where2 = where3 = '';
	var zindex = '2';
	var theme = "tooltipster_subscribe_gdpr";

	if (typeof js_CS_Config_two_newsletters !== 'undefined' && js_CS_Config_two_newsletters == 1){
		jQuery('.lm_email').removeClass('emailSubscrActive');
		elemObjLetr = jQuery(elem).closest('.newsletter_module');
		elemObjLetr.find('.lm_email').addClass('emailSubscrActive');
		email = elemObjLetr.find('input[name="email"]').val();
		where1 = 'input[name="email"]';
		where2 = '.newsletter_module';
		where3 = '.newsletter_inputs';
	} else {
		email = document.lettermanMod && document.lettermanMod.email && document.lettermanMod.email.value;
		where1 = '#lm_email';
		where2 = '.newsletter_module';
		where3 = '.newsletter_inputs';
	}

	if ((vex != undefined) && (typeof content !== 'undefined' && content != '')) {
		where1 = '.vex_news';
		where2 = '.vex_news_input';
		email = jQuery('.vex_news_input').val();
		zindex = '999999';
		theme = "army_newsletter";
	} else {
		if (jQuery(where3).hasClass('tooltipstered')) {
			jQuery(where3).tooltipster('destroy');
		}
	}

	if (jQuery(where2).hasClass('tooltipstered')) {
		jQuery(where2).tooltipster('destroy');
	}

	if (!email) {
		tool_email("no", where1, where2,elemObjLetr);

		return false;
	}

	if (!validateEmail(email)) {
		tool_email('', where1, where2,elemObjLetr);

		return false;
	}

	jQuery(where2).removeClass('error');

	if (jQuery(where1).hasClass('tooltipstered')) {
		jQuery(where1+'.tooltipstered').tooltipster('destroy');
	}
	new AjaxRequest({'email': email})
		.setController("Subscribe")
		.setAction('checkEmail')
		.onSuccess(function (jsonData) {
			// ak sa uz nachadza v db, ale nepotvrdil email sa len zobrazi vex
			if (typeof jsonData.data.check[0] != 'undefined' && jsonData.data.check[0].confirmed != 1) {
				jQuery('.vex-close').trigger('click');
				vex.dialog.open({
					className: 'vex-cs newsletter_vex2',
					message: '',
					input: GDPR_EMAIL_SEND2,
					buttons: [jQuery.extend({}, vex.dialog.buttons.YES)]
				});
			} else {
				var user_geoip = script_manage_params_user_geoip;
				var use_google_recaptcha = script_manage_params_use_google_recaptcha;
				var easycaptcha = "";
				var subscribe = "1";
				var text = script_manage_params_LM_unsubscribe;

				if (jsonData.data.check[0] == null) {
					// email sa nenachadza v db
					easycaptcha = "1";
					subscribe = "";
					text = script_manage_params_LM_subscribe;
				}

				new AjaxRequest({
					'easycaptcha': easycaptcha,
					'subscribe': email,
					//'subscribe': subscribe,
					'text': text,
					'user_geoip': user_geoip,
					'g_validate' : g_validate,
					'use_google_recaptcha' : use_google_recaptcha !== null ? use_google_recaptcha : 'null'
				})
					.setController("Subscribe")
					.setAction('subscribe')
					.onSuccess(function (jsonData) {
						var where1obj = jQuery(where1);
						if(elemObjLetr != ''){
							where1obj = elemObjLetr.find(where1);
						}
						// sem
						where1obj.tooltipster({
							theme: theme,
							contentAsHTML: true,
							interactive: true,
							multiple: true,
							trigger: 'custom',
							zIndex: zindex,
							content: jsonData.data.html
						}).tooltipster('open');

						if (config('js_Config_newsletter_agree_checkbox')) {
							let gdprCheckbox = jQuery('.letterman_subscribe_agree_wrapper input[name="letterman_subscribe_agree"]');
							let tooltipGdprCheckbox = jQuery('#agreed_personal_info_field_subscriber');
							if (tooltipGdprCheckbox.length > 0) {
								let gdprChecked = gdprCheckbox.length > 0 && gdprCheckbox.is(':checked');
								tooltipGdprCheckbox.prop('checked', gdprChecked);
							}
						}
					}).send();

				jQuery(".subscribe_gdpr").css('display', '');
			}
		})
		.onError(function (jsonData) {
			tool_email('', where1, where2,elemObjLetr);
		}).send();
}

function tooltip(bordered, class_name, content_text, open) {
	if (typeof bordered != 'undefined') {
		jQuery(bordered).css({'border': '2px solid red', 'background-color': '#ff9090', 'color': 'white'});
	}
	if (open == 1) {
		jQuery(class_name).tooltipster({
			theme: "tooltipster-gdpr",
			contentAsHTML: true,
			trackTooltip: true,
			trackOrigin: true,
			multiple: true,
			timer: 5000,
			content: "<b>" + content_text + "</b>"
		}).tooltipster('open');
	}
}

function tooltip_close() {
	jQuery(".tooltipstered").tooltipster('destroy');
	jQuery('input[name="cansw"]').css({'border': '', 'background-color': '', 'color': ''});
}

function send_email(email, key, sub) {
	new AjaxRequest({'recipient': email, 'key': key, 'sub': sub})
		.setController("Subscribe")
		.setAction('sendMail')
		.onSuccess(function (jsonData) {
		})
		.send();
}

function submit_subscribe(action_text, subscribe_button) {
	var emailSelector = '';

	if((typeof js_CS_Config_two_newsletters !== 'undefined' && js_CS_Config_two_newsletters == 1)){
		if (typeof subscribe_button !== 'undefined') {
			jQuery('.lm_email').removeClass('emailSubscrActive');
			elemObjLetr = jQuery(subscribe_button).closest('.newsletter_module');
			elemObjLetr.find('.lm_email').addClass('emailSubscrActive');
		}

		var email = jQuery('.emailSubscrActive').val().trim();
		emailSelector = '.emailSubscrActive';
	} else {
		var email = document.lettermanMod.email.value.trim();
		emailSelector = document.lettermanMod.email;
	}

	if (email == '') {
		email = jQuery('.vex_news_input').val();
		emailSelector = '.vex_news_input';
	}

	var form_id = '6';
	var user_id = script_manage_params_uid;
	var user_name = script_manage_params_uname;
	var submit = jQuery('input[name="task"]').val();
	var vex_discount = '';

	if (jQuery('.vex_news').length) {
		vex_discount = 1;
	}

	if( typeof js_CS_Config_no_agree_newsletter !== 'undefined' && js_CS_Config_no_agree_newsletter) {
		if(typeof email === 'undefined' || email === '') {
			vex.dialog.alert({
				className: 'vex-cs newsletter_email_error',
				message: cms_js_lang_products_shipping_message_error_1,
				input: js_lang_nsu_lm_wrong_email,
			});
			return;
		} else if (!validateEmail(email)) {
			jQuery(emailSelector).addClass('error');
			vex.dialog.alert({
				className: 'vex-cs newsletter_email_error',
				message: cms_js_lang_products_shipping_message_error_1,
				input: js_lang_nsu_lm_wrong_email,
			});
			return;
		}
	}

	var recaptcha_response = jQuery('#g-recaptcha-response').val();
	if( recaptcha_response == null || typeof recaptcha_response !== 'string' ) recaptcha_response = '';

	new AjaxRequest({
		'email': (typeof email === "undefined" ? '' : email),
		'user_id': (typeof user_id === "undefined" ? '' : user_id),
		'user_name': (typeof user_name === "undefined" ? '' : user_name),
		'submit': (typeof submit === "undefined" ? '' : submit),
		'form_id': (typeof form_id === "undefined" ? '' : form_id),
		'vex_discount': (typeof vex_discount === "undefined" ? '' : vex_discount),
		'g-recaptcha-response': (typeof recaptcha_response === "undefined" ? '' : recaptcha_response),
	})
		.setController("Subscribe")
		.setAction('submitSubscribe')
		.onSuccess(function (jsonData) {
			if (typeof isApiActive !== 'undefined' && isApiActive && typeof jsonData.data.submit !== 'undefined' && jsonData.data.submit === 'subscribe') {
				apiRequest('submitSubscribe', {email: email});
			}

			vex.dialog.open({
				className: 'vex-cs newsletter_vex newsletter_confirm',
				message: '',
				input: action_text,
				zIndex: 99999999,
				buttons: [jQuery.extend({}, vex.dialog.buttons.YES)],
				afterOpen: function (data) {
					close_gdpr();
					setTimeout(function () {
						vex.close();
					}, 5000);
					send_email(email, jsonData.data.response, submit);
				},
				afterClose: function () {
					if (jsonData.data.vex_discount == 1) {
						vex.dialog.open({
							showCloseButton: true,
							escapeButtonCloses: false,
							overlayClosesOnClick: false,
							className: 'vex-cs newsletter_vex',
							input: script_manage_params_vex_input_ok,
							//buttons: [jQuery.extend({}, vex.dialog.buttons., {text: ''})]
							//jQuery.extend({}, vex.dialog.buttons.NO, {text: cms_js_lang_content_modules_cancel})],
							afterOpen: function (data) {
								jQuery(data).find('.vex-dialog-message').css('display', 'none');
								jQuery(data).find('[type="submit"]').attr("onClick", "subscribe_tooltip(this, 'vex')");
							}
						});
						jQuery('.newsletter_vex').find('.vex-dialog-buttons').hide();
					}
				}
			});
		})
		.send();

	var newsletterInput = jQuery('.newsletter_inputs .inputbox');
	if (newsletterInput.hasClass('tooltipstered')) {
		newsletterInput.removeClass('tooltipstered');
	}
	else {
	}
}

function gdpr_validate(action) {
	var $agreedInfoSubscriber = jQuery('#agreed_personal_info_field_subscriber');

	$agreedInfoSubscriber.siblings('.error_box').remove();
	$agreedInfoSubscriber.removeClass('error');

	// ak nieje potvrdeny suhlas
	if (jQuery('input#agreed_personal_info_field_subscriber').prop('checked') == false) {
		$agreedInfoSubscriber.addClass('error');
		$agreedInfoSubscriber.after('<div class="error_box">'+GDPR_NO_ACCEPTED+'</div>');

		return false;
	}

	if (action == 'sub') {
		submit_subscribe(GDPR_EMAIL_SEND);

		return false;
	}

	if (action == '') {//odhlasenie
		submit_subscribe(GDPR_EMAIL_SEND);
	}
	//vex.dialog.open({
	//	showCloseButton: true,
	//		className: 'vex-cs newsletter_vex',
	//		message: '',
	//		input: GDPR_EMAIL_QUESTION,
	//		buttons: [jQuery.extend({}, vex.dialog.buttons.YES, {text: script_manage_params_LM_unsubscribe})],
	//		onSubmit: function (e) {
	//			e.preventDefault();
	//			submit_subscribe(GDPR_EMAIL_SEND);
	//			vex.close();
	//		}
	//});

}

function subscribe_validate(sub) {
	// po kliknuti na button prihlasit / odhlasit z newsletteru
	if (sub == 1) {
		var user_geoip = script_manage_params_user_geoip;

		// kontrola recapcha v mod_letterman ;)
		if (typeof grecaptcha_mod_letterman_id !== "undefined") {
			if (grecaptcha.getResponse(grecaptcha_mod_letterman_id) == "") {
				jQuery("#mod_letterman_subscribe_check_grecaptcha").addClass("error");
				return false;
			} else {
				jQuery("#mod_letterman_subscribe_check_grecaptcha").removeClass("error");
			}
		}

		if (typeof js_Config_google_recaptcha !== 'undefined' && js_Config_google_recaptcha && (typeof js_Config_google_recaptcha_enable === 'undefined' || js_Config_google_recaptcha_enable.newsletter)) {
			grecaptcha.ready(function () {
				grecaptcha.execute(js_Config_google_recaptcha, {action: 'newsletter'}).then(function (token) {

					new AjaxRequest({token: token})
						.setMethod('POST')
						.setController('Captcha')
						.setAction('verify')
						.onSuccess(function (jsonData) {
							gdpr_validate('sub');
						})
						.onError(function (jsonData) {
							jQuery.each(jsonData.errors, function (errorMsgIndex, errorMsg) {
								vex.dialog.alert(errorMsg);// TODO notifikacia o chybe
							});
						})
						.send();
				});
			});
		} else if ( (typeof googleRecaptchaResponse === 'undefined' || googleRecaptchaResponse == false ) && jQuery('input[name="cansw"]').length ) {
			// ak uzivatel je zo slovenska alebo ceska sa mu nezobrazi captcha
			var captcha = jQuery('input[name="cansw"]').val();
			var captcha_id = jQuery('input[name="ccode"]').val();
			var googleCaptcha = jQuery('.g-recaptcha').length;

			var $captchaCode = jQuery('.captcha_enter_code');
			$captchaCode.removeClass('error');

			// nieje zadana capcha
			if (!captcha) {
				$captchaCode.addClass('error');

				return false;
			}

			new AjaxRequest({'entered_code': captcha, 'capcha_id': captcha_id})
				.setController("Captcha")
				.setAction('checkEnteredCodeEasyCapcha')
				.onSuccess(function (jsonData) {
					// captcha nieje spravna
					if (jsonData.data.captcha == false) {
						$captchaCode.addClass('error');
					} else {
						gdpr_validate('sub');
					}
				})
				.send();
		} else if ( (typeof googleRecaptchaResponse === 'undefined' || googleRecaptchaResponse == false ) && jQuery('input[name="captcha_code"]').length ) {
			var captcha = jQuery('input[name="captcha_code"]');
			var captchaCode = captcha.val();
			captcha.removeClass('error');

			// nieje zadana capcha
			if (!captchaCode) {
				captcha.addClass('error').focus();
				vex.dialog.alert(cms_js_lang_add_comment_captcha_error);
				return false;
			}

			new AjaxRequest({'entered_code': captchaCode})
				.setController("Captcha")
				.setAction('secureImage')
				.onSuccess(function (jsonData) {
					// captcha nieje spravna
					if (jsonData.data.captcha == false) {
						captcha.addClass('error');
					} else {
						gdpr_validate('sub');
					}
				})
				.send();
		} else {
			gdpr_validate('sub');
		}

		return true;
	}

	gdpr_validate('');
}

function submit_enter(e) {
	// ak stlaci enter
	if (e.keyCode == 13) {
		jQuery('.subscribe_gdpr_button').trigger('click');
	}
}

function js_mod_subscriber_submit(elem) {
	// TODO: zobrazenie jedneho tooltipstera kde bude capcha a aj gdpr suhlas so spracovanim osobných udajov
	googleRecaptchaResponse = false;
	subscribe_tooltip(elem, '', '');
}

window.addEventListener('DOMContentLoaded', function() {
	if ( jQuery('#g-recaptcha-response').length ) {
		if ( typeof js_Config_use_google_recaptcha === 'undefined' ) {
			js_show_re_captcha(); // do funkcie sa to nedostane? pretoze sa captcha generuje v twigu config 'Config_use_google_recaptcha' kde sa generuje html tu pre if vyssie nevojde
		}
	}
});


/* ========================================
 FILE: /modules/js/mod_shop_login.js
 ==================== */

(function(){
	script_manage_params = typeof script_manage_params === 'object' ? script_manage_params : {};
	script_manage_params.sh_lg = typeof script_manage_params.sh_lg !== 'undefined' ? script_manage_params.sh_lg : {};

	const params = {
		'ijs': typeof script_manage_params.sh_lg.ijs !== 'undefined' ? script_manage_params.sh_lg.ijs : '',
		'li': typeof script_manage_params.sh_lg.li !== 'undefined' ? script_manage_params.sh_lg.li : '',
		'im3chrq': typeof script_manage_params.sh_lg.im3chrq !== 'undefined' ? script_manage_params.sh_lg.im3chrq : '',
		'_un': typeof script_manage_params.sh_lg._un !== 'undefined' ? script_manage_params.sh_lg._un : ''
	};

	if ( params.ijs ) {
		var $passwordField = jQuery('form[name="login"] #login_password_field');
		var $passwordFieldVirtual = jQuery('form[name="login"] #password_field_virtual');

		var pos = $passwordField.position();

		if (typeof pos !== 'undefined') {
			$passwordFieldVirtual.css({'left': (pos.left) + 'px', 'top': (pos.top) + 'px', 'position': 'absolute' });
		}

		$passwordField.hide().attr('tabindex', -1);

		$passwordFieldVirtual.on('focus', function () {
			js_show_password_field();
		});

		$passwordField.on('change blur', function () {
			hidePasswordFieldIfEmpty();
		});

		window.js_show_password_field = function js_show_password_field() {
			$passwordField.show().removeAttr('tabindex').trigger('focus');
			$passwordFieldVirtual.hide();
		};

		window.hidePasswordFieldIfEmpty = function hidePasswordFieldIfEmpty() {
			if ($passwordField.val() === '') {
				$passwordField.hide().attr('tabindex', -1);
				$passwordFieldVirtual.show();
			}
		}

		window.js_default_login = function js_default_login(e, js_action) {
			var elem = document.getElementById(e);
			// alert(elem.value);

			switch ( js_action ) {
				case 'blur':
					if ( elem.value == '' ) {
						elem.style.color = '#777';
						elem.value=params._un;
					}
				break;

				case 'focus':
					if ( elem.value == params._un ) {
						elem.style.color = '#333';
						elem.value = '';
					}
				break;

				case 'submit':
					if ( elem.value == params._un) {
						elem.style.color = '#333';
						elem.focus();
						return false;
					}
					if (elem.value.length < 3) {
						alert(params.im3chrq);
						return false;
					}
					return true;
			}
		};
	}

	window.js_login_form_valid_submit = function js_login_form_valid_submit(form) {
		if (typeof window['mod_login_submitting'] !== 'undefined' && window['mod_login_submitting']) {
			return false;
		}

		if (form.username.value == '' || form.passwd.value == '') {
			alert(params.li);
			return false;
		}

		window['mod_login_submitting'] = true;
		jQuery(form).find('input[type="submit"]').attr('disabled', true);
		return true;
	};

})();


/* ========================================
 FILE: /includes/comments/comments.js
 ==================== */

/**
 * @fileOverview Comments
 * @author Creativesites
 * @copyright Copyright (c) 2017 CreativeSites
 * @version 1.4.7
 * @link https://www.creativesites.sk/
 * @requires jQuery
 */

/**
 * See <a href="http://jquery.com">http://jquery.com</a>.
 * @name jQuery
 * @class
 * See the jQuery Library (<a href="http://jquery.com">http://jquery.com</a>) for full details.
 * This just documents the function and classes that are added to jQuery by this plug-in.
 */

/**
 * Check whether element is schema comment
 * @function isSchemaComments
 *
 * @param {HTMLElement} parent
 *
 * @return {Boolean}
 */
function isSchemaComments(parent)
{
	return parent.hasClass('schema');
}

/**
 *
 * @function ratePrint
 *
 * @param {HTMLElement} container
 * @param {Number} rating
 * @param {Number} fullStar
 * @param {Boolean} readOnly
 * @param {Number} width
 *
 * @return {void}
 */
function ratePrint(container, rating, fullStar, readOnly, width)
{
	if (typeof container == 'undefined' || !container.length) return;

	if(is_cs_user('separate_js')) {

		var props = {
			readOnly: readOnly,
			rating: rating,
			fullStar: fullStar,
			starWidth: width + "px"
		};
		container.rateYo(props);

		//// pridanie hodnoty 3/5 do title
		//var numStars = container.rateYo("option", "numStars");
		//container.rateYo().on("rateyo.change", function (e, data) {
		//	var rating = data.rating;
		//	jQuery(this).prop('title', rating + '/' + numStars);
		//});

	} else {
		var props = {
			readOnly: readOnly,
			rating: rating,
			fullStar: fullStar,
			starWidth: width + "px",
			ratedFill: "#F39C12",
			spacing: "0px",
			normalFill: "#808080",
		};
		if(typeof js_CS_Config_rateyo_configuration !== 'undefined'){
			for (var key in props) {
				if (!props.hasOwnProperty(key)) continue;
				if( typeof js_CS_Config_rateyo_configuration[key] !== 'undefined'){
					props[key] = js_CS_Config_rateyo_configuration[key];
				}
			}
			if(typeof js_CS_Config_rateyo_configuration.starSvg !== 'undefined'){
				props.starSvg = js_CS_Config_rateyo_configuration.starSvg;
			}
		}
		container.rateYo(props);
	}


}

function rateAjaxComments() {
	var container_element = jQuery('.comments_container');

	if (isSchemaComments(container_element)) {
		// comments
		jQuery('.rating-container').each(function() {
			var rating = jQuery(this).find('meta[itemprop=ratingValue]').attr('content');
			ratePrint(jQuery(this).find('.review_rating'), rating, true, true, 20);
		});

		// add comment
		var add_review_rating = container_element.find('#addCommentContainer .review_rating');
		ratePrint(add_review_rating, 0, true, false, 30);

		// reply comment
		var reply_review_rating = container_element.find('#addCommentReplyForm .review_rating');
		ratePrint(reply_review_rating, 0, true, false, 30);
	}

	if ( typeof js_Config_replying_to_comments_hide_btn !== 'undefined' && js_Config_replying_to_comments_hide_btn ) {
		if (typeof js_Config_replying_to_comments_enabled === 'undefined') {
			jQuery('.reply_button_panel').hide();
		} else {
			if ( typeof js_Config_replying_to_comments_enabled !== 'undefined' && js_Config_replying_to_comments_enabled == 2 ) {
				if ( ( typeof js_global_user_info === "undefined" ) || ( typeof js_global_user_info != 'undefined' && js_global_user_info.gid < 24 ) ) {
					jQuery('.reply_button_panel').hide();
				}
			}
		}
	}



	// product_rating
	setTimeout(function() {
		js_parse_ratings();
	}, 1000);
}

jQuery(function() {
	var container_element = jQuery('.comments_container');

	autofillUserInput(container_element);

	if (isSchemaComments(container_element)) {
		// comments
		jQuery('.rating-container').each(function() {
			var rating = jQuery(this).find('meta[itemprop=ratingValue]').attr('content');
			ratePrint(jQuery(this).find('.review_rating'), rating, true, true, 20);
		});

		// add comment
		var add_review_rating = container_element.find('#addCommentContainer .review_rating');
		ratePrint(add_review_rating, 0, true, false, 30);

		// reply comment
		var reply_review_rating = container_element.find('#addCommentReplyForm .review_rating');
		ratePrint(reply_review_rating, 0, true, false, 30);
	}

	if ( typeof js_Config_replying_to_comments_hide_btn !== 'undefined' && js_Config_replying_to_comments_hide_btn ) {
		if (typeof js_Config_replying_to_comments_enabled === 'undefined') {
			jQuery('.reply_button_panel').hide();
		} else {
			if ( typeof js_Config_replying_to_comments_enabled !== 'undefined' && js_Config_replying_to_comments_enabled == 2 ) {
				if ( ( typeof js_global_user_info === "undefined" ) || ( typeof js_global_user_info != 'undefined' && js_global_user_info.gid < 24 ) ) {
					jQuery('.reply_button_panel').hide();
				}
			}
		}
	}

	// product_rating
	setTimeout(function() {
		js_parse_ratings();
	}, 1000);


});

/**
 * Automatically fills user inputs if logged in.
 * @function autofillUserInput
 *
 * @return {void}
 */
function autofillUserInput(container)
{
	var addCommentForm = container.find('#addCommentForm');
	var addCommentReplyForm = container.find('#addCommentReplyForm');

	if( typeof js_global_user_info === 'undefined' ) {
		return;
	}

	if( typeof js_global_user_info.name !== 'undefined' ) {
		addCommentForm.find('#add_comment_name').val(js_global_user_info.name);
		addCommentReplyForm.find('#reply_comment_name').val(js_global_user_info.name);
	}

	if( typeof js_global_user_info.email !== 'undefined' ) {
		addCommentForm.find('#add_comment_email').val(js_global_user_info.email);
		addCommentReplyForm.find('#reply_comment_email').val(js_global_user_info.email);
	}
}

/**
 * Parse rating elements
 * @function js_parse_ratings
 *
 * @return {void}
 */
function js_parse_ratings()
{
	if (jQuery('.product_rating').length > 0) {
		jQuery('.product_rating').each(function() {
			var rating = jQuery(this).find('.prod_rating_val').html();

			if (rating != '' && rating > 0) {
				var prod_rating = jQuery(this).find('.prod_rating');

				ratePrint(prod_rating, parseFloat(rating), false, true, 25);
			}
		});
	}
}

/**
 * Trim comment body
 * @function js_comment_trim_input_value
 *
 * @param {HTMLElement} input_element
 *
 * @return {void}
 */
function js_comment_trim_input_value(input_element)
{
	jQuery(input_element).attr('value', jQuery.trim( jQuery(input_element).val() ));
}

/**
 * Comment mouseover event handler
 * @function js_comment_mouseover
 *
 * @param {HTMLElement} element
 *
 * @return {void}
 */
function js_comment_mouseover(element)
{
	var container_element = jQuery(element);

	if (!container_element.hasClass('comment')) {
		container_element = container_element.parents('.comment:first');
	}

	if (container_element.data('editing_comment') == 1) {
		return;
	}

	container_element.find('.comment_edit_panel:first, .comment_delete_panel:first, .comment_approve_panel:first').show();
}

/**
 * Comment mouseout event handler
 * @function js_comment_mouseout
 *
 * @param {HTMLElement} element
 *
 * @return {void}
 */
function js_comment_mouseout( element ) {
	var container_element = jQuery(element);

	if (!container_element.hasClass('comment')) {
		container_element = container_element.parents('.comment:first');
	}

	container_element.find('.comment_edit_panel:first, .comment_delete_panel:first, .comment_approve_panel:first').hide();
}

/**
 * Sanitize comment
 * @function js_make_comment_text_html_safe
 *
 * @param {String} text
 *
 * @return {String}
 */
function js_make_comment_text_html_safe(text)
{
	return (text.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/"/g, '&quot;'));
}

/**
 * Comment cancel edit event handler
 * @function js_edit_comment_cancel_click
 *
 * @param {HTMLElement} link_element
 *
 * @return {Boolean}
 */
function js_edit_comment_cancel_click(link_element)
{
	var container_element = jQuery(link_element).parents('.comment:first');

	container_element.removeData('editing_comment');
	container_element.find('.comment_content_editing_panel').remove();
	container_element.find('p:last').removeClass('comment_data_editing');
	container_element.find('.name:first').removeClass('comment_data_editing');
	container_element.find('.date:first').removeClass('comment_data_editing');

	if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1') ) {
		container_element.find('.upload_edit_content_img').remove();
		container_element.find('.comment_image').show();
	}

	if (isSchemaComments(container_element)) {
		var comment_rating_el = container_element.find('.review_rating');
		var oldRating = container_element.find('meta[itemprop=ratingValue]').attr('content');

		comment_rating_el.rateYo('option', 'rating', oldRating);
		comment_rating_el.rateYo('option', 'readOnly', true);
	}

	container_element.find('select').hide();

	return false;
}

/**
 * Comment edit timeout
 * @function js_update_edit_comment_timeout
 *
 * @param {Number} comment_id
 *
 * @return {void}
 */
function js_update_edit_comment_timeout( comment_id ) {
	var container_element = jQuery('.comments_list_container:first .comment_id_'+comment_id.toString()+':first');

	if (!container_element.length || !container_element.find('.edit_comment_timeout:first').length) {
		return;
	}

	var timeout_left = container_element.data('edit_timeout_left');

	// koniec casu pre upravu komentara
	if (timeout_left <= 0) {
		container_element.find('.comment_edit_buttons:first .mp_action_cancel:first').trigger('click');
		container_element.find('.edit_comment_timeout:first, .comment_edit_panel:first, .comment_delete_panel:first, input[name="editing_timeout_left"]:first').remove();
		container_element.off('mouseover').removeAttr('onmouseover').off('mouseout').removeAttr('onmouseout');
		if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1')  ) { //js_CS_Config_comments_attachment_in_detail_accout_index
			if(container_element.data('hidden_img') != ''){
				container_element.addClass(container_element.data('hidden_img'));
			}
		}

		return;
	}

	var timeout_minutes = Math.ceil(timeout_left / 60);
	var timeout_update_interval = (timeout_left % 60);

	if (timeout_update_interval == 0) {
		timeout_update_interval = 30;
	}

	if (timeout_minutes > 1 && timeout_minutes < 5) {
		var minutes_text = cms_js_lang_edit_commnet_minutes;
	} else if (timeout_minutes >= 5) {
		var minutes_text = cms_js_lang_edit_commnet_minutes2;
	} else {
		var minutes_text = cms_js_lang_edit_commnet_minute;
	}

	container_element
		.find('.edit_comment_timeout:first .time_left').html(timeout_minutes +' '+ minutes_text)
		.end().data('edit_timeout_left', timeout_left - timeout_update_interval)
		.data('edit_timeout_timer', setTimeout('js_update_edit_comment_timeout('+comment_id+');', timeout_update_interval * 1000));
}

/**
 * Set comment edit timeout
 * @function js_set_edit_comment_timeout
 *
 * @param {HTMLElement} container_element
 *
 * @return {void}
 */
function js_set_edit_comment_timeout(container_element)
{
	container_element = jQuery(container_element);

	if (!container_element.find('input[name="editing_timeout_left"]:first').length || container_element.find('.edit_comment_timeout:first').length) {
		return;
	}

	var comment_id = container_element.find('input[name="comment_id"]:first').val();
	var timeout_left = container_element.find('input[name="editing_timeout_left"]:first').val();
	var timeout_minutes = Math.ceil(timeout_left / 60);

	if (timeout_minutes > 1 && timeout_minutes < 5) {
		var minutes_text = cms_js_lang_edit_commnet_minutes;
	} else if (timeout_minutes >= 5) {
		var minutes_text = cms_js_lang_edit_commnet_minutes2;
	} else {
		var minutes_text = cms_js_lang_edit_commnet_minute;
	}

	//container_element.find('p:last').after([
	container_element.find('.reply_button_panel').before([
		'<div class="edit_comment_timeout">',
			cms_js_lang_edit_comment_time_left.replace('%s', timeout_minutes +' '+ minutes_text),
		'</div>'
	].join(''));
	if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1')  ) {
		if(container_element.hasClass('hidden')){ //js_CS_Config_comments_attachment_in_detail_accout_index
			var img_is_hidden = 'hidden';
			container_element.removeClass('hidden');
			container_element.data('hidden_img',img_is_hidden);
		}
	}
	container_element.data('edit_timeout_left', timeout_left);

	js_update_edit_comment_timeout(comment_id);
}

/**
 * Comment edit save event handler
 * @function js_edit_comment_save_click
 *
 * @param {HTMLElement} link_element
 *
 * @return {(Boolean|void)}
 */
function js_edit_comment_save_click(link_element)
{
	var container_element = jQuery(link_element).parents('.comment:first');
	var body_textarea_element = container_element.find('textarea[name="body"]:first');
	var name_input_element = container_element.find('input[name="name"]:first');
	var date_input_element = container_element.find('input[name="date"]:first');
	var comment_id = container_element.find('input[name="comment_id"]:first').val();
	var page_url = container_element.find('input[name="page_url"]:first').val();

	if (isSchemaComments(container_element)) {
		if ( typeof js_CS_Config_cs_rating !== 'undefined' && js_CS_Config_cs_rating ) {
			var comment_rating_el = container_element.find('.cs_rating_wrapper.set_rating');
		} else {
			var comment_rating_el = container_element.find('.review_rating');

			comment_rating_el.rateYo('option', 'readOnly', true);
		}
	}

	js_comment_trim_input_value(name_input_element);

	if (name_input_element.val() == '') {
		vex.dialog.alert(cms_js_lang_add_comment_your_name_error);
		name_input_element.trigger('focus');

		return false;
	} else if (jQuery.trim(body_textarea_element.val()) == '') {
		vex.dialog.alert(cms_js_lang_add_comment_body_error);
		body_textarea_element.trigger('focus');
		return false;
	}

	var dateTemp = jQuery.trim(date_input_element.val());

	if (dateTemp == '' || !dateTemp.match(/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})$/)) {
		vex.dialog.alert(cms_js_lang_edit_comment_date_error);
		date_input_element.trigger('focus');

		return false;
	}

	container_element.find('.comment_edit_buttons:first').hide();
	container_element.find('.comments_ajax_loader:first').show();

	var ajax_params = {
		name: name_input_element.val(),
		body: body_textarea_element.val(),
		comment_id: comment_id,
		page_url: page_url,
		date: date_input_element.val()
	};

	if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1')  ) {
		var comment_images = container_element.find('.upload_edit_content_img').find('.dz-filename').map(function () {
			return jQuery(this).data('file_name');
		}).get();
		ajax_params.comment_images = comment_images;

	}

	if (container_element.find('select[name="lang"]:first') != false) {
		ajax_params.lang = (typeof container_element.find('select[name="lang"]:first').val() === "undefined" ? "" : container_element.find('select[name="lang"]:first').val());
	}

	// if there's no rating, don't send it as an option in ajax_params
	if (isSchemaComments(container_element) && comment_rating_el.length) {
		var rating;

		if ( typeof js_CS_Config_cs_rating !== 'undefined' && js_CS_Config_cs_rating ) {
			rating = comment_rating_el.data('val');
		} else {
			rating = comment_rating_el.rateYo('option', 'rating');
		}

		ajax_params.rating = rating;

		container_element.find('meta[itemprop=ratingValue]').attr('content', rating);
	}


	var url = js_global_live_site +'/includes/comments/comments_ajax.php?option=com_shop&ajax_call=1&ajax_func=edit_comment&no_html=1&no_vm_html=1&no_menu=1&no_css=1';

	jQuery.post(url, ajax_params, function(res) {
		container_element.find('.comments_ajax_loader:first').hide();
		container_element.find('.comment_edit_buttons:first').show();

		var res_splitted = res.split('|');

		if (typeof(res_splitted[1]) === 'undefined') {
			res_splitted[1] = '';
		}

		if (res == '' || res.substr(0,1) == '0') {
			switch(res_splitted[1]) {
				case 'error_name':
					vex.dialog.alert(cms_js_lang_add_comment_your_name_error);
					break;

				case 'error_body':
					vex.dialog.alert(cms_js_lang_add_comment_body_error);
					break;

				default:
					vex.dialog.alert(cms_js_lang_edit_comment_error);
					break;
			}

			return;
		}

		if (res_splitted[0] == '1' && res_splitted[1] == 'clear') {
			container_element.remove();
			return;
		}

		if ( typeof js_CS_Config_cs_rating !== 'undefined' && js_CS_Config_cs_rating ) {
			var setRating = CsRating.get(comment_rating_el.find('.rating').get(0));
			setRating && setRating.destroy();
		}

		var new_comment_container = jQuery(res_splitted[1]);

		container_element.find('.date').after(new_comment_container.find('.date').detach()).remove();
		container_element.find('.name:first').after( new_comment_container.find('.name:first').detach() ).remove();
		container_element.find('p:last').after( new_comment_container.find('p:last').detach() ).remove();
		if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1')  ) {
			container_element.find('.comment_images').after( new_comment_container.find('.comment_images').detach() ).remove();
		}
		container_element.find('.mp_action_cancel:first').trigger('click');

		js_set_edit_comment_timeout(container_element);
	});

	return false;
}

/**
 * Comment edit event handler
 * @function js_edit_comment_click
 *
 * @param {HTMLElement} link_element
 *
 * @return {Boolean}
 */
function js_edit_comment_click(link_element)
{
	link_element = jQuery(link_element);

	var container_element = link_element.parents('.comment:first');
	var comment_id = container_element.find('input[name="comment_id"]:first').val();

	if ( typeof js_CS_Config_cs_rating !== 'undefined' && js_CS_Config_cs_rating ) {
		container_element.find('.cs_rating_wrapper').addClass('set_rating');
		var $setRatingElem = container_element.find('.cs_rating_wrapper .rating').get(0);
		if ($setRatingElem) {
			new CsRating($setRatingElem);
		}
	}

	container_element.find(".rating-container").show();

	container_element.data('editing_comment', 1);
	js_comment_mouseout( container_element );

	var comment_body_element;
	if ( container_element.find('p.comment_body').length ) {
        comment_body_element = container_element.find('p.comment_body');
	} else if ( container_element.find('p.review-body').length ) {
        comment_body_element = container_element.find('p.review-body');
	}
	var comment_name_element = container_element.find('.name:first');
	var comment_date_element = container_element.find('.date');

	comment_name_element.addClass('comment_data_editing').addClass('comment_data_editing').after([
		'<div class="comment_content_editing_panel">',
			'<input type="text" style="width:70%" name="name" value="'+ js_make_comment_text_html_safe(comment_name_element.text()) +'" maxlength="255"/>',
			'<input type="text" style="width:29%" name="date" value="'+ js_make_comment_text_html_safe(comment_date_element.find('a').text()) +'" maxlength="255"/>',
		'</div>'
	].join(''));

	if (typeof js_global_user_info != 'undefined' && (js_global_user_info.gid=='24' || js_global_user_info.gid=='25')) {
		container_element.find('select').show();
	}

	comment_body_element.addClass('comment_data_editing').after([
		'<div class="comment_content_editing_panel">',
			'<textarea name="body" cols="" rows="5" style="width:100%">',
				js_make_comment_text_html_safe(comment_body_element.html().replace(/\<br\s?\/?\>/g, "\n")),
			'</textarea>',
			'<br/>',
			'<img src="/images/ajax-loader-05.gif" class="comments_ajax_loader" alt="..." />',
			'<div class="comment_edit_buttons">',
				'<input type="button" class="button edit_comment_button" value="'+ cms_js_lang_products_group_4 +'" onclick="return js_edit_comment_save_click(this);"/>',
				'<a href="#" onclick="return js_edit_comment_cancel_click(this);" class="mp_action_cancel" style="display:inline;float:none;padding-left:10px">',
					cms_js_lang_products_group_3,
				'</a>',
			'</div>',
		'</div>'
	].join(''));

	if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1')  ) {

		var comment_images = '<div class="upload_edit_content_img_div_'+ js_product_id +' upload_edit_content_img"><div id="dropzone-previews_edit_'+ js_product_id +'" class="dropzone-previews"><div class="dz-message needsclick"><span class="needsclick">Nahrajte obrázok ako prílohu komentáru</span> <span class="info-popup">info popup</span> </div> </div></div>';
		container_element.find('.comment_form_edit').find('.comment_image').hide();
		jQuery(comment_images).appendTo(container_element.find('.comment_form_edit'));
		Dropzone.autoDiscover = false;

		jQuery("div.upload_edit_content_img_div_"+js_product_id).dropzone({
			url: "includes/frontend_ajax.php",
			maxFilesize: 5,
			maxFiles: 3,
			clickable: true,
			acceptedFiles:'.jpg,.jpeg,.png',
			dictDefaultMessage: cms_dropzone_drop_images_here,
			dictRemoveFile: cms_dropzone_remove_file,
			dictMaxFilesExceeded: js_lang_admin_media_dropzone_too_many_files,
			dictFileTooBig: js_lang_admin_media_dropzone_file_too_big,
			dictCancelUpload: js_lang_admin_media_dropzone_upload_cancel,
			paramName: 'qqfile',
			params: {'function':'saveCommentAttachment', 'product_id': +js_product_id },
			previewsContainer: '#dropzone-previews_edit_'+js_product_id,
			addRemoveLinks: true,
			init: function() {
				this.on('error', function(file, message) {
					alert(message);
					this.removeFile(file);
				});
				myDropzone = this;
				container_element.find('.comment_image img').each(function(i,v){
					var elem = jQuery(v);
					var img_name = elem.prop('alt');
					var img_path = elem.prop('src');
					var img_size = elem.data('file_size');
					var mockFile = { name: img_name, size: img_size};

					myDropzone.emit("addedfile", mockFile);
					myDropzone.emit("thumbnail", mockFile, img_path);
					myDropzone.emit("complete", mockFile);

					jQuery(mockFile.previewElement).find('.dz-filename').data('file_name',img_name);// potrebne pre save/update
					myDropzone.options.maxFiles -= 1;
				});
			},
			success: function(dropzone) {
				commentAttachment = JSON.parse(dropzone.xhr.response).fileName;
				jQuery(dropzone.previewElement).find('.dz-filename').data('file_name',JSON.parse(dropzone.xhr.response).fileName);
			},
			//removedfile: function(file) {
			//	showLoader();
			//	dropzoneRemoveContentImage_+js_product_id(js_product_id,file);
			//}
		});

	}

	if (isSchemaComments(container_element)) {
		var comment_rating_el = container_element.find('.review_rating');

		comment_rating_el.rateYo('option', 'readOnly', false);
	}

	container_element.find('.comment_content_editing_panel:first input:first').trigger('focus');

	return false;
}

/**
 * Comment delete event handler
 * @function js_delete_comment_click
 *
 * @param {HTMLElement} link_element
 *
 * @return {Boolean}
 */
function js_delete_comment_click(link_element)
{
	link_element = jQuery(link_element);

	vex.dialog.confirm({
		message: cms_js_lang_delete_comment_confirm,
		callback: function(confirmed) {
			if (confirmed) {
				var container_element = link_element.parents('.comment:first');
				var comment_id = container_element.find('input[name="comment_id"]:first').val();
				var comment_list = container_element.parents('.comments_list_container');
				container_element.data('editing_comment', 1);


				js_comment_mouseout(container_element);

				jQuery.post(js_global_live_site +'/includes/comments/comments_ajax.php?option=com_shop&ajax_call=1&ajax_func=delete_comment&no_html=1&no_vm_html=1&no_menu=1&no_css=1', {
					comment_id: comment_id
				}, function(res) {
					var res_splitted = res.split('|');

					if (typeof(res_splitted[1]) === 'undefined') {
						res_splitted[1] = '';
					}

					if (res == '' || res.substr(0,1) == '0') {
						container_element.removeData('editing_comment');

						vex.dialog.alert(cms_js_lang_delete_comment_error);

						return;
					}

					// ak je otvorena reakcia na tento komentar, ukonci ju
					var reply_container_element = container_element.next('.addCommentReplyContainer:first:visible');

					if (reply_container_element.length) {
						if (reply_container_element.next('.comment_reply_container').length) {
							reply_container_element.next('.comment_reply_container').slideUp(400, function() {
								jQuery(this).remove();
							});
						}

						reply_container_element.find('.mp_action_cancel:first').trigger('click');
					} else if (container_element.next('.comment_reply_container').length) {
						container_element.next('.comment_reply_container').slideUp(400, function() {
							jQuery(this).remove();
						});
					}

					container_element.slideUp(400, function() {
						jQuery(this).removeData('edit_timeout_left');

						if (jQuery(this).data('edit_timeout_timer') != null) {
							clearTimeout(jQuery(this).data('edit_timeout_timer'));

							jQuery(this).removeData('edit_timeout_timer');
						}

						jQuery(this).remove();

						if(comment_list.find('.comment').length == 0) {
							comment_list.closest('.comments_container.schema').addClass('comments_container_empty');
						}
					});

				});
			}
		}
	});

	return false;
}

/**
 * Comment delete event handler
 * @function js_delete_comment_click
 *
 * @param {HTMLElement} link_element
 *
 * @return {Boolean}
 */
function js_approve_comment_click(link_element)
{
	link_element = jQuery(link_element);

	vex.dialog.confirm({
		message: 'Potvrdiť obrázkovú prílohu komentáru',
		callback: function(confirmed) {
			if (confirmed) {
				var container_element = link_element.parents('.comment:first');
				var comment_id = container_element.find('input[name="comment_id"]:first').val();

				container_element.data('editing_comment', 1);

				js_comment_mouseout(container_element);//

				jQuery.post(js_global_live_site +'/includes/comments/comments_ajax.php?option=com_shop&ajax_call=1&ajax_func=approve_comment&no_html=1&no_vm_html=1&no_menu=1&no_css=1', {
					comment_id: comment_id
				}, function(res) {
					var res_splitted = res.split('|');

					if (typeof(res_splitted[1]) === 'undefined') {
						res_splitted[1] = '';
					}

					if (res == '' || res.substr(0,1) == '0') {
						container_element.removeData('editing_comment');

						vex.dialog.alert('Nepodarilo sa potvrdiť obrázkovú prílohu komentáru');

						return;
					}

				});
			}
		}
	});

	return false;
}


/**
 * Cancel reply to comment event handler
 * @function js_reply_to_comment_cancel_click
 *
 * @param {HTMLElement} link_element
 *
 * @return {Boolean}
 */
function js_reply_to_comment_cancel_click(link_element)
{
	link_element = jQuery(link_element);

	var comments_container = link_element.parents('.comments_container:first');
	var reply_form_container = link_element.parents('.addCommentReplyContainer:first');

	reply_form_container.find('input[name="parent_comment_id"]:first').val('0');
	reply_form_container.find('input[name="url"]:first').val('');
	reply_form_container.find('textarea[name="body"]:first').val('');

	if (isSchemaComments(comments_container)) {
		reply_form_container.find('.review_rating').rateYo('rating', 0);
	}

	reply_form_container.slideUp(400);

	return false;
}

/**
 * Reply to comment
 * @function js_reply_to_comment_click
 *
 * @param {HTMLElement} link_element
 *
 * @return {Boolean}
 */
function js_reply_to_comment_click(input_element)
{
	input_element = jQuery(input_element);
	var panel_element = input_element.parents('.reply_button_panel:first');
	var comment_element = panel_element.parents('.comment:first');
	var comment_id = comment_element.find('input[name="comment_id"]:first').val();
	var reply_form_container = panel_element.parents('.comments_container:first').find('.addCommentReplyContainer:first');

	if (reply_form_container.is(':visible')) {
		vex.dialog.alert(cms_js_lang_reply_to_comment_opened_error);
		return false;
	}

	input_element.hide();
	panel_element.find('.reply_to_comment_ajax_loader:first').show();
	reply_form_container.find('input[name="parent_comment_id"]:first').val(comment_id);

	if(typeof js_CS_Config_display_comment_ajax_slick !== 'undefined' && js_CS_Config_display_comment_ajax_slick) {
		if(!comment_element.parent().find('.addCommentReplyContainer:first').length) {
			comment_element.after(reply_form_container.clone());
		}
		reply_form_container = comment_element.parent().find('.addCommentReplyContainer:first');
	} else {
		comment_element.after(reply_form_container.detach());
	}

	reply_form_container.slideDown(400, function() {
		jQuery(this).find('input[name="name"]:first').trigger('focus');
	});

	panel_element.find('.reply_to_comment_ajax_loader:first').hide();
	input_element.show();

	return false;
}

/**
 * Load less comments
 * @function js_load_less_comments
 *
 * @param {HTMLElement} input_element
 */
function js_load_less_comments(input_element) {
	var lessButton = jQuery(input_element);
	var moreButton = lessButton.parent().find('.btn-show-more:first');
	var options_input = lessButton.parent().find('.comment_data:first');

	var offset = moreButton.attr('data-offset');
	var isReply = lessButton.closest('.comments_btns_wrap').hasClass('is_reply');

	var skipHiding = options_input.attr(isReply ? 'data-more_reply' : 'data-more');

	var comments = isReply ? lessButton.closest('.comment_reply_container').find('> .comment') : lessButton.closest('.comments_container').find('> div > .comment');

	if(comments.length) {
		comments.each(function() {
			if(skipHiding > 0) {
				skipHiding--;
				return true;
			}

			jQuery(this)
				.addClass('hidden')
				.hide()
				.next('.comment_reply_container')
				.addClass('hidden')
				.hide();
		});
	}

	lessButton.addClass('hidden').hide();
	moreButton.show();
}

/**
 * Load more comments
 * @function js_load_more_comments
 *
 * @param {HTMLElement} input_element
 */
function js_load_more_comments(input_element) {
	var options_input = jQuery(input_element).parent().find('.comment_data:first');
	var isReply = parseInt(options_input.attr('data-comment_parent_id')) > 0;

	var hiddenComments = isReply ? jQuery(input_element).closest('.comment_reply_container').find('> .hidden') : jQuery(input_element).closest('.comments_container').find('> div > .hidden');

	if(hiddenComments.length) {
		hiddenComments.removeClass('hidden').show();
		options_input.parent().find('.btn-show-less:first').removeClass('hidden').show();
		options_input.parent().find('.showed_all').hide();
		return;
	}

	var options = {
		'page_type': options_input.attr('data-page_type'),
		'page_id': options_input.attr('data-page_id'),
		'heureka': options_input.attr('data-heureka'),
		'mail_review': options_input.attr('data-mail_review'),
		'iterator': options_input.attr('data-iterator'),
		'parent_id': options_input.attr('data-comment_parent_id')
	};

	var offset = jQuery(input_element).attr('data-offset');

	if(typeof offset !== 'undefined') {
		options.offset = offset;
	}

	var loaderHtml = '<span class="comments_loader"></span>';

	jQuery('.comments_list_container .btn-show-more').before(loaderHtml);

	new AjaxRequest(options)
		.setController('Product')
		.setAction('getMoreComments')
		.onSuccess(function (jsonData) {
			var elem = jQuery(input_element).parent();
			elem.parent().append(jsonData.data[0]);
			elem.remove();
			rateAjaxComments();
			jQuery('.comments_list_container .comments_loader').remove();
		})
		.onError(function (jsonData) {
			vex.dialog.alert(mod_quickicon_delete_cookie_error);/*TODO: LANG*/
		})
		.send();
}

/**
 * Reply to comment
 * @function js_comment_slide
 *
 * @param {HTMLElement}
 *
 * @return {VoidFunction}
 */
function js_comment_slide()
{
	var comments = jQuery('.comments_container.schema');

	comments.each(function(item) {
		var schema = jQuery(this);
		var arrows = schema.find('.comments_title_arrows');
		var commentData = schema.find('span.hidden.comment_data');

		arrows.find('.comment_current').text('1');
		arrows.find('.comment_count').text(commentData.attr('data-count'));

		if(commentData.attr('data-count') !== '0') {
			arrows.removeClass('hidden');
			if(commentData.attr('data-count') > '1') {
				arrows.find('.prev_arrow').click({param: 'prev'}, js_comment_slide_comment);
				arrows.find('.next_arrow').click({param: 'next'}, js_comment_slide_comment);
			}
		}
	});
}

/**
 * Reply to comment
 * @function js_comment_slide_comment
 *
 * @param {Event}
 *
 * @return {VoidFunction}
 */
function js_comment_slide_comment(event)
{
	if(typeof event.data.param === 'undefined') return;

	var next = (event.data.param === 'next');

	var schema = jQuery(event.target).closest('.comments_container.schema');
	var commentData = schema.find('span.hidden.comment_data');
	var current = parseInt(commentData.attr('data-iterator'));
	var count = parseInt(commentData.attr('data-count'));

	if (next) {
		if(current === (count - 1)) {
			current = 0;
		} else {
			current++;
		}
	} else {
		if(current === 0) {
			current = (count - 1);
		} else {
			current--;
		}
	}

	var commentDataArr = {
		'page_type' : commentData.attr('data-page_type'),
		'page_id' : commentData.attr('data-page_id'),
		'heureka' : commentData.attr('data-heureka'),
		'mail_review' : commentData.attr('data-mail_review'),
		'iterator' : current,
		'parent_id' : commentData.attr('data-comment_parent_id'),
		'slider': true,
	};

	var loaderHtml = '<span class="comments_loader"></span>';

	schema.find('comments_list_container').before(loaderHtml);

	new AjaxRequest(commentDataArr)
		.setController('Product')
		.setAction('getMoreComments')
		.onSuccess(function (jsonData) {
			comWrap = schema.find('.comments_list_container').find('.comment_group_wrap');

			if (!comWrap.length) {
				comWrap = schema.find('.comments_list_container').children().wrapAll('<div class="comment_group_wrap"></div>').parent();
			}

			comWrap.animate({
				opacity: 0
			}, 125, function() {
				comWrap.html(jsonData.data);
				rateAjaxComments();
				schema.find('.comment_current').text(current+1);
				commentData.attr('data-iterator', current);
				comWrap.animate({
					opacity: 1
				},125);
			});
		})
		.onError(function (jsonData) {
			console.log('TODO: error loading comment');
		})
		.send();

}

/**
 * zakomentovane a funkcia presunuta do system_functions.js - [2020-03-02] - tomasL
 * Validate google recaptcha
 * @function validation_by_google_recaptcha
 *
 * @author Miro
 *
 * @return {Boolean}
 */
//function validation_by_google_recaptcha()
//{
//	return jQuery('#g-recaptcha-response').val();
//}

/**
 * Submit comment add event handler
 * @function js_add_comment_submit
 *
 * @param {HTMLElement} input_element
 *
 * @return {Boolean}
 */
function js_add_comment_submit(input_element, modalView)
{
	var comments_container = null;
	var add_comment_form = null;
	var add_comment_container = null;
	var is_reply = false;

	var modal = null;
	var addButton = null;
	var isNsu = 0;

	if (typeof modalView !== 'undefined' && modalView) {
		comments_container = input_element.container;
		add_comment_container = input_element.form;
		is_reply = input_element.is_reply;
		modal = input_element.modal;
		addButton = input_element.addButton;
		isNsu = input_element.isNsu;

		input_element = input_element.button;
	} else {
		input_element = jQuery(input_element);

		comments_container = input_element.parents('.comments_container:first');
		add_comment_form = input_element.parents('form:first');
		add_comment_container = null;
		is_reply = false;

		if (add_comment_form.attr('id') == 'addCommentForm') {
			add_comment_container = add_comment_form.closest('#addCommentContainer');
		} else {
			add_comment_container = add_comment_form.parents('.addCommentReplyContainer:first');
			is_reply = true;
		}
	}

	if (input_element.hasClass('disabled')) {
		return false;
	}

	input_element.addClass('disabled');

	// povinne hodnotenie hviezdickami v komentaroch
	if (typeof js_CS_Config_comments_rating_required !== 'undefined' && js_CS_Config_comments_rating_required && !is_reply) {
		var ratingWrap = add_comment_container.find('div.jq-ry-rated-group');
		var ratingFilled  = typeof ratingWrap.css('width') !== 'undefined' && ratingWrap.css('width') !== '0px';

		if (!ratingWrap.length) {
			ratingWrap = add_comment_container.find('.cs_rating_wrapper.set_rating');
			ratingFilled = typeof ratingWrap.attr('data-val') !== 'undefined' && parseInt(ratingWrap.attr('data-val')) > 0;
		}

		if (ratingWrap.length && !ratingFilled) {
			showAlert(js_lang_must_fill_rating_of_product);
			input_element.removeClass('disabled');
			return false;
		}
	}

	var is_schema = isSchemaComments(comments_container) && !is_reply;
	var captcha_code_input_element = add_comment_container.find('input[name="captcha_code"]:first');
	var name_input_element = add_comment_container.find('input[name="name"]:first');
	var email_input_element = add_comment_container.find('input[name="email"]:first');
	var url_input_element = add_comment_container.find('input[name="url"]:first');
	var body_textarea_element = add_comment_container.find('textarea[name="body"]:first');
	var page_type = add_comment_container.find('input[name="page_type"]:first').val();
	var page_id = add_comment_container.find('input[name="page_id"]:first').val();
	var parent_comment_id = add_comment_container.find('input[name="parent_comment_id"]:first').val();
	var page_url = add_comment_container.find('input[name="page_url"]:first').val();
	var gdpr_checkbox = add_comment_container.find('input[name="gdpr_personal_info_agreed_comment"]:checked').val();
	var gdpr_form_id = add_comment_container.find('input[name="form_id"]:first').val();

	if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1')  ) {
		var vex_acc_index_add_comment = comments_container.parents('.vex-account-index-add-product-comment:first');
		var added_from_acc_index = (vex_acc_index_add_comment.length > 0 || isNsu) ? 1: 0;
		var user_id = add_comment_container.find('input[name="comment_user_id"]:first').length > 0 ? add_comment_container.find('input[name="comment_user_id"]:first').val() : '';
		//var comment_images = jQuery("#addCommentContainer").find('.dz-filename').map(function () {
		var comment_images = add_comment_container.find('.dz-filename').map(function () { //jQuery("#addCommentContainer")
			return jQuery(this).data('file_name');
		}).get();
	}

	js_comment_trim_input_value(name_input_element);
	js_comment_trim_input_value(email_input_element);
	js_comment_trim_input_value(url_input_element);

	var v_body_text = true;
	var v_rating = false;

	if (typeof comment_validation !== 'undefined' ) {
		if (typeof comment_validation.body_text != 'undefined' ) {
			v_body_text = comment_validation.body_text;
		}

		if (typeof comment_validation.rating != 'undefined' ) {
			v_rating = comment_validation.rating;
		}
	}

	// meno
	if (!name_input_element.hasClass('field_no_required') && name_input_element.val() == '') {
		showAlert(cms_js_lang_add_comment_your_name_error, name_input_element);
		input_element.removeClass('disabled');
		return false;
	}

	// email
	if (!email_input_element.hasClass('field_no_required') && email_input_element.val() == '') {
		showAlert(cms_js_lang_add_comment_your_email_error, email_input_element);
		input_element.removeClass('disabled');
		return false;
	}

	// text komentara
	if (!body_textarea_element.hasClass('field_no_required') && v_body_text && jQuery.trim(body_textarea_element.val()) == '') {
		showAlert(cms_js_lang_add_comment_body_error, body_textarea_element);
		input_element.removeClass('disabled');
		return false;
	}

	var ajax_params = {
		name: name_input_element.val(),
		email: email_input_element.val(),
		url: url_input_element.val(),
		body: body_textarea_element.val(),
		page_type: page_type,
		page_id: page_id,
		parent_comment_id: parent_comment_id,
		page_url: page_url,
		captcha_code: captcha_code_input_element.val(),
		mailreview: (comments_container.hasClass('comments_mail_review') ? 1 : 0)
	};

	if (gdpr_checkbox != 1) {
		showAlert(js_gdpr_agree_to_gdpr);
		input_element.removeClass('disabled');
		return false;
	}

	ajax_params.gdpr_checkbox = gdpr_checkbox;
	ajax_params.gdpr_form_id = gdpr_form_id;

	if (is_schema) {
		var rating;

		if ( typeof js_CS_Config_cs_rating !== 'undefined' && js_CS_Config_cs_rating ) {
			var reviewRating = add_comment_container.find('.cs_rating_wrapper.set_rating');
			rating = reviewRating.data('val');
		} else {
			var review_rating = add_comment_container.find('.review_rating');
			rating = review_rating.rateYo('rating');
		}

		if (v_rating && rating == 0) {
			showAlert(cms_js_lang_add_comment_rating_error);
			input_element.removeClass('disabled');
			return false;
		}

		ajax_params.rating = parseInt(rating);
	}

	if ((typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1') ) {
		if( user_id != '' && user_id > 0 ){
			ajax_params.user_id = user_id;
		}

		ajax_params.comment_images = comment_images;
	}

	input_element.hide();

	if ( typeof js_Config_comments_disable_button_on_comment_submit !== 'undefined' && js_Config_comments_disable_button_on_comment_submit ) {
		input_element.prop('disabled', true);
		input_element.parents('.vex-dialog-form:first').find('.vex-dialog-buttons').find('.vex-dialog-button-primary').prop('disabled', true);
	}

	add_comment_container.find('.mp_action_cancel:first').hide();
	add_comment_container.find('.comments_ajax_loader:first').show();

	jQuery.post(js_global_live_site +'/includes/comments/comments_ajax.php?option=com_shop&ajax_call=1&ajax_func=add_new_comment&no_html=1&no_vm_html=1&no_menu=1&no_css=1', ajax_params, function(res) {
		if (res == '') {
			enableClickingAddButton();
			input_element.removeClass('disabled');
			return false;
		}

		var res_splitted = res.split('|');

		if (typeof(res_splitted[1]) === 'undefined') {
			res_splitted[1] = '';
		}

		add_comment_container.find('.comments_ajax_loader:first').hide();
		input_element.show();

		if ( typeof js_Config_comments_disable_button_on_comment_submit !== 'undefined' && js_Config_comments_disable_button_on_comment_submit ) {
			input_element.prop('disabled', false);
			input_element.parents('.vex-dialog-form:first').find('.vex-dialog-buttons').find('.vex-dialog-button-primary').prop('disabled', false);
		}

		add_comment_container.find('.mp_action_cancel:first').show();

		if (res.substr(0,1) == '0') {
			switch (res_splitted[1]) {
				case 'error_name':
					showAlert(cms_js_lang_add_comment_your_name_error, name_input_element);
					break;

				case 'error_email':
					showAlert(cms_js_lang_add_comment_your_email_error, email_input_element);
					break;

				case 'error_body':
					showAlert(cms_js_lang_add_comment_body_error, body_textarea_element);
					break;

				case 'captcha_error':
					showAlert(cms_js_lang_add_comment_captcha_error, body_textarea_element);
					break;
				case 'error_maximum_comments':
					showAlert('Nieje možné pridať viac komentárov', name_input_element);
					break;

				default:
					showAlert(cms_js_lang_content_alert_1);
					break;
			}

			input_element.removeClass('disabled');
			return false;
		} else {

			var success_message = (ajax_params.mailreview ? cms_js_lang_add_review_success : cms_js_lang_add_comment_success);

			if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1' && added_from_acc_index) ) {
				vex.dialog.alert({
					message: success_message,
					callback: function() {
						if (typeof modalView !== 'undefined' && modalView) {
							addButton
								.text(addButton.attr('data-lang-comment-added'))
								.addClass('comment-added')
								.removeAttr('onclick');
						} else if (added_from_acc_index) {
							vex_acc_index_add_comment.addClass('indexCommentAdded');
							vex_acc_index_add_comment.find('.vex-close').trigger('click');
						}
					}
				});
			} else {
				showAlert(success_message);
			}

			if (typeof modalView !== 'undefined' && modalView) {
				modal.close();
			}
		}

		if(typeof js_CS_Config_display_comment_ajax !== 'undefined' && js_CS_Config_display_comment_ajax) {
			var ajaxComments = true;
		}

		var new_comment_container = jQuery(res_splitted[1]);

		new_comment_container.hide();

		if (is_schema && typeof js_CS_Config_cs_rating === 'undefined') {
			review_rating.rateYo('rating', 0);

			var review_rating_new = new_comment_container.find('.review_rating');
			var rating = new_comment_container.find('meta[itemprop=ratingValue]').attr('content');

			ratePrint(review_rating_new, rating, true, true, 20);
		}

		if ( typeof js_Config_replying_to_comments_hide_btn !== 'undefined' && js_Config_replying_to_comments_hide_btn ) {
			if (typeof js_Config_replying_to_comments_enabled === 'undefined') {
				new_comment_container.find('.reply_button_panel').hide();
			} else {
				if ( typeof js_Config_replying_to_comments_enabled !== 'undefined' && js_Config_replying_to_comments_enabled == 2 ) {
					if ( ( typeof js_global_user_info === "undefined" ) || ( typeof js_global_user_info != 'undefined' && js_global_user_info.gid < 24 ) ) {
						new_comment_container.find('.reply_button_panel').hide();
					}
				}
			}
		}

		if (is_reply) {
			var comments_list_container = add_comment_container;

			if (typeof modalView !== 'undefined' && modalView) {
				comments_list_container = comments_container.find('.comment_id_' + parent_comment_id);
			}

			if (!comments_list_container.next('.comment_reply_container').length) {
				comments_list_container.after('<div class="comment_reply_container"></div>');
			}

			if (ajaxComments && comments_list_container.next('.comment_reply_container').children('.comments_btns_wrap').length) {
				var btnMore = comments_list_container.next('.comment_reply_container').children('.comments_btns_wrap').find('button');
				var offset = parseInt(jQuery(btnMore).attr('data-offset'));

				if(offset > 0) {
					offset++;
				} else {
					offset = 1;
				}

				jQuery(btnMore).attr('data-offset', offset);

				comments_list_container.next('.comment_reply_container').prepend( new_comment_container );
			} else {
				comments_list_container.next('.comment_reply_container').prepend( new_comment_container );
			}
		} else {

			var comments_list_container = add_comment_container.parents('.comments_container:first').find('.comments_list_container:first');

			// Quickfix
			if (comments_list_container.length == 0){

				comments_list_container = jQuery('.comments_wrap').find('.comments_container:first').find('.comments_list_container:first');
			}

			if (typeof modalView !== 'undefined' && modalView) {
				comments_list_container = comments_container.find('.comments_list_container:first');
			}

			if (ajaxComments && comments_list_container.children('.comments_btns_wrap').length) {
				var btnMore = comments_list_container.children('.comments_btns_wrap').find('button');
				var offset = parseInt(jQuery(btnMore).attr('data-offset'));

				if(offset > 0) {
					offset++;
				} else {
					offset = 1;
				}

				jQuery(btnMore).attr('data-offset', offset);
				comments_list_container.prepend( new_comment_container );
			} else {
				if(comments_list_container.find('.comments_list_container_title').length) {
					comments_list_container.find('.comments_list_container_title').after(new_comment_container);
				} else {
					comments_list_container.prepend( new_comment_container );
				}
			}
		}

		var hardlink_element = new_comment_container.find('.comment_hardlink:first');

		if (typeof(js_global_live_site_sef) !== 'undefined' ) {
			var hardlink_anchor = hardlink_element.attr('href').replace(/^[^#]*/, '');

			hardlink_element.attr('href', js_global_live_site_sef + hardlink_anchor);
		}

		new_comment_container.slideDown(400, function() {
			js_set_edit_comment_timeout( jQuery(this) );
		});

		body_textarea_element.val('');

		if ( (typeof js_CS_Config_comments_attachment_in_detail_accout_index !== "undefined" && js_CS_Config_comments_attachment_in_detail_accout_index == '1')  ) {
			add_comment_container.find('.dz-preview').remove();
		}

		add_comment_container.find('.mp_action_cancel:first').trigger('click');

		comments_list_container.closest('.comments_container.schema').removeClass('comments_container_empty');
	});

	input_element.removeClass('disabled');
	return false;
}

function showAlert(message, focusElement) {
	focusElement = typeof focusElement === 'undefined' ? false : focusElement;

	vex.dialog.alert(message);
	enableClickingAddButton();

	if (focusElement.length) {
		focusElement.focus();
	}
}

function enableClickingAddButton() {
	var addButton = jQuery('.vex-account-index-add-product-comment').find('.vex-dialog-button-primary');

	if (addButton) {
		addButton.attr('disabled', false);
	}
}

function addCommentModal(element, isNsu)
{
	var elm = jQuery(element);

	if (elm.hasClass('opened')) {
		return false;
	}

	elm.addClass('opened');

	var comment = elm.closest('.comment');

	var params = {
		'page_id': elm.attr('data-id'),
		'page_type': elm.attr('data-type'),
		'is_reply': elm.hasClass('reply_button') ? 1 : 0,
	};

	if (elm.hasClass('reply_button')) {
		params.parent_id = comment.find('input[name="comment_id"]').val();
		params.parent_comment_name = comment.find('span.name').text().trim();
		params.parent_comment_body = comment.find('.review-body').text().trim();
	}

	new AjaxRequest({
		params: params,
	})
		.setController('Comment')
		.setAction('addCommentModal')
		.onSuccess(function (res) {
			if(typeof res.data.html !== 'undefined') {
				new CsModal()
					.setType('confirm')
					.setTitle(js_lang_adminlang_swe_content_comments_add_main_title)
					.setClassName('add-comment')
					.setContent(res.data.html)
					.setButtonTexts([cms_js_lang_products_group_3, cms_js_lang_products_group_8])
					.onSubmit(function () {
						var inputs = {
							'form': this.node.find('.addCommentInputsWrap'),
							'container': elm.closest('.comments_container'),
							'button': this.node.find('.submit_button'),
							'modal': this,
							'addButton': elm,
							'is_reply': this.node.find('input[name="parent_comment_id"]').val() > 0,
							'isNsu': typeof isNsu !== 'undefined' && isNsu ? 1 : 0
						};

						js_add_comment_submit(inputs, true)
					})
					.afterOpen(function (modal) {
						initAddCommentContainer(this.$vex.find('.addCommentWrap'));
					})
					.afterClose(function (modal) {
						elm.removeClass('opened');
					})
					.open();
			}
		})
		.onError(function (res) {})
		.send();
}

function commentToggleTranslated(element) {
	let elm = jQuery(element);
	let comment = elm.closest('[data-is-translated]');
	let reviewBody = comment.find('.review-body, .message');
	let isTranslated = comment.attr('data-is-translated') === '1';

	reviewBody.html(comment.data(isTranslated ? 'original-value' : 'translated-value'));
	elm.find('span').html(elm.data(isTranslated ? 'translated' : 'original'));
	comment.attr('data-is-translated', isTranslated ? '0' : '1');
}

function initAddCommentContainer(container) {
	if (typeof element === 'undefined') {
		container = jQuery('.addCommentWrap');
	}

	if ( typeof js_CS_Config_cs_rating !== 'undefined' && js_CS_Config_cs_rating ) {
		container
			.find('.cs_rating_wrapper')
			.addClass('set_rating');

		container.each(function() {
			var $setRatingElem = jQuery(this).find('.cs_rating_wrapper .rating').get(0);

			if ($setRatingElem) {
				new CsRating($setRatingElem);
			}
		});
	}

	container.find('input, textarea').on('change', function() {
		var $this = jQuery(this);
		var valid = $this.val().length > 0;

		if (valid) {
			if ($this.hasClass('required')) {
				$this.addClass('valid');
				$this.removeClass('error');
			}

			$this.addClass('filled');
		} else {
			if ($this.hasClass('required')) {
				$this.removeClass('valid');
				$this.addClass('error');
			}

			$this.removeClass('filled');
		}
	}).each(function() {
		var $this = jQuery(this);
		if ($this.val().length > 0) {
			$this.trigger('change');
		}
	});
}


/* ========================================
 FILE: /modules/js/mod_shop_cart_ajax.js
 ==================== */

// museli sme takto, aby fungovali shopy, kde nemaju ajax kosik aktivny
if ( typeof js_global_ajax_cart_active !== 'undefined' && js_global_ajax_cart_active ) {

	if ( typeof js_Config_parser_enabled !== 'undefined' && js_Config_parser_enabled ) {
		jQuery(window).on('load', function () {
			js_first_init_ajax_cart();
		});
	} else {
		jQuery(function () {
			js_first_init_ajax_cart();
		});
	}

	var modalAfterAddToCartSlickSettings = 	{
		slide: '.cs_product_item',
		autoplay: false,
		autoplaySpeed: 4000,
		slidesToShow: 3,
		slidesToScroll: 3,
		infinite: true,
		variableWidth: false,
		swipeToSlide: true,
        responsive: [
            {
                breakpoint: 800,
                settings: { slidesToShow: 2,slidesToScroll: 2, autoplay: false, }
            },
            {
                breakpoint: 400,
                settings: { slidesToShow: 1,slidesToScroll: 1, autoplay: false, }
            }
        ]
	};

	function js_first_init_ajax_cart(){
		js_ajax_cart_init(); // init scroll
		js_ajax_cart_container_events_init();
		js_cart_link_update(); // cart link
		js_add_to_cart_form_ajax_cart_bind(); // bind add to cart buttons
		js_refresh_extended_waranty();
		// js_refresh_surcharge_products();
		js_remove_gift_free_msg(); // zmaze message o darceku z kosika v pripade, ze nie je skladom (ta appka co ho pridava sa instaluje do local.js-iek)
	}

	function js_ajax_cart_init() {
		var box = jQuery('.cart_ajax_container_inner');
		// ajax container doesn't exists
		if (box.length < 1) {
			jQuery('.cart_ajax_container').remove();
			jQuery('.module-cart table:first, .module-cart .moduleCartInfo').after('<div class="cart_ajax_container"><div class="cart_ajax_container_inner"></div></div>');
			js_ajax_cart_container_events_init({'no_products':1});
			js_cart_link_update(); // cart link
		}

	}

	function js_ajax_cart_container_events_init(params) {
		if (is_cs_user('profdev')) csstack('js_ajax_cart_container_events_init',[params]);
		jQuery('.module-cart:first')
			.off('mouseenter mouseleave')
			.on('mouseenter', function () {
				if (typeof jQuery !== 'function') { return false; }

				if (js_ajax_cart_open_disabled()) // frontend.js
					return false;

				var cart_ajax_container = jQuery(this).find('.cart_ajax_container');
				if (cart_ajax_container.find('.product_cont').length > 0 || (typeof(params) != 'undefined' && typeof(params.no_products) != 'undefined'))
					cart_ajax_container.stop().slideDown(50, 'easeInExpo', function () {
						cart_ajax_container.addClass('is_open');
						cart_ajax_container.removeAttr('style').css('display','block'); //fix miznutia kosika
					});
			})
			.on('mouseleave', function () {
				if (typeof jQuery !== 'function') { return false; }

				var cart_ajax_container = jQuery(this).find('.cart_ajax_container');
				cart_ajax_container.stop().slideUp(50, 'easeOutExpo', function () {
					cart_ajax_container.removeClass('is_open');
					cart_ajax_container.removeAttr('style').hide(); //fix miznutia kosika
				});
			});
	}

	function js_remove_gift_free_msg(){
		if( typeof js_CS_Config_product_as_gift_empty_stock !== 'undefined' && js_CS_Config_product_as_gift_empty_stock){
			jQuery('.cart_ajax_container .gift_free').remove();
		}
	}

	function js_ajax_cart_update(elem, product_id, quantity, params) {
		elem = jQuery(elem);
		if (js_is_empty(params)) params = {};

		if (typeof js_Config_product_store_reservation !== 'undefined' && typeof js_Config_product_store_reservation.extended !== 'undefined' && typeof js_Config_product_store_reservation.active !== 'undefined' && js_Config_product_store_reservation.active === true && params.reservationCanceled !== true) {
			let reservationCookie = jQuery.cookie('product_reservation_active');
			if (typeof reservationCookie !== 'undefined' && reservationCookie !== null && reservationCookie === '1') {
				reservationCancelModal = new CsModal()
				.setClassName('product_reservation_disable_modal')
				.setType('info')
				.setTitle(js_lang_checkout_product_reservation.modalTitle)
				.setContent(js_lang_checkout_product_reservation.leavingReservation)
				.hideCloseButton(false)
				.setButtons("<input type=\"button\" name=\"reservation-disable-confirm\" class=\"button\" title=\"\" value=\"" + js_lang_checkout_product_reservation.confirm + "\"><input type=\"button\" name=\"reservation-disable-cancel\" class=\"button\" title=\"\" onclick=\"reservationCancelModal.close();\" value=\"" + js_lang_checkout_product_reservation.cancel + "\">")
				.afterOpen(()=>{
					let confirmButton = jQuery('input[name="reservation-disable-confirm"]');
					if (confirmButton.length > 0) {
						confirmButton.on('click', ()=>{
							Cookies.remove('product_reservation_active');
							params.reservationCanceled = true;
							if (typeof reservationCancelModal !== 'undefined' ) {
								reservationCancelModal.close();
							}
							js_ajax_cart_update(elem, product_id, quantity, params);
						});
					}
				})
				.open();
				return;
			}
		}

		elem.addClass('js_img_animate_' + product_id);

		var action = (elem.hasClass('minus') || elem.hasClass('remove')) ? '-' : '+';
		var cart_update = function () {
			var ajax_container = elem.parent();

			var options = {
				'ajax_func'           : 'get_ajax_cart',
				'ajax_cart_product_id': product_id,
				'ajax_cart_action'    : action,
				'ajax_cart_quantity'  : quantity
			};

			if (typeof params.cart_item_id !== 'undefined') {
				options.is_ajax = true;
			}

			if (typeof(js_cart_form_ajax_selector) != 'undefined' && !js_is_empty(js_cart_form_ajax_selector) && elem.find(js_cart_form_ajax_selector).length) {
				ajax_container = elem.find(js_cart_form_ajax_selector);
			}

			if (!options.is_ajax && typeof ProductPackDetail !== 'undefined') {
				var productPackParams = ProductPackDetail.getCartParams();
				if (Object.keys(productPackParams).length > 0) {
					params.productPackData = JSON.stringify(productPackParams);
				}
			}

			// JAN Product offer: vex s upozornenim o zmazani ponuk
			if (action === '-' && typeof params.cart_qty !== 'undefined' && params.cart_qty === 1 && typeof prof === 'object' && elem.hasClass('pof_cart_parent') && !elem.hasClass('pof_del_confirmed')) {
				if (!prof.showWarning(elem)) {
					return false;
				}
			}

			// JAN Produkt offer: povinne vybratie ponuk iba pre hlavny button pridat do kosika
			if (typeof prof === 'object' && prof.options.mandatoryoffer && !jQuery.isEmptyObject(prof.box) && prof.box.length > 0 && !prof.prepared && elem.attr('name') == 'addtocart' && !prof.set_plugin) {
				prof.highlight();
				return false;
			}

			jQuery.each(params, function (i, val) {
				options[i] = val;
			});

			// ulozime si info o tom, ci bolo vybrane aj predlzenie zaruky , po pridani do kosiku uz tuto mzonost odstranime(nemoze si vybrat 2 predlzenai zaruky na jeden produkt)
			var extendedWarranty              = jQuery('input[name="extended_warranty_product"]');
			extended_warranty_product_checked = extendedWarranty.length && extendedWarranty.is(':checked');

			// Sety
			var isAjaxCart = elem.hasClass('minus') || elem.hasClass('plus');

			// if is ajax cart and not set
			if (typeof prof === 'object' && prof.set_plugin && !isAjaxCart) {
				options.is_set    = true;
				options.selection = JSON.stringify(prof.selection);
			}

			if (typeof params.set !== 'undefined') {
				options.is_set = true;
				options.set    = params.set;
			}

			var parentElem = elem.parents('.shop-category-product, .featured-prod');

			if (typeof options.select_value !== 'undefined' && options.select_value == null) {
				delete options.select_value;
			}

			if (typeof options.select_name !== 'undefined' && typeof options.select_value === 'undefined' && js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED === '2' ){
				options.is_ajax_cart = true;
			}

			var ajaxOptions = {async: true};
			if (typeof options.dynamic_attribute === 'undefined') {
				ajaxOptions = {async: false};
			}

			options.fromDetail = jQuery('.shop_page_class_shop_product_details').length > 0;

			ajax_container.startAjaxLoader();
			parentElem.addClass('ajaxProcess');
			jQuery.ajaxSetup(ajaxOptions); // adding to card have to be sync ! to avoid problems with fast purchase

			jQuery.post('/modules/mod_shop_cart_ajax.php', options, function (ajax_res) {
				var cartError = false;
				var result;

				try {
					result = JSON.parse(decodeURIComponent(ajax_res));
				} catch (err) {
					result = JSON.parse(ajax_res);
				}

				if ('image_source' in result) {
					localStorage.setItem('ajaxCartUpdateVariants', JSON.stringify(result));
				} else if ('log_params' in result) {
					for (var i = 0; i < result.log_params.length; i++) {
						if (typeof result.log_params[i] === 'object' && result.log_params[i].hasOwnProperty('select_value')) {
							localStorage.setItem('selectedItemValue', JSON.stringify(result.log_params[i].select_value));
						}
					}
				}

				if (typeof js_Config_product_details_vex_product_restricted !== 'undefined' && js_Config_product_details_vex_product_restricted ) {
					if ( typeof result.restricted_product !== 'undefined' && result.restricted_product.is_product_restricted == '1' && result.restricted_product.contains_restricted == '0' && typeof result.restricted_product.message !== 'undefined' ) {
						vex.dialog.alert(result.restricted_product.message);
					}
				}

				if (typeof result.productModifiedQuantities !== 'undefined' && result.productModifiedQuantities !== null && result.productModifiedQuantities.length) {
					var before = result.productModifiedQuantities.before;
					var after  = (typeof result.productModifiedQuantities.after != 'undefined') ? result.productModifiedQuantities.after : 0;
					var unit = result.productModifiedQuantities.unit;

					if (parseFloat(before) !== parseFloat(after)) {
						var opts  = {};

						opts.text = '';

						if (typeof js_lang_insufficient_quantity_inform != 'undefined') {
							opts.text = js_lang_insufficient_quantity_inform;
						}

						if (typeof js_lang_insufficient_quantity_inform_max != 'undefined' && after < before) {
							opts.text = js_lang_insufficient_quantity_inform_max;
						}

						if (typeof js_lang_insufficient_quantity_inform_min != 'undefined' && after > before) {
							opts.text = js_lang_insufficient_quantity_inform_min;
						}

						opts.text = opts.text.replace('{from}',before);
						opts.text = opts.text.replace('{to}',after);
						//2 krát unit v langu.. najrýchlejšie riešenie (aj keď hlúpe)
						opts.text = opts.text.replace('{unit}',unit);
						opts.text = opts.text.replace('{unit}',unit);

						//opts.text = 'Kvôli úprave množstva produktu bolo množstvo zmenené z ' + before + ' na ' + after;
						opts.type = 'warning';

						if (typeof options === 'object') {
							opts = jQuery.extend(true, {}, opts, options);
						}

						//TODO znazať ostatné (staré Notifikácie)

						//jQuery('.ui-pnotify-container').remove();

						if ( typeof CsModal !== "undefined" && after < before ) {

							if ( typeof skipAnimate === 'undefined' ) {
								var skipAnimate = true;
							} else {
								skipAnimate = true;
							}

							if ( typeof quantityMessageModal !== 'undefined' ) {
								quantityMessageModal.open();
							} else {
								quantityMessageModal = new CsModal()
								.setClassName("modify-quantity")
								.setType('info')
								.setTitle(js_lang_mess_coupon_import_start_title)
								.setContent(js_lang_insufficient_quantity_inform_max_2)
								.hideEmptySpace(true)
								.setButtons("<input type=\"button\" class=\"button cs_modal_sec_button\" name=\"submit\" title=\"\" onclick=\"quantityMessageModal.close();\" value=\"Ok\">")
								.hideCloseButton(true)
								.open();
							}

							if ( typeof ajax_container !== 'undefined' ) {
								var productQuantityInput = ajax_container.find('input[name="quantity"]');
								if ( productQuantityInput.length === 1 ) {
									var productQuantityInputMin = typeof productQuantityInput.data('minimum_quantity') !== 'undefined' ? productQuantityInput.data('minimum_quantity') : 1;
									productQuantityInput.val(productQuantityInputMin);
								}
							}

						} else {
							PNotify.removeAll();
							showNotification(opts.text, '', opts.type,'8000',opts.hide,'','pnotify_modify_quantiity');
						}
					}
				}

				js_cart_total = result.cart_order_total; //config_cart_total_js

				// bonusovy system
				if (typeof result.bonus_system !== 'undefined' && typeof result.bonus_system.action !== 'undefined') {
					var bonusCurrency = typeof result.bonus_system.currency !== 'undefined' ? result.bonus_system.currency : 'EUR';

					//vex prompt
					if (typeof result.bonus_system.cartItems !== 'undefined') {
						bonus_system_prompt(result.bonus_system.cartItems, bonusCurrency, result.bonus_system.action);
					}

					//nastavenie sphinx filtra
					if (typeof result.bonus_system.setFilter !== 'undefined' && result.bonus_system.setFilter) {
						if (typeof sphf !== 'undefined' && typeof sphf.initialized !== 'undefined' && sphf.initialized == 1) {
							console.log('resetFilter');
							sphf.resetFilter();
						}

						//aktualizacia bonusoveho modulu (vyska zozstatkoveho kreditu)
						if (typeof result.bonus_system.actualBonusAmount !== 'undefined') {
							jQuery('.bonus-system-module-wrapper .bonus-module-amount-lbl strong').html(result.bonus_system.actualBonusAmount + ' ' + bonusCurrency);
						}
					}
				}

				//mesacny limit na nakup pre vybranych pouzivatelov
				if (typeof result.monthlyOrderLimitExceeded !== 'undefined') {
					vex.dialog.alert({message: result.monthlyOrderLimitExceeded.message, input: result.monthlyOrderLimitExceeded.input});
				}

				if (typeof(result) !== 'undefined' && typeof(result.update_res) !== 'undefined') {
					if (typeof(result.update_res.error) !== 'undefined') {
						cartError = true;

						vex.dialog.alert({
							message: result.update_res.error,
							callback: function() {
								var $productPackSection = jQuery('#product_pack_section');

								if (typeof result.update_res.highlight_product_pack !== 'undefined' && result.update_res.highlight_product_pack && $productPackSection.length) {
									$productPackSection.addClass('choose_variant');

									setTimeout(function() {
										$productPackSection.removeClass('choose_variant');
									}, 3000);
								}
							}
						});
					}

					if ( jQuery('.shop_page_class_shop_cart').length ) {
						if( jQuery(result.update_res).filter('.shop_tip').length > 0 ){
							jQuery(result.update_res).insertBefore('#middle_content_inner .shop_cart_ac_add_to_cart_div');

							setTimeout(function () {
								jQuery('#middle_content_inner .shop_tip').remove();
							}, 9000);

							return false;
						}
					}
				}

				var matrix = (typeof(params.matrix) != 'undefined');

				if ( params.attr_selectbox == null && result.method == 'get_variants' && result.html_variants != '' && !matrix ) {
					// nove vex okno na vyber variantu produktu
					vex.open({
						content         : [
							'<form class="vex-dialog-form test">',
							'<div class="vex-dialog-message">',
							'<span class="login-title">',
							result.product_name,
							'</span>',
							'</div>',
							'<div class="vex-dialog-input" style="padding-top: 1.5em;">',
							'</div>',
							'<div class="vex-dialog-buttons">',
							'</div>',
							'</form>'
						].join(''),
						contentClassName: 'vex-content pretty_cart',
						afterOpen       : function (vexContent) {
							jQuery(vexContent).on('click', 'div.vex-close', function () {
								vex.close(vexContent.data().vex.id);
							});
							ajax_container.stopAjaxLoader();
							parentElem.removeClass('ajaxProcess');
							var vexForm  = vexContent.find('form.vex-dialog-form');
							var vexInput = vexForm.find('.vex-dialog-input');
							var vexButtons = vexForm.find('.vex-dialog-buttons');

							var form_elem = ajax_container.clone();
							var parent    = ajax_container.parent();
							var product_link;

							if (typeof result.surchargeProductsHtml !== 'undefined' && result.surchargeProductsHtml) {
								vexInput.prepend(result.surchargeProductsHtml);
							}

							if ( typeof js_CS_Config_change_input_to_button !== 'undefined' && js_CS_Config_change_input_to_button ) {
								jQuery(vexContent).on('click', '.vex_cart_quantity [type="submit"]', function (event) {

									if (jQuery('.prod_adv_attrib_select select').val() == '' && typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED !== 'undefined' && js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED != '2') {
										var newFind = jQuery('.prod_adv_attrib_select select').find("option:selected");
										if (typeof newFind[1] === 'undefined' || (typeof newFind[1] !== 'undefined' && newFind[1].value == '')) {
											var elem              = jQuery(event.target);
											var variant_container = jQuery(elem).parents('.vex-dialog-form:first').find('.prod_adv_attrib_select');
											var msg               = '<span class="select_variant_error">' + js_lang_prof_select_main_variant + '</span>';
											variant_container.prepend(msg);
											return false;
										} else {
											vex.close(vexContent.data().vex.id);
										}
									} else {
										if ( is_cs_user('separate_js') && ( typeof js_CS_Config_empy_radio_select_variant !== 'undefined' && js_CS_Config_empy_radio_select_variant == '1' ) ) { // jaro
											var form_varaints = vexForm.find('.prod_adv_attribs_div').find('.shop_addtocart_advanced_attribute_radio');
											if( ( typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED !== 'undefined' && js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED == '1') && ( form_varaints.length > 0 ) && (form_varaints.is(':checked') == false ) ){
												//console.log(vexForm.find('.prod_adv_attribs_div').find('.shop_addtocart_advanced_attribute_radio'));
												var elem              = jQuery(event.target);
												var variant_container = jQuery(elem).parents('.vex-dialog-form:first').find('.prod_adv_attribs_div:first');
												var msg               = '<span class="radio_variant_error">' + js_lang_prof_select_main_variant + '</span>';
												if(vexForm.find('.radio_variant_error').length == 0 ){
													jQuery(msg).insertAfter(variant_container).delay(2500).fadeOut('slow', function(){ //insertBefore
														jQuery(this).remove();
													});
													//variant_container.prepend(msg);
												}
												return false;
											} else {
												vex.close(vexContent.data().vex.id);
											}
										} else {
											if (typeof product_id !== 'undefined' && typeof js_Config_product_variant !== 'undefined' && js_Config_product_variant && typeof window['ProductVariantInstance_' + product_id] !== 'undefined' && typeof window['ProductVariantInstance_' + product_id].selectedAttribute == 'undefined') {
												var msg = '<span class="select_variant_error">' + js_lang_prof_select_main_variant + '</span>';
												if (vexForm.find('.select_variant_error').length == 0) {
													jQuery(msg).insertAfter(vexForm.find('.vex-dialog-input')).delay(2500).fadeOut('slow', function () { //insertBefore
														jQuery(this).remove();
													});
												}
												return false;
											}
											vex.close(vexContent.data().vex.id);
										}
									}
								});
							} else {
								jQuery(vexContent).on('click', '.vex_cart_quantity input[name="submit"]', function (event) {

									if (jQuery('.prod_adv_attrib_select select').val() == '' && typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED !== 'undefined' && js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED != '2') {
										var newFind = jQuery('.prod_adv_attrib_select select').find("option:selected");
										if (typeof newFind[1] === 'undefined' || (typeof newFind[1] !== 'undefined' && newFind[1].value == '')) {
											var elem              = jQuery(event.target);
											var variant_container = jQuery(elem).parents('.vex-dialog-form:first').find('.prod_adv_attrib_select');
											var msg               = '<span class="select_variant_error">' + js_lang_prof_select_main_variant + '</span>';
											variant_container.prepend(msg);
											return false;
										} else {
											vex.close(vexContent.data().vex.id);
										}
									} else {
										if ( is_cs_user('separate_js') && ( typeof js_CS_Config_empy_radio_select_variant !== 'undefined' && js_CS_Config_empy_radio_select_variant == '1' ) ) { // jaro
											var form_varaints = vexForm.find('.prod_adv_attribs_div').find('.shop_addtocart_advanced_attribute_radio');
											if( ( typeof js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED !== 'undefined' && js_global_VM_PRODUCT_ATTRIB_FIRST_OPTION_REQUIRED == '1') && ( form_varaints.length > 0 ) && (form_varaints.is(':checked') == false ) ){
												//console.log(vexForm.find('.prod_adv_attribs_div').find('.shop_addtocart_advanced_attribute_radio'));
												var elem              = jQuery(event.target);
												var variant_container = jQuery(elem).parents('.vex-dialog-form:first').find('.prod_adv_attribs_div:first');
												var msg               = '<span class="radio_variant_error">' + js_lang_prof_select_main_variant + '</span>';
												if(vexForm.find('.radio_variant_error').length == 0 ){
													jQuery(msg).insertAfter(variant_container).delay(2500).fadeOut('slow', function(){ //insertBefore
														jQuery(this).remove();
													});
													//variant_container.prepend(msg);
												}
												return false;
											} else {
												vex.close(vexContent.data().vex.id);
											}
										} else {
											if (typeof product_id !== 'undefined' && typeof js_Config_product_variant !== 'undefined' && js_Config_product_variant && typeof window['ProductVariantInstance_' + product_id] !== 'undefined' && typeof window['ProductVariantInstance_' + product_id].selectedAttribute == 'undefined') {
												var msg = '<span class="select_variant_error">' + js_lang_prof_select_main_variant + '</span>';
												if (vexForm.find('.select_variant_error').length == 0) {
													jQuery(msg).insertAfter(vexForm.find('.vex-dialog-input')).delay(2500).fadeOut('slow', function () { //insertBefore
														jQuery(this).remove();
													});
												}
												return false;
											}
											vex.close(vexContent.data().vex.id);
										}
									}
								});
							}

							jQuery(document).on('change', '.prod_adv_attrib_div .prod_adv_attrib_select select', function (event) {
								var elem = jQuery(event.target);
								if (elem.val() !== '') {
									jQuery(elem).parents('.prod_adv_attrib_select').find('.select_variant_error').remove();
								}
							});

							if (!form_elem.is('form')) {
								form_elem = form_elem.parents('form:first').length ? form_elem.parents('form:first').clone() : form_elem.find('form:first').clone();
							}

							jQuery(form_elem).find('.shop_browse_addtocart_quantity_label').remove();
							jQuery(form_elem).find('[name="quantity"]').removeAttr('id');
							jQuery(form_elem).find('[name="quantity"]').removeAttr('onkeyup');
							jQuery(form_elem).find('[name="prod_url"]').remove();
							if ( typeof js_CS_Config_change_input_to_button !== 'undefined' && js_CS_Config_change_input_to_button ) {
								jQuery(form_elem).find('[type="submit"]').attr('class', 'button');
								jQuery(form_elem).find('[type="submit"]').removeAttr('onclick');
							} else {
								jQuery(form_elem).find('[name="submit"]').attr('class', 'button');
								jQuery(form_elem).find('[name="submit"]').removeAttr('onclick');
							}
							//vexInput.prepend(result['html_variants']);
							//vexInput.append(form_elem.html());
							//console.log('pred returnom');
							//return;
							//console.log('za returnom');

							vexForm
								.attr('action', form_elem.attr('action'))
								.attr('method', form_elem.attr('method'))
								.attr('name', form_elem.attr('name'))
								.attr('id', form_elem.attr('id'));

							if ( typeof js_Config_mod_shop_cart_product_full_link_fix !== 'undefined' && js_Config_mod_shop_cart_product_full_link_fix ) {
								if ( parent.parents('.shop-category-product').find('.product_full_link').length > 0 ) {
									product_link =  parent.parents('.shop-category-product').find('.product_full_link').prop('href');
								}
							}

							while (typeof product_link === 'undefined') {
								if ( typeof js_Config_mod_shop_cart_product_full_link_fix !== 'undefined' && js_Config_mod_shop_cart_product_full_link_fix ) {
									if (parent.find('a.product_full_link').length > 0) {
										product_link = parent.find('a.product_full_link').prop('href');
									} else if ( parent.find('a').prop('href') != '' ) {
										product_link = parent.find('a').prop('href');
									}
								} else {
									if (parent.find('a.product_full_link').length > 0) {
										product_link = parent.find('a.product_full_link').prop('href');
									} else {
										product_link = parent.find('a').prop('href');
									}
								}
								parent = parent.parent();
							}

							if (form_elem.find('.prod_adv_attribs_div').length == 0) {
								vexInput.prepend(result.html_variants);
							}

							form_elem.find('input[name="quantity"]').attr('id', 'quantity');
							form_elem.find('label[for^="quantity"]').attr('for', 'quantity');
							if (!jQuery.inArray(js_global_VM_PRODUCT_ATTRIB_STYLE, ['1', '2'])) {
								form_elem.append('<input type="hidden" name="attribute_select_mode" value="1"/>');
								if (js_global_VM_PRODUCT_ATTRIB_STYLE == '1') {
									jQuery('.pretty_avil').hide();
								}
							}

							if (typeof js_Config_change_product_quantity != 'undefined') {
								form_elem.find('input[name="quantity"]').show();
							} else {
								if (form_elem.find('input[name="quantity"]:visible').length == 0) {
									if ( typeof params.vex_quantity !== 'undefined' ) {
										vex_quantity = params.vex_quantity;
									} else {
										if(elem.find('input[name="quantity"]').length > 0 ){
											vex_quantity = elem.find('input[name="quantity"]').val();
										} else {
											vex_quantity = 1;
										}
									}

									form_elem.find('input[name="quantity"]:hidden, label[for="quantitFsubmity"]').remove();
									if ( typeof js_CS_Config_change_input_to_button !== 'undefined' && js_CS_Config_change_input_to_button ) {
										jQuery([
											'<label for="quantity" class="shop_browse_addtocart_quantity_label">',
											(typeof js_shop_cart_quantity !== 'undefined' ? js_shop_cart_quantity + ':' : ''),
											'</label>',
											'<input id="quantity" class="inputbox shop-addtocart-quantity-inputbox" type="text" size="3" name="quantity" value="' + vex_quantity + '" onkeyup="(parseInt(this.value)>0)?this.style.borderColor=\'\' : this.style.borderColor=\'red\';">'
										].join('')).insertBefore(jQuery(form_elem.find('[type="submit"]')));
									} else {
										jQuery([
											'<label for="quantity" class="shop_browse_addtocart_quantity_label">',
											(typeof js_shop_cart_quantity !== 'undefined' ? js_shop_cart_quantity + ':' : ''),
											'</label>',
											'<input id="quantity" class="inputbox shop-addtocart-quantity-inputbox" type="text" size="3" name="quantity" value="' + vex_quantity + '" onkeyup="(parseInt(this.value)>0)?this.style.borderColor=\'\' : this.style.borderColor=\'red\';">'
										].join('')).insertBefore(jQuery(form_elem.find('input[name="submit"]')));
									}

								}
							}
							if ( typeof js_CS_Config_change_input_to_button !== 'undefined' && js_CS_Config_change_input_to_button ) {
								var submitBtn = form_elem.find('[type="submit"].categ_add_to_cart');
							} else {
								var submitBtn = form_elem.find('input[type="submit"].categ_add_to_cart');
							}

							if (submitBtn.length) {
								submitBtn.removeAttr('onclick');
								vexButtons.append(submitBtn.clone().addClass('vex-dialog-button-primary vex-dialog-button vex-first'));
								submitBtn.remove();
							}

							if (typeof product_link === 'undefined' || product_link == 0 || product_link == 'javascript:void(0)') {
								if (elem.data('product-link')) {
									product_link = elem.data('product-link');
								}
							}

							// link na produkt z virtualnych variantov
							if (typeof product_link === 'undefined' || product_link == 0 || product_link == 'javascript:void(0)') {
								var productLinkHref = elem.closest('tr.vv_tr').find('a.vv_box_image').attr('href');
								if (typeof productLinkHref !== 'undefined' && productLinkHref !== '') {
									product_link = productLinkHref;
								}
							}

							if (typeof js_CS_Config_change_input_to_button !== 'undefined' && js_CS_Config_change_input_to_button ) {
								vexButtons.append('<button onclick="window.location=\'' + product_link + '\';" type="button" class="vex-dialog-button-secondary vex-dialog-button vex-last button">' + (typeof js_shop_flypage_lbl !== 'undefined' ? js_shop_flypage_lbl : '') + '</button>');
							} else {
								vexButtons.append('<input onclick="window.location=\'' + product_link + '\';" type="button" class="vex-dialog-button-secondary vex-dialog-button vex-last button" value="' + (typeof js_shop_flypage_lbl !== 'undefined' ? js_shop_flypage_lbl : '') + '">');
							}


							//vexInput.append(form_elem.html());
							vexButtons.prepend('<div class="vex_cart_quantity"></div>');
							vexButtons.find('.vex_cart_quantity').prepend(form_elem.html());


							// init availability text
							var availText = jQuery('.vex-content select');
							if (availText.length) {
								form_elem.prepend('<div class="pretty_avil">' + result.html_avail + '</div>');
								availText.trigger('change');
							}

							js_add_to_cart_form_ajax_cart_bind();

							vexForm.find('.shop_addtocart_advanced_attribute_radio:checked').addClass('active');
							vexForm.on('click', '[class^="shop_addtocart_advanced_attribute_row_"]', function (event) {
								jQuery(this).siblings().removeClass('active').find('.shop_addtocart_advanced_attribute_radio').prop('checked', false);
								jQuery(this).addClass('active').find('.shop_addtocart_advanced_attribute_radio').prop('checked', true);
							});

							vexContent.on('click', '.categ_add_to_cart', function (event) {
								var selectElem = vexContent.find('select.main_attr_select');
								var firstVal   = selectElem.find('option').filter(function () {
									return jQuery(this).val() !== '';
								}).first().val();

								if (selectElem.val() === '') {
									if (typeof firstVal !== 'undefined') {
										selectElem.css('border', 'red solid 1px');
										return false;
										//selectElem.val(firstVal);
										//vex.close(vexContent.data().vex.id);
									} else {
										event.preventDefault();
									}
								} else {
									vex.close(vexContent.data().vex.id); // TODO: px zmazat ak zistim co skutocne zatvara
								}
							});

							if (typeof js_variants_browse_table_js_init == 'function') {
								js_variants_browse_table_js_init();
							}

						},
						afterClose      : function () {
							if (typeof window['ProductVariantInstance_' + product_id] !== 'undefined') {
								//delete window['ProductVariantInstance_' + product_id];

								if( !(delete window['ProductVariantInstance_' + product_id]) ){// nebolo mozne zmazat premennu s pomocou 'delete'
									window['ProductVariantInstance_' + product_id] = undefined;
								}
							}

							js_add_to_cart_form_ajax_cart_bind();
						}
					});

					return false;
				}

				// Skontroluj spravy a aktivuj messengera
				if (typeof messenger !== 'undefined') {
					messenger.check(result.update_res);
				}

				if ( jQuery('.shop_cart_ac_add_to_cart_div').length ){
					js_reload_current_page();
					return false;
				}

				let is_dynamic_attribute = false;
				let reloadCurrentPageAfterTimeout = (jQuery('.shop_page_class_shop_cart').length || (typeof(reloadAfterAddToCart) !== 'undefined' && reloadAfterAddToCart == 1));
				if (reloadCurrentPageAfterTimeout) {	// ak som v nakupnom kosiku, vykonam reload
					setTimeout(function () {
						js_reload_current_page();
						return false;
					}, 900);
				}

				if ( !( (typeof(options.is_gift) != 'undefined' && options.is_gift === true) || (typeof(options.is_special_offer) != 'undefined' && options.is_special_offer === true) ) && !( typeof cart_animate_false !== 'undefined' && cart_animate_false ) ) {
					js_ajax_cart_container_init(result);
				}

				js_refresh_extended_waranty();
				js_refresh_surcharge_products();

				if(typeof js_Config_product_detail_free_shipping_info !== 'undefined' && js_Config_product_detail_free_shipping_info && jQuery('body').hasClass('shop_page_class_shop_product_details') && typeof js_flypage_free_shipping_update_info == 'function'){
					js_flypage_free_shipping_update_info();
				}

				// zmena dostupnosti na buducu dostupnost
				if (typeof result === 'object' && typeof result.futureAvailability === 'object') {
					js_refresh_product_availability_by_future_availability(result.futureAvailability);
				}

				parentElem.removeClass('ajaxProcess');
				ajax_container.stopAjaxLoader();

				// JAN dynamicke atributy
				if (elem.find('.daf_wrap').length && typeof dattr == 'object' && typeof dattr.afterCart == 'function') {
					is_dynamic_attribute = true;
					dattr.afterCart();
				}

				// JAN Produkt offer: Pridanie ponuk do kosika po ajax requeste!!!
				// sety maju defaultne vypnute pridavanie cez offer ajax
				if (typeof prof == 'object' && !jQuery.isEmptyObject(prof.box) && prof.box.length > 0 && prof.prepared && !prof.set_plugin) {
					prof.add(result);
				}

				// JAN dary pre detsky domov
				var custom_gifts = elem.hasClass('customGiftInput');

				js_add_to_cart_form_ajax_cart_bind();	// bind add to cart buttons

				var success_added = jQuery('<div>' + result.update_res + '</div>').find('.shop_tip').length == 0;

				//ecomail trackovanie obsahu kosika (len pre non cs)
				if (!is_cs_user() && typeof js_Config_ecomail_track_cart_content !== 'undefined') {
					//ziskame naformatovany obsah kosika
					new AjaxRequest()
						.setController('Cart')
						.setAction('getCartContentForEcomail')
						.onSuccess(function (result) {
							//odosleme obsah kosika
							if (typeof window.ecotrack !== 'undefined') {
								window.ecotrack('trackUnstructEvent', {
									schema: '',
									data  : {
										action  : 'Basket',
										products: result.data
									}
								});
							}
							//console.log(result.data);
						})
						.send();
				}

				if (typeof freeShippingInfoData !== 'undefined' && typeof result.totalCartWeight !== 'undefined') {
					var totalCartWeight = result.totalCartWeight;
					var selectedVariant = jQuery('.prod_adv_attrib_div .selected_attr');

					freeShippingInfoData.totalWeight = totalCartWeight;
					freeShippingInfoData.canShowInfo = freeShippingInfoData.maxFreeShippingWeight > (totalCartWeight + freeShippingInfoData.currentProductWeight);

					if (selectedVariant.length) {
						selectedVariant.trigger('click');
					}
				}

				if (typeof (js_ajax_cart_update_after_init) != 'undefined') {
					js_ajax_cart_update_after_init({
						'product_id': product_id,
						'quantity'  : quantity,
						'attribute' : params.select_value
					});
				}

				var redirectFunc = function() {
					if (typeof(result.redirect) != 'undefined' && result.redirect !== '') {
						location.href = js_global_live_site + result.redirect;
					}
				};


				var apiRequestRun = false;

				if (success_added && !cartError) {
					if (result.method !== 'remove' && !(custom_gifts
						|| (
							(typeof (options.is_gift) != 'undefined' && options.is_gift === true)
							||
							(typeof (options.is_special_offer) != 'undefined' && options.is_special_offer === true)
						))
					) {
						if (elem.attr('data-skip-animate')) {
							skipAnimate = true;
						}

						if ( typeof skipAnimate === 'undefined' || ( typeof skipAnimate !== 'undefined' && skipAnimate == false ) ) {
							if (typeof js_cart_image_animate_custom == 'function') {
								js_cart_image_animate_custom(ajax_container);
							} else {
								if (ajax_container.hasClass('vex-content')) {
									js_cart_image_animate(jQuery('.js_img_animate_' + product_id).not('.vex-dialog-form'));
								} else {
									js_cart_image_animate(ajax_container);
								}

								jQuery('.js_img_animate_' + product_id).removeClass('js_img_animate_' + product_id);
							}
						}
					}

					if (typeof isApiActive !== 'undefined' && isApiActive) {
						var apiAction = action === '+' ? 'addToCart' : 'removeFromCart';
						var pageMatch = js_server_request_uri.match(/(&|;|\?)page\=([^&]+)/);
						var manMatch  = js_server_request_uri.match(/(&|;|\?)pc_manufacturer_id\=([^&]+)/);
						var page      = '';

						if (typeof manMatch === 'object' && manMatch !== null) {
							page = 'manufacturer';
						} else if (typeof pageMatch === 'object' && pageMatch !== null && typeof pageMatch[2] !== 'undefined') {
							page = pageMatch[2];
						}

						apiRequest(apiAction, {
							'products': [{
								'product_id' : product_id,
								'quantity'   : quantity,
								'description': params.select_value,
								'idx'        : params.cart_item_id
							}],
							'page'    : page,
							'isAjax'  : true
						}, redirectFunc);

						apiRequestRun = true;
					}
				}

				// close prettyphoto with variants
				js_prettyphoto_close();

				// bonusovy system
				if (typeof result.bonus_system !== 'undefined' && typeof result.bonus_system.action !== 'undefined' && typeof result.bonus_system.setFilter !== 'undefined' && typeof result.bonus_system.actualBonusAmount !== 'undefined') {
					//zamedzenie pridaniu poloziek do kosika, ktore prekracuju vysku aktualnej hodnoty bonusoveho kreditu
					bonus_system_update_cart_plus_sign(result.bonus_system.bonusItems, result.bonus_system.actualBonusAmount);
				}

				if (!reloadCurrentPageAfterTimeout && !is_dynamic_attribute && typeof params !== 'undefined' && typeof params.cart_item_id === 'undefined' && typeof js_Config_modal_after_add_to_cart !== 'undefined' && js_Config_modal_after_add_to_cart && typeof result.update_res !== 'undefined' && typeof result.update_res.success !== 'undefined' && result.update_res.success == 1 && typeof result.update_res.method !== 'undefined' && ['add', 'update'].indexOf(result.update_res.method) >= 0) {
					if (typeof params.cart_item_id === 'undefined' && typeof result.update_res.log_d !== 'undefined' && typeof result.update_res.log_d.cart_item_id !== 'undefined') {
						params.cart_item_id = result.update_res.log_d.cart_item_id;
					}
					showLoader();
					new AjaxRequest({productId: product_id, params: params})
						.setController('Cart')
						.setAction('getModalAfterAddToCart')
						.onSuccess(function (result) {
							hideLoader();
							if (typeof result !== 'undefined' && typeof result.data !== 'undefined' && typeof result.data.html !== 'undefined') {
								if (typeof window.ModalAfterAddToCart === 'undefined') {
									window.ModalAfterAddToCart = new CsModal()
										.setClassName('modal_after_add_to_cart_vex fresh')
										.setType('info')
										.setTitle(typeof js_lang_modal_after_add_to_cart_vex_title !== 'undefined' ? js_lang_modal_after_add_to_cart_vex_title : 'And it\'s in the basket!')
										.setContent(result.data.html)
										.setButtons('')
										.afterOpen(function(vexContent) {
											jQuery('body').addClass('modal_after_add_to_cart_open');
											vexContent.find('.related_products_div').slick(modalAfterAddToCartSlickSettings);
										})
										.afterSetContent(function (vexContent) {
											vexContent.find('.related_products_div').slick(modalAfterAddToCartSlickSettings);
										})
										.afterClose(function() { // nastavi callback, ktory sa vykona po uzavreti modalu
											window.ModalAfterAddToCart = undefined;
											jQuery('body').removeClass('modal_after_add_to_cart_open');
										})
										.open();
								}

								// bind eventu na reload // TODO neako refactorovat ?
								jQuery('body').on('addToCartFinished', function(event, triggeredData) {
									window.ModalAfterAddToCart.setClassName('loading');
									window.ModalAfterAddToCart.removeClass('fresh');
									new AjaxRequest({productId: triggeredData.productId, params: {select_value: triggeredData.attribute, cart_item_id: triggeredData.cart_item_id}})
										.setController('Cart')
										.setAction('getModalAfterAddToCart')
										.onSuccess(function (result) {
											window.ModalAfterAddToCart.removeClass('loading');
											if (typeof result !== 'undefined' && typeof result.data !== 'undefined' && typeof result.data.html !== 'undefined') {
												window.ModalAfterAddToCart.setContent(result.data.html);
											}
										})
										.send();
								});
							}
						})
						.onError(function () {
							hideLoader();
						})
						.send();
				}

				// Redirect
				if (!apiRequestRun) {
					redirectFunc();
				}
			});

			jQuery.ajaxSetup({async: true});
		};

		// do anonymnej funkcie dat potom v if sa spytat na vex confirm a potom zavolat anonymnu funkciu, dodefinovat este potom elem ako parameter anonymnej funkcie
		if ((elem.hasClass('minus') && params.cart_qty == quantity) || elem.hasClass('remove')) {
			vex.dialog.confirm({
				message  : js_lang_shopping_cart_delete_item_confirm,
				callback : function (value) {
					if (value) {
						cart_update(elem, product_id, quantity, params, action);
					} else {
						var cart_ajax_container = jQuery(document).find('.cart_ajax_container');
						if (cart_ajax_container.find('.product_cont').length > 0 || (typeof (params) != 'undefined' && typeof (params.no_products) != 'undefined')) {
							cart_ajax_container.stop().slideDown(50, 'easeInExpo', function () {
								cart_ajax_container.addClass('is_open');
								cart_ajax_container.removeAttr('style').css('display', 'block'); //fix miznutia kosika
							});
						}
					}
				},
				afterOpen: function () {
					setTimeout(function () {
						jQuery(document).find('.vex-dialog-buttons .vex-dialog-button-primary').trigger('focus');
					}, 100);
				}
			});
		} else {
			if (typeof js_CS_Config_check_if_product_in_cart !== 'undefined' && js_CS_Config_check_if_product_in_cart && elem.hasClass('has_variant') == false && elem.hasClass('minus') == false) {
				js_check_if_product_in_cart(product_id, params).then((response) => {
					if (response.data.message.isInCart) {
						let cofirmModal = new CsModal()
								.setClassName('product_in_cart_already')
								.setType('info')
								.setContent(response.data.message.confirm)
								.setButtons("<button type='button' class='confirm_button_is_in_cart'>"+ cms_js_lang_yes.toUpperCase() +"</button><button type='button' class='close_button'>"+ cms_js_lang_no.toUpperCase() +"</button>")
								.afterOpen(function () {
									jQuery('.confirm_button_is_in_cart').on('click', function () {
										cofirmModal.close();
										cart_update();
									})
								})
								.open();
					} else {
						cart_update();
					}
				});
			} else if (config('js_Config_exchange_product_in_cart') && elem.hasClass('minus') == false) {
				getProductToChange(product_id, params).then((response) => {
					let productForExchange = response.data.productForExchange;
					if (productForExchange && productForExchange.product_snapshot) {
						let productForExchangeModal = new CsModal()
							.setClassName('product_exchange_modal')
							.setType('info')
							.setTitle(productForExchange.title)
							.setContent(productForExchange.product_snapshot)
							.setButtons(productForExchange.buttons)
							.afterOpen(function () {
								jQuery('.product_exchange_modal button').on('click', function () {
									productForExchangeModal.close();
									if (jQuery(this).hasClass('close_button_product_exchange')) {
										cart_update();
									}
								})
							})
							.open();
					} else {
						cart_update();
					}
				})
			} else {
				cart_update();
			}
		}

		return false;
	}

	function js_init_fixed_ajax_cart() {
		var window_scroll_top = 0;
		if (navigator.userAgent.indexOf('MSIE') > -1) {
			window_scroll_top = parseInt(document.documentElement.scrollTop);
		} else {
			window_scroll_top = parseInt(window.pageYOffset);
		}
		if (typeof js_cart_css_obj === 'undefined') {
			return;
		}
		var js_cart_css_obj_top = js_cart_css_obj.top == 'auto' ? 0 : js_cart_css_obj.top;
		if (window_scroll_top > 0 && window_scroll_top > (js_cart_css_obj_top + 40)) {
			if (js_cart_css_scroll_obj.left == 'auto') {
				js_cart_css_scroll_obj.left = jQuery('.module-cart:first').offset().left; // fix palo 16.9. - v responzivite vyhadzovalo js chybu
				// js_cart_css_scroll_obj.left = jQuery('#topmenu .module-cart').offset().left;
			}
			jQuery('#topmenu .module-cart').addClass('scroll').css(js_cart_css_scroll_obj);
			jQuery(window)
				.on("scroll", function () {
					//#5795
					if (!jQuery('#topmenu .module-cart').hasClass('scroll')) {
						return;
					}
					jQuery('#topmenu .cart_ajax_container').slideUp(200, function () {
						jQuery('#topmenu .module-cart').removeClass('scroll').css(js_cart_css_obj);
					});
				});
		} else {
			jQuery('#topmenu .module-cart').removeClass('scroll').css(js_cart_css_obj);
		}
	}
	function js_add_to_cart_form_ajax_cart_bind() {
		jQuery('div.mp_discount_product_vals form, .wishlist_item_btns form, .product-cart form, .flypage-kosik form, .akcia-buttons form, .acc_item form, .compare_cart form, .pretty_cart form, .custom_gifts form, .vig-addtocart form').each(function (e) {
			var $form = jQuery(this);
			// SAKY MATRIX
			if (jQuery('.matrixQuantity').length > 0) {
				jQuery('.matrixControlQ .but')
					.off('click')
					.on('click', function () {
						var input             = jQuery(this).parents('td').find('.matrixQuantity');
						var matrixMaxQuantity = jQuery(this).closest('td').find('.matrixMaxQuantity').text();
						var inputVal          = input.val();
						if (jQuery(this).hasClass('plus')) {
							//ak je zapnuta kontrola skladu tak nedovol dat do kosika viac variantov ako je skladom
							if (parseInt(matrixMaxQuantity) > 0 && parseInt(matrixMaxQuantity) - 1 == parseInt(inputVal)) {
								//zmen farbu pluska (indikator, ze uz nie je mozne kupit viac kusov)
								input.val(parseInt(inputVal) + 1);
								jQuery(this).addClass('disabled-plus');
							} else if (parseInt(matrixMaxQuantity) > 0 && parseInt(matrixMaxQuantity) == parseInt(inputVal)) {
								//nepridavaj uz dalsie varianty
							} else {
								input.val(parseInt(inputVal) + 1);
							}
						} else {
							jQuery(this).closest('.matrixControlQ').find('.plus').removeClass('disabled-plus');
							if(inputVal > 0) input.val(inputVal - 1);
						}
					});
			}

			if (is_cs_user()){
				$form.find('.categ_add_to_cart_not_on_stock')
					.off('click.ajaxcart')
					.on('click.ajaxcart', function (e) {
						if( e.preventDefault )
							e.preventDefault();
						jQuery(this).parents('form').trigger('submit');
					});
			} else {
				$form.find('.categ_add_to_cart_not_on_stock')
					.off('click')
					.on('click', function (e) {
						if( e.preventDefault )
							e.preventDefault();
						jQuery(this).parents('form').trigger('submit');
					});
			}

			if (jQuery('.pp_pic_holder').length) {
				return;
			}

			$form.off('submit').on('submit', function (e) {

				// v detaile produktu ak nie je zvoleny variant, vykona sa klasicky submit, aby sa predislo vyskakovaniu modalneho okna
				if ( jQuery('.shop_page_class_shop_product_details').length && jQuery('.flypage1 .flypage-top select.main_attr_select').length &&
					jQuery('.flypage1 select.main_attr_select').filter(function() { return jQuery(this).val() == ''; }).length ) {
					return true;
				}

				if(e.preventDefault) {
					e.preventDefault();
				}

				var elem = this;
				var $elem = jQuery(this);
				var params = {};

				// form submit disabled
				if ($elem.hasClass('disabled')) {
					return false;
				}

				if ($elem.hasClass('custom_attribute_submit_error')) {
					$elem.removeClass('custom_attribute_submit_error');
					return false;
				}

				var product_id = $elem.find('[name=product_id]').val();
				var quantity            = $elem.find('[name=quantity]').val();
				var $elemFlypage1Parents = $elem.parents('.flypage1');
				params.is_gift          = $elem.find('[name=is_gift]').val() == 1;
				params.is_special_offer = $elem.find('[name=is_special_offer]').val() == 1;

				if ($elem.find('[name=product_availability]').length > 0) {
					params.product_availability = $elem.find('[name=product_availability]').val();
				}

				if(!product_id) {
					product_id = $elemFlypage1Parents.find('[name=product_id]').val();
				}

				if (!quantity) {
					quantity = $elemFlypage1Parents.find('[name=quantity]').val();
				}

				// priplatkove produkty - add to cart
				var surchargeProducts = $elem.closest('.flypage-cart').find('div[data-surcharge-product-id]');
				if (surchargeProducts.length === 0) {
					surchargeProducts = $elem.closest('.flypage1').find('div[data-surcharge-product-id]');
				}
				params.hasSurchargeProducts = surchargeProducts.length > 0; // ak je false a v Backende mame priplatkove produkty tak sa zobrazi modalne okno s vyberom priplatkovych produktov

				if (!params.hasSurchargeProducts || e.currentTarget.id.indexOf('_') !== -1) { // vex okno pre varianty
					surchargeProducts = $elem.closest('.vex').find('div[data-surcharge-product-id]');
					params.hasSurchargeProducts = surchargeProducts.length > 0;
				}
				if (surchargeProducts.length) {
					params.surchargeProducts = [];
					surchargeProducts.each(function () {
						var $this = jQuery(this);
						if ($this.find('div.surcharge_product_main_content input[type="checkbox"]:checked').length === 1) {
							params.surchargeProducts.push( parseInt($this.attr('data-surcharge-product-id')) );
						}
					});
					// surchargeProducts.parent().html('');
				}

				// na server pojde aj udaj o predlzenej zaruke, pokial je zaskrtnuta
				if ($elem.find('[name=extended_warranty_product]:checked').length > 0) {
					params.extended_warranty_product = $elem.find('[name=extended_warranty_product]:checked').val();
				}

				if (jQuery('input[name="special_product"]').length) {
					special_products_imploded = [];
					jQuery('input[name="special_product"]:checked').each(function (index, value) {
						special_products_imploded[index] = jQuery(this).val();
					});
					params.special_products = special_products_imploded.join(',');
				}

				$select = $elem.find('.prod_adv_attrib_select select.main_attr_select');
				$advAttrRadio = $elem.find('.prod_adv_attrib_radio');
				$advAttrSelect = $elem.find('.prod_adv_attrib_select');

				// 27.12.2018 - pato $elem.parents('.flypage-related') je zle lebo to neberie sibling ... ako asi niekto chcel  ($elem.parents('.flypage1').find('.flypage-related').length == 0)
				if ($elem.closest('.shop_addtocart_with_advanced_attributes').length && $elem.parents('.flypage-related').length == 0) {
					var $flypageElem = $elem.parents('.flypage1');

					if ($advAttrSelect.length == 0) {
						tmp = $flypageElem.find('.prod_adv_attrib_select');

						if (tmp.parents('.flypage-related').length == 0) {
							$advAttrSelect = tmp;
						}
					}

					if ($advAttrSelect.length == 0 && $advAttrRadio.length == 0) {
						tmp = $flypageElem.find('.prod_adv_attrib_radio');

						if (tmp.parents('.flypage-related').length == 0) {
							$advAttrRadio = tmp;
						}
					}

					if ($advAttrSelect.length == 0 && $advAttrRadio.length == 0 && $select.length == 0) {
						tmp = $flypageElem.find('.prod_adv_attrib_select select.main_attr_select');

						if (tmp.parents('.flypage-related').length == 0) {
							$select = tmp;
						}
					}
				}

				if ($select.length > 0) {
					if ($select.hasClass('no_submit')) {
						return false;
					}
					if ($select.length > 1) {
						// old mode, more selectboxes
						params.select_name      = [];
						params.select_value     = [];
						params.more_select_mode = 1;
						$select.each(function () {
							params.select_name.push(jQuery(this).attr('name'));
							params.select_value.push(jQuery(this).val());
						});
					} else {
						// new mode, only 1 selectbox
						params.select_name  = $select.attr('name');
						params.select_value = $select.val();
					}
				} else if ($advAttrRadio.length > 0) {
					params.select_name = $advAttrRadio.find('input[type="radio"]:first').attr('name');
					params.select_value = $advAttrRadio.find('input[type="radio"]:checked').val();
				} else if ($advAttrSelect.find('select.main_attr_select:first').length > 0 || $advAttrSelect.find('input[name="attribute_select_mode"]').length) {

					if ($advAttrSelect.length > 1) {
						// old mode, more selectboxes
						params.select_name      = [];
						params.select_value     = [];
						params.more_select_mode = 1;
						$advAttrSelect.each(function () {
							params.select_name.push(jQuery(this).find('select.main_attr_select:first').attr('name'));
							params.select_value.push(jQuery(this).find('select.main_attr_select:first').val());
						});
					} else {
						params.select_name = $advAttrSelect.find('select.main_attr_select:first').attr('name');
						params.select_value = $advAttrSelect.find('select.main_attr_select:first').val();
					}
				}

				if (typeof product_id !== 'undefined' && typeof js_Config_product_variant !== 'undefined' && js_Config_product_variant && typeof window['ProductVariantInstance_' + product_id] !== 'undefined' && typeof window['ProductVariantInstance_' + product_id].selectedAttribute !== 'undefined') {

					params.select_name = 'faadd750a6fbb9ea11a94c6074db79144';
					params.select_value = window['ProductVariantInstance_' + product_id].selectedAttribute.source;
				}

				if ( typeof js_Config_product_attachment !== 'undefined' && js_Config_product_attachment && typeof productAttachment !== 'undefined' && productAttachment != '' ) {
					params.product_attachment = productAttachment;
				}

				if ( $elem.parents('.flypage1').find('.product-custom-attributes').length && typeof js_Config_vex_after_add_to_cart_skip_custom_attributes === 'undefined' ) {

					if (typeof params.select_name == 'undefined') {
						params.select_name = [];
					} else if (typeof params.select_name == 'string') {
						params.select_name = [ params.select_name ];
					}

					if (typeof params.select_value == 'undefined') {
						params.select_value = [];
					} else if (typeof params.select_value == 'string') {
						params.select_value = [ params.select_value ];
					}

					$elem.parents('.flypage1').find('.product-custom-attribute .inputbox').each(function () {
						params.select_name.push(jQuery(this).attr('name'));
						params.select_value.push(jQuery(this).val());
					});
				}

				if(params.select_value == "") delete params.select_value;

				if ($elem.find('[name=gift_text]').length && jQuery.trim($elem.find('[name=gift_text]').val()) != '') {
					params.select_name      = 'faadd750a6fbb9ea11a94c6074db79144';
					params.select_value     = $elem.find('[name=gift_text]').val();
					params.forced_add       = 1;
					params.is_gift          = 1;
				}

				// JAN nakupovanie v rozmeroch : pridanie parametrov do postu
				if ( $elem.find('[name=dim_a]').length > 0 && $elem.find('[name=dim_b]').length > 0) {
					params.dim_a = $elem.find('[name=dim_a]').val();
					params.dim_b = $elem.find('[name=dim_b]').val();
				}
				if ( $elem.find('[name=modify_cart_item]').length > 0 && $elem.find('[name=modify_cart_item]').val() != '') {
					params.modify_cart_item = $elem.find('[name=modify_cart_item]').val();
				}
				if ( $elem.find('[name=category_id]').length > 0 && $elem.find('[name=category_id]').val() != '' ) {
					params.category_id = $elem.find('[name=category_id]').val();
				}

				// JAN doplnky produktu : pridanie parametrov do postu
				if ( $elem.find('.product_accessory_options').length > 0 ) {
					var accessories = [];

					$elem.find('.product_accessory_options').find('.product_accessory_group_box:visible select').each(function(){
						var sel_box = jQuery(this);
						var box = sel_box.parents('.product_accessory_group_box');
						var sel_box_id = box.data('box');

						sel_box.find('option:selected').each(function(){
							var acc_id = jQuery(this).val();
							var acc_field = jQuery('.custom_accessory_field_box.cafb_'+sel_box_id);
							if( acc_field.length > 0 && acc_field.is(':visible') ){
								var acc_pap_item = acc_field.find('.pap_item_'+acc_id);
								if( acc_pap_item.length > 0 && acc_pap_item.is(':visible') ){
									var acc_label_f = acc_pap_item.find('label').html();
									var acc_field_f = acc_pap_item.find('.product_accessory_param_'+acc_id).val();
									var acc_txt = acc_label_f + ': ' + acc_field_f;
									var acc_qty = (box.hasClass('quantity_add_check') ? quantity : '1');
									accessories.push( JSON.stringify({"id": acc_id,"qty": acc_qty,"custom": acc_txt}) );
								} else accessories.push( JSON.stringify({"id": acc_id}) );
							} else accessories.push( JSON.stringify({"id": acc_id}) );
						});
					});
					params.product_accessories = accessories.join(';');
				}


				if (quantity > 0) {
					// SAKY MATRIX
					if(jQuery('input.matrixQuantity').length > 0) {
						var mq = [];
						var mv = [];

						jQuery('input.matrixQuantity').each(function() {
							var q = parseInt(jQuery(this).val());

							if(q > 0) {
								mq.push(q);
								mv.push(jQuery(this).closest('td').find('input.matrixQuantityVal').val());
							}
						});

						var i;
						params.matrix = true;
						for(i = 0; i < mq.length; i++) {
							params.select_value = mv[i];
							js_ajax_cart_update(elem, product_id, mq[i], params);
						}

						return false;
					}

					if(jQuery('#product_custom_shipping_district2').length && jQuery('#shipping_date').length){

						if (jQuery.trim(jQuery('#product_custom_shipping_district2').val()) == '') {
							vex.dialog.alert({message:'Prosím vyberte miesto doručenia.'});
							return false;
						}
						params.delivery_district_and_date = jQuery('#product_custom_shipping_district2').val()+' - '+ jQuery('#shipping_date').val();
					}

					// JAN dynamicke atributy
					if ($elem.find('.daf_wrap').length && typeof dattr === 'object' && typeof dattr.parseCart === 'function') {
						params.quantity = quantity;
						dattr.parseCart(params, function(result) {

							if ( !result || jQuery.isEmptyObject(result) ) return false;

							params = result;
							js_ajax_cart_update(elem, product_id, quantity, params);
						});
					} else {

						js_ajax_cart_update(elem, product_id, quantity, params);
					}
				}
				return false;
			});
		});
	}

	function js_cart_image_animate(elem) {

		// disable animation for specific funcion
		if (typeof js_Config_modal_after_add_to_cart !== 'undefined') {
			return;
		}

		elem = jQuery(elem);

		if (elem.find('#addtocart').hasClass('custom_attribute_submit_error')) {
			elem.find('#addtocart').removeClass('custom_attribute_submit_error');
			return false;
		}

		var product_img = null;
		var ajaxCartUpdate = localStorage.getItem('ajaxCartUpdateVariants');
		var variantImgSrc = null;
		var selectValue   = null;
		if (localStorage.getItem('selectedItemValue') != null) {
			selectValue = localStorage.getItem('selectedItemValue');
		}
		localStorage.removeItem('ajaxCartUpdateVariants');
		localStorage.removeItem('selectedItemValue');
		if (selectValue != null) {
			var attributes = selectValue.split('{');
			for (var i = 0; i < attributes.length; i++) {
				if (attributes[i].indexOf('IMG=') > -1) {
					variantImgSrc = attributes[i].substring(4, attributes[i].indexOf('}')); // attributes[i] = 'IMG=cesta/obrazka.jpg}'
					break;
				}
			}
		}
		if (variantImgSrc != null) {
			product_img = jQuery('<img src="' + window.js_global_skvelyweb_site + '/images/shop-active-images/' + variantImgSrc + '" alt="' + variantImgSrc + '">');
		} else {
			if (ajaxCartUpdate != null) {
				ajaxCartUpdate  = JSON.parse(ajaxCartUpdate);
				var imageSource = ajaxCartUpdate.image_source;
				product_img     = jQuery('<img src="' + imageSource + '" alt="' + imageSource + '">');
			}
		}

		if (elem.parents('.related_product1:first, .related_product2:first, .related_product3:first').length > 0) {
			if (elem.parents('.related_product1:first, .related_product2:first, .related_product3:first').find('.featured-image-span:first img:first').length > 0) {
				product_img = elem.parents('.related_product1:first, .related_product2:first, .related_product3:first').find('.featured-image-span:first img:first');
			} else {
				product_img = elem.closest('.related_product1, .related_product2, .related_product3').find('.shop-cat-img a img');
			}
		} else if (elem.parents('.featured-prod:first').length > 0) {
			product_img = elem.parents('.featured-prod:first').find('.featured-image-span:first img:first, .shop-cat-img img.thumb:first');
		} else if (elem.parents('.shop-category-product:first').length > 0) {
			product_img = elem.parents('.shop-category-product:first').find('img.thumb:first');
		} else if (elem.parents('.acc_item:first').length > 0) {
			product_img = elem.parents('.acc_item:first').find('img:first');
		} else if (elem.parents('.article_product:first').length > 0) {
			product_img = elem.parents('.article_product:first').find('img:first');
		} else if (elem.parents('.article_product_listing:first').length > 0) {
			product_img = elem.parents('.article_product_listing:first').find('img:first');
		} else if (elem.parents('.flypage1:first').length > 0) {
			product_img = elem.parents('.flypage1:first').find('.flypage-image img.default_flypage_img');

			if ((typeof js_Config_product_variant !== 'undefined') && (typeof js_Config_product_variant.options !== 'undefined') && (typeof js_Config_product_variant.options.table_data !== 'undefined') &&
				(jQuery.inArray('_IMAGE_', js_Config_product_variant.options.table_data) > -1)) {
				if (elem.parents('.flypage1:first').find('.prod_adv_attribs_div').find('tr.active').find('img').length > 0) {
					product_img = elem.parents('.flypage1:first').find('.prod_adv_attribs_div').find('tr.active').find('img');
				}
			}
			if ((typeof js_rotate_active_images_detail_data !== 'undefined') && (typeof js_rotate_active_images_detail_data._hideActiveImages !== 'undefined') && (js_rotate_active_images_detail_data._hideActiveImages == false)) {
				if (elem.parents('.flypage1:first').find('.flypage-slick-images').find('.slick-active img').length > 0) {
					product_img = elem.parents('.flypage1:first').find('.flypage-slick-images').find('.slick-active img');
				}
			}

		} else if (elem.parents('.prod:first').length > 0) {	// comparing table
			product_img = elem.parents('.prod:first').find('.prod-img img');
		} else if (elem.closest('tr.product_item').length) {
			product_img = elem.closest('tr.product_item').find('img:first');
		} else if (elem.parents('.product_exchange_modal').find('img').length) {
			product_img = elem.parents('.product_exchange_modal').find('img');
		} else if (elem.parents('.module-latest-viewed-item').length) {
			product_img = elem.parents('.module-latest-viewed-item').find('.shop-cat-img').find('img');
		} else if (jQuery('.flypage-image img').length) {
			product_img = jQuery('.flypage-image img');
		} else if (elem.closest('.wishlist_item').length) {
			product_img = elem.closest('.wishlist_item').find('.wishlist_item_img img');
		} else if (elem.parents('.bl_product_cart_wrap:first').siblings('.bl_product_image_wrap').length) {
			product_img = elem.parents('.bl_product_cart_wrap:first').siblings('.bl_product_image_wrap').find('img');
		}

		if (product_img != null && product_img.length) {
			// set fixed position for cart
			if (typeof ('js_cart_css_obj') != 'undefined' && jQuery('#topmenu .module-cart').length > 0) {
				js_init_fixed_ajax_cart();
			}
			var product_ajax_img = product_img.clone();
			var offset           = product_img.offset();
			if (elem.hasClass('vex-content')) {
				offset = elem.offset();
			}
			var $html = jQuery('html');
			product_ajax_img.addClass('ajax_image_animate');
			var cart_obj    = jQuery('.module_cont-cart .mainlevel, .module_cont-cart .moduleCartTop a, .module_cont-cart a.cartLink');
			var cart_offset = cart_obj.offset();
			var posX = offset.left;
			if ( elem.hasClass('vex-content') || !(typeof is_responsive !== 'undefined' && is_responsive()) ) {
				posX = offset.left + (elem.width() / 2);
			}
			var posY            = offset.top;
			var inHalfViewport = $html.scrollTop() > offset.top + product_img.height() / 2;
			var productImgWidth = product_img.width();
			var width           = $html.width() * 0.6;
			if (elem.hasClass('vex-content')) {
				if (productImgWidth == 0) {
					productImgWidth = 100;
				}
			}
			if (inHalfViewport) {
				product_ajax_img.css({width: (productImgWidth > width ? width : productImgWidth)});
				// zakomentovane na ziadost LM a MM
				// if (typeof is_responsive !== 'undefined' && is_responsive()) {
				// 	posX = 10;
				// }
				posY = $html.scrollTop() + 70;
			} else {
				product_ajax_img.css({width: productImgWidth});
			}

			product_ajax_img.css({position: 'absolute', top: posY, left: posX});
			product_ajax_img
				.appendTo('body')
				.show()
				.css({'z-index' : 100002,
					'box-shadow':'0 0 3px 3px #e5e5e5', '-moz-box-shadow' : '0 0 3px 3px #e5e5e5', '-webkit-boxshadow' : '0 0 3px 3px #e5e5e5', 'width:': product_img.width(), height: product_img.height()})
				.animate({left:cart_offset.left + cart_obj.width() / 2, top: cart_offset.top + cart_obj.height() / 2, width:40, height:30}, 1000, 'easeInCirc', function () {
					product_ajax_img.remove();
				});

		}
	}

	function js_ajax_cart_flush(elem, extraSettings) {
		vex.dialog.confirm({
			message : js_lang_shopping_cart_empty_confirm,
			callback: function (value) {
				if (value) {
					elem               = jQuery(elem);
					var ajax_container = elem.parent();

					var ajax_items = jQuery(ajax_container).parents('.cart_ajax_container').find('.product_cont');
					if (ajax_items.length && typeof isApiActive !== 'undefined' && isApiActive) {
						var pageMatch = js_server_request_uri.match(/(&|;|\?)page\=([^&]+)/);
						var manMatch = js_server_request_uri.match(/(&|;|\?)pc_manufacturer_id\=([^&]+)/);
						var page = '';

						if (typeof manMatch === 'object' && manMatch !== null) {
							page = 'manufacturer';
						} else if (typeof pageMatch === 'object' && pageMatch !== null && typeof pageMatch[2] !== 'undefined') {
							page = pageMatch[2];
						}

						apiRequest('flushCart', {
							'page': page,
							'isAjax': true
						});
					}

					var options = {'ajax_func': 'flush_ajax_cart'};
					ajax_container.startAjaxLoader();

					jQuery.post('/modules/mod_shop_cart_ajax.php', options, function (ajax_res) {
						var result = JSON.parse(decodeURIComponent(ajax_res));
						js_cart_total = 0; //config_cart_total_js
						js_ajax_cart_container_init(result, 'flush');

						if (typeof (js_ajax_cart_update_after_init) != 'undefined') {
							js_ajax_cart_update_after_init();
						}
						ajax_container.stopAjaxLoader();

						if (typeof extraSettings !== 'undefined' && extraSettings.refreshAfterComplete !== 'undefined' && extraSettings.refreshAfterComplete) {
							window.location.reload();
						}
					});

					// odstranenie ikoniek kosika s pridanym quantity (abenys)
					var amountDiv = jQuery('div.product_amount_in_cart_div');
					var amountSpan = amountDiv.find('span');
					if (amountSpan.length > 0) {
						amountSpan.text('');
						amountDiv.find('img').prop('src', '');
					}

					if (typeof (js_ajax_cart_update_after_init) != 'undefined') {
						js_ajax_cart_update_after_init();
					}

					// ecomail trackovanie obsahu kosika (len pre non cs)
					if(!is_cs_user() && typeof js_Config_ecomail_track_cart_content !== 'undefined') {
						//ziskame naformatovany obsah kosika
						new AjaxRequest()
							.setController('Cart')
							.setAction('getCartContentForEcomail')
							.onSuccess(function (result) {

								//odosleme obsah kosika
								if (typeof window.ecotrack !== 'undefined' ) {
									window.ecotrack('trackUnstructEvent', {
										schema: '',
										data: {
											action: 'Basket',
											products: result.data
										}
									});
								}
								//console.log(result.data);
							})
							.send();
					}
				}
			},
			afterOpen: function () {
				setTimeout(function () {
					jQuery(document).find('.vex-dialog-buttons .vex-dialog-button-primary').trigger('focus');
				}, 100);
			}
		});
		return false;
	}

	function js_ajax_cart_container_init(result, action) {
		// Ak je sprava urcena pre messenger
		var res = typeof result.update_res === 'string' ? result.update_res.search('<div class="msg_wrap">') : '-1';

		if (typeof(result.update_res) == 'string' && result.update_res.substr(1,3) == 'div' && res == '-1' ) {	// error message
			var jqo_message = jQuery('<div>'+result.update_res+'</div>');
			jqo_message.find('br:last').remove();
			jqo_message = jqo_message.children();
			jqo_message
				.css({width:500, position:'fixed', top:(jQuery(window).height() / 2 - 70), left:(jQuery(window).width() / 2 - 280), 'z-index':10001 })
				.hide();
			jQuery('body').append(jqo_message.fadeIn(1000));
			setTimeout(function () { jqo_message.fadeOut(1000, function () { jqo_message.remove(); }); }, 8000);

		} else if (action == 'flush' || typeof(result.update_res) != 'undefined' && typeof(result.update_res.success) != 'undefined' && result.update_res.success == '1') {	// flush || update cart
			jQuery('.module-cart .module-cart-products, .module-cart .moduleCartInfo').html(result.html_cart_values);

			if ( Cookies.get('gifts-h46L32i6u') !== undefined && Cookies.get('gifts-h46L32i6u') !== '' ) {
				if (typeof(js_gift_init) == 'function')
					js_gift_init();
			}

			var new_ajax_content = jQuery('<div>'+result.html_products+'</div>').html();
			if (new_ajax_content != null && new_ajax_content != 'null') {
				if (jQuery('.module-cart .cart_ajax_container').length < 1)
					jQuery('.module-cart .module_cont-cart table').after(result.html_products);
				else {
					jQuery('.module-cart .cart_ajax_container').replaceWith(result.html_products);

					if (typeof(result.method) != 'undefined') {
						jQuery('.module-cart .cart_ajax_container').stop().show();
						js_cart_link_update(); // cart link
						js_ajax_cart_container_events_init();
						// doprava zdarma
						if (typeof(js_freeshipping_init) == 'function')
							js_freeshipping_init();

						if (typeof(js_gift_init) == 'function')
							js_gift_init();

						if (typeof(js_product_as_gift_init) == 'function') {
							if (typeof js_CS_Config_product_as_gift_empty_stock !== 'undefined') {
								if (!(typeof js_Config_product_as_gift_disable != 'undefined' && js_Config_product_as_gift_disable) && !js_CS_Config_product_as_gift_empty_stock) {
									js_product_as_gift_init();
								}
							} else if (!(typeof js_Config_product_as_gift_disable != 'undefined' && js_Config_product_as_gift_disable)) {
								js_product_as_gift_init();
							}
						}
						if (typeof (js_ajax_cart_after_init) == 'function') {
							js_ajax_cart_after_init();
						}
						if (typeof (product_accessory_bind) == 'function') {
							product_accessory_bind();
						}
						return false;
					} else {
						setTimeout(function () {
							jQuery('.module-cart .cart_ajax_container').stop().slideDown(700);
						}, 500);
					}
				}
			} else
				jQuery('.module-cart .cart_ajax_container_inner').html('');
			jQuery('.module-cart .cart_ajax_container').stop().slideUp(50, 'easeOutExpo', function () { jQuery(this).removeClass('is_open'); });
		} else if(res == '-1'){
			if (typeof(console) != 'undefined') console.log('CART UPDATE ERROR2:', result);
		}

		js_cart_link_update(); // cart link
		js_ajax_cart_container_events_init();
		js_refresh_extended_waranty();
		js_refresh_surcharge_products();

		// doprava zdarma
		if (typeof(js_freeshipping_init) == 'function')
			js_freeshipping_init();
		if (typeof(js_gift_init) == 'function')
			js_gift_init();

		if (typeof(js_ajax_cart_after_init) == 'function')
			js_ajax_cart_after_init();

		if( typeof(product_accessory_bind) == 'function' ){
			product_accessory_bind();
		}
	}

	/**
	 * @var futureAvailability {id: number, value: string}
	 * @param futureAvailability
	 */
	function js_refresh_product_availability_by_future_availability(futureAvailability) {

		if (typeof futureAvailability == 'undefined' || futureAvailability == null || typeof futureAvailability.id == 'undefined' || futureAvailability.id == null) {
			return;
		}

		let availElement = jQuery('.flypage1 .shop_product_availability_value:first');
		let newAvailClass = `attr_avail_${futureAvailability.id}`;

		if ( availElement.length ) {
			if (!availElement.hasClass(newAvailClass) || availElement.text() !== futureAvailability.value) {
				// odoberieme povodne classy pre dostupnost
				jQuery(availElement).attr('class',
					jQuery(availElement).attr('class').split(" ").filter(c => !c.startsWith('attr_avail_')).join(" ").trim()
				);
				// priradime novu classu s novimy hodnotami
				availElement
					.addClass(newAvailClass)
					.attr('title', futureAvailability.value)
					.text(futureAvailability.value);

				if ( typeof futureAvailability.description !== 'undefined' ) {

					var availDescElement = availElement.parent().siblings('.flypage-avail-info').find('.shop_product_availability_value');

					if ( availDescElement.length > 0 ) {
						if ( futureAvailability.description != '' ) {
							availDescElement.attr('data-description', futureAvailability.description).text(futureAvailability.description);
						} else {
							availDescElement.attr('data-description', '').text('');
						}

					}
				}
			}
		}

		jQuery('input[name="quantity"]').trigger('blur');
	}

	function js_refresh_surcharge_products() {
		// overime ci sme na detaile produktu
		if (jQuery('.shop_page_class_shop_product_details').length) {

			// console.log('CALLLED X')

			var cart = jQuery('.flypage-kosik');
			var box = cart.find('div.surcharge_products_wrap');
			var productId = cart.find('input[name="product_id"]').val();

			if (box.length && productId){

				/*new AjaxRequest({
					productId: productId
				})
					.setController('Product')
					.setAction('getSurchargeProductsHtml')
					.onSuccess(function (jsonData) {
						if (jsonData && jsonData.data && jsonData.data.html) {
							box.replaceWith(jsonData.data.html);
						}
					})
					.send();*/

			}

		}
	}

	function js_refresh_extended_waranty(){

		if (jQuery('.shop_page_class_shop_product_details').length){

			var cart = jQuery('.flypage-kosik');
			var box = cart.find('.extended_warranty_products');

			if (box.length){

				var options = { function: 'extended_waranty_products', product_id: cart.find('input[name="product_id"]').val() };

				jQuery.post('/includes/frontend_ajax.php', options, function (res) {

					var result = csJsonParse(res) || {};

					if (typeof result.content !== 'undefined'){
						box.html(result.content);
						jQuery('input[name="extended_warranty_product"]:checked').data("chk", true);
						jQuery('input[name="extended_warranty_product"]').click(function () {
							jQuery('input[name="' + jQuery(this).attr('name') + '"]:radio').not(this).removeData("chk");
							jQuery(this).data("chk", !jQuery(this).data("chk"));
							jQuery(this).prop("checked", jQuery(this).data("chk"));
						});
					}
				});
			}
		}
	}
	function js_cart_link_update(){
		var moduleCartCount = jQuery('.module-cart-products .module-cart-count, .moduleCartInfo .module-cart-count');

		if(jQuery('.moduleCartInfo').length > 0) {
			var link = jQuery('.module_cont-cart a.cartLink');
		} else {
			var link = jQuery('.module_cont-cart a:first');
		}

		link.attr('onclick', typeof(js_cart_link_click) != 'undefined' && js_cart_link_click || moduleCartCount.length || (typeof(js_Config_show_empty_cart) != 'undefined' && js_Config_show_empty_cart == 1) ? 'return true' : 'return false');
		moduleCartCount.length ? jQuery('.cart_ajax_container, .module-cart').removeClass('empty') : jQuery('.cart_ajax_container, .module-cart').addClass('empty');
		if (typeof(js_Config_show_empty_cart) != 'undefined' && js_Config_show_empty_cart == 1) {
			if (moduleCartCount.length) {
				link.removeClass('show_empty');
			} else {
				link.addClass('show_empty');
			}
		}

		if (typeof prof == 'object') prof.sortCart();
	}

// bonusovy system (vex prompt)
	function bonus_system_prompt(cartItems, currency, action) {

		var SendData = {};
		var vexButtons = [];
		var promptText = '<div class="bonus-prompt-wrapper">';
		var productId = 0;
		var CreditValues = {};

		//aktualne dostupne zlavy pre dany produkt (posielany je sucasne vzdy len jeden produkt)
		jQuery.each(cartItems, function (i, v) {

			//id produktu
			productId = i;

			//tlacidla pre zvolenie typu zlavy
			if (v.mode == 'prompt') {

				//bonus - pridaj informaciu o zlave
				//pridaj tlacidlo
				if (v.bonus > 0) {
					CreditValues.bonus = v.bonus.toFixed(2)+' '+currency;
					vexButtons.push(
						jQuery.extend({}, vex.dialog.buttons.YES, {
								text: js_lang_bonus_system_apply_bonus_btn,
								className: 'vex-dialog-button-primary bonus',
								click: function ($vexContent, event) {
									//tlacidlo "Uplatnit bonus"
									$vexContent.data().vex.value = 'bonus';
									vex.close($vexContent.data().vex.id);
								}
							}
						)
					);
				}

				//bonus_discount - pridaj informaciu o zlave
				//pridaj tlacidlo
				if (v.bonus_discount > 0) {
					CreditValues.bonus_discount = v.bonus_discount.toFixed(2)+' '+currency;
					vexButtons.push(
						jQuery.extend({}, vex.dialog.buttons.YES, {
								text: js_lang_bonus_system_apply_bonus_discount_btn,
								className: 'vex-dialog-button-primary bonus-discount',
								click: function ($vexContent, event) {
									//tlacidlo "Uplatnit bonusovu zlavu"
									$vexContent.data().vex.value = 'bonus_discount';
									vex.close($vexContent.data().vex.id);
								}
							}
						)
					);
				}
				/*
				//tlacidlo cancel - nepraju si pouzit (Xko bude ako nahrada)
				vexButtons.push(
					jQuery.extend({}, vex.dialog.buttons.NO, {
							text: js_lang_bonus_system_cancel_btn, click: function ($vexContent, event) {
								//tlacidlo "Zatial neuplatnit"
								$vexContent.data().vex.value = 'cancel';
								vex.close($vexContent.data().vex.id);
							}
						}
					)
				);
				*/
			}

			//tlacidlo pre suhlas s tym ze uz nie je mozne pridat tento produkt do kosika (plati len v bonusovom rezime)
			if (v.mode == 'promptDiscard') {
				vexButtons.push(
					jQuery.extend({}, vex.dialog.buttons.NO, {
							text: js_lang_bonus_system_discard_btn, click: function ($vexContent, event) {
								//tlacidlo "Ok"
								$vexContent.data().vex.value = 'discard';
								vex.close($vexContent.data().vex.id);
							}
						}
					)
				);
				promptText += '<span class="bonus-discard-text" style="padding-top:10px;display:block;"><strong>'+window[v.promptLang]+'</strong></span>';
			}
		});


		//text vexu
		if (cartItems[productId].mode != 'promptDiscard') {
			promptText += '<span class="bonus-text-1" style="padding-top:10px;display:block;">'+js_lang_bonus_system_text_1+'</span>';
		}
		promptText += '<div class="bonus-buttons-replacement"></div>';
		promptText += '<span class="bonus-text-2" style="padding-top:10px;display:block;">'+js_lang_bonus_system_text_2+'</span>';
		promptText += '</div>';

		if (action == '+') {
			//zobraz vex pri pridavani do kosika
			var timestamp = jQuery.now();

			vex.dialog.open({
				message: '<span class="bonus-title">'+js_lang_bonus_system_title+'</span>',
				className: 'vex-cs vex-bonus '+timestamp+'-bonus',
				showCloseButton: true,
				input: promptText,
				buttons: vexButtons.reverse(), //otocenie pola len kvoli poradiu tlacidiel
				callback: function (value) {

					if (value == 'bonus' || value == 'bonus_discount') {

						//bonus alebo bonus_discount
						SendData = {
							mode: value, //mod ktory si zakaznik zvolil
							prodId: productId, //id produktu
							bonusValue: cartItems[productId][value], //vyska kreditu ktory mu ma byt pripocitany
							tmpBonusValues: cartItems[productId]
						};

					} else {
						//cancel
						SendData = {
							mode: '', //mod ktory si zakaznik zvolil
							prodId: productId, //id produktu
							bonusValue: '', //vyska kreditu ktory mu ma byt pripocitany
							tmpBonusValues: cartItems[productId] //zakaznik si nezvolil rezim ale musime si pamatat vysku potencialneho kreditu
						};
					}

					//prenos hodnot do session
					new AjaxRequest(SendData)
						.setMethod('POST')
						.setController('BonusSystem')
						.setAction('setItemMode')
						.onSuccess(function (res) {
							//console.log(res);
						})
						.send();
				},
				afterOpen: function () {
					//zobraz hodnoty zliav priamo v tlacidle
					var btns = jQuery('.'+timestamp+'-bonus .vex-dialog-buttons .vex-dialog-button');
					jQuery.each(btns, function (i,v) {
						//bonus
						if (jQuery(v).hasClass('bonus') && typeof CreditValues.bonus != 'undefined') {
							jQuery(v).wrap('<div class="bonus-button-wrap"></div>');
							jQuery(v).before('<span class="bonus-height">'+CreditValues.bonus+'</span>');
						}
						//bonus discount
						if (jQuery(v).hasClass('bonus-discount') && typeof CreditValues.bonus_discount != 'undefined') {
							jQuery(v).wrap('<div class="bonus-button-wrap"></div>');
							jQuery(v).before('<span class="bonus-discount-height">'+CreditValues.bonus_discount+'</span>');
						}
					});
					//zobraz text pri ikone pre zavretie vexu
					jQuery('.'+timestamp+'-bonus .vex-close').append('<span class="vex-close-lbl">'+js_lang_bonus_system_cancel_btn+'</span><span class="vex-close-btn"></span>');
					//posun tlacidla medzi text
					jQuery('.'+timestamp+'-bonus .vex-dialog-buttons').appendTo(jQuery('.'+timestamp+'-bonus .bonus-buttons-replacement'));

				}
			});
		} else {

			if (cartItems[productId].mode == 'promptDiscard') {
				//pri odoberani zobraz vex ak sme v bonusovom rezime a snazime sa odobrat nepovolenu polozku
				vex.dialog.open({
					message: '<span class="bonus-title">'+js_lang_bonus_system_title+'</span>',
					input: promptText,
					buttons: vexButtons
				});

			} else {

				//nezobrazuj vex pri odoberani z kosika (ale odpocitaj tmpCredit)
				SendData = {
					mode: '', //mod ktory si zakaznik zvolil
					prodId: productId, //id produktu
					bonusValue: '', //vyska kreditu ktory mu ma byt pripocitany
					tmpBonusValues: cartItems[productId] //zakaznik si nezvolil rezim ale musime si pamatat vysku potencialneho kreditu
				};

				//prenos hodnot do session
				new AjaxRequest(SendData)
					.setMethod('POST')
					.setController('BonusSystem')
					.setAction('setItemMode')
					.onSuccess(function(res) {
						//console.log(res);
					})
					.send();
			}
		}

	}

// bonusovy system (aktivacia/deaktivacia specialneho bonusoveho rezimu)
	function bonus_system_activate(jqo, activate) {

		var SendData = {
			mode: activate ? 'bonus' : 'normal'
		};

		//aktivacia specialneho bonusoveho rezimu (zmena zakaznickej skupiny)
		new AjaxRequest(SendData)
			.setMethod('POST')
			.setController('BonusSystem')
			.setAction('setShoppingMode')
			.onSuccess(function (res) {
				//presmeruj do vybranej kategorie
				window.location = res.data.redirect_path;
			})
			.send();
	}

// bonusovy system (nedovol pridat polozku ktora by prekrocila vysku nazbieraneho bonusu)
	function bonus_system_update_cart_plus_sign(bonusItems, actualBonusAmount) {

		if (Object.keys(bonusItems).length > 0) {
			jQuery.each(bonusItems, function(i,v) {
				if (actualBonusAmount < v.price) {
					//add
					jQuery('.cart_ajax_container #'+v.hash+' .cajx_quant .plus').addClass('basket-input-disabled');
				} else {
					//remove
					jQuery('.cart_ajax_container #'+v.hash+' .cajx_quant .plus').removeClass('basket-input-disabled');
				}
			});
		}
	}

// bonusovy system NEMAZAT! (vynuteny prepocet cenoveho slidera - treba zavolat v local.js ako onBrowseRequest vo sphinx filtri)
	function setBonusRange() {
		if (sphf.groups.price_range.bonus_active == 1){
			sphf.resetSlider('price_range', true);
		}
	}

	//JB modifikácia pre varianty v riadkovom výpise
	//odstráni option zo selectu
	function refreshVariantSelect(elem, attr) {
		//zistíme všetky riadky ktoré sú vypísané a podľa nich upravíme options v selecte
		var wrapper = elem.closest('.product-variant-wrap');
		var newFinalAmount = 0;

		if (typeof attr == 'string') {
			if (attr.includes(':')) {
				var option = elem.find('option[data-index="' + attr + '"]');
			} else {
				var option = elem.find('option[data-index=""]');
			}
			option.prop('disabled', !option.prop('disabled'));
			option.prop('selected', !option.prop('selected'));

			//nakoľko nefunguje jquery toggle je prepínať viditeľnosť takto
			if (option.get(0).style.display === "none" || option.get(0).style.display === "" && jQuery.css( option.get(0), "display" ) === "none") {
				option.show();
			} else {
				option.hide();
			}
			if (elem.find('option:selected').length) {
				elem.closest('.product-chooser-wrap').show();
			} else {
				elem.closest('.product-chooser-wrap').hide();
			}
		}
		//zapísanie reálneho množstva do inputu

		//---------------------------

		//časť kódu upraví
		wrapper.find('input.variant-amount').each(function(){
			newFinalAmount += parseInt(jQuery(this).val());
		});

		//newFinal value môže presahovať povolený limit
		var finalAmountInput = wrapper.closest('tr[class*=product_]').find('input.product_quantity');

		finalAmountInput.attr('value',newFinalAmount);

		//refreshneme input, aby nám vrátil reálnu hodnotu ->ako sa zachovať pri načítaní údajov
		js_change_quantity(finalAmountInput.get(0));

	}

	//vytvorí nám nový riadok vybraného variantu
	function lineAddVariant(elem) {
		elem = jQuery(elem);
		var select = elem.closest('.product-variant-wrap').find('select:first');
		var variant = select.find('option:selected');

		if (variant.data('index') == '') {
			if (typeof js_browse_listing_choose_variant != 'undefined') {
				var tmpContent = js_browse_listing_choose_variant;
			}

			variant.closest('select').tooltipster({
				theme        : 'tooltipster-noir',
				animation    : 'fade',
				delay        : 10,
				timer        : 1500,
				content      : tmpContent,
				functionAfter: function (instance) {
					instance.destroy();
				}
			}).tooltipster('open');
			return false;

		}

		var input = elem.closest('.product-variant-wrap').find('input[name=productVariantAmountTemplate]');
		var amount = input.val();
		input.val('');

		// ak má variant vlastný Stock, ak nie tak v selecte bude údaj o množstve, musí sa sčítať všetko a zároveň amount, a povoliť maximálne

		if (typeof variant.data('qty') != 'undefined' && variant.data('qty') > 0) {
			amount = (amount > variant.data('qty') ? variant.data('qty') : amount);
		} else {
			var finalAmount = elem.closest('.product-variant-wrap').data('qty');
			elem.closest('.product-variant-wrap').find('input[name="productVariantAmount"]').each(function(){
				finalAmount -= jQuery(this).val();
			});
			amount = (amount > finalAmount ? finalAmount : amount);
		}

		if (!(amount > 0)) {
			input.addClass('error');
			if (input.parent().find('.stock_amount_error').length < 1) {
				input.after('<span class="stock_amount_error" style="color:red;">iba ' + ((typeof variant.data('qty') != 'undefined' && variant.data('qty')) ? variant.data('qty') : elem.closest('.product-variant-wrap').data('qty') ) + ' ks </span>');
			}
			return;
		} else {
			input.removeClass('error');
			input.parent().find('span.stock_amount_error').remove();
		}

		var html = '<span class="selected-variant"><span class="variant-index" data-index="' + variant.data('index') + '" data-qty="' + variant.data('qty') + '">' + variant.html() + '</span><input style="width:20px;" class="variant-amount" type="text" name="productVariantAmount" value="' + amount + '"><span class="csi-check" onclick="lineChangeVariant(this)"></span><span class="csi-times" onclick="lineRemoveVariant(this)"></span></span>';

		//todo: overovanie podľa {S} ?? ->ak nie je setnuté, čo robiť ?

		select.closest('.product-variant-wrap').prepend(html);
		refreshVariantSelect(select, variant.data('index'));
	}

	//zmení množstvo variantu
	function lineChangeVariant(elem) {
		//len zmenime hodnotu na danom riadku, po overení množstva
		elem = jQuery(elem);

		var amount = elem.closest('span.selected-variant').find('input.variant-amount').val();
		var variant = elem.closest('span.selected-variant').find('span.variant-index');
		if (typeof variant.data('qty') != 'undefined' && variant.data('qty') > 0) {
			console.log('variant qty');
			amount = (amount > variant.data('qty') ? variant.data('qty') : amount);
		} else {
			var finalAmount = elem.closest('.product-variant-wrap').data('qty');
			elem.closest('.product-variant-wrap').find('input[name="productVariantAmount"]').each(function(){

				//vo final amount je aj hodnota prave upraveného inputu, potrebujeme ju odčítať od final Amount a s tým pracovať ďalej
				finalAmount -= jQuery(this).val();
			});
			console.log('finalAmount',finalAmount);
			console.log('actualAmount',amount);
			console.log('shouldBeAmount',parseInt(amount) + parseInt(finalAmount));
			amount = (finalAmount < 0 ? parseInt(amount) + parseInt(finalAmount) : amount);
			console.log('realAmount',amount);
		}
		elem.closest('span.selected-variant').find('input.variant-amount').val(amount);
		refreshVariantSelect(elem);
	}

	//odstáni riadok variantu
	function lineRemoveVariant(elem) {
		elem = jQuery(elem);
		var select = elem.closest('.product-variant-wrap').find('select:first');

		var variant = elem.closest('span.selected-variant');
		var variantIndex = variant.find('span.variant-index').html();
		variant.remove();

		refreshVariantSelect(select, variantIndex);
	}

	function lineSubmit(elem) {

		elem = jQuery(elem);
		elem.addClass('ajax-loader');
		var product = elem.closest('tr[class*=product_]');
		var addToCartList = {};
		if (product.find('input.product_quantity').val() < 1) {
			elem.removeClass('ajax-loader');
			return false;
		}

		var productId = product.find('input[name="product_id"]').val();
		addToCartList[productId] = [];

		if (product.find('span.selected-variant').length) {
			product.find('span.selected-variant').each(function() {
				var variantIndex = jQuery(this).find('span.variant-index');
				var variantAmount = jQuery(this).find('input.variant-amount');
				var tmpRow = {
					'variantIndex' : variantIndex.data('index'),
					'variantAmount' : variantAmount.val()
				};

				addToCartList[productId].push(tmpRow);
			});
		} else {
			var tmpRow = {
				'variantAmount' : product.closest('tr[class*=product_]').find('input.product_quantity').val()
			};

			addToCartList[productId].push(tmpRow);
		}

		new AjaxRequest({'data': JSON.stringify(addToCartList)})
			.setMethod('POST')
			.setController('Product')
			.setAction('lineSubmitAll')
			.onSuccess(function(response){
				var html = response.data.html;
				elem.removeClass('ajax-loader');
				jQuery('.moduleCartInfo').html(html.html_cart_values);
				jQuery('.cart_ajax_container').replaceWith(html.html_products);
				jQuery('div.module-cart').removeClass('empty');

				//custom uprava pre wiky, hromadná skladová zásoba pre varianty, preto upravujeme js hodnoty

				lineReset(product);
			})
			.send();
		//toto tu je len kvoli hlúpej predošlej forme
		return false;
	}

	function lineSubmitAll(elem) {

		elem = jQuery(elem);
		elem.addClass('ajax-loader');
		var productWrap = elem.closest('#product_list');

		var addToCartList = {};

		//new product list code
		productWrap.find('tr[class*=product_]').each(function(){

			if (jQuery(this).find('input.product_quantity').val() < 1) {
				return;
			}

			var productId = jQuery(this).find('input[name="product_id"]').val();
			addToCartList[productId] = [];

			if (jQuery(this).find('span.selected-variant').length) {
				jQuery(this).find('span.selected-variant').each(function() {
					var variantIndex = jQuery(this).find('span.variant-index');
					var variantAmount = jQuery(this).find('input.variant-amount');
					var tmpRow = {
						'variantIndex' : variantIndex.data('index'),
						'variantAmount' : variantAmount.val()
					};

					addToCartList[productId].push(tmpRow);
				});
			} else {
				var tmpRow = {
					'variantAmount' : jQuery(this).closest('tr[class*=product_]').find('input.product_quantity').val()
				};

				addToCartList[productId].push(tmpRow);
			}
			//resetovanie
		});
		if (JSON.stringify(addToCartList) == '{}') {
			elem.removeClass('ajax-loader');
			return false;
		}

		new AjaxRequest({'data': JSON.stringify(addToCartList)})
			.setMethod('POST')
			.setController('Product')
			.setAction('lineSubmitAll')
			.onSuccess(function(response){
				var html = response.data.html;
				elem.removeClass('ajax-loader');
				jQuery('.moduleCartInfo').html(html.html_cart_values);
				jQuery('.cart_ajax_container').replaceWith(html.html_products);
				jQuery('div.module-cart').removeClass('empty');

				var reset = jQuery('div.reset_all').find('.reset_all');
				lineResetAll(reset);
			})
			.send();


		//nájsť všetky inputy a vytiahnuť celkový objekt v ktorom budú IDčka -> attribúty
	}

	function lineReset(elem) {
		//vstupom je tr ELEMENT
		elem = jQuery(elem);

		if (elem.hasClass('product-has-attributes')) {
				//zmažeme všetky varianty a resetujeme select

			elem.find('.stock_amount_error').remove();
			elem.find('.variant-amount-template').val('').removeClass('error');

			elem.find('span.selected-variant').each(function(){
				jQuery(this).remove();
			});

			elem.find('.product-chooser-wrap').show();

			elem.find('option').each(function(){
				jQuery(this).show().prop('disabled',false);
			});
		}

		//wiky custom úprava
		var value = elem.find('input.product_quantity').val();
		var oldValue = 0;
		if (elem.hasClass('product-has-attributes')) {
			oldValue = elem.find('.product-variant-wrap').data('qty');
			elem.find('.product-variant-wrap').data('qty', oldValue - value);
		} else {
			//možno prekomplikované, ale custom a rýchle
			oldValue = jQuery('div.productArrayAsInputHiddenBlock div#product_' + elem.find('input[name=product_id]').val()).find('input[name=product_in_stock]').val();
			jQuery('div.productArrayAsInputHiddenBlock div#product_' + elem.find('input[name=product_id]').val()).find('input[name=product_in_stock]').val(oldValue-value);
		}

		elem.find('span.info-value').html(oldValue-value);
		//koniec custom úpravy
		elem.find('input.product_quantity').val(0);
	}

	function lineResetAll(elem) {
		if (!is_cs_user('separate_js')) {
			jQuery('.product_quantity').val('0').change();
		}
		//najideálnejšie by bolo spraviť refresh stránky
		jQuery('div#product_list').find('tr[class*=product_]').each(function() {
			lineReset(this);
		});
		jQuery('#price_all').html(0);
		//len kvoli forme
		return false;
	}

	function getProductToChange(productId, params) {

		return	new AjaxRequest({productId: productId, params: params})
					.setMethod('POST')
					.setController('Product')
					.setAction('getProductToChange')
					.onSuccess(function (response) {
						return response;
					}).send();
	}

	function js_check_if_product_in_cart(productId, params) {

		return	new AjaxRequest({productId: productId, params: params})
					.setMethod('POST')
					.setController('ProductInCart')
					.setAction('productInCartCheck')
					.onSuccess(function (response) {
						return response;
					}).send();
	}
}


/* ========================================
 FILE: /includes/js/system/AjaxRequest.js
 ==================== */

/**
 * @fileOverview AjaxRequest class
 * @name AjaxRequest (/includes/js/system/AjaxRequest.js)
 * @author Martin Hucko <marzineez@gmail.com>
 * @version 1.0.0
 * @requires jQuery
 */

/**
 * @class AjaxRequest
 * @classdesc Basic AJAX request class
 * @constructor
 *
 * @param {Object} [data = {}]
 *
 * @returns {AjaxRequest}
 */
var AjaxRequest = function (data) {

	/**
	 * @member {String} [AjaxRequest#url = '/includes/ajax_handle.php'] - Request URL
	 */
	this.url = '/includes/ajax_handle.php';

	/**
	 * @member {Object} [AjaxRequest#data = {}] - Ajax data
	 */
	this.data = data || {};

	/**
	 * @member {String} [AjaxRequest#method = 'GET'] - Ajax method (POST | GET | PUT | ...)
	 */
	this.method = 'GET';

	/**
	 * @member {Number} [AjaxRequest#timeout = 0] - Ajax timeout in [ms]
	 */
	this.timeout = 0;

	/**
	 * @member {Object.<String, String>} [AjaxRequest#headers = {}] - Ajax headers
	 */
	this.headers = {};

	/**
	 * @member {Boolean} [AjaxRequest#cache = true]
	 */
	this.cache = true;

	/**
	 * @member {String} [AjaxRequest#dataType = 'json']
	 */
	this.dataType = 'json';

	/**
	 * @member {Boolean} [AjaxRequest#ignore = false]
	 */
	this.ignore = false;

	/**
	 * @member {Function} AjaxRequest#successCallback
	 * @see AjaxRequest.prototype.send
	 */
	this.successCallback = null;

	/**
	 * @member {Function} AjaxRequest#errorCallback
	 * @see AjaxRequest.prototype.send
	 */
	this.errorCallback = null;

	/**
	 * @member {Function} AjaxRequest#ajaxFailCallback
	 * @see AjaxRequest.prototype.send
	 */
	this.ajaxFailCallback = null;

	/**
	 * @member {Function} AjaxRequest#completeCallback
	 * @see AjaxRequest.prototype.send
	 */
	this.completeCallback = null;

	/**
	 * @member {Boolean} [AjaxRequest#isExternal = false] - Provided url is external
	 */
	this.isExternal = false;

	/**
	 * @member {Boolean} [AjaxRequest#async = true]
	 */
	this.async = true;

	/**
	 * @member {Object} [AjaxRequest#localData = {}]
	 * @property {String} [AjaxRequest#localData.controller = 'Front']
	 * @property {String} [AjaxRequest#localData.action = 'order.index']
	 */
	this.localData = {};

	this.setLocalData(this.data);

	if (typeof js_CS_Config_csrf !== 'undefined' && js_CS_Config_csrf && typeof js_CS_Config_csrf_header !== 'undefined' && js_CS_Config_csrf_header) {
		this.addHeader(js_CS_Config_csrf_header, jQuery('meta[name="csrf-token"]').attr('content'));
	}

	this.nonCF = false;

	return this;
};

/**
 * jQuery.ajax()
 *   - success
 *     - response is JSON
 *       - jsonData.success -> successCallback(jsonData, textStatus, jqXHR);
 *       - !jsonData.success
 *         - errorCallback provided -> errorCallback(jsonData, textStatus, jqXHR);
 *         - errorCallback not provided
 *           - jsonData.error provided -> vex.dialog.alert(jsonData.error);
 *           - jsonData.error not provided -> vex.dialog.alert(cms_js_lang_content_alert_1); // Unknown error.
 *     - response is something else -> errorCallback(data, textStatus, jqXHR);
 *   - error
 *     - ajaxFailCallback provided -> ajaxFailCallback(jqXHR, textStatus, errorThrown);
 *     - ajaxFailCallback not provided -> vex.dialog.alert(cms_js_lang_content_alert_1); // Unknown error.
 *   - complete -> completeCallback(jqXHR, textStatus);
 *
 * @method AjaxRequest.prototype.send
 * @return {jqXHR}
 */
AjaxRequest.prototype.send = function () {
	return jQuery.ajax({
		url: this.getParsedUrl(),
		data: this.getParsedData(),
		type: this.method,

		cache: this.cache,
		async: this.isAsync(),
		dataType: this.dataType,
		timeout: this.timeout,
		headers: this.headers,
		success: jQuery.proxy(this.handleResponse, this),
		error: jQuery.proxy(this.handleError, this),
		complete: jQuery.proxy(this.handleComplete, this)
	});
};

/**
 * @method AjaxRequest.prototype.handleResponse
 * @param {Object} data
 * @param {String} textStatus
 * @param {Object} jqXHR
 */
AjaxRequest.prototype.handleResponse = function (data, textStatus, jqXHR) {
	if (this.ignore) {
		if (typeof this.successCallback === 'function') {
			this.successCallback(data, textStatus, jqXHR);
		}

		return;
	}

	if (this.dataType === 'json') {
		this.handleJsonResponse(data, textStatus, jqXHR);
	} else if (typeof this.successCallback === 'function') {
		this.successCallback(data, textStatus, jqXHR);
	}
};

/**
 * @method AjaxRequest.prototype.handleJsonResponse
 * @param {Object} data
 * @param {String} textStatus
 * @param {Object} jqXHR
 */
AjaxRequest.prototype.handleJsonResponse = function (data, textStatus, jqXHR) {
	var errorString;

	try {
		jsonData = data;

		this.handleModal(jsonData);

		if (jsonData.success) {
			if (typeof this.successCallback === 'function') {
				this.successCallback(jsonData, textStatus, jqXHR);
			}

			return;
		}

		if (typeof this.errorCallback === 'function') {
			this.errorCallback(jsonData, textStatus, jqXHR);

			return;
		}

		errorString = this.getResponseErrors(jsonData).map(function (error) {
			return '<li>' + error + '</li>';
		}).join('');

		vex.dialog.alert('<ul style="list-style: none; padding: 0; margin: 0;">' + errorString + '</ul>');
	} catch (exception) {
		if (typeof this.errorCallback === 'function') {
			this.errorCallback(data, textStatus, jqXHR);
		}

		if (is_cs_user()) {
			console.log(exception);
		}
	}
};

/**
 * @method AjaxRequest.prototype.handleError
 * @param {Object} jqXHR
 * @param {String} textStatus
 * @param {Object} errorThrown
 */
AjaxRequest.prototype.handleError = function (jqXHR, textStatus, errorThrown) {
	if (typeof this.ajaxFailCallback === 'function') {
		this.ajaxFailCallback(jqXHR, textStatus, errorThrown);

		return;
	}

	if (!this.ignore) {
		vex.dialog.alert(cms_js_lang_content_alert_1);
	}
};

/**
 * @method AjaxRequest.prototype.handleComplete
 * @param {Object} jqXHR
 * @param {String} textStatus
 */
AjaxRequest.prototype.handleComplete = function (jqXHR, textStatus) {
	if (typeof this.completeCallback === 'function') {
		this.completeCallback(jqXHR, textStatus);
	}

	this.showNotifications(jqXHR);
};

/**
 *
 * @param {Object} data
 * @returns {jQuery|null}
 */
AjaxRequest.prototype.handleModal = function (data) {
	if (data.modal && data.body) {
		return vex.dialog.alert(data.body);
	}

	return null;
};

/**
 * @method AjaxRequest.prototype.getResponseErrors
 * @param {Object} data
 * @return {String[]}
 */
AjaxRequest.prototype.getResponseErrors = function (data) {
	if (data.errors && data.errors.length) {
		return data.errors;
	}

	return [cms_js_lang_content_alert_1];
};

/**
 * @method AjaxRequest.prototype.getParsedUrl
 * @return {String}
 */
AjaxRequest.prototype.getParsedUrl = function () {
	var url = this.url;

	if (this.isExternal) {
		return url;
	}

	if (typeof url === 'undefined' || url === null) {

		if ( this.nonCF && js_cf_active ) {
			return (js_cf_active ? js_global_live_site.replace('www.', 'api.') : js_global_live_site) + '/index3.php?' + this.serialize(this.localData);
		}

		return js_global_live_site + '/index3.php?' + this.serialize(this.localData);
	}

	if ( this.nonCF && js_cf_active ) {
		url = js_global_live_site.replace('www.', 'api.') + url;
	}

	return url;
};

/**
 * @method AjaxRequest.prototype.getParsedData
 * @return {Object}
 */
AjaxRequest.prototype.getParsedData = function () {
	return jQuery.extend(true, {}, {
		no_css: 1,
		no_html: 1,
		no_vm_html: 1,
		no_menu: 1,
		ajax_call: 2
	}, this.localData, this.data);
};

/**
 * @method AjaxRequest.prototype.serialize
 * @param {Object} data
 * @param {String} [prefix = '']
 * @return {String}
 */
AjaxRequest.prototype.serialize = function (data, prefix) {
	var parts = [];
	var property, key, value, part;

	for (property in data) {
		if (data.hasOwnProperty(property)) {
			key = prefix ? prefix + '[' + property + ']' : property;
			value = data[property];
			part = (value !== null && typeof value === 'object') ?
				this.serialize(value, property) :
				encodeURIComponent(key) + '=' + encodeURIComponent(value);

			parts.push(part);
		}
	}

	return parts.join('&');
};

/**
 * @method AjaxRequest.prototype.isUrlExternal
 * @param {String} [url = this.url]
 * @return {Boolean}
 */
AjaxRequest.prototype.isUrlExternal = function (url) {
	var domainRe = /https?:\/\/((?:[\w\d-]+\.)+[\w\d]{2,})/i;
	var domain = function (urlInner) {
		return domainRe.exec(urlInner)[1];
	};

	return domain(location.href) !== domain(url || this.url);
};

/**
 * @method AjaxRequest.prototype.setUrl
 * @param {String} url
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setUrl = function (url) {
	this.url = url;
	this.isExternal = this.isUrlExternal();

	return this;
};

/**
 * @method AjaxRequest.prototype.setData
 * @param {Object} data
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setData = function (data) {
	this.data = data;

	return this;
};

/**
 * @method AjaxRequest.prototype.setMethod
 * @param {String} method
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setMethod = function (method) {
	this.method = method;

	return this;
};

/**
 * @method AjaxRequest.prototype.setTimeout
 * @param {Number} timeout
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setTimeout = function (timeout) {
	this.timeout = parseInt(timeout);

	return this;
};

/**
 * @method AjaxRequest.prototype.setHeaders
 * @param {Object} headers
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setHeaders = function (headers) {
	this.headers = headers;

	return this;
};

/**
 * @method AjaxRequest.prototype.addHeader
 * @param {String} name
 * @param {String} header
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.addHeader = function (name, header) {
	this.headers[name] = header;

	return this;
};

/**
 * @method AjaxRequest.prototype.setCache
 * @param {Boolean} cache
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setCache = function (cache) {
	this.cache = cache;

	return this;
};

/**
 * @method AjaxRequest.prototype.setDataType
 * @param {String} dataType
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setDataType = function (dataType) {
	this.dataType = dataType;

	return this;
};

/**
 * @method AjaxRequest.prototype.addCallback
 * @param {String} type
 * @param {Function} callback
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.after = function (type, callback) {
	switch (type) {
		case 'success':
			return this.onSuccess(callback);

		case 'error':
			return this.onError(callback);

		case 'ajaxFail':
			return this.onAjaxFail(callback);

		case 'complete':
			return this.onComplete(callback);

		default:
			return this;
	}
};

/**
 * @method AjaxRequest.prototype.onSuccess
 * @param {Function} callback
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.onSuccess = function (callback) {
	this.successCallback = callback;

	return this;
};

/**
 * @method AjaxRequest.prototype.onError
 * @param {Function} callback
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.onError = function (callback) {
	this.errorCallback = callback;

	return this;
};

/**
 * @method AjaxRequest.prototype.onAjaxFail
 * @param {Function} callback
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.onAjaxFail = function (callback) {
	this.ajaxFailCallback = callback;

	return this;
};

/**
 * @method AjaxRequest.prototype.onComplete
 * @param {Function} callback
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.onComplete = function (callback) {
	this.completeCallback = callback;

	return this;
};

/**
 * @method AjaxRequest.prototype.isExternal
 * @returns {Boolean|AjaxRequest}
 */

/**
 * @method AjaxRequest.prototype.isExternal
 * @param {Boolean} isExternal
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.isExternal = function (isExternal) {
	if (typeof isExternal === 'undefined' || isExternal === null) {
		return this.isExternal;
	}

	this.isExternal = isExternal;

	return this;
};

/**
 * @method AjaxRequest.prototype.isAsync
 * @param {Boolean} [isAsync]
 * @returns {Boolean|AjaxRequest}
 */
AjaxRequest.prototype.isAsync = function (isAsync) {
	if (typeof isAsync === 'undefined' || isAsync === null) {
		return this.async;
	}

	this.async = isAsync;

	return this;
};

/**
 *
 * @param {Boolean} async
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setAsync = function (async) {
	this.async = async;

	return this;
};

/**
 * @method AjaxRequest.prototype.setLocalData
 * @param {Object} data
 * @param {String} data.controller
 * @param {String} data.action
 * @returns {AjaxRequest}
 */
AjaxRequest.prototype.setLocalData = function (data) {
	if (typeof data !== 'object') {
		return this;
	}

	if (data.hasOwnProperty('controller')) {
		this.setController(data.controller);
	}

	if (data.hasOwnProperty('action')) {
		this.setAction(data.action);
	}

	return this;
};

/**
 * @method AjaxRequest.prototype.setController
 * @param {String} controller
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setController = function (controller) {
	this.localData.controller = controller;

	return this;
};

/**
 * @method AjaxRequest.prototype.setAction
 * @param {String} action
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.setAction = function (action) {
	this.localData.action = action;

	return this;
};

AjaxRequest.prototype.setNonCF = function () {
	this.nonCF = true;

	return this;
};

/**
 * @method AjaxRequest.prototype.ignoreDefault
 * @param {Boolean} [ignore = true]
 * @return {AjaxRequest}
 */
AjaxRequest.prototype.ignoreDefault = function (ignore) {
	this.ignore = typeof ignore === 'undefined' ? true : ignore;

	return this;
};

AjaxRequest.prototype.showNotifications = function (jqXHR) {
	try {
		if (typeof jqXHR !== 'object' || !typeof jqXHR.responseText === 'string') {
			return this;
		}
		var response = JSON.parse(jqXHR.responseText);
		if (
			typeof response === 'object' &&
			typeof response.notifications === 'object' &&
			typeof showNotificationsFromList === 'function' &&
			typeof localStorage === 'object' &&
			localStorage.getItem('NotificationsAfterReload') === null
		) {
			showNotificationsFromList(response.notifications);
		}
	} catch (e) {
		console.warn('Problem while showing notifications', e);
	}

	return this;
};

AjaxRequest.prototype.scheduleNotifications = function (notifications) {
	try {
		if (typeof notifications === 'object' && typeof localStorage === 'object') {
			localStorage.setItem('NotificationsAfterReload', JSON.stringify(notifications));
		}
	} catch (e) {
		console.warn('Problem while scheduling notifications', e);
	}

	return this;
};


/* ========================================
 FILE: /includes/js/rateyo/jquery.rateyo.min.js
 ==================== */

/*rateYo V2.3.2, A simple and flexible star rating plugin
prashanth pamidi (https://github.com/prrashi)*/
!function(a){"use strict";function b(){var a=!1;return function(b){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(b)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(b.substr(0,4)))&&(a=!0)}(navigator.userAgent||navigator.vendor||window.opera),a}function c(a,b,c){return a===b?a=b:a===c&&(a=c),a}function d(a,b,c){if(!(a>=b&&a<=c))throw Error("Invalid Rating, expected value between "+b+" and "+c);return a}function e(a){return void 0!==a}function f(a,b,c){var d=c/100*(b-a);return d=Math.round(a+d).toString(16),1===d.length&&(d="0"+d),d}function g(a,b,c){if(!a||!b)return null;c=e(c)?c:0,a=q(a),b=q(b);var d=f(a.r,b.r,c),g=f(a.b,b.b,c);return"#"+d+f(a.g,b.g,c)+g}function h(f,i){function k(a){e(a)||(a=i.rating),Z=a;var b=a/P,c=b*R;b>1&&(c+=(Math.ceil(b)-1)*T),r(i.ratedFill),c=i.rtl?100-c:c,c<0?c=0:c>100&&(c=100),X.css("width",c+"%")}function l(){U=Q*i.numStars+S*(i.numStars-1),R=Q/U*100,T=S/U*100,f.width(U),k()}function n(a){var b=i.starWidth=a;return Q=window.parseFloat(i.starWidth.replace("px","")),W.find("svg").attr({width:i.starWidth,height:b}),X.find("svg").attr({width:i.starWidth,height:b}),l(),f}function p(a){return i.spacing=a,S=parseFloat(i.spacing.replace("px","")),W.find("svg:not(:first-child)").css({"margin-left":a}),X.find("svg:not(:first-child)").css({"margin-left":a}),l(),f}function q(a){return i.normalFill=a,(i.rtl?X:W).find("svg").attr({fill:i.normalFill}),f}function r(a){if(i.multiColor){var b=Z-Y,c=b/i.maxValue*100,d=i.multiColor||{};a=g(d.startColor||o.startColor,d.endColor||o.endColor,c)}else _=a;return i.ratedFill=a,(i.rtl?W:X).find("svg").attr({fill:i.ratedFill}),f}function s(a){a=!!a,i.rtl=a,q(i.normalFill),k()}function t(a){i.multiColor=a,r(a?a:_)}function u(b){i.numStars=b,P=i.maxValue/i.numStars,W.empty(),X.empty();for(var c=0;c<i.numStars;c++)W.append(a(i.starSvg||m)),X.append(a(i.starSvg||m));return n(i.starWidth),q(i.normalFill),p(i.spacing),k(),f}function v(a){return i.maxValue=a,P=i.maxValue/i.numStars,i.rating>a&&C(a),k(),f}function w(a){return i.precision=a,C(i.rating),f}function x(a){return i.halfStar=a,f}function y(a){return i.fullStar=a,f}function z(a){var b=a%P,c=P/2,d=i.halfStar,e=i.fullStar;return e||d?(e||d&&b>c?a+=P-b:(a-=b,b>0&&(a+=c)),a):a}function A(a){var b=W.offset(),c=b.left,d=c+W.width(),e=i.maxValue,f=a.pageX,g=0;if(f<c)g=Y;else if(f>d)g=e;else{var h=(f-c)/(d-c);if(S>0){h*=100;for(var j=h;j>0;)j>R?(g+=P,j-=R+T):(g+=j/R*P,j=0)}else g=h*i.maxValue;g=z(g)}return i.rtl&&(g=e-g),parseFloat(g)}function B(a){return i.readOnly=a,f.attr("readonly",!0),N(),a||(f.removeAttr("readonly"),M()),f}function C(a){var b=a,e=i.maxValue;return"string"==typeof b&&("%"===b[b.length-1]&&(b=b.substr(0,b.length-1),e=100,v(e)),b=parseFloat(b)),d(b,Y,e),b=parseFloat(b.toFixed(i.precision)),c(parseFloat(b),Y,e),i.rating=b,k(),$&&f.trigger("rateyo.set",{rating:b}),f}function D(a){return i.onInit=a,f}function E(a){return i.onSet=a,f}function F(a){return i.onChange=a,f}function G(a){var b=A(a).toFixed(i.precision),d=i.maxValue;b=c(parseFloat(b),Y,d),k(b),f.trigger("rateyo.change",{rating:b})}function H(){b()||(k(),f.trigger("rateyo.change",{rating:i.rating}))}function I(a){var b=A(a).toFixed(i.precision);b=parseFloat(b),O.rating(b)}function J(a,b){i.onInit&&"function"==typeof i.onInit&&i.onInit.apply(this,[b.rating,O])}function K(a,b){i.onChange&&"function"==typeof i.onChange&&i.onChange.apply(this,[b.rating,O])}function L(a,b){i.onSet&&"function"==typeof i.onSet&&i.onSet.apply(this,[b.rating,O])}function M(){f.on("mousemove",G).on("mouseenter",G).on("mouseleave",H).on("click",I).on("rateyo.init",J).on("rateyo.change",K).on("rateyo.set",L)}function N(){f.off("mousemove",G).off("mouseenter",G).off("mouseleave",H).off("click",I).off("rateyo.init",J).off("rateyo.change",K).off("rateyo.set",L)}this.node=f.get(0);var O=this;f.empty().addClass("jq-ry-container");var P,Q,R,S,T,U,V=a("<div/>").addClass("jq-ry-group-wrapper").appendTo(f),W=a("<div/>").addClass("jq-ry-normal-group").addClass("jq-ry-group").appendTo(V),X=a("<div/>").addClass("jq-ry-rated-group").addClass("jq-ry-group").appendTo(V),Y=0,Z=i.rating,$=!1,_=i.ratedFill;this.rating=function(a){return e(a)?(C(a),f):i.rating},this.destroy=function(){return i.readOnly||N(),h.prototype.collection=j(f.get(0),this.collection),f.removeClass("jq-ry-container").children().remove(),f},this.method=function(a){if(!a)throw Error("Method name not specified!");if(!e(this[a]))throw Error("Method "+a+" doesn't exist!");var b=Array.prototype.slice.apply(arguments,[]),c=b.slice(1);return this[a].apply(this,c)},this.option=function(a,b){if(!e(a))return i;var c;switch(a){case"starWidth":c=n;break;case"numStars":c=u;break;case"normalFill":c=q;break;case"ratedFill":c=r;break;case"multiColor":c=t;break;case"maxValue":c=v;break;case"precision":c=w;break;case"rating":c=C;break;case"halfStar":c=x;break;case"fullStar":c=y;break;case"readOnly":c=B;break;case"spacing":c=p;break;case"rtl":c=s;break;case"onInit":c=D;break;case"onSet":c=E;break;case"onChange":c=F;break;default:throw Error("No such option as "+a)}return e(b)?c(b):i[a]},u(i.numStars),B(i.readOnly),i.rtl&&s(i.rtl),this.collection.push(this),this.rating(i.rating,!0),$=!0,f.trigger("rateyo.init",{rating:i.rating})}function i(b,c){var d;return a.each(c,function(){if(b===this.node)return d=this,!1}),d}function j(b,c){return a.each(c,function(a){if(b===this.node){var d=c.slice(0,a),e=c.slice(a+1,c.length);return c=d.concat(e),!1}}),c}function k(b){var c=h.prototype.collection,d=a(this);if(0===d.length)return d;var e=Array.prototype.slice.apply(arguments,[]);if(0===e.length)b=e[0]={};else{if(1!==e.length||"object"!=typeof e[0]){if(e.length>=1&&"string"==typeof e[0]){var f=e[0],g=e.slice(1),j=[];return a.each(d,function(a,b){var d=i(b,c);if(!d)throw Error("Trying to set options before even initialization");var e=d[f];if(!e)throw Error("Method "+f+" does not exist!");var h=e.apply(d,g);j.push(h)}),j=1===j.length?j[0]:j}throw Error("Invalid Arguments")}b=e[0]}return b=a.extend({},n,b),a.each(d,function(){var d=i(this,c);if(d)return d;var e=a(this),f={},g=a.extend({},b);return a.each(e.data(),function(a,b){if(0===a.indexOf("rateyo")){var c=a.replace(/^rateyo/,"");c=c[0].toLowerCase()+c.slice(1),f[c]=b,delete g[c]}}),new h(a(this),a.extend({},f,g))})}function l(){return k.apply(this,Array.prototype.slice.apply(arguments,[]))}var m='<?xml version="1.0" encoding="utf-8"?><svg version="1.1"xmlns="http://www.w3.org/2000/svg"viewBox="0 12.705 512 486.59"x="0px" y="0px"xml:space="preserve"><polygon points="256.814,12.705 317.205,198.566 512.631,198.566 354.529,313.435 414.918,499.295 256.814,384.427 98.713,499.295 159.102,313.435 1,198.566 196.426,198.566 "/></svg>',n={starWidth:"32px",normalFill:"gray",ratedFill:"#f39c12",numStars:5,maxValue:5,precision:1,rating:0,fullStar:!1,halfStar:!1,readOnly:!1,spacing:"0px",rtl:!1,multiColor:null,onInit:null,onChange:null,onSet:null,starSvg:null},o={startColor:"#c0392b",endColor:"#f1c40f"},p=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i,q=function(a){if(!p.test(a))return null;var b=p.exec(a);return{r:parseInt(b[1],16),g:parseInt(b[2],16),b:parseInt(b[3],16)}};h.prototype.collection=[],window.RateYo=h,a.fn.rateYo=l}(window.jQuery);


/* ========================================
 FILE: /includes/js/shop/Forms/EmailEnquiry.js
 ==================== */

function sendEmailEnquiryNew() {
	jQuery.get(pretty_email_url, {
		open_in_vex: 1
	}, function (res) {
		var jsonRes = jsGetJSON(res);

		var newValidation = (typeof js_Config_email_to_friend_new_validation !== "undefined" && js_Config_email_to_friend_new_validation > 0) && (typeof js_Config_product_question_new_validation !== "undefined" && js_Config_product_question_new_validation > 0);

		vex.open({
			content: [
				'<div class="vex-dialog-form">',
				'<div class="vex-dialog-message">',
				'<span class="login-title">',
				jsonRes.title,
				'</span>',
				'</div>',
				'<div class="vex-dialog-input" style="padding-top: 1.5em;">',
				jsonRes.html,
				'</div>',
				'<div class="vex-dialog-buttons">',
				'<button type="submit" class="vex-dialog-button-primary vex-dialog-button vex-first">'+ jsonRes.submit_btn +'</button>',
				'<button type="button" class="vex-dialog-button-secondary vex-dialog-button vex-last">'+ jsonRes.cancel_btn +'</button>',
				'</div>',
				'</div>'
			].join(''),
			afterOpen: function(vexContent, vexInstance) {
				if (newValidation) {
					bindEmailEnquiry(vexContent);
				}

				vexContent.find('button.vex-dialog-button-primary').click(function(event) {
					if (newValidation) {
						submitEmailEnquiryMaterial(event, this, vexInstance);
					} else {
						submitEmailEnquiry(event, this, vexInstance);
					}
				});

				vexContent.find('button.vex-dialog-button-secondary').click(function() {
					vex.close();
				});

			}
		});
	});
}

function submitEmailEnquiry(event, elem, parentVex) {
	event.preventDefault();

	var submitBtn = jQuery(elem);
	var options = {};
	var valid = true;

	if (!submitBtn.is('input') || !submitBtn.is('button')) {
		if (submitBtn.find('.email_enquiry_button .primary_button').length > 0) {
			submitBtn = submitBtn.find('.email_enquiry_button .primary_button');
		}
	}

	var form = submitBtn.closest('form');

	if (typeof form === 'undefined' || form.length === 0) {
		form = submitBtn.closest('.vex-dialog-form').find('form:first');
	}
	
	if ( !submitBtn.prop('disabled') ) {
		submitBtn.attr('disabled', true);
	}

	// Validation
	if (form.find("input[type=checkbox]:checked").length === 0) {
		vex.dialog.alert(js_gdpr_agree_to_gdpr);

		valid = false;
	}

	if (form.find('input[name=youremail]').val() == "") {
		vex.dialog.alert(cms_js_lang_add_comment_your_email_error);

		valid = false;
	}

	if (form.find('input[name=yourname]').val() == "") {
		vex.dialog.alert(cms_js_lang_add_comment_your_name_error);

		valid = false;
	}

	if (form.find('textarea[name=question]').val() == "") {
		vex.dialog.alert(cms_fill_message);

		valid = false;
	}

	if (!valid)	{
		submitBtn.attr('disabled', false);

		return false;
	}

	form.find('input,textarea').each(function () {
		options[jQuery(this).attr('name')] = jQuery(this).val();
	});

	jQuery.post(form.attr('action'), options, function (res) {
		var res_splitted = res.split('||');

		vex.dialog.alert(res_splitted[1]);

		if (res_splitted[0] != '0' && typeof parentVex !== 'undefined' && typeof parentVex.id !== 'undefined') {
			vex.close(parentVex.id);
		}

		if ( submitBtn.prop('disabled') ) {
			submitBtn.attr('disabled', false);
		}

		clearForm(form);

		if (jQuery('#pp_full_res').length == 0) {
			js_reload_current_page();
		} else {
			js_prettyphoto_close();
		}	
	});
	
	return false;
}

function submitEmailEnquiryMaterial(event, elem, parentVex) {
	event.preventDefault();

	var submitBtn = jQuery(elem);
	var form = submitBtn.closest('form');

	if (typeof form === 'undefined' || form.length === 0) {
		form = submitBtn.closest('.vex-dialog-form').find('form:first');
	}

	var options = {};
	var valid_material_form = true;
	
	if ( !submitBtn.prop('disabled') ) {
		submitBtn.attr('disabled', true);
			// .after('<span class="ajaxLoaderWrap"></span>');
	}
	
	submitBtn
		.siblings('span.ajaxLoaderWrap')
		.startAjaxLoader();

	if ( (typeof js_Config_email_to_friend_new_validation !== "undefined" && js_Config_email_to_friend_new_validation > 0) && (typeof js_Config_product_question_new_validation !== "undefined" && js_Config_product_question_new_validation > 0) ) {
		if (form.find('input[name=youremail]').length > 0 && form.find('input[name=youremail]').hasClass("required")) {
			if (form.find('input[name=youremail]').val() == "" || !validateEmail(form.find('input[name=youremail]').val())) {
				form.find('input[name=youremail]').removeClass("valid").removeClass("filled").addClass("error");
				if (form.find('input[name=youremail]').parent().find('div.error_box').length == 0) {
					form.find('input[name=youremail]').after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_lm_wrong_email.replace(/\./g,' ') + '</div>');
				}
				valid_material_form = false;
			}
			if (form.find('input[name=youremail]').val() != "" && !validateEmail(form.find('input[name=youremail]').val())) {
				form.find('input[name=youremail]').addClass("filled");
			}
		}

		if (form.find('input[name=email]').length > 0 && form.find('input[name=email]').hasClass("required")) {
			if (form.find('input[name=email]').val() == "" || !validateEmail(form.find('input[name=email]').val())) {
				form.find('input[name=email]').removeClass("valid").removeClass("filled").addClass("error");
				if (form.find('input[name=email]').parent().find('div.error_box').length == 0) {
					form.find('input[name=email]').after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' "' + form.find('input[name=email]').parent().find("label").html() + '" ' + js_lang_new_form_nesessery +'</div>');
				}
				valid_material_form = false;
			}
		}

		if (form.find('input[name=yourname]').length > 0 && form.find('input[name=yourname]').hasClass("required")) {
			if (form.find('input[name=yourname]').val() == "") {
				form.find('input[name=yourname]').removeClass("valid").removeClass("filled").addClass("error");
				if (form.find('input[name=yourname]').parent().find('div.error_box').length == 0) {
					form.find('input[name=yourname]').after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' "' + form.find('input[name=yourname]').parent().find("label").html() + '" ' + js_lang_new_form_nesessery + '</div>');
				}
				valid_material_form = false;
			} else {
				form.find('input[name=yourname]').removeClass("error").addClass("valid");
			}
		}

		if (form.find('textarea[name=question]').length > 0 && form.find('textarea[name=question]').hasClass("required")) {
			if (form.find('textarea[name=question]').val() == "") {
				form.find('textarea[name=question]').removeClass("valid").removeClass("filled").addClass("error");
				if (form.find('textarea[name=question]').parent().find('div.error_box').length == 0) {
					form.find('textarea[name=question]').after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item +' "' + form.find('textarea[name=question]').parent().find("label").html() + '" ' + js_lang_new_form_nesessery + '.</div>');
				}
				valid_material_form = false;
			}
		}

		if (form.find('input[name=captcha_code]').length > 0) {
			if (form.find('input[name=captcha_code]').val() == "") {
				form.find('input[name=captcha_code]').removeClass("valid").removeClass("filled").addClass("error");
				if (form.find('input[name=captcha_code]').parent().find('label.error').length == 0) {
					form.find('input[name=captcha_code]').parent().find("label").addClass("error");
				}
				valid_material_form = false;
			}
		}

		if (form.find('input[name=agreed_personal_info_emailtofriend]').length > 0) {
			if (!form.find('input[name=agreed_personal_info_emailtofriend]').prop('checked')) {
				form.find('input[name=agreed_personal_info_emailtofriend]').removeClass("valid").removeClass("filled").addClass("error");
				if (form.find('input[name=agreed_personal_info_emailtofriend]').parent().find('div.error_box').length == 0) {
					form.find('input[name=agreed_personal_info_emailtofriend]').closest("div").append('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_nesessery_item + '</div>');
				}
				valid_material_form = false;
			}
		}

		if (form.find('input[name=agreed_personal_info_p_question]').length > 0) {
			if (!form.find('input[name=agreed_personal_info_p_question]').prop('checked')) {
				form.find('input[name=agreed_personal_info_p_question]').removeClass("valid").removeClass("filled").addClass("error");
				if (form.find('input[name=agreed_personal_info_p_question]').parent().find('div.error_box').length == 0) {
					form.find('input[name=agreed_personal_info_p_question]').closest("div").append('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_nesessery_item + '</div>');
				}
				valid_material_form = false;
			}
		}

		form.find('input,textarea').each(function () {
			options[jQuery(this).attr('name')] = jQuery(this).val();
		});

		if (valid_material_form) {
			submitBtn.attr('disabled', true);
			jQuery.post(form.attr('action') + '&referer_url=' + encodeURIComponent(window.location.href), options, function (res) {

				if ( typeof js_Config_email_send_enquiry_antispam !== 'undefined' && js_Config_email_send_enquiry_antispam == true ) {
					jQuery(this).siblings('span.ajaxLoaderWrap').stopAjaxLoader();
				}

				var res_splitted = res.split('||');

				vex.dialog.alert(res_splitted[1]);

				if (res_splitted[0] !== '0' && typeof parentVex !== 'undefined' && typeof parentVex.id !== 'undefined') {
					vex.close(parentVex.id);
				}

				submitBtn.siblings('span.ajaxLoaderWrap').stopAjaxLoader();

				if (submitBtn.prop('disabled')) {
					submitBtn.attr('disabled', false);
				}

				clearForm(form);
			});
		} else {
			submitBtn.siblings('span.ajaxLoaderWrap').stopAjaxLoader();

			if (submitBtn.prop('disabled')) {
				submitBtn.attr('disabled', false);
			}

			return valid_material_form;
		}

	}
}

function bindEmailEnquiry(form) {
	var form = jQuery(form);

	form.on('focusout', 'input, textarea', function (event) {
		var this_element = jQuery(this);

		if (this_element.parent().find(".error_box").length) {
			this_element.parent().find(".error_box, .cleaner").remove();
		}
		
		if (this_element.val() == "") {		
			if (!this_element.hasClass("error")) {
				this_element.addClass("error");
			}

			this_element.after('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_item + ' "' + this_element.parent().find("label").html() + '" ' + js_lang_new_form_nesessery + '</div>');
			
			switch (this_element.attr("name")) {
				case "captcha_code":
					// doplnit vymazanie box_error, cleaner a pridat error na label
					break;
			}
		} else {
			this_element
				.removeClass("error")
				.removeClass("valid")
				.addClass("filled");

			switch (this_element.attr("name")) {
				case "email":
				case "youremail":
					if (validateEmail(this_element.val())) {
						this_element.removeClass("error").addClass("valid");
					} else {
						this_element.removeClass("valid").addClass("error").after('<div class="cleaner"></div><div class="error_box">' + cms_js_lang_lm_wrong_email.replace(/\./g,' ') + '</div>');
					}
					break;
				case "yourname":
					this_element.addClass("valid");
					break;
			}
		}
	});
	
	form.on('change', "input[id=agreed_personal_info_field_emailtofriend]", function (event) {
		var this_element = jQuery(this);

		if (this_element.parent().find("input[type=checkbox]").is(':checked')) {
			this_element.parent().find(".error_box, .cleaner").remove();
		} else {
			this_element.parent().append('<div class="cleaner"></div><div class="error_box">' + js_lang_new_form_nesessery_item + '</div>');
		}
	});
}

function clearForm(form) {
	var form = jQuery(form);

	form.find('input,textarea').each(function () {
		jQuery(this).val('');
	});
	
	form.find('input,textarea').removeClass("error").removeClass("valid").removeClass("filled");

	form.find('input[type=checkbox]').each(function () {
		jQuery(this).removeAttr('checked');
	});

	form.find('.ajaxLoaderWrap').remove();
}

/* ========================================
 FILE: /includes/js/hybridauth.js
 ==================== */

function hybridauth_popup(event) {
	var button = jQuery(this);

	if (button.length == 0) return;

	var provider = button.data('provider');

	var width = 600;
	var height = 700;

	var top = window.innerHeight - height;
	top = top > 0 ? top / 2 : 0;

	var left = window.innerWidth - width;
	left = left > 0 ? left / 2 + window.screenX : 0;

	var url = button.data('url') + "?provider=" + provider + "&_ts=" + ( new Date() ).getTime() + "&from=" + window.location.href;

	var $overlay = jQuery('<div id="ha_overlay" style="display: none; background: #00000080; height:100%; width: 100%; position: absolute; top: 0; z-index: 999"></div>');
	jQuery('body').append($overlay);
	$overlay.fadeIn();

	var hybridAuthWin = window.open(
		url,
		"hybridauth_social_sing_on",
		"directories=no,titlebar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height + ",top=" + top + ",left=" + left
	);

	$overlay.on('click', function () {
		hybridAuthWin.close();
	});

	var loop = setInterval(function() {
		if(typeof hybridAuthWin !== 'undefined' && hybridAuthWin !== null && hybridAuthWin.closed) {
			clearInterval(loop);
			jQuery('#ha_overlay').fadeOut('300', function() {
				jQuery(this).remove();
			});
		}
	}, 100);


	window.addEventListener('message', function(event) {
		if (event.data.type === 'universalLogin') {
			window.location.href = event.data.data.redirect;
		}
	});

}

window.addEventListener('DOMContentLoaded', function() {
	jQuery('.hybridauth_button').on('click', hybridauth_popup);
});


/* ========================================
 FILE: /includes/js/dropzone/dropzone.min.js
 ==================== */

// Dropzone v4.5.0
"use strict";function _possibleConstructorReturn(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function _inherits(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function __guard__(a,b){return void 0!==a&&null!==a?b(a):void 0}function __guardMethod__(a,b,c){return void 0!==a&&null!==a&&"function"==typeof a[b]?c(a,b):void 0}var _createClass=function(){function a(a,b){for(var c=0;c<b.length;c++){var d=b[c];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(a,d.key,d)}}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}(),Emitter=function(){function a(){_classCallCheck(this,a)}return _createClass(a,[{key:"on",value:function(a,b){return this._callbacks=this._callbacks||{},this._callbacks[a]||(this._callbacks[a]=[]),this._callbacks[a].push(b),this}},{key:"emit",value:function(a){this._callbacks=this._callbacks||{};var b=this._callbacks[a];if(b){for(var c=arguments.length,d=Array(c>1?c-1:0),e=1;e<c;e++)d[e-1]=arguments[e];for(var f=b,g=0,f=f;;){var h;if(g>=f.length)break;h=f[g++];h.apply(this,d)}}return this}},{key:"off",value:function(a,b){if(!this._callbacks||0===arguments.length)return this._callbacks={},this;var c=this._callbacks[a];if(!c)return this;if(1===arguments.length)return delete this._callbacks[a],this;for(var d=0;d<c.length;d++){if(c[d]===b){c.splice(d,1);break}}return this}}]),a}(),Dropzone=function(a){function b(a,c){_classCallCheck(this,b);var d=_possibleConstructorReturn(this,(b.__proto__||Object.getPrototypeOf(b)).call(this)),e=void 0,f=void 0;if(d.element=a,d.version=b.version,d.defaultOptions.previewTemplate=d.defaultOptions.previewTemplate.replace(/\n*/g,""),d.clickableElements=[],d.listeners=[],d.files=[],"string"==typeof d.element&&(d.element=document.querySelector(d.element)),!d.element||null==d.element.nodeType)throw new Error("Invalid dropzone element.");if(d.element.dropzone)throw new Error("Dropzone already attached.");b.instances.push(d),d.element.dropzone=d;var g=null!=(f=b.optionsForElement(d.element))?f:{};if(d.options=b.extend({},d.defaultOptions,g,null!=c?c:{}),d.options.forceFallback||!b.isBrowserSupported()){var h;return h=d.options.fallback.call(d),_possibleConstructorReturn(d,h)}if(null==d.options.url&&(d.options.url=d.element.getAttribute("action")),!d.options.url)throw new Error("No URL provided.");if(d.options.acceptedFiles&&d.options.acceptedMimeTypes)throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");if(d.options.uploadMultiple&&d.options.chunking)throw new Error("You cannot set both: uploadMultiple and chunking.");return d.options.acceptedMimeTypes&&(d.options.acceptedFiles=d.options.acceptedMimeTypes,delete d.options.acceptedMimeTypes),null!=d.options.renameFilename&&(d.options.renameFile=function(a){return d.options.renameFilename.call(d,a.name,a)}),d.options.method=d.options.method.toUpperCase(),(e=d.getExistingFallback())&&e.parentNode&&e.parentNode.removeChild(e),!1!==d.options.previewsContainer&&(d.options.previewsContainer?d.previewsContainer=b.getElement(d.options.previewsContainer,"previewsContainer"):d.previewsContainer=d.element),d.options.clickable&&(!0===d.options.clickable?d.clickableElements=[d.element]:d.clickableElements=b.getElements(d.options.clickable,"clickable")),d.init(),d}return _inherits(b,a),_createClass(b,null,[{key:"initClass",value:function(){this.prototype.Emitter=Emitter,this.prototype.events=["drop","dragstart","dragend","dragenter","dragover","dragleave","addedfile","addedfiles","removedfile","thumbnail","error","errormultiple","processing","processingmultiple","uploadprogress","totaluploadprogress","sending","sendingmultiple","success","successmultiple","canceled","canceledmultiple","complete","completemultiple","reset","maxfilesexceeded","maxfilesreached","queuecomplete"],this.prototype.defaultOptions={url:null,method:"post",withCredentials:!1,timeout:3e4,parallelUploads:2,uploadMultiple:!1,chunking:!1,forceChunking:!1,chunkSize:2e6,parallelChunkUploads:!1,retryChunks:!1,retryChunksLimit:3,maxFilesize:256,paramName:"file",createImageThumbnails:!0,maxThumbnailFilesize:10,thumbnailWidth:120,thumbnailHeight:120,thumbnailMethod:"crop",resizeWidth:null,resizeHeight:null,resizeMimeType:null,resizeQuality:.8,resizeMethod:"contain",filesizeBase:1e3,maxFiles:null,headers:null,clickable:!0,ignoreHiddenFiles:!0,acceptedFiles:null,acceptedMimeTypes:null,autoProcessQueue:!0,autoQueue:!0,addRemoveLinks:!1,previewsContainer:null,hiddenInputContainer:"body",capture:null,renameFilename:null,renameFile:null,forceFallback:!1,dictDefaultMessage:"Drop files here to upload",dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",dictFallbackText:"Please use the fallback form below to upload your files like in the olden days.",dictFileTooBig:"File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",dictInvalidFileType:"You can't upload files of this type.",dictResponseError:"Server responded with {{statusCode}} code.",dictCancelUpload:"Cancel upload",dictCancelUploadConfirmation:"Are you sure you want to cancel this upload?",dictRemoveFile:"Remove file",dictRemoveFileConfirmation:null,dictMaxFilesExceeded:"You can not upload any more files.",dictFileSizeUnits:{tb:"TB",gb:"GB",mb:"MB",kb:"KB",b:"b"},init:function(){},params:function(a,b,c){if(c)return{dzuuid:c.file.upload.uuid,dzchunkindex:c.index,dztotalfilesize:c.file.size,dzchunksize:this.options.chunkSize,dztotalchunkcount:c.file.upload.totalChunkCount,dzchunkbyteoffset:c.index*this.options.chunkSize}},accept:function(a,b){return b()},chunksUploaded:function(a,b){b()},fallback:function(){var a=void 0;this.element.className=this.element.className+" dz-browser-not-supported";for(var c=this.element.getElementsByTagName("div"),d=0,c=c;;){var e;if(d>=c.length)break;e=c[d++];var f=e;if(/(^| )dz-message($| )/.test(f.className)){a=f,f.className="dz-message";break}}a||(a=b.createElement('<div class="dz-message"><span></span></div>'),this.element.appendChild(a));var g=a.getElementsByTagName("span")[0];return g&&(null!=g.textContent?g.textContent=this.options.dictFallbackMessage:null!=g.innerText&&(g.innerText=this.options.dictFallbackMessage)),this.element.appendChild(this.getFallbackForm())},resize:function(a,b,c,d){var e={srcX:0,srcY:0,srcWidth:a.width,srcHeight:a.height},f=a.width/a.height;null==b&&null==c?(b=e.srcWidth,c=e.srcHeight):null==b?b=c*f:null==c&&(c=b/f),b=Math.min(b,e.srcWidth),c=Math.min(c,e.srcHeight);var g=b/c;if(e.srcWidth>b||e.srcHeight>c)if("crop"===d)f>g?(e.srcHeight=a.height,e.srcWidth=e.srcHeight*g):(e.srcWidth=a.width,e.srcHeight=e.srcWidth/g);else{if("contain"!==d)throw new Error("Unknown resizeMethod '"+d+"'");f>g?c=b/f:b=c*f}return e.srcX=(a.width-e.srcWidth)/2,e.srcY=(a.height-e.srcHeight)/2,e.trgWidth=b,e.trgHeight=c,e},transformFile:function(a,b){return(this.options.resizeWidth||this.options.resizeHeight)&&a.type.match(/image.*/)?this.resizeImage(a,this.options.resizeWidth,this.options.resizeHeight,this.options.resizeMethod,b):b(a)},previewTemplate:'<div class="dz-preview dz-file-preview">\n  <div class="dz-image"><img data-dz-thumbnail /></div>\n  <div class="dz-details">\n    <div class="dz-size"><span data-dz-size></span></div>\n    <div class="dz-filename"><span data-dz-name></span></div>\n  </div>\n  <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>\n  <div class="dz-error-message"><span data-dz-errormessage></span></div>\n  <div class="dz-success-mark">\n    <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n      <title>Check</title>\n      <defs></defs>\n      <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n        <path d="M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" stroke-opacity="0.198794158" stroke="#747474" fill-opacity="0.816519475" fill="#FFFFFF" sketch:type="MSShapeGroup"></path>\n      </g>\n    </svg>\n  </div>\n  <div class="dz-error-mark">\n    <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">\n      <title>Error</title>\n      <defs></defs>\n      <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">\n        <g id="Check-+-Oval-2" sketch:type="MSLayerGroup" stroke="#747474" stroke-opacity="0.198794158" fill="#FFFFFF" fill-opacity="0.816519475">\n          <path d="M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" sketch:type="MSShapeGroup"></path>\n        </g>\n      </g>\n    </svg>\n  </div>\n</div>',drop:function(a){return this.element.classList.remove("dz-drag-hover")},dragstart:function(a){},dragend:function(a){return this.element.classList.remove("dz-drag-hover")},dragenter:function(a){return this.element.classList.add("dz-drag-hover")},dragover:function(a){return this.element.classList.add("dz-drag-hover")},dragleave:function(a){return this.element.classList.remove("dz-drag-hover")},paste:function(a){},reset:function(){return this.element.classList.remove("dz-started")},addedfile:function(a){var c=this;if(this.element===this.previewsContainer&&this.element.classList.add("dz-started"),this.previewsContainer){a.previewElement=b.createElement(this.options.previewTemplate.trim()),a.previewTemplate=a.previewElement,this.previewsContainer.appendChild(a.previewElement);for(var d=a.previewElement.querySelectorAll("[data-dz-name]"),e=0,d=d;;){var f;if(e>=d.length)break;f=d[e++];var g=f;g.textContent=a.name}for(var h=a.previewElement.querySelectorAll("[data-dz-size]"),i=0,h=h;!(i>=h.length);)g=h[i++],g.innerHTML=this.filesize(a.size);this.options.addRemoveLinks&&(a._removeLink=b.createElement('<a class="dz-remove" href="javascript:undefined;" data-dz-remove>'+this.options.dictRemoveFile+"</a>"),a.previewElement.appendChild(a._removeLink));for(var j=function(d){return d.preventDefault(),d.stopPropagation(),a.status===b.UPLOADING?b.confirm(c.options.dictCancelUploadConfirmation,function(){return c.removeFile(a)}):c.options.dictRemoveFileConfirmation?b.confirm(c.options.dictRemoveFileConfirmation,function(){return c.removeFile(a)}):c.removeFile(a)},k=a.previewElement.querySelectorAll("[data-dz-remove]"),l=0,k=k;;){var m;if(l>=k.length)break;m=k[l++];m.addEventListener("click",j)}}},removedfile:function(a){return null!=a.previewElement&&null!=a.previewElement.parentNode&&a.previewElement.parentNode.removeChild(a.previewElement),this._updateMaxFilesReachedClass()},thumbnail:function(a,b){if(a.previewElement){a.previewElement.classList.remove("dz-file-preview");for(var c=a.previewElement.querySelectorAll("[data-dz-thumbnail]"),d=0,c=c;;){var e;if(d>=c.length)break;e=c[d++];var f=e;f.alt=a.name,f.src=b}return setTimeout(function(){return a.previewElement.classList.add("dz-image-preview")},1)}},error:function(a,b){if(a.previewElement){a.previewElement.classList.add("dz-error"),"String"!=typeof b&&b.error&&(b=b.error);for(var c=a.previewElement.querySelectorAll("[data-dz-errormessage]"),d=0,c=c;;){var e;if(d>=c.length)break;e=c[d++];e.textContent=b}}},errormultiple:function(){},processing:function(a){if(a.previewElement&&(a.previewElement.classList.add("dz-processing"),a._removeLink))return a._removeLink.textContent=this.options.dictCancelUpload},processingmultiple:function(){},uploadprogress:function(a,b,c){if(a.previewElement)for(var d=a.previewElement.querySelectorAll("[data-dz-uploadprogress]"),e=0,d=d;;){var f;if(e>=d.length)break;f=d[e++];var g=f;"PROGRESS"===g.nodeName?g.value=b:g.style.width=b+"%"}},totaluploadprogress:function(){},sending:function(){},sendingmultiple:function(){},success:function(a){if(a.previewElement)return a.previewElement.classList.add("dz-success")},successmultiple:function(){},canceled:function(a){return this.emit("error",a,"Upload canceled.")},canceledmultiple:function(){},complete:function(a){if(a._removeLink&&(a._removeLink.textContent=this.options.dictRemoveFile),a.previewElement)return a.previewElement.classList.add("dz-complete")},completemultiple:function(){},maxfilesexceeded:function(){},maxfilesreached:function(){},queuecomplete:function(){},addedfiles:function(){}},this.prototype._thumbnailQueue=[],this.prototype._processingThumbnail=!1}},{key:"extend",value:function(a){for(var b=arguments.length,c=Array(b>1?b-1:0),d=1;d<b;d++)c[d-1]=arguments[d];for(var e=c,f=0,e=e;;){var g;if(f>=e.length)break;g=e[f++];var h=g;for(var i in h){var j=h[i];a[i]=j}}return a}}]),_createClass(b,[{key:"getAcceptedFiles",value:function(){return this.files.filter(function(a){return a.accepted}).map(function(a){return a})}},{key:"getRejectedFiles",value:function(){return this.files.filter(function(a){return!a.accepted}).map(function(a){return a})}},{key:"getFilesWithStatus",value:function(a){return this.files.filter(function(b){return b.status===a}).map(function(a){return a})}},{key:"getQueuedFiles",value:function(){return this.getFilesWithStatus(b.QUEUED)}},{key:"getUploadingFiles",value:function(){return this.getFilesWithStatus(b.UPLOADING)}},{key:"getAddedFiles",value:function(){return this.getFilesWithStatus(b.ADDED)}},{key:"getActiveFiles",value:function(){return this.files.filter(function(a){return a.status===b.UPLOADING||a.status===b.QUEUED}).map(function(a){return a})}},{key:"init",value:function(){var a=this;if("form"===this.element.tagName&&this.element.setAttribute("enctype","multipart/form-data"),this.element.classList.contains("dropzone")&&!this.element.querySelector(".dz-message")&&this.element.appendChild(b.createElement('<div class="dz-default dz-message"><span>'+this.options.dictDefaultMessage+"</span></div>")),this.clickableElements.length){!function b(){return a.hiddenFileInput&&a.hiddenFileInput.parentNode.removeChild(a.hiddenFileInput),a.hiddenFileInput=document.createElement("input"),a.hiddenFileInput.setAttribute("type","file"),(null===a.options.maxFiles||a.options.maxFiles>1)&&a.hiddenFileInput.setAttribute("multiple","multiple"),a.hiddenFileInput.className="dz-hidden-input",null!==a.options.acceptedFiles&&a.hiddenFileInput.setAttribute("accept",a.options.acceptedFiles),null!==a.options.capture&&a.hiddenFileInput.setAttribute("capture",a.options.capture),a.hiddenFileInput.style.visibility="hidden",a.hiddenFileInput.style.position="absolute",a.hiddenFileInput.style.top="0",a.hiddenFileInput.style.left="0",a.hiddenFileInput.style.height="0",a.hiddenFileInput.style.width="0",document.querySelector(a.options.hiddenInputContainer).appendChild(a.hiddenFileInput),a.hiddenFileInput.addEventListener("change",function(){var c=a.hiddenFileInput.files;if(c.length)for(var d=c,e=0,d=d;;){var f;if(e>=d.length)break;f=d[e++];var g=f;a.addFile(g)}return a.emit("addedfiles",c),b()})}()}this.URL=null!==window.URL?window.URL:window.webkitURL;for(var c=this.events,d=0,c=c;;){var e;if(d>=c.length)break;e=c[d++];var f=e;this.on(f,this.options[f])}this.on("uploadprogress",function(){return a.updateTotalUploadProgress()}),this.on("removedfile",function(){return a.updateTotalUploadProgress()}),this.on("canceled",function(b){return a.emit("complete",b)}),this.on("complete",function(b){if(0===a.getAddedFiles().length&&0===a.getUploadingFiles().length&&0===a.getQueuedFiles().length)return setTimeout(function(){return a.emit("queuecomplete")},0)});var g=function(a){return a.stopPropagation(),a.preventDefault?a.preventDefault():a.returnValue=!1};return this.listeners=[{element:this.element,events:{dragstart:function(b){return a.emit("dragstart",b)},dragenter:function(b){return g(b),a.emit("dragenter",b)},dragover:function(b){var c=void 0;try{c=b.dataTransfer.effectAllowed}catch(a){}return b.dataTransfer.dropEffect="move"===c||"linkMove"===c?"move":"copy",g(b),a.emit("dragover",b)},dragleave:function(b){return a.emit("dragleave",b)},drop:function(b){return g(b),a.drop(b)},dragend:function(b){return a.emit("dragend",b)}}}],this.clickableElements.forEach(function(c){return a.listeners.push({element:c,events:{click:function(d){return(c!==a.element||d.target===a.element||b.elementInside(d.target,a.element.querySelector(".dz-message")))&&a.hiddenFileInput.click(),!0}}})}),this.enable(),this.options.init.call(this)}},{key:"destroy",value:function(){return this.disable(),this.removeAllFiles(!0),(null!=this.hiddenFileInput?this.hiddenFileInput.parentNode:void 0)&&(this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput),this.hiddenFileInput=null),delete this.element.dropzone,b.instances.splice(b.instances.indexOf(this),1)}},{key:"updateTotalUploadProgress",value:function(){var a=void 0,b=0,c=0;if(this.getActiveFiles().length){for(var d=this.getActiveFiles(),e=0,d=d;;){var f;if(e>=d.length)break;f=d[e++];var g=f;b+=g.upload.bytesSent,c+=g.upload.total}a=100*b/c}else a=100;return this.emit("totaluploadprogress",a,c,b)}},{key:"_getParamName",value:function(a){return"function"==typeof this.options.paramName?this.options.paramName(a):this.options.paramName+(this.options.uploadMultiple?"["+a+"]":"")}},{key:"_renameFile",value:function(a){return"function"!=typeof this.options.renameFile?a.name:this.options.renameFile(a)}},{key:"getFallbackForm",value:function(){var a=void 0,c=void 0;if(a=this.getExistingFallback())return a;var d='<div class="dz-fallback">';this.options.dictFallbackText&&(d+="<p>"+this.options.dictFallbackText+"</p>"),d+='<input type="file" name="'+this._getParamName(0)+'" '+(this.options.uploadMultiple?'multiple="multiple"':void 0)+' /><input type="submit" value="Upload!"></div>';var e=b.createElement(d);return"FORM"!==this.element.tagName?(c=b.createElement('<form action="'+this.options.url+'" enctype="multipart/form-data" method="'+this.options.method+'"></form>'),c.appendChild(e)):(this.element.setAttribute("enctype","multipart/form-data"),this.element.setAttribute("method",this.options.method)),null!=c?c:e}},{key:"getExistingFallback",value:function(){for(var a=["div","form"],b=0;b<a.length;b++){var c,d=a[b];if(c=function(a){for(var b=a,c=0,b=b;;){var d;if(c>=b.length)break;d=b[c++];var e=d;if(/(^| )fallback($| )/.test(e.className))return e}}(this.element.getElementsByTagName(d)))return c}}},{key:"setupEventListeners",value:function(){return this.listeners.map(function(a){return function(){var b=[];for(var c in a.events){var d=a.events[c];b.push(a.element.addEventListener(c,d,!1))}return b}()})}},{key:"removeEventListeners",value:function(){return this.listeners.map(function(a){return function(){var b=[];for(var c in a.events){var d=a.events[c];b.push(a.element.removeEventListener(c,d,!1))}return b}()})}},{key:"disable",value:function(){var a=this;return this.clickableElements.forEach(function(a){return a.classList.remove("dz-clickable")}),this.removeEventListeners(),this.files.map(function(b){return a.cancelUpload(b)})}},{key:"enable",value:function(){return this.clickableElements.forEach(function(a){return a.classList.add("dz-clickable")}),this.setupEventListeners()}},{key:"filesize",value:function(a){var b=0,c="b";if(a>0){for(var d=["tb","gb","mb","kb","b"],e=0;e<d.length;e++){var f=d[e];if(a>=Math.pow(this.options.filesizeBase,4-e)/10){b=a/Math.pow(this.options.filesizeBase,4-e),c=f;break}}b=Math.round(10*b)/10}return"<strong>"+b+"</strong> "+this.options.dictFileSizeUnits[c]}},{key:"_updateMaxFilesReachedClass",value:function(){return null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(this.getAcceptedFiles().length===this.options.maxFiles&&this.emit("maxfilesreached",this.files),this.element.classList.add("dz-max-files-reached")):this.element.classList.remove("dz-max-files-reached")}},{key:"drop",value:function(a){if(a.dataTransfer){this.emit("drop",a);var b=a.dataTransfer.files;if(this.emit("addedfiles",b),b.length){var c=a.dataTransfer.items;c&&c.length&&null!=c[0].webkitGetAsEntry?this._addFilesFromItems(c):this.handleFiles(b)}}}},{key:"paste",value:function(a){if(null!=__guard__(null!=a?a.clipboardData:void 0,function(a){return a.items})){this.emit("paste",a);var b=a.clipboardData.items;return b.length?this._addFilesFromItems(b):void 0}}},{key:"handleFiles",value:function(a){var b=this;return a.map(function(a){return b.addFile(a)})}},{key:"_addFilesFromItems",value:function(a){var b=this;return function(){for(var c=[],d=a,e=0,d=d;;){var f;if(e>=d.length)break;f=d[e++];var g,h=f;null!=h.webkitGetAsEntry&&(g=h.webkitGetAsEntry())?g.isFile?c.push(b.addFile(h.getAsFile())):g.isDirectory?c.push(b._addFilesFromDirectory(g,g.name)):c.push(void 0):null!=h.getAsFile&&(null==h.kind||"file"===h.kind)?c.push(b.addFile(h.getAsFile())):c.push(void 0)}return c}()}},{key:"_addFilesFromDirectory",value:function(a,b){var c=this,d=a.createReader(),e=function(a){return __guardMethod__(console,"log",function(b){return b.log(a)})};return function a(){return d.readEntries(function(d){if(d.length>0){for(var e=d,f=0,e=e;;){var g;if(f>=e.length)break;g=e[f++];var h=g;h.isFile?h.file(function(a){if(!c.options.ignoreHiddenFiles||"."!==a.name.substring(0,1))return a.fullPath=b+"/"+a.name,c.addFile(a)}):h.isDirectory&&c._addFilesFromDirectory(h,b+"/"+h.name)}a()}return null},e)}()}},{key:"accept",value:function(a,c){return a.size>1024*this.options.maxFilesize*1024?c(this.options.dictFileTooBig.replace("{{filesize}}",Math.round(a.size/1024/10.24)/100).replace("{{maxFilesize}}",this.options.maxFilesize)):b.isValidFile(a,this.options.acceptedFiles)?null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(c(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}",this.options.maxFiles)),this.emit("maxfilesexceeded",a)):this.options.accept.call(this,a,c):c(this.options.dictInvalidFileType)}},{key:"addFile",value:function(a){var c=this;return a.upload={uuid:b.uuidv4(),progress:0,total:a.size,bytesSent:0,filename:this._renameFile(a),chunked:this.options.chunking&&(this.options.forceChunking||a.size>this.options.chunkSize),totalChunkCount:Math.ceil(a.size/this.options.chunkSize)},this.files.push(a),a.status=b.ADDED,this.emit("addedfile",a),this._enqueueThumbnail(a),this.accept(a,function(b){return b?(a.accepted=!1,c._errorProcessing([a],b)):(a.accepted=!0,c.options.autoQueue&&c.enqueueFile(a)),c._updateMaxFilesReachedClass()})}},{key:"enqueueFiles",value:function(a){for(var b=a,c=0,b=b;;){var d;if(c>=b.length)break;d=b[c++];var e=d;this.enqueueFile(e)}return null}},{key:"enqueueFile",value:function(a){var c=this;if(a.status!==b.ADDED||!0!==a.accepted)throw new Error("This file can't be queued because it has already been processed or was rejected.");if(a.status=b.QUEUED,this.options.autoProcessQueue)return setTimeout(function(){return c.processQueue()},0)}},{key:"_enqueueThumbnail",value:function(a){var b=this;if(this.options.createImageThumbnails&&a.type.match(/image.*/)&&a.size<=1024*this.options.maxThumbnailFilesize*1024)return this._thumbnailQueue.push(a),setTimeout(function(){return b._processThumbnailQueue()},0)}},{key:"_processThumbnailQueue",value:function(){var a=this;if(!this._processingThumbnail&&0!==this._thumbnailQueue.length){this._processingThumbnail=!0;var b=this._thumbnailQueue.shift();return this.createThumbnail(b,this.options.thumbnailWidth,this.options.thumbnailHeight,this.options.thumbnailMethod,!0,function(c){return a.emit("thumbnail",b,c),a._processingThumbnail=!1,a._processThumbnailQueue()})}}},{key:"removeFile",value:function(a){if(a.status===b.UPLOADING&&this.cancelUpload(a),this.files=without(this.files,a),this.emit("removedfile",a),0===this.files.length)return this.emit("reset")}},{key:"removeAllFiles",value:function(a){null==a&&(a=!1);for(var c=this.files.slice(),d=0,c=c;;){var e;if(d>=c.length)break;e=c[d++];var f=e;(f.status!==b.UPLOADING||a)&&this.removeFile(f)}return null}},{key:"resizeImage",value:function(a,c,d,e,f){var g=this;return this.createThumbnail(a,c,d,e,!1,function(c,d){if(null===d)return f(a);var e=g.options.resizeMimeType;null==e&&(e=a.type);var h=d.toDataURL(e,g.options.resizeQuality);return"image/jpeg"!==e&&"image/jpg"!==e||(h=ExifRestore.restore(a.dataURL,h)),f(b.dataURItoBlob(h))})}},{key:"createThumbnail",value:function(a,b,c,d,e,f){var g=this,h=new FileReader;return h.onload=function(){return a.dataURL=h.result,"image/svg+xml"===a.type?void(null!=f&&f(h.result)):g.createThumbnailFromUrl(a,b,c,d,e,f)},h.readAsDataURL(a)}},{key:"createThumbnailFromUrl",value:function(a,b,c,d,e,f,g){var h=this,i=document.createElement("img");return g&&(i.crossOrigin=g),i.onload=function(){var g=function(a){return a(1)};return"undefined"!=typeof EXIF&&null!==EXIF&&e&&(g=function(a){return EXIF.getData(i,function(){return a(EXIF.getTag(this,"Orientation"))})}),g(function(e){a.width=i.width,a.height=i.height;var g=h.options.resize.call(h,a,b,c,d),j=document.createElement("canvas"),k=j.getContext("2d");switch(j.width=g.trgWidth,j.height=g.trgHeight,e>4&&(j.width=g.trgHeight,j.height=g.trgWidth),e){case 2:k.translate(j.width,0),k.scale(-1,1);break;case 3:k.translate(j.width,j.height),k.rotate(Math.PI);break;case 4:k.translate(0,j.height),k.scale(1,-1);break;case 5:k.rotate(.5*Math.PI),k.scale(1,-1);break;case 6:k.rotate(.5*Math.PI),k.translate(0,-j.height);break;case 7:k.rotate(.5*Math.PI),k.translate(j.width,-j.height),k.scale(-1,1);break;case 8:k.rotate(-.5*Math.PI),k.translate(-j.width,0)}drawImageIOSFix(k,i,null!=g.srcX?g.srcX:0,null!=g.srcY?g.srcY:0,g.srcWidth,g.srcHeight,null!=g.trgX?g.trgX:0,null!=g.trgY?g.trgY:0,g.trgWidth,g.trgHeight);var l=j.toDataURL("image/png");if(null!=f)return f(l,j)})},null!=f&&(i.onerror=f),i.src=a.dataURL}},{key:"processQueue",value:function(){var a=this.options.parallelUploads,b=this.getUploadingFiles().length,c=b;if(!(b>=a)){var d=this.getQueuedFiles();if(d.length>0){if(this.options.uploadMultiple)return this.processFiles(d.slice(0,a-b));for(;c<a;){if(!d.length)return;this.processFile(d.shift()),c++}}}}},{key:"processFile",value:function(a){return this.processFiles([a])}},{key:"processFiles",value:function(a){for(var c=a,d=0,c=c;;){var e;if(d>=c.length)break;e=c[d++];var f=e;f.processing=!0,f.status=b.UPLOADING,this.emit("processing",f)}return this.options.uploadMultiple&&this.emit("processingmultiple",a),this.uploadFiles(a)}},{key:"_getFilesWithXhr",value:function(a){return this.files.filter(function(b){return b.xhr===a}).map(function(a){return a})}},{key:"cancelUpload",value:function(a){if(a.status===b.UPLOADING){for(var c=this._getFilesWithXhr(a.xhr),d=c,e=0,d=d;;){var f;if(e>=d.length)break;f=d[e++];f.status=b.CANCELED}void 0!==a.xhr&&a.xhr.abort();for(var g=c,h=0,g=g;;){var i;if(h>=g.length)break;i=g[h++];var j=i;this.emit("canceled",j)}this.options.uploadMultiple&&this.emit("canceledmultiple",c)}else a.status!==b.ADDED&&a.status!==b.QUEUED||(a.status=b.CANCELED,this.emit("canceled",a),this.options.uploadMultiple&&this.emit("canceledmultiple",[a]));if(this.options.autoProcessQueue)return this.processQueue()}},{key:"resolveOption",value:function(a){if("function"==typeof a){for(var b=arguments.length,c=Array(b>1?b-1:0),d=1;d<b;d++)c[d-1]=arguments[d];return a.apply(this,c)}return a}},{key:"uploadFile",value:function(a){return this.uploadFiles([a])}},{key:"uploadFiles",value:function(a){var c=this;this._transformFiles(a,function(d){if(a[0].upload.chunked){var e=a[0],f=d[0],g=0;e.upload.chunks=[];var h=function(){for(var d=0;void 0!==e.upload.chunks[d];)d++;if(!(d>=e.upload.totalChunkCount)){g++;var h=d*c.options.chunkSize,i=Math.min(h+c.options.chunkSize,e.size),j={name:c._getParamName(0),data:f.webkitSlice?f.webkitSlice(h,i):f.slice(h,i),filename:e.upload.filename,chunkIndex:d};e.upload.chunks[d]={file:e,index:d,dataBlock:j,status:b.UPLOADING,progress:0,retries:0},c._uploadData(a,[j])}};if(e.upload.finishedChunkUpload=function(d){var f=!0;d.status=b.SUCCESS,d.dataBlock=null;for(var g=0;g<e.upload.totalChunkCount;g++){if(void 0===e.upload.chunks[g])return h();e.upload.chunks[g].status!==b.SUCCESS&&(f=!1)}f&&c.options.chunksUploaded(e,function(){c._finished(a,"",null)})},c.options.parallelChunkUploads)for(var i=0;i<e.upload.totalChunkCount;i++)h();else h()}else{for(var j=[],k=0;k<a.length;k++)j[k]={name:c._getParamName(k),data:d[k],filename:a[k].upload.filename};c._uploadData(a,j)}})}},{key:"_getChunk",value:function(a,b){for(var c=0;c<a.upload.totalChunkCount;c++)if(void 0!==a.upload.chunks[c]&&a.upload.chunks[c].xhr===b)return a.upload.chunks[c]}},{key:"_uploadData",value:function(a,c){for(var d=this,e=new XMLHttpRequest,f=a,g=0,f=f;;){var h;if(g>=f.length)break;h=f[g++];h.xhr=e}a[0].upload.chunked&&(a[0].upload.chunks[c[0].chunkIndex].xhr=e);var i=this.resolveOption(this.options.method,a),j=this.resolveOption(this.options.url,a);e.open(i,j,!0),e.timeout=this.resolveOption(this.options.timeout,a),e.withCredentials=!!this.options.withCredentials,e.onload=function(b){d._finishedUploading(a,e,b)},e.onerror=function(){d._handleUploadError(a,e)},(null!=e.upload?e.upload:e).onprogress=function(b){return d._updateFilesUploadProgress(a,e,b)};var k={Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"};this.options.headers&&b.extend(k,this.options.headers);for(var l in k){var m=k[l];m&&e.setRequestHeader(l,m)}var n=new FormData;if(this.options.params){var o=this.options.params;"function"==typeof o&&(o=o.call(this,a,e,a[0].upload.chunked?this._getChunk(a[0],e):null));for(var p in o){var q=o[p];n.append(p,q)}}for(var r=a,s=0,r=r;;){var t;if(s>=r.length)break;t=r[s++];var u=t;this.emit("sending",u,e,n)}this.options.uploadMultiple&&this.emit("sendingmultiple",a,e,n),this._addFormElementData(n);for(var v=0;v<c.length;v++){var w=c[v];n.append(w.name,w.data,w.filename)}this.submitRequest(e,n,a)}},{key:"_transformFiles",value:function(a,b){for(var c=this,d=[],e=0,f=0;f<a.length;f++)!function(f){c.options.transformFile.call(c,a[f],function(c){d[f]=c,++e===a.length&&b(d)})}(f)}},{key:"_addFormElementData",value:function(a){if("FORM"===this.element.tagName)for(var b=this.element.querySelectorAll("input, textarea, select, button"),c=0,b=b;;){var d
;if(c>=b.length)break;d=b[c++];var e=d,f=e.getAttribute("name"),g=e.getAttribute("type");if(g&&(g=g.toLowerCase()),void 0!==f&&null!==f)if("SELECT"===e.tagName&&e.hasAttribute("multiple"))for(var h=e.options,i=0,h=h;;){var j;if(i>=h.length)break;j=h[i++];var k=j;k.selected&&a.append(f,k.value)}else(!g||"checkbox"!==g&&"radio"!==g||e.checked)&&a.append(f,e.value)}}},{key:"_updateFilesUploadProgress",value:function(a,b,c){var d=void 0;if(void 0!==c){if(d=100*c.loaded/c.total,a[0].upload.chunked){var e=a[0],f=this._getChunk(e,b);f.progress=d,f.total=c.total,f.bytesSent=c.loaded;e.upload.progress=0,e.upload.total=0,e.upload.bytesSent=0;for(var g=0;g<e.upload.totalChunkCount;g++)void 0!==e.upload.chunks[g]&&void 0!==e.upload.chunks[g].progress&&(e.upload.progress+=e.upload.chunks[g].progress,e.upload.total+=e.upload.chunks[g].total,e.upload.bytesSent+=e.upload.chunks[g].bytesSent);e.upload.progress=e.upload.progress/e.upload.totalChunkCount}else for(var h=a,i=0,h=h;;){var j;if(i>=h.length)break;j=h[i++];var k=j;k.upload.progress=d,k.upload.total=c.total,k.upload.bytesSent=c.loaded}for(var l=a,m=0,l=l;;){var n;if(m>=l.length)break;n=l[m++];var o=n;this.emit("uploadprogress",o,o.upload.progress,o.upload.bytesSent)}}else{var p=!0;d=100;for(var q=a,r=0,q=q;;){var s;if(r>=q.length)break;s=q[r++];var t=s;100===t.upload.progress&&t.upload.bytesSent===t.upload.total||(p=!1),t.upload.progress=d,t.upload.bytesSent=t.upload.total}if(p)return;for(var u=a,v=0,u=u;;){var w;if(v>=u.length)break;w=u[v++];var x=w;this.emit("uploadprogress",x,d,x.upload.bytesSent)}}}},{key:"_finishedUploading",value:function(a,c,d){var e=void 0;if(a[0].status!==b.CANCELED&&4===c.readyState){if("arraybuffer"!==c.responseType&&"blob"!==c.responseType&&(e=c.responseText,c.getResponseHeader("content-type")&&~c.getResponseHeader("content-type").indexOf("application/json")))try{e=JSON.parse(e)}catch(a){d=a,e="Invalid JSON response from server."}this._updateFilesUploadProgress(a),200<=c.status&&c.status<300?a[0].upload.chunked?a[0].upload.finishedChunkUpload(this._getChunk(a[0],c)):this._finished(a,e,d):this._handleUploadError(a,c,e)}}},{key:"_handleUploadError",value:function(a,c,d){if(a[0].status!==b.CANCELED){if(a[0].upload.chunked&&this.options.retryChunks){var e=this._getChunk(a[0],c);if(e.retries++<this.options.retryChunksLimit)return void this._uploadData(a,[e.dataBlock]);console.warn("Retried this chunk too often. Giving up.")}for(var f=a,g=0,f=f;;){if(g>=f.length)break;f[g++];this._errorProcessing(a,d||this.options.dictResponseError.replace("{{statusCode}}",c.status),c)}}}},{key:"submitRequest",value:function(a,b,c){a.send(b)}},{key:"_finished",value:function(a,c,d){for(var e=a,f=0,e=e;;){var g;if(f>=e.length)break;g=e[f++];var h=g;h.status=b.SUCCESS,this.emit("success",h,c,d),this.emit("complete",h)}if(this.options.uploadMultiple&&(this.emit("successmultiple",a,c,d),this.emit("completemultiple",a)),this.options.autoProcessQueue)return this.processQueue()}},{key:"_errorProcessing",value:function(a,c,d){for(var e=a,f=0,e=e;;){var g;if(f>=e.length)break;g=e[f++];var h=g;h.status=b.ERROR,this.emit("error",h,c,d),this.emit("complete",h)}if(this.options.uploadMultiple&&(this.emit("errormultiple",a,c,d),this.emit("completemultiple",a)),this.options.autoProcessQueue)return this.processQueue()}}],[{key:"uuidv4",value:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(a){var b=16*Math.random()|0;return("x"===a?b:3&b|8).toString(16)})}}]),b}(Emitter);Dropzone.initClass(),Dropzone.version="5.2.0",Dropzone.options={},Dropzone.optionsForElement=function(a){return a.getAttribute("id")?Dropzone.options[camelize(a.getAttribute("id"))]:void 0},Dropzone.instances=[],Dropzone.forElement=function(a){if("string"==typeof a&&(a=document.querySelector(a)),null==(null!=a?a.dropzone:void 0))throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");return a.dropzone},Dropzone.autoDiscover=!0,Dropzone.discover=function(){var a=void 0;if(document.querySelectorAll)a=document.querySelectorAll(".dropzone");else{a=[];var b=function(b){return function(){for(var c=[],d=b,e=0,d=d;;){var f;if(e>=d.length)break;f=d[e++];var g=f;/(^| )dropzone($| )/.test(g.className)?c.push(a.push(g)):c.push(void 0)}return c}()};b(document.getElementsByTagName("div")),b(document.getElementsByTagName("form"))}return function(){for(var b=[],c=a,d=0,c=c;;){var e;if(d>=c.length)break;e=c[d++];var f=e;!1!==Dropzone.optionsForElement(f)?b.push(new Dropzone(f)):b.push(void 0)}return b}()},Dropzone.blacklistedBrowsers=[/opera.*(Macintosh|Windows Phone).*version\/12/i],Dropzone.isBrowserSupported=function(){var a=!0;if(window.File&&window.FileReader&&window.FileList&&window.Blob&&window.FormData&&document.querySelector)if("classList"in document.createElement("a"))for(var b=Dropzone.blacklistedBrowsers,c=0,b=b;;){var d;if(c>=b.length)break;d=b[c++];var e=d;e.test(navigator.userAgent)&&(a=!1)}else a=!1;else a=!1;return a},Dropzone.dataURItoBlob=function(a){for(var b=atob(a.split(",")[1]),c=a.split(",")[0].split(":")[1].split(";")[0],d=new ArrayBuffer(b.length),e=new Uint8Array(d),f=0,g=b.length,h=0<=g;h?f<=g:f>=g;h?f++:f--)e[f]=b.charCodeAt(f);return new Blob([d],{type:c})};var without=function(a,b){return a.filter(function(a){return a!==b}).map(function(a){return a})},camelize=function(a){return a.replace(/[\-_](\w)/g,function(a){return a.charAt(1).toUpperCase()})};Dropzone.createElement=function(a){var b=document.createElement("div");return b.innerHTML=a,b.childNodes[0]},Dropzone.elementInside=function(a,b){if(a===b)return!0;for(;a=a.parentNode;)if(a===b)return!0;return!1},Dropzone.getElement=function(a,b){var c=void 0;if("string"==typeof a?c=document.querySelector(a):null!=a.nodeType&&(c=a),null==c)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector or a plain HTML element.");return c},Dropzone.getElements=function(a,b){var c=void 0,d=void 0;if(a instanceof Array){d=[];try{for(var e=a,f=0,e=e;!(f>=e.length);)c=e[f++],d.push(this.getElement(c,b))}catch(a){d=null}}else if("string"==typeof a){d=[];for(var g=document.querySelectorAll(a),h=0,g=g;!(h>=g.length);)c=g[h++],d.push(c)}else null!=a.nodeType&&(d=[a]);if(null==d||!d.length)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");return d},Dropzone.confirm=function(a,b,c){return window.confirm(a)?b():null!=c?c():void 0},Dropzone.isValidFile=function(a,b){if(!b)return!0;b=b.split(",");for(var c=a.type,d=c.replace(/\/.*$/,""),e=b,f=0,e=e;;){var g;if(f>=e.length)break;g=e[f++];var h=g;if(h=h.trim(),"."===h.charAt(0)){if(-1!==a.name.toLowerCase().indexOf(h.toLowerCase(),a.name.length-h.length))return!0}else if(/\/\*$/.test(h)){if(d===h.replace(/\/.*$/,""))return!0}else if(c===h)return!0}return!1},"undefined"!=typeof jQuery&&null!==jQuery&&(jQuery.fn.dropzone=function(a){return this.each(function(){return new Dropzone(this,a)})}),"undefined"!=typeof module&&null!==module?module.exports=Dropzone:window.Dropzone=Dropzone,Dropzone.ADDED="added",Dropzone.QUEUED="queued",Dropzone.ACCEPTED=Dropzone.QUEUED,Dropzone.UPLOADING="uploading",Dropzone.PROCESSING=Dropzone.UPLOADING,Dropzone.CANCELED="canceled",Dropzone.ERROR="error",Dropzone.SUCCESS="success";var detectVerticalSquash=function(a){var b=(a.naturalWidth,a.naturalHeight),c=document.createElement("canvas");c.width=1,c.height=b;var d=c.getContext("2d");d.drawImage(a,0,0);for(var e=d.getImageData(1,0,1,b),f=e.data,g=0,h=b,i=b;i>g;){0===f[4*(i-1)+3]?h=i:g=i,i=h+g>>1}var j=i/b;return 0===j?1:j},drawImageIOSFix=function(a,b,c,d,e,f,g,h,i,j){var k=detectVerticalSquash(b);return a.drawImage(b,c,d,e,f,g,h,i,j/k)},ExifRestore=function(){function a(){_classCallCheck(this,a)}return _createClass(a,null,[{key:"initClass",value:function(){this.KEY_STR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}},{key:"encode64",value:function(a){for(var b="",c=void 0,d=void 0,e="",f=void 0,g=void 0,h=void 0,i="",j=0;;)if(c=a[j++],d=a[j++],e=a[j++],f=c>>2,g=(3&c)<<4|d>>4,h=(15&d)<<2|e>>6,i=63&e,isNaN(d)?h=i=64:isNaN(e)&&(i=64),b=b+this.KEY_STR.charAt(f)+this.KEY_STR.charAt(g)+this.KEY_STR.charAt(h)+this.KEY_STR.charAt(i),c=d=e="",f=g=h=i="",!(j<a.length))break;return b}},{key:"restore",value:function(a,b){if(!a.match("data:image/jpeg;base64,"))return b;var c=this.decode64(a.replace("data:image/jpeg;base64,","")),d=this.slice2Segments(c),e=this.exifManipulation(b,d);return"data:image/jpeg;base64,"+this.encode64(e)}},{key:"exifManipulation",value:function(a,b){var c=this.getExifArray(b),d=this.insertExif(a,c);return new Uint8Array(d)}},{key:"getExifArray",value:function(a){for(var b=void 0,c=0;c<a.length;){if(b=a[c],255===b[0]&225===b[1])return b;c++}return[]}},{key:"insertExif",value:function(a,b){var c=a.replace("data:image/jpeg;base64,",""),d=this.decode64(c),e=d.indexOf(255,3),f=d.slice(0,e),g=d.slice(e),h=f;return h=h.concat(b),h=h.concat(g)}},{key:"slice2Segments",value:function(a){for(var b=0,c=[];;){var d;if(255===a[b]&218===a[b+1])break;if(255===a[b]&216===a[b+1])b+=2;else{d=256*a[b+2]+a[b+3];var e=b+d+2,f=a.slice(b,e);c.push(f),b=e}if(b>a.length)break}return c}},{key:"decode64",value:function(a){var b=void 0,c=void 0,d="",e=void 0,f=void 0,g=void 0,h="",i=0,j=[],k=/[^A-Za-z0-9\+\/\=]/g;for(k.exec(a)&&console.warn("There were invalid base64 characters in the input text.\nValid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\nExpect errors in decoding."),a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");;)if(e=this.KEY_STR.indexOf(a.charAt(i++)),f=this.KEY_STR.indexOf(a.charAt(i++)),g=this.KEY_STR.indexOf(a.charAt(i++)),h=this.KEY_STR.indexOf(a.charAt(i++)),b=e<<2|f>>4,c=(15&f)<<4|g>>2,d=(3&g)<<6|h,j.push(b),64!==g&&j.push(c),64!==h&&j.push(d),b=c=d="",e=f=g=h="",!(i<a.length))break;return j}}]),a}();ExifRestore.initClass();var contentLoaded=function(a,b){var c=!1,d=!0,e=a.document,f=e.documentElement,g=e.addEventListener?"addEventListener":"attachEvent",h=e.addEventListener?"removeEventListener":"detachEvent",i=e.addEventListener?"":"on",j=function d(f){if("readystatechange"!==f.type||"complete"===e.readyState)return("load"===f.type?a:e)[h](i+f.type,d,!1),!c&&(c=!0)?b.call(a,f.type||f):void 0};if("complete"!==e.readyState){if(e.createEventObject&&f.doScroll){try{d=!a.frameElement}catch(a){}d&&function a(){try{f.doScroll("left")}catch(b){return void setTimeout(a,50)}return j("poll")}()}return e[g](i+"DOMContentLoaded",j,!1),e[g](i+"readystatechange",j,!1),a[g](i+"load",j,!1)}};Dropzone._autoDiscoverFunction=function(){if(Dropzone.autoDiscover)return Dropzone.discover()},contentLoaded(window,Dropzone._autoDiscoverFunction);

/* ========================================
 FILE: /includes/js/shop/CsRating.js
 ==================== */

// V tejto premennej su ulozene instancie CsRating
// Preco som pouzil WeakMap?
// Lebo WeakMap dovoluje pouzit ako kluc hocijaku hodnotu, vratane HTMLElement ako v tomto pripade
// a zaroven tym, ze je to WeakMap a nie Map/Object, tak nedochadza k memory leakom

var setRatingElements = new WeakMap();

var CsRating = (function(_setRatingElements) {
	/**
	 * author TL
	 *
	 * @param elem {HTMLElement}
	 * @constructor
	 */
	function CsRating(elem) {
		this.$elem = jQuery(elem);
		this.$wrapper = this.$elem.closest('.cs_rating_wrapper');
		this._bindEvents();

		_setRatingElements.set(elem, this);
	}

	/**
	 * Static function that returns an existing CsRating instance for the passed element
	 * If there is no instance tied to the element, it returns undefined
	 *
	 * The CsRating instance is tied to the element through WeakMap _setRatingElements
	 *
	 * @param elem {HTMLElement}
	 * @returns {CsRating|undefined}
	 */
	CsRating.get = function(elem) {
		return _setRatingElements.get(elem);
	};

	/**
	 * Unbinds events and destroys the current instance
	 *
	 * Necessary after we save an edited comment
	 *
	 * @returns {void}
	 */
	CsRating.prototype.destroy = function() {
		this.$wrapper.removeClass('set_rating');
		this._unbindEvents();

		if (_setRatingElements.has(this.$elem[0])) {
			_setRatingElements.delete(this.$elem[0]);
		}
	};

	/**
	 * Binds events
	 *
	 * @returns {void}
	 * @private
	 */
	CsRating.prototype._bindEvents = function() {
		this.$elem
			.on('mousemove', (function(event) {
				var val = this._getVal(event);
				var spaceKoef = this._getSpaceKoef(val);
				this.$wrapper.attr('style', '--rating:' + (val * 20) + '%; --space-koef:' + spaceKoef + ';');
			}).bind(this))
			.on('click', (function(event) {
				var val = this._getVal(event);
				var spaceKoef = this._getSpaceKoef(val);
				this.$wrapper.attr('data-val', val);
				this.$wrapper.attr('style', '--rating:' + (val * 20) + '%; --space-koef:' + spaceKoef + ';');
			}).bind(this))
			.on('mouseleave', (function(event) {
				var val = this.$wrapper.attr('data-val');
				var spaceKoef = this._getSpaceKoef(val);
				this.$wrapper.attr('style', '--rating:' + (val * 20) + '%; --space-koef:' + spaceKoef + ';');
			}).bind(this));
	};

	/**
	 * Computes val for data-val attribute
	 *
	 * @param event {event}
	 * @returns {number}
	 * @private
	 */
	CsRating.prototype._getVal = function(event) {
		var pos = ( event.pageX - this.$elem.offset().left) / this.$elem.width(),
		    val = 0;

		if ( pos < 0.1 ) {
			val = 0;
		} else if ( pos < 0.2) {
			val = 1;
		} else if ( pos < 0.4) {
			val = 2;
		} else if ( pos < 0.6) {
			val = 3;
		} else if ( pos < 0.8) {
			val = 4;
		} else {
			val = 5;
		}

		return val;
	};

	/**
	 * Computes spaceKoef for style attribute
	 *
	 * @param val {number}
	 * @returns {number}
	 * @private
	 */
	CsRating.prototype._getSpaceKoef = function(val) {
		var spaceKoef;
		var percentage = val * 20;

		if ( percentage > 80 ) {
			spaceKoef = 4;
		} else if ( percentage > 60 ) {
			spaceKoef = 3;
		} else if ( percentage > 40 ) {
			spaceKoef = 2;
		} else if ( percentage > 10 ) {
			spaceKoef = -4;
		} else {
			spaceKoef = 0;
		}

		return spaceKoef;
	};

	/**
	 * Unbinds events
	 *
	 * @returns {void}
	 * @private
	 */
	CsRating.prototype._unbindEvents = function() {
		this.$elem.off();
	};

	var setRatings = jQuery('.cs_rating_wrapper.set_rating .rating');
	setRatings.each(function(index, elem) {
		new CsRating(elem);
	});

	return CsRating;
})(setRatingElements);



/* ========================================
 FILE: /modules/js/mod_vm_product_watch.js
 ==================== */

jQuery(function () {
	var product_watch_unfollow_key = location.search.split('unfollow_watched_product=')[1];
	if (typeof product_watch_unfollow_key != 'undefined') {
		showLoader();
		new AjaxRequest({'unfollow_key': product_watch_unfollow_key})
			.setController("User")
			.setAction('unfollowWatchedProduct')
			.onSuccess(function (jsonData) {
				hideLoader();
				if (jsonData.data.success === 1) {
					var vexText = js_lang_product_watch_unfollow_confirm_msg || 'Boli ste úspešne odhlásený zo sledovania produktu';

					vex.dialog.open({
						className: 'vex-cs watchdog-vex',
						message: '',
						input: vexText,
						buttons: [jQuery.extend({}, vex.dialog.buttons.YES)],
						afterClose: function () {
							if ( typeof script_manage_params_ismyid !== 'undefined' && script_manage_params_ismyid) {
								window.location = js_global_live_site + '/sprava-uctu/';
							} else {
								window.location = js_global_live_site;
							}
						}
					});
				} else {
					alert(js_lang_product_watch_unfollow_error_msg);
				}
			})
			.send();
	}
});

/* ========================================
 FILE: /includes/js/system/Modal.js
 ==================== */

/**
 * Modal Class
 *
 * @author TL
 * @type {CsModal}
 */
var CsModal = (
	/**
	 *
	 * @param modalPlugin {object}
	 * @returns {Modal}
	 */
	function(modalPlugin) {
		'use strict';

		/**
		 * Plugin
		 * @type {vex}
		 */
		var PLUGIN = modalPlugin;

		/**
		 * Default class for all modal windows
		 * @type {string}
		 */
		var MODAL_DEFAULT_CLASSNAME = 'cs_modal';

		/**
		 * Default class for overlay element
		 * @type {string}
		 */
		var MODAL_OVERLAY_CLASSNAME = 'cs_modal_overlay';

		/**
		 * Default class for heading element
		 * @type {string}
		 */
		var MODAL_HEADING_CLASSNAME = 'cs_modal_heading';

		/**
		 * Default class for content element
		 * @type {string}
		 */
		var MODAL_CONTENT_CLASSNAME = 'cs_modal_content';

		/**
		 * Default class for content inner element
		 * @type {string}
		 */
		var MODAL_CONTENT_INNER_CLASSNAME = 'cs_modal_content_inner';

		/**
		 * Default class for actions container element
		 * @type {string}
		 */
		var MODAL_ACTIONS_CLASSNAME = 'cs_modal_actions';

		/**
		 * Default class for close button
		 * @type {string}
		 */
		var MODAL_CLOSE_CLASSNAME = 'cs_modal_close';

		/**
		 * Default class for cancel button
		 * @type {string}
		 */
		var MODAL_CANCEL_CLASSNAME = 'close_button';

		/**
		 * Default class for cancel button
		 * @type {string}
		 */
		var MODAL_SUBMIT_CLASSNAME = 'submit_button';

		/**
		 * Allowed types [info, warning, error, confirm, prompt]
		 * @type {object}
		 */
		var ALLOWED_TYPES = {
			info: 'info',
			warning: 'warning',
			error: 'error',
			confirm: 'confirm',
			prompt: 'prompt'
		};

		var listOfCsModals = new WeakMap();

		/**
		 *
		 * @constructor
		 */
		function Modal() {
			this.plugin = PLUGIN;
			this.id = 0;
			this.modal = null;
			this.hideEmptyContent = false;
			this.options = {
				type: 'alert',
				className: MODAL_DEFAULT_CLASSNAME,
				overlayClassName: MODAL_OVERLAY_CLASSNAME,
				contentClassName: MODAL_CONTENT_CLASSNAME,
				actionsClassName: MODAL_ACTIONS_CLASSNAME,
				closeClassName: MODAL_CLOSE_CLASSNAME,
				message: ''
			};

			return this;
		}

		/**
		 * Sets type of modal window (info, warning, error, confirm, prompt)
		 *
		 * @param type {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setType = function(type) {
			if ( !_isString(type) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( !_isAllowedType(type) ) {
				throw new Error('This type is not allowed');
			}

			switch (type) {
				case 'info':
				case 'warning':
				case 'error':
					this.options.type = 'alert';
					break;
				default:
					this.options.type = type;
					break;
			}

			this.setClassName('type_' + type);

			return this;
		};

		Modal.prototype.removeClass = function(className) {
			if ( !_isString(className) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				this.modal.removeClass(className);
			} else {
				throw new TypeError('removeClass should not be called on init');
			}

			return this;
		};

		/**
		 * Sets classes for modal window
		 *
		 * @param className {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setClassName = function(className) {
			if ( !_isString(className) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				this.modal.addClass(className);
			} else {
				this.options.className = this.options.className + ' ' + className;
			}

			return this;
		};

		/**
		 * Sets classes for modal content element
		 *
		 * @param className {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setContentClassName = function(className) {
			if ( !_isString(className) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				this.modal.find('.' + MODAL_CONTENT_CLASSNAME).addClass(className);
			} else {
				this.options.contentClassName = this.options.contentClassName + ' ' + className;
			}

			return this;
		};

		/**
		 * Sets classes for modal actions container element
		 *
		 * @param className
		 * @returns {Modal}
		 */
		Modal.prototype.setActionsClassName = function (className) {
			if ( !_isString(className) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				this.modal.find('.' + MODAL_ACTIONS_CLASSNAME).addClass(className);
			} else {
				this.options.actionsClassName = this.options.actionsClassName + ' ' + className;
			}

			return this;
		};

		/**
		 * Sets icon of modal window
		 *
		 * @param icon {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setIcon = function(icon) {
			if ( !_isString(icon) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				// TODO
				//this.modal.find('.' + MODAL_CONTENT_CLASSNAME).addClass(className);
			} else {
				this.options.icon = icon;
			}

			return this;
		};
		/**
		 * Sets title of modal window
		 *
		 * @param title {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setTitle = function(title) {
			if ( !_isString(title) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				this.modal.find('.' + MODAL_HEADING_CLASSNAME + ' .title').addClass(title);
			} else {
				this.options.message = title;
			}

			return this;
		};

		/**
		 * Sets subtitle of modal window
		 *
		 * @param subtitle {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setSubtitle = function(subtitle) {
			if ( !_isString(subtitle) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				this.modal.find('.' + MODAL_HEADING_CLASSNAME + ' .subtitle').addClass(subtitle);
			} else {
				this.options.subtitle = subtitle;
			}

			return this;
		};

		/**
		 * Sets content of modal window
		 *
		 * @param content {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setContent = function(content) {
			if ( !_isString(content) ) {
				throw new TypeError('Argument must be a String');
			}

			if ( _isModalInitialized(this.id) ) {
				this.modal.find('.' + MODAL_CONTENT_INNER_CLASSNAME).html(content);

				if (typeof this.options.afterSetContentFn === 'function' ) { // nahradit za _isFunction(this.options.afterSetContentFn) ?
					this.options.afterSetContentFn(this.modal);
				}

			} else {
				this.options.input = content;
			}

			return this;
		};

		Modal.prototype.afterSetContent = function (fn) {
			if ( !_isFunction(fn) ) {
				throw new TypeError('Argument must be a Function');
			}

			this.options.afterSetContentFn = fn;

			return this;
		};

		/**
		 * Sets langs/texts for modal buttons
		 *
		 * @param buttons {string[]}
		 * @returns {Modal}
		 */
		Modal.prototype.setButtonTexts = function(buttons) {
			if ( !_isArray(buttons) ) {
				throw new TypeError('Argument must be an Array');
			}

			this.options.buttons = buttons;

			return this;
		};

		/**
		 * Sets custom buttons for modal window as a html string
		 *
		 * @param buttons {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setButtons = function(buttons) {
			if ( !_isString(buttons) ) {
				throw new TypeError('Argument must be a HTML string');
			}

			this.options.buttons = buttons;

			return this;
		};

		/**
		 * Sets initial value for prompt modal
		 *
		 * @param value {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setPromptValue = function(value) {
			if ( !_isString(value) ) {
				throw new TypeError('Argument must be a String');
			}

			this.options.value = value;

			return this;
		};

		/**
		 * Sets placeholder value for prompt modal
		 *
		 * @param placeholder {string}
		 * @returns {Modal}
		 */
		Modal.prototype.setPromptPlaceholder = function(placeholder) {
			if ( !_isString(placeholder) ) {
				throw new TypeError('Argument must be a String');
			}

			this.options.placeholder = placeholder;

			return this;
		};

		/**
		 * Shows close button
		 *
		 * @param bool {boolean}
		 * @returns {Modal}
		 */
		Modal.prototype.hideCloseButton = function(bool) {
			var hideBtn = bool;

			if ( typeof hideBtn === 'undefined' ) {
				hideBtn = true;
			}

			if ( !_isBool(hideBtn) ) {
				throw new TypeError('Argument must be a Boolean');
			}

			this.options.showCloseButton = !hideBtn;

			return this;
		};

		/**
		 * Hides empty content or title
		 *
		 * @param bool {boolean}
		 * @returns {Modal}
		 */
		Modal.prototype.hideEmptySpace = function(bool) {
			var hideEmptySpace = bool;

			if ( typeof hideEmptySpace === 'undefined' ) {
				hideEmptySpace = true;
			}

			if ( !_isBool(hideEmptySpace) ) {
				throw new TypeError('Argument must be a Boolean');
			}

			this.hideEmptyContent = hideEmptySpace;

			return this;
		};

		/**
		 * Disables pressing escape key to close modal
		 *
		 * @param bool {boolean}
		 * @returns {Modal}
		 */
		Modal.prototype.disableEscapeKey = function(bool) {
			var disableEscape = bool;

			if ( typeof disableEscape === 'undefined' ) {
				disableEscape = true;
			}

			if ( !_isBool(disableEscape) ) {
				throw new TypeError('Argument must be a Boolean');
			}

			this.options.escapeButtonCloses = !disableEscape;

			return this;
		};

		/**
		 * Disables clicking on overlay/backdrop to close modal
		 *
		 * @param bool {boolean}
		 * @returns {Modal}
		 */
		Modal.prototype.disableClickOnOverlay = function(bool) {
			var disableClickOnOverlay = bool;

			if ( typeof disableClickOnOverlay === 'undefined' ) {
				disableClickOnOverlay = true;
			}

			if ( !_isBool(disableClickOnOverlay) ) {
				throw new TypeError('Argument must be a Boolean');
			}

			this.options.overlayClosesOnClick = !disableClickOnOverlay;

			return this;
		};

		/**
		 * @callback callbackFunction
		 */

		/**
		 * Sets callback function that is called after opening the modal
		 *
		 * @param fn {callbackFunction}
		 * @returns {Modal}
		 */
		Modal.prototype.afterOpen = function(fn) {
			if ( !_isFunction(fn) ) {
				throw new TypeError('Argument must be a Function');
			}

			this.options.afterOpen = fn;

			return this;
		};

		/**
		 * Sets callback function that is called before closing the modal, but after callback function is called
		 *
		 * @param fn {callbackFunction}
		 * @returns {Modal}
		 */
		Modal.prototype.beforeClose = function(fn) {
			if ( !_isFunction(fn) ) {
				throw new TypeError('Argument must be a Function');
			}

			this.options.beforeClose = fn;

			return this;
		};

		/**
		 * Sets callback function that is called after closing the modal
		 *
		 * @param fn {callbackFunction}
		 * @returns {Modal}
		 */
		Modal.prototype.afterClose = function(fn) {
			if ( !_isFunction(fn) ) {
				throw new TypeError('Argument must be a Function');
			}

			this.options.afterClose = fn;

			return this;
		};

		/**
		 * Sets callback function that is called on submitting the modal
		 *
		 * @param fn {callbackFunction}
		 * @returns {Modal}
		 */
		Modal.prototype.onSubmit = function(fn) {
			if ( !_isFunction(fn) ) {
				throw new TypeError('Argument must be a Function');
			}

			this.options.onSubmit = fn;

			return this;
		};

		/**
		 * Opens modal window
		 *
		 * @returns {Modal}
		 */
		Modal.prototype.open = function() {
			var $this = this; // nemozeme pouzit () => {} takze preto a krajsie ako jQuery.proxy
			//this.id = this.plugin.dialog[this.options.type](this.options).data('vex').id;
			if (this.hideEmptyContent) {
				if (typeof this.options.input === 'undefined' || this.options.input === '') {
					this.options.className += ' empty_body';
				} else if (typeof this.options.message === 'undefined' || this.options.message === '') {
					this.options.className += ' empty_header';
				}
			}
			this.options = _setHtml(this.options);
			var modalContentElem = this.plugin.open(this.options);
			this.id = modalContentElem.data('vex').id;
			this.modal = modalContentElem.closest('.' + MODAL_DEFAULT_CLASSNAME);


			this.options.node = this.modal;
			this.options.close = function () {
				$this.plugin.close($this.id);
			};

			_bindEvents(this);

			listOfCsModals.set(this.modal[0], this);
			return this;
		};

		/**
		 * Closes modal window
		 *
		 * @returns {Modal}
		 */
		Modal.prototype.close = function() {
			if (this.id === 0) {
				return this;
			}

			this.plugin.close(this.id);
			if (listOfCsModals.has(this.modal[0])) {
				listOfCsModals.delete(this.modal[0]);
			}

			return this;
		};

		Modal.prototype.getInstance = function(elem) {
			return listOfCsModals.get(jQuery(elem)[0]);
		};

		/*****************************
		 * Private functions
		 *****************************/

		/**
		 * Sets modal's html content
		 *
		 * @param options
		 * @returns {*}
		 * @private
		 */
		function _setHtml(options) {

			var modalHeading = _getModalHeading(options);

			var modalContent = _getModalContent(options);

			var buttons = _getModalButtons(options);

			var html = [
				modalHeading,
				modalContent,
				buttons
			].join('');

			return Object.assign({}, options, {
				content: html
			});
		}

		/**
		 * Gets modal's heading
		 *
		 * @param options
		 * @returns {string}
		 * @private
		 */
		function _getModalHeading(options) {
			return [
				'<div class="' + MODAL_HEADING_CLASSNAME + ( options.icon ? ' has_icon' : '' ) +'">',
				options.icon ? '<div class="icon cs_icon ' + options.icon + '"></div>' : '',
				'<div class="title"><span>' + (options.message ? options.message : '') + '</span></div>',
				'<div class="subtitle"><span>' + (options.subtitle ? options.subtitle : '') + '</span></div>',
				'</div>'
			].join('');
		}

		/**
		 * Gets modal's content
		 *
		 * @param options
		 * @returns {string}
		 * @private
		 */
		function _getModalContent(options) {
			var promptInput = '<input class="inputbox" type="text"' + (options.placeholder ? ' placeholder="' + options.placeholder + '"' : '') + (options.value ? ' value="' + options.value + '"' : '') + '>';

			return [
				'<div class="' + MODAL_CONTENT_INNER_CLASSNAME + '">',
				options.input ? options.input : '',
				(options.type === 'prompt' ? promptInput : ''),
				'</div>'
			].join('');
		}

		/**
		 * Gets modal's buttons
		 *
		 * @param options
		 * @returns {string}
		 * @private
		 */
		function _getModalButtons(options) {
			var buttons;

			if ( _isString(options.buttons) ) {
				return '<div class="' + (_isString(options.actionsClassName) ? options.actionsClassName : MODAL_ACTIONS_CLASSNAME) + '">' + options.buttons + '</div>'; //
			}

			if ( options.type === 'alert' ) {
				var closeBtn = _isArray(options.buttons) && _isString(options.buttons[0]) ? options.buttons[0] : cms_js_lang_close;

				buttons = '<div class="' + (_isString(options.actionsClassName) ? options.actionsClassName : MODAL_ACTIONS_CLASSNAME) + '"><button class="' + MODAL_CANCEL_CLASSNAME + '">' + closeBtn + '</button></div>';
			} else {
				var cancelBtn = _isArray(options.buttons) && _isString(options.buttons[0]) ? options.buttons[0] : 'Cancel';
				var confirmBtn = _isArray(options.buttons) && _isString(options.buttons[1]) ? options.buttons[1] : 'OK';

				buttons = [
					'<div class="' + (_isString(options.actionsClassName) ? options.actionsClassName : MODAL_ACTIONS_CLASSNAME) + '">',
					'<button class="' + MODAL_CANCEL_CLASSNAME + '">' + cancelBtn + '</button>',
					'<button class="button ' + MODAL_SUBMIT_CLASSNAME + '">' + confirmBtn + '</button>',
					'</div>'

				].join('');
			}

			return buttons;
		}

		/**
		 * Binds events
		 *
		 * @param instance
		 * @private
		 */
		function _bindEvents(instance) {
			instance.modal.find('.' + MODAL_CANCEL_CLASSNAME).on('click', instance.plugin.close.bind(null, instance.id));
			instance.modal.find('.' + MODAL_SUBMIT_CLASSNAME).on('click', function() {
				if ( _isFunction(instance.options.onSubmit) ) {
					instance.options.onSubmit();
				}
			});
		}

		/**
		 * Checks whether modal is already intialiazed or is being initialized
		 *
		 * @param id {number}
		 * @returns {boolean}
		 * @private
		 */
		function _isModalInitialized(id) {
			return id !== 0;
		}

		/**
		 * Checks if param is boolean
		 *
		 * @param param
		 * @returns {boolean}
		 * @private
		 */
		function _isBool(param) {
			return typeof param === 'boolean';
		}

		/**
		 * Checks if param is string
		 *
		 * @param param
		 * @returns {boolean}
		 * @private
		 */
		function _isString(param) {
			return typeof param === 'string';
		}

		/**
		 * Checks if param is object
		 *
		 * @param param
		 * @returns {boolean}
		 * @private
		 */
		function _isObject(param) {
			return typeof param === 'object' && !Array.isArray(param);
		}

		/**
		 * Checks if param is function
		 *
		 * @param param
		 * @returns {boolean}
		 * @private
		 */
		function _isFunction(param) {
			return typeof param === 'function';
		}

		/**
		 * Checks if param is array
		 *
		 * @param param
		 * @returns {boolean}
		 * @private
		 */
		function _isArray(param) {
			return typeof param !== 'undefined' && Array.isArray(param);
		}

		/**
		 * Checks if type is allowed
		 *
		 * @param type {string}
		 * @returns {boolean}
		 * @private
		 */
		function _isAllowedType(type) {
			return Object.values(ALLOWED_TYPES).indexOf(type) > -1;
		}

		return Modal;
	}
)(vex);


