/* Minification failed. Returning unminified contents.
(1,1): run-time error CSS1019: Unexpected token, found '$'
(1,2): run-time error CSS1019: Unexpected token, found '('
(1,12): run-time error CSS1031: Expected selector, found '('
(1,12): run-time error CSS1025: Expected comma or open brace, found '('
(18,2): run-time error CSS1019: Unexpected token, found ')'
(20,1): run-time error CSS1019: Unexpected token, found '$'
(20,2): run-time error CSS1019: Unexpected token, found '('
(20,11): run-time error CSS1031: Expected selector, found ')'
(20,11): run-time error CSS1025: Expected comma or open brace, found ')'
(22,2): run-time error CSS1019: Unexpected token, found ')'
(24,1): run-time error CSS1019: Unexpected token, found '$'
(24,2): run-time error CSS1019: Unexpected token, found '('
(24,11): run-time error CSS1031: Expected selector, found ')'
(24,11): run-time error CSS1025: Expected comma or open brace, found ')'
(38,2): run-time error CSS1019: Unexpected token, found ')'
(40,10): run-time error CSS1031: Expected selector, found 'AjaxPost('
(40,10): run-time error CSS1025: Expected comma or open brace, found 'AjaxPost('
(76,10): run-time error CSS1031: Expected selector, found 'AjaxPostObj('
(76,10): run-time error CSS1025: Expected comma or open brace, found 'AjaxPostObj('
(114,19): run-time error CSS1031: Expected selector, found '='
(114,19): run-time error CSS1025: Expected comma or open brace, found '='
(117,10): run-time error CSS1031: Expected selector, found 'openCollapse('
(117,10): run-time error CSS1025: Expected comma or open brace, found 'openCollapse('
(130,10): run-time error CSS1031: Expected selector, found 'closeCollapse('
(130,10): run-time error CSS1025: Expected comma or open brace, found 'closeCollapse('
(138,1): run-time error CSS1019: Unexpected token, found '$'
(138,2): run-time error CSS1019: Unexpected token, found '('
(138,3): run-time error CSS1019: Unexpected token, found '".menu-buttons .menu > table tr:first-child td:last-child .fa"'
(138,65): run-time error CSS1019: Unexpected token, found ')'
(138,67): run-time error CSS1030: Expected identifier, found 'on('
(138,67): run-time error CSS1019: Unexpected token, found 'on('
(138,70): run-time error CSS1019: Unexpected token, found '"click"'
(138,77): run-time error CSS1019: Unexpected token, found ','
(138,88): run-time error CSS1031: Expected selector, found '('
(138,88): run-time error CSS1025: Expected comma or open brace, found '('
(141,2): run-time error CSS1019: Unexpected token, found ')'
(143,1): run-time error CSS1019: Unexpected token, found '$'
(143,2): run-time error CSS1019: Unexpected token, found '('
(143,3): run-time error CSS1019: Unexpected token, found '"nav > .menu-burger > .fa, .close-menu-burger"'
(143,49): run-time error CSS1019: Unexpected token, found ')'
(143,51): run-time error CSS1030: Expected identifier, found 'on('
(143,51): run-time error CSS1019: Unexpected token, found 'on('
(143,54): run-time error CSS1019: Unexpected token, found '"click"'
(143,61): run-time error CSS1019: Unexpected token, found ','
(143,72): run-time error CSS1031: Expected selector, found '('
(143,72): run-time error CSS1025: Expected comma or open brace, found '('
(145,2): run-time error CSS1019: Unexpected token, found ')'
(149,1): run-time error CSS1019: Unexpected token, found '$'
(149,2): run-time error CSS1019: Unexpected token, found '('
(149,3): run-time error CSS1019: Unexpected token, found '".userOptions"'
(149,17): run-time error CSS1019: Unexpected token, found ')'
(149,19): run-time error CSS1030: Expected identifier, found 'children('
(149,19): run-time error CSS1019: Unexpected token, found 'children('
(149,28): run-time error CSS1019: Unexpected token, found '"ul"'
(149,32): run-time error CSS1019: Unexpected token, found ')'
(149,34): run-time error CSS1030: Expected identifier, found 'children('
(149,34): run-time error CSS1019: Unexpected token, found 'children('
(149,43): run-time error CSS1019: Unexpected token, found '"li:first-child"'
(149,59): run-time error CSS1019: Unexpected token, found ')'
(149,61): run-time error CSS1030: Expected identifier, found 'on('
(149,61): run-time error CSS1019: Unexpected token, found 'on('
(149,64): run-time error CSS1019: Unexpected token, found '"click"'
(149,71): run-time error CSS1019: Unexpected token, found ','
(149,82): run-time error CSS1031: Expected selector, found '('
(149,82): run-time error CSS1025: Expected comma or open brace, found '('
(152,2): run-time error CSS1019: Unexpected token, found ')'
(154,1): run-time error CSS1019: Unexpected token, found '$'
(154,2): run-time error CSS1019: Unexpected token, found '('
(154,3): run-time error CSS1019: Unexpected token, found '".product-menu"'
(154,18): run-time error CSS1019: Unexpected token, found ')'
(154,20): run-time error CSS1030: Expected identifier, found 'on('
(154,20): run-time error CSS1019: Unexpected token, found 'on('
(154,23): run-time error CSS1019: Unexpected token, found '"click"'
(154,30): run-time error CSS1019: Unexpected token, found ','
(154,41): run-time error CSS1031: Expected selector, found '('
(154,41): run-time error CSS1025: Expected comma or open brace, found '('
(156,2): run-time error CSS1019: Unexpected token, found ')'
(159,1): run-time error CSS1019: Unexpected token, found '$'
(159,2): run-time error CSS1019: Unexpected token, found '('
(159,3): run-time error CSS1019: Unexpected token, found '".searcher form"'
(159,19): run-time error CSS1019: Unexpected token, found ')'
(159,21): run-time error CSS1030: Expected identifier, found 'on('
(159,21): run-time error CSS1019: Unexpected token, found 'on('
(159,24): run-time error CSS1019: Unexpected token, found '"submit"'
(159,32): run-time error CSS1019: Unexpected token, found ','
(159,43): run-time error CSS1031: Expected selector, found '('
(159,43): run-time error CSS1025: Expected comma or open brace, found '('
(161,2): run-time error CSS1019: Unexpected token, found ')'
(162,1): run-time error CSS1019: Unexpected token, found '$'
(162,2): run-time error CSS1019: Unexpected token, found '('
(162,3): run-time error CSS1019: Unexpected token, found '".searcher form"'
(162,19): run-time error CSS1019: Unexpected token, found ')'
(162,21): run-time error CSS1030: Expected identifier, found 'on('
(162,21): run-time error CSS1019: Unexpected token, found 'on('
(162,24): run-time error CSS1019: Unexpected token, found '"keyup"'
(162,31): run-time error CSS1019: Unexpected token, found ','
(162,33): run-time error CSS1019: Unexpected token, found 'applyDelay('
(162,54): run-time error CSS1031: Expected selector, found '1500'
(163,1): run-time error CSS1019: Unexpected token, found '$'
(163,2): run-time error CSS1019: Unexpected token, found '('
(163,3): run-time error CSS1019: Unexpected token, found '".close-search"'
(163,18): run-time error CSS1019: Unexpected token, found ')'
(163,20): run-time error CSS1030: Expected identifier, found 'on('
(163,20): run-time error CSS1019: Unexpected token, found 'on('
(163,23): run-time error CSS1019: Unexpected token, found '"click"'
(163,30): run-time error CSS1019: Unexpected token, found ','
(163,43): run-time error CSS1031: Expected selector, found ')'
(163,43): run-time error CSS1025: Expected comma or open brace, found ')'
(164,1): run-time error CSS1019: Unexpected token, found '$'
(164,2): run-time error CSS1019: Unexpected token, found '('
(164,3): run-time error CSS1019: Unexpected token, found '".searcher .icon"'
(164,20): run-time error CSS1019: Unexpected token, found ')'
(164,22): run-time error CSS1030: Expected identifier, found 'on('
(164,22): run-time error CSS1019: Unexpected token, found 'on('
(164,25): run-time error CSS1019: Unexpected token, found '"click"'
(164,32): run-time error CSS1019: Unexpected token, found ','
(164,43): run-time error CSS1031: Expected selector, found ')'
(164,43): run-time error CSS1025: Expected comma or open brace, found ')'
(165,1): run-time error CSS1019: Unexpected token, found '$'
(165,2): run-time error CSS1019: Unexpected token, found '('
(165,3): run-time error CSS1019: Unexpected token, found '".searcher .search"'
(165,22): run-time error CSS1019: Unexpected token, found ')'
(165,24): run-time error CSS1030: Expected identifier, found 'on('
(165,24): run-time error CSS1019: Unexpected token, found 'on('
(165,27): run-time error CSS1019: Unexpected token, found '"keyup"'
(165,34): run-time error CSS1019: Unexpected token, found ','
(165,45): run-time error CSS1031: Expected selector, found '('
(165,45): run-time error CSS1025: Expected comma or open brace, found '('
(183,2): run-time error CSS1019: Unexpected token, found ')'
(184,1): run-time error CSS1019: Unexpected token, found '$'
(184,2): run-time error CSS1019: Unexpected token, found '('
(184,3): run-time error CSS1019: Unexpected token, found '"#winModalSearcher #ddlManufacturer"'
(184,39): run-time error CSS1019: Unexpected token, found ')'
(184,41): run-time error CSS1030: Expected identifier, found 'change('
(184,41): run-time error CSS1019: Unexpected token, found 'change('
(184,66): run-time error CSS1031: Expected selector, found ')'
(184,66): run-time error CSS1025: Expected comma or open brace, found ')'
(185,1): run-time error CSS1019: Unexpected token, found '$'
(185,2): run-time error CSS1019: Unexpected token, found '('
(185,3): run-time error CSS1019: Unexpected token, found '"#winModalSearcher #btnModalSearcherDo"'
(185,42): run-time error CSS1019: Unexpected token, found ')'
(185,44): run-time error CSS1030: Expected identifier, found 'click('
(185,44): run-time error CSS1019: Unexpected token, found 'click('
(185,65): run-time error CSS1031: Expected selector, found ')'
(185,65): run-time error CSS1025: Expected comma or open brace, found ')'
(186,1): run-time error CSS1019: Unexpected token, found '$'
(186,2): run-time error CSS1019: Unexpected token, found '('
(186,3): run-time error CSS1019: Unexpected token, found '"#ddlManufacturer"'
(186,21): run-time error CSS1019: Unexpected token, found ')'
(186,23): run-time error CSS1030: Expected identifier, found 'change('
(186,23): run-time error CSS1019: Unexpected token, found 'change('
(186,48): run-time error CSS1031: Expected selector, found ')'
(186,48): run-time error CSS1025: Expected comma or open brace, found ')'
(187,1): run-time error CSS1019: Unexpected token, found '$'
(187,2): run-time error CSS1019: Unexpected token, found '('
(187,3): run-time error CSS1019: Unexpected token, found '"#btnModalSearcherDo"'
(187,24): run-time error CSS1019: Unexpected token, found ')'
(187,26): run-time error CSS1030: Expected identifier, found 'click('
(187,26): run-time error CSS1019: Unexpected token, found 'click('
(187,47): run-time error CSS1031: Expected selector, found ')'
(187,47): run-time error CSS1025: Expected comma or open brace, found ')'
(189,10): run-time error CSS1031: Expected selector, found 'searchNow('
(189,10): run-time error CSS1025: Expected comma or open brace, found 'searchNow('
(211,10): run-time error CSS1031: Expected selector, found 'applyDelay('
(211,10): run-time error CSS1025: Expected comma or open brace, found 'applyDelay('
(221,10): run-time error CSS1031: Expected selector, found 'closeSearch('
(221,10): run-time error CSS1025: Expected comma or open brace, found 'closeSearch('
(225,10): run-time error CSS1031: Expected selector, found 'showAutocomplete('
(225,10): run-time error CSS1025: Expected comma or open brace, found 'showAutocomplete('
(229,10): run-time error CSS1031: Expected selector, found 'hideAutoComplete('
(229,10): run-time error CSS1025: Expected comma or open brace, found 'hideAutoComplete('
(233,10): run-time error CSS1031: Expected selector, found 'setDdlProductModel('
(233,10): run-time error CSS1025: Expected comma or open brace, found 'setDdlProductModel('
(253,10): run-time error CSS1031: Expected selector, found 'modalSearcherDo('
(253,10): run-time error CSS1025: Expected comma or open brace, found 'modalSearcherDo('
(281,8): run-time error CSS1031: Expected selector, found ';'
(281,8): run-time error CSS1025: Expected comma or open brace, found ';'
(282,17): run-time error CSS1031: Expected selector, found ';'
(282,17): run-time error CSS1025: Expected comma or open brace, found ';'
(284,1): run-time error CSS1019: Unexpected token, found '$'
(284,2): run-time error CSS1019: Unexpected token, found '('
(284,11): run-time error CSS1031: Expected selector, found ')'
(284,11): run-time error CSS1025: Expected comma or open brace, found ')'
(594,2): run-time error CSS1019: Unexpected token, found ')'
(596,10): run-time error CSS1031: Expected selector, found 'updateBreadcrumb('
(596,10): run-time error CSS1025: Expected comma or open brace, found 'updateBreadcrumb('
(605,1): run-time error CSS1019: Unexpected token, found '$'
(605,2): run-time error CSS1019: Unexpected token, found '('
(605,11): run-time error CSS1031: Expected selector, found ')'
(605,11): run-time error CSS1025: Expected comma or open brace, found ')'
(606,1): run-time error CSS1019: Unexpected token, found '$'
(606,2): run-time error CSS1019: Unexpected token, found '('
(606,11): run-time error CSS1031: Expected selector, found ')'
(606,11): run-time error CSS1025: Expected comma or open brace, found ')'
(607,1): run-time error CSS1019: Unexpected token, found '$'
(607,2): run-time error CSS1019: Unexpected token, found '('
(607,11): run-time error CSS1031: Expected selector, found ')'
(607,11): run-time error CSS1025: Expected comma or open brace, found ')'
(632,2): run-time error CSS1019: Unexpected token, found ')'
(634,10): run-time error CSS1031: Expected selector, found 'updateItemShopCar('
(634,10): run-time error CSS1025: Expected comma or open brace, found 'updateItemShopCar('
(676,1): run-time error CSS1019: Unexpected token, found '$'
(676,2): run-time error CSS1019: Unexpected token, found '('
(676,11): run-time error CSS1031: Expected selector, found ')'
(676,11): run-time error CSS1025: Expected comma or open brace, found ')'
(685,2): run-time error CSS1019: Unexpected token, found ')'
(687,10): run-time error CSS1031: Expected selector, found 'creditCardForm('
(687,10): run-time error CSS1025: Expected comma or open brace, found 'creditCardForm('
(700,10): run-time error CSS1031: Expected selector, found 'PaypalButtons('
(700,10): run-time error CSS1025: Expected comma or open brace, found 'PaypalButtons('
(711,10): run-time error CSS1031: Expected selector, found 'ObtenerDatosCheckout('
(711,10): run-time error CSS1025: Expected comma or open brace, found 'ObtenerDatosCheckout('
(758,10): run-time error CSS1031: Expected selector, found 'IniciarPagoPayPal('
(758,10): run-time error CSS1025: Expected comma or open brace, found 'IniciarPagoPayPal('
(812,1): run-time error CSS1019: Unexpected token, found '$'
(812,2): run-time error CSS1019: Unexpected token, found '('
(812,11): run-time error CSS1031: Expected selector, found ')'
(812,11): run-time error CSS1025: Expected comma or open brace, found ')'
(921,2): run-time error CSS1019: Unexpected token, found ')'
(922,1): run-time error CSS1019: Unexpected token, found '$'
(922,2): run-time error CSS1019: Unexpected token, found '('
(922,3): run-time error CSS1019: Unexpected token, found '".mya .menu a"'
(922,17): run-time error CSS1019: Unexpected token, found ')'
(922,19): run-time error CSS1030: Expected identifier, found 'on('
(922,19): run-time error CSS1019: Unexpected token, found 'on('
(922,22): run-time error CSS1019: Unexpected token, found '"click"'
(922,29): run-time error CSS1019: Unexpected token, found ','
(922,40): run-time error CSS1031: Expected selector, found '('
(922,40): run-time error CSS1025: Expected comma or open brace, found '('
(925,2): run-time error CSS1019: Unexpected token, found ')'
(927,1): run-time error CSS1019: Unexpected token, found '$'
(927,2): run-time error CSS1019: Unexpected token, found '('
(927,3): run-time error CSS1019: Unexpected token, found '".userNotification"'
(927,22): run-time error CSS1019: Unexpected token, found ')'
(927,24): run-time error CSS1030: Expected identifier, found 'on('
(927,24): run-time error CSS1019: Unexpected token, found 'on('
(927,27): run-time error CSS1019: Unexpected token, found '"click"'
(927,34): run-time error CSS1019: Unexpected token, found ','
(927,45): run-time error CSS1031: Expected selector, found '('
(927,45): run-time error CSS1025: Expected comma or open brace, found '('
(930,2): run-time error CSS1019: Unexpected token, found ')'
(932,1): run-time error CSS1019: Unexpected token, found '$'
(932,2): run-time error CSS1019: Unexpected token, found '('
(932,3): run-time error CSS1019: Unexpected token, found '"#addShippingAddress"'
(932,24): run-time error CSS1019: Unexpected token, found ')'
(932,26): run-time error CSS1030: Expected identifier, found 'on('
(932,26): run-time error CSS1019: Unexpected token, found 'on('
(932,29): run-time error CSS1019: Unexpected token, found '"click"'
(932,36): run-time error CSS1019: Unexpected token, found ','
(932,47): run-time error CSS1031: Expected selector, found '('
(932,47): run-time error CSS1025: Expected comma or open brace, found '('
(939,2): run-time error CSS1019: Unexpected token, found ')'
(941,1): run-time error CSS1019: Unexpected token, found '$'
(941,2): run-time error CSS1019: Unexpected token, found '('
(941,3): run-time error CSS1019: Unexpected token, found '".formShippingAddress"'
(941,25): run-time error CSS1019: Unexpected token, found ')'
(941,27): run-time error CSS1030: Expected identifier, found 'find('
(941,27): run-time error CSS1019: Unexpected token, found 'find('
(941,32): run-time error CSS1019: Unexpected token, found '"button[type=button]"'
(941,53): run-time error CSS1019: Unexpected token, found ')'
(941,55): run-time error CSS1030: Expected identifier, found 'on('
(941,55): run-time error CSS1019: Unexpected token, found 'on('
(941,58): run-time error CSS1019: Unexpected token, found '"click"'
(941,65): run-time error CSS1019: Unexpected token, found ','
(941,76): run-time error CSS1031: Expected selector, found '('
(941,76): run-time error CSS1025: Expected comma or open brace, found '('
(945,2): run-time error CSS1019: Unexpected token, found ')'
(947,1): run-time error CSS1019: Unexpected token, found '$'
(947,2): run-time error CSS1019: Unexpected token, found '('
(947,3): run-time error CSS1019: Unexpected token, found '".mya-shipping-address table tbody"'
(947,38): run-time error CSS1019: Unexpected token, found ')'
(947,40): run-time error CSS1030: Expected identifier, found 'on('
(947,40): run-time error CSS1019: Unexpected token, found 'on('
(947,43): run-time error CSS1019: Unexpected token, found '"click"'
(947,50): run-time error CSS1019: Unexpected token, found ','
(947,52): run-time error CSS1019: Unexpected token, found '"a.eliminar"'
(947,64): run-time error CSS1019: Unexpected token, found ','
(947,75): run-time error CSS1031: Expected selector, found '('
(947,75): run-time error CSS1025: Expected comma or open brace, found '('
(961,2): run-time error CSS1019: Unexpected token, found ')'
(963,1): run-time error CSS1019: Unexpected token, found '$'
(963,2): run-time error CSS1019: Unexpected token, found '('
(963,3): run-time error CSS1019: Unexpected token, found '".mya-shipping-address table tbody"'
(963,38): run-time error CSS1019: Unexpected token, found ')'
(963,40): run-time error CSS1030: Expected identifier, found 'on('
(963,40): run-time error CSS1019: Unexpected token, found 'on('
(963,43): run-time error CSS1019: Unexpected token, found '"click"'
(963,50): run-time error CSS1019: Unexpected token, found ','
(963,52): run-time error CSS1019: Unexpected token, found '"a.editar"'
(963,62): run-time error CSS1019: Unexpected token, found ','
(963,73): run-time error CSS1031: Expected selector, found '('
(963,73): run-time error CSS1025: Expected comma or open brace, found '('
(984,2): run-time error CSS1019: Unexpected token, found ')'
(986,1): run-time error CSS1019: Unexpected token, found '$'
(986,2): run-time error CSS1019: Unexpected token, found '('
(986,3): run-time error CSS1019: Unexpected token, found '"#CheckPrincipal"'
(986,20): run-time error CSS1019: Unexpected token, found ')'
(986,22): run-time error CSS1030: Expected identifier, found 'on('
(986,22): run-time error CSS1019: Unexpected token, found 'on('
(986,25): run-time error CSS1019: Unexpected token, found '"change"'
(986,33): run-time error CSS1019: Unexpected token, found ','
(986,44): run-time error CSS1031: Expected selector, found '('
(986,44): run-time error CSS1025: Expected comma or open brace, found '('
(989,2): run-time error CSS1019: Unexpected token, found ')'
(991,10): run-time error CSS1031: Expected selector, found 'showFormMyAccount('
(991,10): run-time error CSS1025: Expected comma or open brace, found 'showFormMyAccount('
(1274,10): run-time error CSS1031: Expected selector, found 'attachStarHover('
(1274,10): run-time error CSS1025: Expected comma or open brace, found 'attachStarHover('
(1299,1): run-time error CSS1019: Unexpected token, found '$'
(1299,2): run-time error CSS1019: Unexpected token, found '('
(1299,11): run-time error CSS1031: Expected selector, found ')'
(1299,11): run-time error CSS1025: Expected comma or open brace, found ')'
(1829,2): run-time error CSS1019: Unexpected token, found ')'
(1831,10): run-time error CSS1031: Expected selector, found 'showMessage('
(1831,10): run-time error CSS1025: Expected comma or open brace, found 'showMessage('
(1851,10): run-time error CSS1031: Expected selector, found 'hideMessage('
(1851,10): run-time error CSS1025: Expected comma or open brace, found 'hideMessage('
(1861,1): run-time error CSS1019: Unexpected token, found '$'
(1861,2): run-time error CSS1019: Unexpected token, found '('
(1861,3): run-time error CSS1019: Unexpected token, found '"#loginForm"'
(1861,15): run-time error CSS1019: Unexpected token, found ')'
(1861,17): run-time error CSS1030: Expected identifier, found 'validate('
(1861,17): run-time error CSS1019: Unexpected token, found 'validate('
(1861,26): run-time error CSS1019: Unexpected token, found '{'
(1862,11): run-time error CSS1030: Expected identifier, found ' '
(1863,15): run-time error CSS1036: Expected expression, found '{'
(1868,6): run-time error CSS1019: Unexpected token, found ','
(1869,14): run-time error CSS1030: Expected identifier, found ' '
(1870,15): run-time error CSS1036: Expected expression, found '{'
(1876,1): run-time error CSS1019: Unexpected token, found '}'
(1876,2): run-time error CSS1019: Unexpected token, found ')'
(1877,1): run-time error CSS1019: Unexpected token, found '$'
(1877,2): run-time error CSS1019: Unexpected token, found '('
(1877,3): run-time error CSS1019: Unexpected token, found '"#restorePasswordForm #Email"'
(1877,32): run-time error CSS1019: Unexpected token, found ')'
(1877,34): run-time error CSS1030: Expected identifier, found 'inputmask('
(1877,34): run-time error CSS1019: Unexpected token, found 'inputmask('
(1877,44): run-time error CSS1019: Unexpected token, found '{'
(1877,52): run-time error CSS1030: Expected identifier, found ' '
(1877,53): run-time error CSS1031: Expected selector, found ''email''
(1877,53): run-time error CSS1025: Expected comma or open brace, found ''email''
(1905,2): run-time error CSS1019: Unexpected token, found ')'
(1906,4): run-time error CSS1031: Expected selector, found '('
(1906,4): run-time error CSS1025: Expected comma or open brace, found '('
(1965,1): run-time error CSS1019: Unexpected token, found '$'
(1965,2): run-time error CSS1019: Unexpected token, found '('
(1965,11): run-time error CSS1031: Expected selector, found ')'
(1965,11): run-time error CSS1025: Expected comma or open brace, found ')'
(1966,1): run-time error CSS1019: Unexpected token, found '$'
(1966,2): run-time error CSS1019: Unexpected token, found '('
(1966,11): run-time error CSS1031: Expected selector, found ')'
(1966,11): run-time error CSS1025: Expected comma or open brace, found ')'
(1967,1): run-time error CSS1019: Unexpected token, found '$'
(1967,2): run-time error CSS1019: Unexpected token, found '('
(1967,11): run-time error CSS1031: Expected selector, found ')'
(1967,11): run-time error CSS1025: Expected comma or open brace, found ')'
(2004,2): run-time error CSS1019: Unexpected token, found ')'
(2005,1): run-time error CSS1019: Unexpected token, found '$'
(2005,2): run-time error CSS1019: Unexpected token, found '('
(2005,11): run-time error CSS1031: Expected selector, found ')'
(2005,11): run-time error CSS1025: Expected comma or open brace, found ')'
(2026,2): run-time error CSS1019: Unexpected token, found ')'
(2028,1): run-time error CSS1019: Unexpected token, found '$'
(2028,2): run-time error CSS1019: Unexpected token, found '('
(2028,11): run-time error CSS1031: Expected selector, found ')'
(2028,11): run-time error CSS1025: Expected comma or open brace, found ')'
(2051,2): run-time error CSS1019: Unexpected token, found ')'
(2053,1): run-time error CSS1019: Unexpected token, found '$'
(2053,2): run-time error CSS1019: Unexpected token, found '('
(2053,11): run-time error CSS1031: Expected selector, found ')'
(2053,11): run-time error CSS1025: Expected comma or open brace, found ')'
(2096,2): run-time error CSS1019: Unexpected token, found ')'
(2099,10): run-time error CSS1031: Expected selector, found 'fail('
(2099,10): run-time error CSS1025: Expected comma or open brace, found 'fail('
(2103,10): run-time error CSS1031: Expected selector, found 'updateShoppingCarCounter('
(2103,10): run-time error CSS1025: Expected comma or open brace, found 'updateShoppingCarCounter('
(2112,10): run-time error CSS1031: Expected selector, found 'addToCar('
(2112,10): run-time error CSS1025: Expected comma or open brace, found 'addToCar('
(2130,10): run-time error CSS1031: Expected selector, found 'addToCarForMessage('
(2130,10): run-time error CSS1025: Expected comma or open brace, found 'addToCarForMessage('
(2149,1): run-time error CSS1019: Unexpected token, found '$'
(2149,2): run-time error CSS1019: Unexpected token, found '('
(2149,3): run-time error CSS1019: Unexpected token, found '"form .buyNow"'
(2149,17): run-time error CSS1019: Unexpected token, found ')'
(2149,19): run-time error CSS1030: Expected identifier, found 'click('
(2149,19): run-time error CSS1019: Unexpected token, found 'click('
(2149,34): run-time error CSS1031: Expected selector, found '('
(2149,34): run-time error CSS1025: Expected comma or open brace, found '('
(2152,2): run-time error CSS1019: Unexpected token, found ')'
(2154,10): run-time error CSS1031: Expected selector, found 'mostrarMensaje('
(2154,10): run-time error CSS1025: Expected comma or open brace, found 'mostrarMensaje('
(2169,10): run-time error CSS1031: Expected selector, found 'ocultarMensaje('
(2169,10): run-time error CSS1025: Expected comma or open brace, found 'ocultarMensaje('
(2176,1): run-time error CSS1019: Unexpected token, found '$'
(2176,2): run-time error CSS1019: Unexpected token, found '('
(2176,3): run-time error CSS1019: Unexpected token, found '"#fondo"'
(2176,11): run-time error CSS1019: Unexpected token, found ')'
(2176,13): run-time error CSS1030: Expected identifier, found 'click('
(2176,13): run-time error CSS1019: Unexpected token, found 'click('
(2176,28): run-time error CSS1031: Expected selector, found '('
(2176,28): run-time error CSS1025: Expected comma or open brace, found '('
(2180,2): run-time error CSS1019: Unexpected token, found ')'
(2182,1): run-time error CSS1019: Unexpected token, found '$'
(2182,2): run-time error CSS1019: Unexpected token, found '('
(2182,3): run-time error CSS1019: Unexpected token, found ''.Full-Slider''
(2182,17): run-time error CSS1019: Unexpected token, found ')'
(2182,19): run-time error CSS1030: Expected identifier, found 'children('
(2182,19): run-time error CSS1019: Unexpected token, found 'children('
(2182,28): run-time error CSS1019: Unexpected token, found '".FS-Slider"'
(2182,40): run-time error CSS1019: Unexpected token, found ')'
(2182,42): run-time error CSS1030: Expected identifier, found 'on('
(2182,42): run-time error CSS1019: Unexpected token, found 'on('
(2182,45): run-time error CSS1019: Unexpected token, found ''afterChange''
(2182,58): run-time error CSS1019: Unexpected token, found ','
(2182,71): run-time error CSS1031: Expected selector, found ')'
(2182,71): run-time error CSS1025: Expected comma or open brace, found ')'
(2183,1): run-time error CSS1019: Unexpected token, found '$'
(2183,2): run-time error CSS1019: Unexpected token, found '('
(2183,3): run-time error CSS1019: Unexpected token, found ''.Full-Slider''
(2183,17): run-time error CSS1019: Unexpected token, found ')'
(2183,19): run-time error CSS1030: Expected identifier, found 'children('
(2183,19): run-time error CSS1019: Unexpected token, found 'children('
(2183,28): run-time error CSS1019: Unexpected token, found '".FS-Slider"'
(2183,40): run-time error CSS1019: Unexpected token, found ')'
(2183,42): run-time error CSS1030: Expected identifier, found 'on('
(2183,42): run-time error CSS1019: Unexpected token, found 'on('
(2183,45): run-time error CSS1019: Unexpected token, found ''init''
(2183,51): run-time error CSS1019: Unexpected token, found ','
(2183,64): run-time error CSS1031: Expected selector, found ')'
(2183,64): run-time error CSS1025: Expected comma or open brace, found ')'
(2184,1): run-time error CSS1019: Unexpected token, found '$'
(2184,2): run-time error CSS1019: Unexpected token, found '('
(2184,3): run-time error CSS1019: Unexpected token, found ''.Full-Slider''
(2184,17): run-time error CSS1019: Unexpected token, found ')'
(2184,19): run-time error CSS1030: Expected identifier, found 'children('
(2184,19): run-time error CSS1019: Unexpected token, found 'children('
(2184,28): run-time error CSS1019: Unexpected token, found '".FS-Slider"'
(2184,40): run-time error CSS1019: Unexpected token, found ')'
(2184,42): run-time error CSS1030: Expected identifier, found 'slick('
(2184,42): run-time error CSS1019: Unexpected token, found 'slick('
(2184,48): run-time error CSS1019: Unexpected token, found '{'
(2185,10): run-time error CSS1030: Expected identifier, found ' '
(2186,14): run-time error CSS1030: Expected identifier, found ' '
(2187,11): run-time error CSS1030: Expected identifier, found ' '
(2187,12): run-time error CSS1031: Expected selector, found '500'
(2187,12): run-time error CSS1025: Expected comma or open brace, found '500'
(2195,10): run-time error CSS1031: Expected selector, found 'SlickEvents('
(2195,10): run-time error CSS1025: Expected comma or open brace, found 'SlickEvents('
(2208,1): run-time error CSS1019: Unexpected token, found '$'
(2208,2): run-time error CSS1019: Unexpected token, found '('
(2208,9): run-time error CSS1031: Expected selector, found ')'
(2208,9): run-time error CSS1025: Expected comma or open brace, found ')'
(2212,1): run-time error CSS1019: Unexpected token, found '$'
(2212,2): run-time error CSS1019: Unexpected token, found '('
(2212,3): run-time error CSS1019: Unexpected token, found '".Slider-Images>div"'
(2212,23): run-time error CSS1019: Unexpected token, found ')'
(2212,25): run-time error CSS1030: Expected identifier, found 'children('
(2212,25): run-time error CSS1019: Unexpected token, found 'children('
(2212,34): run-time error CSS1019: Unexpected token, found '".SI-Slider"'
(2212,46): run-time error CSS1019: Unexpected token, found ')'
(2212,48): run-time error CSS1030: Expected identifier, found 'slick('
(2212,48): run-time error CSS1019: Unexpected token, found 'slick('
(2212,54): run-time error CSS1019: Unexpected token, found '{'
(2213,10): run-time error CSS1030: Expected identifier, found ' '
(2214,14): run-time error CSS1030: Expected identifier, found ' '
(2215,11): run-time error CSS1030: Expected identifier, found ' '
(2215,12): run-time error CSS1031: Expected selector, found '500'
(2215,12): run-time error CSS1025: Expected comma or open brace, found '500'
(2245,1): run-time error CSS1019: Unexpected token, found '$'
(2245,2): run-time error CSS1019: Unexpected token, found '('
(2245,3): run-time error CSS1019: Unexpected token, found '".Slider-Images>div"'
(2245,23): run-time error CSS1019: Unexpected token, found ')'
(2245,25): run-time error CSS1030: Expected identifier, found 'children('
(2245,25): run-time error CSS1019: Unexpected token, found 'children('
(2245,34): run-time error CSS1019: Unexpected token, found '".SI-Slider"'
(2245,46): run-time error CSS1019: Unexpected token, found ')'
(2245,48): run-time error CSS1030: Expected identifier, found 'on('
(2245,48): run-time error CSS1019: Unexpected token, found 'on('
(2245,51): run-time error CSS1019: Unexpected token, found ''setPosition''
(2245,64): run-time error CSS1019: Unexpected token, found ','
(2245,75): run-time error CSS1031: Expected selector, found '('
(2245,75): run-time error CSS1025: Expected comma or open brace, found '('
(2250,2): run-time error CSS1019: Unexpected token, found ')'
(2253,1): run-time error CSS1019: Unexpected token, found '$'
(2253,2): run-time error CSS1019: Unexpected token, found '('
(2253,3): run-time error CSS1019: Unexpected token, found '".SI-Content"'
(2253,16): run-time error CSS1019: Unexpected token, found ')'
(2253,18): run-time error CSS1030: Expected identifier, found 'on('
(2253,18): run-time error CSS1019: Unexpected token, found 'on('
(2253,21): run-time error CSS1019: Unexpected token, found '"mouseenter"'
(2253,33): run-time error CSS1019: Unexpected token, found ','
(2253,37): run-time error CSS1031: Expected selector, found ')'
(2253,37): run-time error CSS1025: Expected comma or open brace, found ')'
(2254,1): run-time error CSS1019: Unexpected token, found '$'
(2254,2): run-time error CSS1019: Unexpected token, found '('
(2254,3): run-time error CSS1019: Unexpected token, found '".SI-Content"'
(2254,16): run-time error CSS1019: Unexpected token, found ')'
(2254,18): run-time error CSS1030: Expected identifier, found 'on('
(2254,18): run-time error CSS1019: Unexpected token, found 'on('
(2254,21): run-time error CSS1019: Unexpected token, found '"mouseleave"'
(2254,33): run-time error CSS1019: Unexpected token, found ','
(2254,39): run-time error CSS1031: Expected selector, found ')'
(2254,39): run-time error CSS1025: Expected comma or open brace, found ')'
(2255,1): run-time error CSS1019: Unexpected token, found '$'
(2255,2): run-time error CSS1019: Unexpected token, found '('
(2255,3): run-time error CSS1019: Unexpected token, found '".SI-Content"'
(2255,16): run-time error CSS1019: Unexpected token, found ')'
(2255,18): run-time error CSS1030: Expected identifier, found 'click('
(2255,18): run-time error CSS1019: Unexpected token, found 'click('
(2255,33): run-time error CSS1031: Expected selector, found '('
(2255,33): run-time error CSS1025: Expected comma or open brace, found '('
(2262,2): run-time error CSS1019: Unexpected token, found ')'
(2264,10): run-time error CSS1031: Expected selector, found 'up('
(2264,10): run-time error CSS1025: Expected comma or open brace, found 'up('
(2272,10): run-time error CSS1031: Expected selector, found 'down('
(2272,10): run-time error CSS1025: Expected comma or open brace, found 'down('
(2296,1): run-time error CSS1019: Unexpected token, found '$'
(2296,2): run-time error CSS1019: Unexpected token, found '('
(2296,11): run-time error CSS1031: Expected selector, found ')'
(2296,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3048,2): run-time error CSS1019: Unexpected token, found ')'
(3051,1): run-time error CSS1019: Unexpected token, found '$'
(3051,2): run-time error CSS1019: Unexpected token, found '('
(3051,3): run-time error CSS1019: Unexpected token, found '".PT-Slider"'
(3051,15): run-time error CSS1019: Unexpected token, found ')'
(3051,17): run-time error CSS1030: Expected identifier, found 'slick('
(3051,17): run-time error CSS1019: Unexpected token, found 'slick('
(3051,23): run-time error CSS1019: Unexpected token, found '{'
(3052,18): run-time error CSS1030: Expected identifier, found ' '
(3052,19): run-time error CSS1031: Expected selector, found '1'
(3052,19): run-time error CSS1025: Expected comma or open brace, found '1'
(3057,1): run-time error CSS1019: Unexpected token, found '$'
(3057,2): run-time error CSS1019: Unexpected token, found '('
(3057,3): run-time error CSS1019: Unexpected token, found '".PT-SubSlider"'
(3057,18): run-time error CSS1019: Unexpected token, found ')'
(3057,20): run-time error CSS1030: Expected identifier, found 'slick('
(3057,20): run-time error CSS1019: Unexpected token, found 'slick('
(3057,26): run-time error CSS1019: Unexpected token, found '{'
(3058,18): run-time error CSS1030: Expected identifier, found ' '
(3058,19): run-time error CSS1031: Expected selector, found '3'
(3058,19): run-time error CSS1025: Expected comma or open brace, found '3'
(3066,1): run-time error CSS1019: Unexpected token, found '$'
(3066,2): run-time error CSS1019: Unexpected token, found '('
(3066,3): run-time error CSS1019: Unexpected token, found '"body"'
(3066,9): run-time error CSS1019: Unexpected token, found ')'
(3066,11): run-time error CSS1030: Expected identifier, found 'on('
(3066,11): run-time error CSS1019: Unexpected token, found 'on('
(3066,14): run-time error CSS1019: Unexpected token, found '"click"'
(3066,21): run-time error CSS1019: Unexpected token, found ','
(3066,23): run-time error CSS1019: Unexpected token, found '".a-info-product"'
(3066,40): run-time error CSS1019: Unexpected token, found ','
(3066,51): run-time error CSS1031: Expected selector, found '('
(3066,51): run-time error CSS1025: Expected comma or open brace, found '('
(3070,2): run-time error CSS1019: Unexpected token, found ')'
(3073,1): run-time error CSS1019: Unexpected token, found '$'
(3073,2): run-time error CSS1019: Unexpected token, found '('
(3073,11): run-time error CSS1031: Expected selector, found ')'
(3073,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3113,2): run-time error CSS1019: Unexpected token, found ')'
(3114,1): run-time error CSS1019: Unexpected token, found '$'
(3114,2): run-time error CSS1019: Unexpected token, found '('
(3114,3): run-time error CSS1019: Unexpected token, found '"#contactForm"'
(3114,17): run-time error CSS1019: Unexpected token, found ')'
(3114,19): run-time error CSS1030: Expected identifier, found 'validate('
(3114,19): run-time error CSS1019: Unexpected token, found 'validate('
(3114,28): run-time error CSS1019: Unexpected token, found '{'
(3115,19): run-time error CSS1030: Expected identifier, found ' '
(3115,29): run-time error CSS1031: Expected selector, found '('
(3115,29): run-time error CSS1025: Expected comma or open brace, found '('
(3126,6): run-time error CSS1019: Unexpected token, found ','
(3127,11): run-time error CSS1030: Expected identifier, found ' '
(3129,13): run-time error CSS1062: Expected semicolon or closing curly-brace, found ':'
(3134,6): run-time error CSS1019: Unexpected token, found ','
(3135,14): run-time error CSS1030: Expected identifier, found ' '
(3137,13): run-time error CSS1062: Expected semicolon or closing curly-brace, found ':'
(3143,1): run-time error CSS1019: Unexpected token, found '}'
(3143,2): run-time error CSS1019: Unexpected token, found ')'
(3145,1): run-time error CSS1019: Unexpected token, found '$'
(3145,2): run-time error CSS1019: Unexpected token, found '('
(3145,3): run-time error CSS1019: Unexpected token, found '".ctc-options"'
(3145,17): run-time error CSS1019: Unexpected token, found ')'
(3145,19): run-time error CSS1030: Expected identifier, found 'on('
(3145,19): run-time error CSS1019: Unexpected token, found 'on('
(3145,22): run-time error CSS1019: Unexpected token, found '"click"'
(3145,29): run-time error CSS1019: Unexpected token, found ','
(3145,31): run-time error CSS1019: Unexpected token, found '"li"'
(3145,35): run-time error CSS1019: Unexpected token, found ','
(3145,46): run-time error CSS1031: Expected selector, found '('
(3145,46): run-time error CSS1025: Expected comma or open brace, found '('
(3152,2): run-time error CSS1019: Unexpected token, found ')'
(3153,1): run-time error CSS1019: Unexpected token, found '$'
(3153,2): run-time error CSS1019: Unexpected token, found '('
(3153,3): run-time error CSS1019: Unexpected token, found '".ctc-options li:first-child"'
(3153,32): run-time error CSS1019: Unexpected token, found ')'
(3153,34): run-time error CSS1030: Expected identifier, found 'click('
(3153,34): run-time error CSS1019: Unexpected token, found 'click('
(3153,40): run-time error CSS1019: Unexpected token, found ')'
(3154,1): run-time error CSS1019: Unexpected token, found '$'
(3154,2): run-time error CSS1019: Unexpected token, found '('
(3154,11): run-time error CSS1031: Expected selector, found ')'
(3154,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3230,2): run-time error CSS1019: Unexpected token, found ')'
(3231,10): run-time error CSS1031: Expected selector, found 'IniciarPagoConekta('
(3231,10): run-time error CSS1025: Expected comma or open brace, found 'IniciarPagoConekta('
(3319,26): run-time error CSS1031: Expected selector, found '='
(3319,26): run-time error CSS1025: Expected comma or open brace, found '='
(3326,1): run-time error CSS1019: Unexpected token, found '$'
(3326,2): run-time error CSS1019: Unexpected token, found '('
(3326,11): run-time error CSS1031: Expected selector, found ')'
(3326,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3438,2): run-time error CSS1019: Unexpected token, found ')'
 */
$(function () {
    $(window).on("resize", event);
    function event() {
        var useropt = $(".userOptions").children("ul");
        closeCollapse(useropt, useropt.children("li").height() + 4, 0);
        var dropdown = $(".dropdown").children("ul");
        closeCollapse(dropdown, dropdown.children("li").height() + 1, 0);
        var menu = $(".menu-buttons").parent().children("ul");
        closeCollapse(menu, 0, 0);
        var CateMarcaResultados = $(".PR-Container .PR-Aside").children("section").children("ul");
        closeCollapse(CateMarcaResultados, 0, 0);

        var optionsNavigationResult = $(".PR-Container .PR-Right .select").parent("ul");
        closeCollapse(optionsNavigationResult, 0, 0);

        closeSearch()
    }
});

$(document).ajaxStart(function () {
    $(".loading").fadeIn("fast");
});

$(document).ajaxComplete(function (event, request, settings) {
    $(".loading").fadeOut("fast");

    if ($(".btn.co-pay").length > 0) {
        if ($(".btn.co-pay").is(":disabled")) {
            $(".btn.co-pay").removeAttr("disabled");
        }
    }

    if ($(".btn.co-back").length > 0) {
        if ($(".btn.co-back").is(":disabled")) {
            $(".btn.co-back").removeAttr("disabled");
        }
    }
});

function AjaxPost(url, data, success) {
    if (typeof url != "string")
        console.error("AjaxPost(url, data, success) : URL inválida");
    else if (typeof data != "string")
        console.error("AjaxPost(url, data, success) : DATA inválida");
    else if (typeof success != "function")
        console.error("AjaxPost(url, data, success) : SUCCESS inválido");
    else
        $.post({
            url: url,
            dataType: "JSON",
            data: data,
            cache:false,
            success: function (result) {
                if (data != null) {
                    var jsonResult
                    if (typeof result != 'object') {
                        jsonResult = JSON.parse(result);
                    } else {
                        jsonResult = result;
                    }


                    if (jsonResult.status) {
                        success(jsonResult);
                    }
                    else
                        Swal.fire('Ocurrió un error:', jsonResult.message, 'error');
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                Swal.fire(textStatus.toUpperCase() + " (" + jqXHR.status + "):", errorThrown, 'error');
            }
        });
}

function AjaxPostObj(url, data, success) {
    if (typeof url != "string")
        console.error("AjaxPostObj(url, data, success) : URL inválida");
    else if (typeof data != "object")
        console.error("AjaxPostObj(url, data, success) : DATA inválida");
    else if (typeof success != "function")
        console.error("AjaxPostObj(url, data, success) : SUCCESS inválido");
    else
        $.post({
            url: url,
            dataType: "JSON",
            data: data,
            cache: false,
            success: function (result) {
                if (result != null) {
                    var jsonResult;

                    if (typeof result != "object") {
                        jsonResult = JSON.parse(result);
                    }
                    else {
                        jsonResult = result;
                    }

                    if (jsonResult.Status) {
                        success(jsonResult);
                    }
                    else
                        Swal.fire('Ocurrió un error:', jsonResult.Message, 'error');
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                debugger;
                Swal.fire(textStatus.toUpperCase() + " (" + jqXHR.status + "):", errorThrown, 'error');
            }
        });
}

var updateCaptcha = function (token) {
    $("#ReCaptcha").val(token)
}
function openCollapse(element, buttonHeight, speed) {
    if (Math.round(element.height()) === Math.round(buttonHeight)) {
        if (buttonHeight === 0) {
            buttonHeight = element.children("li:visible:first").height();
        }
        var ulHeight = element.children("li:visible").length * buttonHeight;
        element.stop().animate({
            "height": ulHeight
        }, speed);
    } else {
        closeCollapse(element, speed, buttonHeight);
    }
}
function closeCollapse(element, speed, height) {
    element.stop().animate({
        "height": height
    }, speed, function () {
        element.attr("style", "");
    });
}
//Start Menu
$(".menu-buttons .menu > table tr:first-child td:last-child .fa").on("click", function () {
    var element = $(this).closest(".menu-container").children("ul");
    openCollapse(element, 0, 500);
});

$("nav > .menu-burger > .fa, .close-menu-burger").on("click", function () {
    $("nav.menu-burger").toggleClass("opened");
});
//End Menu

//Start UserMenu
$(".userOptions").children("ul").children("li:first-child").on("click", function () {
    var element = $(this).parent("ul");
    openCollapse(element, element.children("li").height() + 4, 100);
});
//End UserMenu
$(".product-menu").on("click", function () {
    $(".container-products").toggleClass("show")
});
//Start Searcher
//start autocomplete
$(".searcher form").on("submit", function () {
    return false;
});
$(".searcher form").on("keyup", applyDelay(searchNow,1500));
$(".close-search").on("click", closeSearch);
$(".searcher .icon").on("click", searchNow);
$(".searcher .search").on("keyup", function (ev) {
    if (ev.keyCode === 13) {
        var form = $(".searcher form:visible");
        var input = form.children("input");
        if (input.val().length < 2) {
            hideAutoComplete();
            return;
        }
        $.post("/busqueda/autocompletado", { SearchParam: input.val() }).done(success).fail(fail);
        function success(data) {
            $(".searcher .autocomplete").children().remove()
            $(".searcher .autocomplete").append(data)
            showAutocomplete();
        }
        function fail(data) {
            showAutocomplete();
        }
    }
});
$("#winModalSearcher #ddlManufacturer").change(setDdlProductModel);
$("#winModalSearcher #btnModalSearcherDo").click(modalSearcherDo);
$("#ddlManufacturer").change(setDdlProductModel);
$("#btnModalSearcherDo").click(modalSearcherDo);

function searchNow(evt) {
    if (evt.keyCode === 13) {
        evt.preventDefault();
    }
    if ((evt.which <= 90 && evt.which >= 48) || evt.type=="click") {
        var form = $(".searcher form:visible");
        var input = form.children("input");
        if (input.val().length < 2) {
            hideAutoComplete();
            return;
        }
        $.post("/busqueda/autocompletado",{ SearchParam: input.val() }).done(success).fail(fail);
    }
    function success(data) {
        $(".searcher .autocomplete").children().remove()
        $(".searcher .autocomplete").append(data)
        showAutocomplete();
    }
    function fail(data) {
        showAutocomplete();
    }
}
function applyDelay(fn, delay) {
    var timer = null;
    return function () {
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    };
}
function closeSearch() {
    $(".searcher .autocomplete").children().remove()
    hideAutoComplete();
}
function showAutocomplete() {
    $(".searcher .autocomplete").show();
    $(".close-search").show();
};
function hideAutoComplete() {
    $(".searcher .autocomplete").hide();
    $(".close-search").hide();
};
function setDdlProductModel() {
    var idManufacturer = this.value;

    var results = $.grep(productModelList, function (e, i) { return e.fkManufacturer != -1 && e.fkManufacturer == idManufacturer });

    $("#ddlModel").empty();
    $("#ddlModel").append("<option value=\"-1\">- SELECCIONE UN MODELO -</option>");

    if (results.length > 0) {
        $.each(results, function (key, value) {
            $("#ddlModel").append($("<option></option>")
                .attr("value", value.pkProductModel).text(value.Name));
        });

        $("#ddlModel").removeAttr("disabled");
    }
    else {
        $("#ddlModel").attr("disabled", "disabled");
    }
};
function modalSearcherDo() {
    var idManufacturer = $("#ddlManufacturer").val();
    var idModel = $("#ddlModel").val();
    var idCategory = $("#ddlCategory").val();
    //var x = document.getElementById("ddlModel").disabled;

    if (idManufacturer != -1) {
        var selectManufacturer = document.getElementById("ddlManufacturer");
        var valor = selectManufacturer.options[selectManufacturer.selectedIndex].text;
        if (idModel != -1) {
            //if (x == true) { idModel = "";}
            window.location.href = "/todas/todas?SearchParam=&Order=5&Distributor=" + idManufacturer + "&Page=1&PerPage=9&ViewMode=grid&Category=" + idCategory + "&Model=" + idModel;
        } else {
            if (idCategory == -1) {
                window.location.href = "/todas/" + valor.replace(/ /g, "-").toLowerCase();
            } else {
                var selectCategory = document.getElementById("ddlCategory");
                var valorC = selectCategory.options[selectCategory.selectedIndex].text;
                window.location.href = "/" + valorC.replace(/ /g, "-").toLowerCase() + "/" + valor.replace(/ /g, "-").toLowerCase();
            }
        }
    } else if (idCategory != -1) {
        var selectCategory = document.getElementById("ddlCategory");
        var valorC = selectCategory.options[selectCategory.selectedIndex].text;
        window.location.href = "/" + valorC.replace(/ /g, "-").toLowerCase() + "/todas";
    }
    //window.location.href = "/todas/todas?SearchParam=&Order=5&Distributor=" + idManufacturer + "&Page=1&PerPage=9&ViewMode=grid&Category=" + idCategory + "&Model=" + idModel;
};
var ppp;
var conektaToken;

$(document).ready(function () {
    if ($(".radio-opt.tdc").length > 0 || $(".radio-opt.pp").length > 0 || $(".radio-opt.oxxo").length > 0) {
        var checkoutForm = $("#checkout").validate({
            submitHandler: checkOutSubmitHandler,
            rules: {
                shipping: "required",
                payment: "required",
                Zip: {
                    required: true,
                    number: true
                },
                Phone: "phone",
                Email: {
                    required: true,
                    email: true,
                }
            },
            messages: {
                Street: "Campo obligatorio",
                ExteriorNumber: "Campo obligatorio",
                Zone: "Campo obligatorio",
                Region: "Campo obligatorio",
                Zip: {
                    required: "Campo obligatorio",
                    number: "Formato incorrecto",
                    maxlength: "Formato incorrecto"
                },
                City: "Campo obligatorio",
                State: "Campo obligatorio",
                Country: "Campo obligatorio",
                Phone: {
                    required: "Campo obligatorio"
                },
                Email: {
                    required: "Campo obligatorio"
                },
                Addressee: {
                    required: "Campo obligatorio"
                },
                shipping: "Campo obligatorio",
                payment: "Campo obligatorio"
            },
            errorPlacement: function (error, element) {
                if (element.is(":radio")) {
                    error.appendTo(element.parents('fieldset').children(".radioError"));
                }
                else {
                    error.insertAfter(element);
                }
            }
        });

        $("#creditCardForm input[name=card_name]").inputmask({
            regex: '[A-Za-z ÁÉÍÓÚáéíóúñ]+',
            placeholder: ''
        });

        $("#creditCardForm input[name=card_number]").inputmask({
            mask: "9999 9999 9999 9999",
            showMaskOnHover: false,
            showMaskOnFocus: false,
            placeholder: ' '
        });

        $("#creditCardForm input[name=card_cvv]").inputmask({
            mask: "9999",
            showMaskOnHover: false,
            showMaskOnFocus: false,
            placeholder: ' '
        });

        $(".co-add-shippingaddress #Email").inputmask({ alias: 'email' });
        $(".co-add-shippingaddress #Phone").inputmask({
            mask: "9999999999",
            showMaskOnHover: false,
            showMaskOnFocus: false,
            placeholder: ' '
        });
    }

    $("#checkout fieldset .checkout-control button").show();

    $(".co-new-shippingaddress").on("click", function () {
        $(".co-new-shippingaddress").addClass("noDisplay")
        $(".co-select-shippingaddress").addClass("noDisplay")
        $(".co-add-shippingaddress").removeClass("noDisplay")
        $(".co-return-to-shippingaddress").removeClass("noDisplay")
    });

    $(".co-return-to-shippingaddress").on("click", function () {
        $(".co-new-shippingaddress").removeClass("noDisplay")
        $(".co-select-shippingaddress").removeClass("noDisplay")
        $(".co-add-shippingaddress").addClass("noDisplay")
        $(".co-return-to-shippingaddress").addClass("noDisplay")
    });

    $("#notesShipping, #notesShippingPay").on("keyup change input", function () {
        let el = $(this);
        let max = parseInt(el.attr("maxlength")) || 200;
        let txt = el.val();

        if (txt.length > max) {
            el.val(txt.substring(0, max));
        }

        let span = el.next("span.contador");
        let usados = (el.val() || "").length;
        span.text(usados + "/" + max);

        span.removeClass("warning danger");
        if (usados > max - 20) {
            span.addClass("danger");
        } else if (usados > max - 50) {
            span.addClass("warning");
        }
    });

    $(".co-new-notespay").on("click", function () {
        var x = document.getElementById("addNotesPay");
        var boton = document.getElementById("btnNotaShippingPay");
        if (x.style.display === "none") {
            x.style.display = "block";
            boton.innerHTML = "Ocultar notas para la entrega";
        } else {
            x.style.display = "none";
            boton.innerHTML = "Agregar notas para la entrega";
        }
    });

    $("#checkout fieldset:nth-child(n+2)").hide();

    $(".co-pay").hide();

    $("#checkout .checkout-control").on("click", ".co-continue", function () {
        if ($("fieldset.address").is(":visible")
            && (
                $("fieldset .co-add-shippingaddress").is(":visible")
                && $(".co-add-shippingaddress #Phone").inputmask('unmaskedvalue').trim().length !== 10
            )
        ) {
            Swal.fire({
                title: '¡Alto!', text: 'El teléfono debe ser de 10 dígitos', type: 'warning', onClose: function () {
                    setTimeout(function () {
                        $(".co-add-shippingaddress #Phone").focus();
                    }, 500);
                }
            });

            event.preventDefault();

            return false;
        }

        var fieldset = $(this).parents("fieldset");
        if ($("#checkout").valid()) {
            fieldset.fadeOut("fast", function () {
                if (fieldset.next().prop("disabled")) {
                    fieldset.next().next().fadeIn("slow");
                    updateBreadcrumb(fieldset.index() + 3)
                } else {
                    updateBreadcrumb(fieldset.index() + 2)
                    fieldset.next().fadeIn("slow");
                }
                checkoutForm.resetForm();

                $($("#checkout .paymentmethod").children(".radio-opt")[0]).trigger("click")
            })
        }
    });

    $("#checkout .checkout-control").on("click", ".co-back", function () {
        var fieldset = $(this).parents("fieldset");
        fieldset.fadeOut("fast", function () {
            if (fieldset.prev().prop("disabled")) {
                updateBreadcrumb(fieldset.index() - 1)
                fieldset.prev().prev().fadeIn("slow");
            } else {
                updateBreadcrumb(fieldset.index())
                fieldset.prev().fadeIn("slow");
            }
            checkoutForm.resetForm();
        });
    });

    $("#checkout .radio-opt").on("click", function () {
        $(this).find("input[type=radio]").prop("checked", true).trigger("change");
    });

    $("#checkout .paymentmethod").on("change", "input[type=radio]", function (evt) {
        if ($("#checkout").valid()) {
            $(".co-pay").fadeIn("fast");

            creditCardForm(this.id == "pm_tdc");
            PaypalButtons(this.id == "pm_pptc");
        }
    });

    $("#checkout .shipping").on("change", "input[type=radio]", function () {
        var parent = $(this).parents(".radio-opt")
        var cost = parseFloat(parent.data("cost"));
        //        var taxP = parseFloat(parent.data("tax"))
        $("#shippingText").text(" $" + cost.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'))
        //var subtotal = parseFloat($("#subtotal").data("subtotal"));
        //subtotal = subtotal + cost;
        //$("#subtotal").text(" $" + subtotal.toFixed(2));
        //var tax = parseFloat($("#tax").data("tax"));
        //tax = tax + (cost * taxP)
        //$("#tax").text(" $" + tax.toFixed(2));
        var total = parseFloat($("#total").data("total"));
        //total = total + cost;

        if ($('#checkShippingInsurance').prop('checked')) {
            var parentCheck = $('#checkShippingInsurance').parents(".shippingIn")
            var costShippI = parseFloat(parentCheck.data("cost"));
            //alert('El check esta Seleccionado' + costShippI);
            $("#shippingInsu").text(" $" + costShippI.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'))
            total = total + cost + costShippI;
        }
        else {
            var costShippIn = parseFloat(0.00);
            $("#shippingInsu").text(" $" + costShippIn.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'))
            total = total + cost + costShippIn;
        }

        $("#total").text(" $" + total.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'));
        $("fieldset.address").prop("disabled", (cost < 1))
    });

    $('#checkShippingInsurance').on('change', function () {
        if ($(this).is(':checked')) {
            var parentCheck = $(this).parents(".shippingIn")
            var costShippI = parseFloat(parentCheck.data("cost"));
            $("#shippingInsu").text(" $" + costShippI.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'))

            var parent = $("[name=shipping]:checked").parents(".radio-opt")
            var cost = parseFloat(parent.data("cost"));

            var total = parseFloat($("#total").data("total"));
            total = total + cost + costShippI;
            $("#total").text(" $" + total.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'));
        } else {
            var costShippIn = parseFloat(0.00);
            $("#shippingInsu").text(" $" + costShippIn.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'))

            var parent = $("[name=shipping]:checked").parents(".radio-opt")
            var cost = parseFloat(parent.data("cost"));

            var total = parseFloat($("#total").data("total"));
            total = total + cost + costShippIn;
            $("#total").text(" $" + total.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'));
        }
    });

    $("#checkout .shipping").on("change", "input[type=radio]", function () {
        var pkShipping = parseInt($("[name=shipping]:checked").val());
        if (pkShipping == 0) {
            $("#divShippingInsurance").addClass("noDisplay");
            $(".divCalculosAlmacenes").css("display", "block");
            $(".divDispInmediata").css("display", "block");
            $(".divDispDiaSig").css("display", "block");
            $(".info").css("display", "block");
            $("input[type=checkbox]").prop("checked", false)

            var costShippIn = parseFloat(0.00);
            $("#shippingInsu").text(" $" + costShippIn.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'))
            var total = parseFloat($("#total").data("total"));
            $("#total").text(" $" + total.toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'));
        }
        else {
            $("#divShippingInsurance").removeClass("noDisplay");
            $(".divCalculosAlmacenes").css("display", "none");
            $(".divDispInmediata").css("display", "none");
            $(".divDispDiaSig").css("display", "none");
            $(".info").css("display", "none");
        }
    });

    // Register postMessage Listener for the iframe.
    if (window.addEventListener) {
        window.addEventListener("message", messageListener, false);
    }
    else if (window.attachEvent) {
        window.attachEvent("onmessage", messageListener);
    }
    else {
        log("Could not attach message listener", "debug");
        throw new Error("Can't attach message listener");
    }

    function messageListener(event) {
        try {
            var data = JSON.parse(event.data);

            if (data.action != "enableContinueButton" &&
                data.action != "disableContinueButton" &&
                data.action != "resizeHeightOfTheIframe" &&
                data.action != "loaded") {
                //console.error(data.action + (data.cause == undefined ? "" : ": " + data.cause));
            }
        }
        catch (ex) {
            //console.error(ex);
        }
    }

    if ($("[name=paymentmethod]:checked").parent().parent().hasClass("pptc")) {
        $("#paypalContinueButton").addClass("noDisplay");
    } else {
        $("#paypalContinueButton").removeClass("noDisplay");
    }
});

function updateBreadcrumb(step) {
    var breadcrumbs = $(".breadcrumb li");
    breadcrumbs.removeClass("active");

    $(breadcrumbs[step]).addClass("active");
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

$(document).on("click", ".co-shop-quantity a.less", updateItemShopCar);
$(document).on("click", ".co-shop-quantity a.more", updateItemShopCar);
$(document).on("click", ".co-item-drop a", function (evt) {
    evt.preventDefault();
    var element = this;
    $.get({
        url: element.href,
        params: {
            withCredentials: true
        }
    }).done(function (data) {
        if ($(element).attr("href").toLowerCase().search("view=true") > 0) {
            let count = $($.parseHTML(data)).filter("#countItems").text().trim();
            let mensaje = $($.parseHTML(data)).filter("#MessageItem").text();
            showMessage(mensaje)
            if (count == "0" || count == "1") {
                location.reload(true);
            } else {
                updateShoppingCarCounter(count);
                $("#shopCartAjax").html(data);
            }
        } else {
            showMessage(data.Message);
            $(".loading").fadeIn("fast");
            location.reload(true);
        }
    })
});

function updateItemShopCar(evt) {
    evt.preventDefault();
    var element = this;
    $.get({
        url: element.href,
        params: {
            withCredentials: true
        }
    }).done(done).fail(fail);

    function done(data) {
        var container = $(element).parents(".co-item");
        if (data.error) {
            location.reload(true);//container.remove();
            showMessage(data.error);
        } else {
            if (data.quantity == 0) {
                location.reload(true);//container.remove();
                showMessage(data.name + ". Ha sido retirado de su carrito")
            }
            if (data.count == 0) {
                location.reload(true);
            }
            updateShoppingCarCounter(data.count);
            container.find("a.quantity").text(data.quantity);
            container.find(".co-item-discount div").text(data.discount);
            container.find(".co-item-subtotal div").text(data.subtotal);
            $(".co-total td#BigSubtotal").text(data.bigsubtotal);
            $(".co-total td#BigDiscount").text(data.bigdiscount);
            $(".co-total td#BigTax").text(data.bigtax);
            $(".co-total td#BigTotal").text(data.bigtotal);
        }

        setTimeout(function () {
            $(".loading").fadeIn("fast");
        }, 0);
    }
    function fail() {
        //showMessage("Error al agregar el producto al carro de compras")
    }
}

$(document).scroll(function () {
    var div = $('.co-shoppingcar').offset();
    if (div == undefined)
        return
    var topDiv = div.top;
    var toFinish = $('.co-shoppingcar').height() - 100;
    var Actualscroll = $(this).scrollTop() + 50;
    if (Actualscroll > topDiv && Actualscroll < toFinish)
        $('.co-total').css('top', Actualscroll);
});

function creditCardForm(show) {
    if (show) {
        $("#creditCardForm").removeClass("noDisplay")
        /*$("#creditCardForm").slideDown(500, function () {
            $("[name=card_number]").focus();
        });*/
    }
    else {
        $("#creditCardForm").addClass("noDisplay");
        //$("#creditCardForm").slideUp("slow");
    }
}

function PaypalButtons(show) {
    if (show) {
        $("#paypal-button-container").removeClass("noDisplay");
        $("#paypalContinueButton").addClass("noDisplay");
    }
    else {
        $("#paypal-button-container").addClass("noDisplay");
        $("#paypalContinueButton").removeClass("noDisplay");
    }
}

function ObtenerDatosCheckout() {
    var params = {};
    params.ShippingID = parseInt($("[name=shipping]:checked").val());
    params.ShippingInsuranceID = parseInt($("[name=checkShippingInsurance]:checked").val());
    params.NotaShipping = $("#notesShipping").val() !== '' ? $("#notesShipping").val().trim() : $("#notesShippingPay").val().trim()

    if (params.ShippingID > 0) {
        if (!$(".co-select-shippingaddress").hasClass("noDisplay")) {
            params.ShippingAddressID = parseInt($("[name=address]:checked").val());
        }
        else {
            params.Street = $("#Street").val().trim();
            params.ExteriorNumber = $("#ExteriorNumber").val().trim();
            params.InteriorNumber = $("#InteriorNumber").val().trim();
            params.Zone = $("#Zone").val().trim();
            params.Region = $("#Region").val().trim();
            params.Zip = $("#Zip").val().trim();
            params.City = $("#City").val().trim();
            params.State = $("#State").val().trim();
            params.Country = $("#Country").val().trim();
            params.Phone = $("#Phone").val().trim();
            params.Email = $("#Email").val().trim();
            params.Addressee = $("#Addressee").val().trim();
        }
    }

    params.PaymentMethodID = parseInt($("[name=paymentmethod]:checked").val());

    if ($("[name=paymentmethod]:checked").parent().parent().hasClass("tdc")) {
        if (typeof conektaToken == "object") {
            params.ConektaToken = conektaToken.id;
            params.PayMethod = "card";

            if ($("select[name='monthly_installments']").length > 0 && $("[name=paymentmethod]:checked").parent().parent().hasClass("tdc")) {
                params.monthly_installments = parseInt($("select[name='monthly_installments']").val());
            }
            else {
                params.monthly_installments = 0;
            }
        }
    }
    else if ($("[name=paymentmethod]:checked").parent().parent().hasClass("oxxo"))
        params.PayMethod = "oxxo_cash";

    return params;
}

function IniciarPagoPayPal(redirect) {
    $(".loading").fadeIn("fast");

    var params = ObtenerDatosCheckout();

    AjaxPost("/pp/create", $.param(params), function (result) {
        $(".loading").fadeOut("fast");

        if (result.status) {
            var payID = result.data.id;
            var approval_url = result.data.approval_url;
            var user = result.data.user;
            var ecommSalesID = result.data.ecommSalesID;

            if (redirect) {
                window.location.href = approval_url;
                return;
            }

            ppp = PAYPAL.apps.PPP({
                "approvalUrl": approval_url,
                "payerFirstName": user.Firstname,
                "payerLastName": user.Lastname,
                "payerEmail": user.Email,
                "payerPhone": user.Phone,
                "payerTaxId": "",
                "placeholder": "ppplus",
                "country": "MX",
                "language": "es_MX",
                "enableContinue": "paypalContinueButton",
                "disableContinue": "paypalContinueButton",
                "mode": "sandbox",
                "rememberedCards": user.RememberedCards,
                onContinue: function (rememberedCards, payerId, token, term) {
                    $(".loading").fadeIn("fast");

                    $("#paypalContinueButton").attr("disabled", "disabled");

                    var shippingID = params.ShippingID;
                    params = {};
                    params.PayID = payID;
                    params.PayerID = payerId;

                    window.location.href = "/pp/execute?paymentId=" + params.PayID + "&payerID=" + params.PayerID + "&rememberedCards=" + rememberedCards + "&ecommSalesID=" + ecommSalesID + "&shippingID=" + shippingID;
                },
                onError: function (err) {
                    $(".loading").fadeOut("fast");
                    Swal.fire('Ocurrió un error:', err.cause, 'error');
                    $("#paypalContinueButton").removeAttr("disabled");
                }
            });
        }
    });
}
$(document).ready(function () {
    $("#register").validate({
        submitHandler: function (form) {
            let swalData = {};
            let showAlert = false;

            if ($("#register #IsCustomer").is(":checked") && ($("#register #Nif").val().trim() === "" || $("#register #Nif").val().trim().length <= 5)) {
                swalData = {
                    title: '¡Alto!', text: 'Debes indicar un RFC válido si ya eres cliente', type: 'warning', onClose: function () {
                        setTimeout(function () {
                            $("#register #Nif").focus();
                        }, 500);
                    }
                };
                showAlert = true;
            }
            else if ($("#register #Phone").inputmask('unmaskedvalue').trim().length < 10) {
                swalData = {
                    title: '¡Alto!', text: 'El teléfono debe ser mínimo de 10 dígitos.', type: 'warning', onClose: function () {
                        setTimeout(function () {
                            $("#register #Phone").focus();
                        }, 500);
                    }
                };
                showAlert = true;
            }
            else {
                if ($("#register #Phone").inputmask('unmaskedvalue').trim().length > 20) {
                    swalData = {
                        title: '¡Alto!', text: 'El teléfono no debe ser mayor de 20 dígitos.', type: 'warning', onClose: function () {
                            setTimeout(function () {
                                $("#register #Phone").focus();
                            }, 500);
                        }
                    };
                    showAlert = true;
                }
            }

            if (showAlert) {
                Swal.fire(swalData);
                return false;
            }

            return true;
        },
        rules: {
            Password: {
                minlength: 6,
            },
            PasswordConfirm: {
                equalTo: "#Password",
                minlength: 6,
            },
            Email: {
                email: true
            },
            Phone: {
                minlength: 10,
                maxlength: 20
            }
        },
        messages: {
            Username: "Campo obligatorio",
            Password: {
                required: "Campo obligatorio",
                minlength: "Introduzca al menos 6 caracteres"
            },
            PasswordConfirm: {
                required: "Campo obligatorio",
                equalTo: "Las contraseñas no coinciden",
                minlength: "Introduzca al menos 6 caracteres"
            },
            Firstname: "Campo obligatorio",
            Lastname: "Campo obligatorio",
            Email: {
                required: "Campo obligatorio",
                email: "Correo electrónico no válido"
            },
            Phone: {
                required: "Campo obligatorio",
                phone: "Teléfono no válido"
            },
            Nif: "Si es cliente de ctr, este campo es obligatorio",
        }
    });

    $("#register").on("change", "#IsCustomer", function () {
        if ($(this).is(":checked")) {
            $("#register .withCustomer").show();
        } else {
            $("#register .withCustomer").hide();
        }
    });

    $("#register #Username").inputmask({ regex: '[A-Za-z0-9_-]+', placeholder: '' });
    $("#register #Firstname").inputmask({ regex: '[A-Za-z ÁÉÍÓÚáéíóúñ]+', placeholder: '' });
    $("#register #Lastname").inputmask({ regex: '[A-Za-z ÁÉÍÓÚáéíóúñ]+', placeholder: '' });
    $("#register #Email").inputmask({ alias: 'email' });
    $("#register #Phone").inputmask({
        mask: "99999999999999999999",
        showMaskOnHover: false,
        showMaskOnFocus: false,
        placeholder: ' '
    });

    if ($("#IsCustomer").is(":checked")) {
        $(".withCustomer").css("display", "block");
    }
});
$(".mya .menu a").on("click", function (evt) {
    var hash = $(this).prop("hash").slice(1);
    showFormMyAccount(hash, $(".panel"))
})

$(".userNotification").on("click", function (evt) {
    var hash = "mya-pending-products";
    showFormMyAccount(hash, $(".panel"))
})

$("#addShippingAddress").on("click", function (evt) {
    $(".formShippingAddress h3").text("Nueva direccion de envío")
    evt.preventDefault();
    $("#addshippingaddress").find("#ID").val("")
    $("#addshippingaddress").find("#Principal").val("false")
    $(".formShippingAddress").fadeIn();
    $(".formShippingAddress form").trigger("reset");
})

$(".formShippingAddress").find("button[type=button]").on("click", function () {
    $(".formShippingAddress").fadeOut("fast", function () {
        $(".formShippingAddress form").trigger("reset");
    });
})

$(".mya-shipping-address table tbody").on("click", "a.eliminar", function (evt) {
    evt.preventDefault();
    $(".formShippingAddress form").trigger("reset");
    $(".formShippingAddress").fadeOut();
    var parent = $(this).parents("tr");
    AjaxPost("/mi-cuenta/DropShippingAddress", "ID=" + $(this).data("id"), function (data) {
        data.type = "error"
        if (data.status) {
            parent.remove();
            data.title = "Hecho";
            data.type = "success"
        }
        Swal.fire(data.title, data.message, data.type);
    });
})

$(".mya-shipping-address table tbody").on("click", "a.editar", function (evt) {
    evt.preventDefault();
    //obtener informacion de direccion de envio a editar y colocarlo dentro del form
    $(".formShippingAddress h3").text("Editar dirección de envío")
    $(".formShippingAddress").fadeIn();
    $.ajax({
        type: "GET",
        url: "/mi-cuenta/ShippingAddress",
        data: { id: $(this).data("id")},
        dataType: "json"
    }).done(function (data) {
        $.each(data[0], function (k, v) {
            if (k == "Principal") {
                $(".formShippingAddress form").find("#CheckPrincipal").prop("checked",v);
            }
            $(".formShippingAddress form").find("#" + k).val(v)
        });
    }).fail(function () {
        Swal.fire('Ocurrió un error:', jsonResult.message, 'error');
    });
    //$(".formShippingAddress form").validate();
})

$("#CheckPrincipal").on("change", function () {
    $(".formShippingAddress form").find("#Principal").val($("#CheckPrincipal").prop("checked"))
    //$("#CheckPrincipal").prop("checked")
})

function showFormMyAccount(form, elements) {
    var any = 0;
    var url, callback,dataType = "json";
    switch (form) {
        case "mya-info-account":
            url = "/mi-cuenta/MyInfo";
            dataType = "html"
            callback = getInformationAccount;
            //getInformationAccount();
            break;
        case "mya-shipping-address":
            url = "/mi-cuenta/ShippingAddress";
            callback = getShippingAddress;
            break;
        case "mya-password":
            $('#cpPassword').val('');
            $('#cpPasswordConfirm').val('');
            url = false;
            break;
        case "mya-orders":
            url = "/mi-cuenta/MyOrders";
            dataType = "html"
            callback = getMyOrders;
            break;
        case "mya-pending-products":
            url = "/mi-cuenta/PendingProducts";
            dataType = "html";
            callback = getPendingProducts;
            break;
        case "":
            url = false;
            break;
        default:
            return fail();
    }
    if (url) {
        $.ajax({
            type: "GET",
            url: url,
            dataType: dataType,
            cache: false
        }).done(callback).fail(fail);

    }
    $.each(elements, function (key, value) {
        if ($(value).css("display") == "block") {
            any++;
            var cl = $(value).attr("class").replace("panel ", "")
            if (cl !== form) {
                $(value).stop().fadeOut("fast", function () {
                    $("." + form).stop().fadeIn();
                })
            }
        }
    })
    if (any == 0) {
        $("." + form).stop().fadeIn(0);
    }
    function getInformationAccount(data) {
        
        $(".mya-info-account").empty();
        $(".mya-info-account").append(data)
        $(".mya-info-account").ready(function () {
            $("#customerDetails").validate({
                submitHandler: function (form) {
                    let swalData = {};
                    let showAlert = false;

                    if ($("#customerDetails #Phone").inputmask('unmaskedvalue').trim().length < 10) {
                        swalData = {
                            title: '¡Alto!', text: 'El teléfono debe ser mínimo de 10 dígitos.', type: 'warning', onClose: function () {
                                setTimeout(function () {
                                    $("#customerDetails #Phone").focus();
                                }, 500);
                            }
                        };
                        showAlert = true;
                    }
                    else {
                        if ($("#customerDetails #Phone").inputmask('unmaskedvalue').trim().length > 20) {
                            swalData = {
                                title: '¡Alto!', text: 'El teléfono no debe ser mayor de 20 dígitos.', type: 'warning', onClose: function () {
                                    setTimeout(function () {
                                        $("#customerDetails #Phone").focus();
                                    }, 500);
                                }
                            };
                            showAlert = true;
                        }
                    }

                    if (showAlert) {
                        Swal.fire(swalData);
                        return false;
                    }

                    AjaxPost("/mi-cuenta/SaveMyInfo", $(form).serialize(), function (data) {
                        if (data.message == "") {
                            showMessage("Actualizado correctamente");
                        } else {
                            Notiflix.Notify.Warning(data.message)
                        }
                        showFormMyAccount("mya-info-account", $(".mya .panel"));
                    });
                    return false;
                },
                rules: {
                    Email: {
                        email: true
                    },
                    Phone: "phone"
                },
                messages: {
                    Firstname: "Campo obligatorio",
                    Lastname: "Campo obligatorio",
                    Email: {
                        required: "Campo obligatorio",
                        email: "Correo electrónico no válido"
                    },
                    Phone: {
                        required: "Campo obligatorio"
                    },
                    LegalName: "Campo obligatorio",
                    ComercialName: "Campo obligatorio",
                    RFC: "Campo obligatorio",
                    Street: "Campo obligatorio",
                    ExteriorNumber: "Campo obligatorio",
                    InteriorNumber: "Campo obligatorio",
                    Zone: "Campo obligatorio",
                    Zip: "Campo obligatorio",
                    Region: "Campo obligatorio",
                    City: "Campo obligatorio",
                    State: "Campo obligatorio",
                    Country: "Campo obligatorio"
                }
            });
        });
        //$("#customerDetails").on("change", "#RFC", function (evt) {
        //    $.ajax({
        //        type: "POST",
        //        url: "/mi-cuenta/SearchCustomers",
        //        data: { rfc: $.trim($(this).val())},
        //        cache: false
        //    }).done(async function (data) {
        //        if (data.length > 0) {
        //            const inputOptions = new Promise((resolve) => {
        //                dataInputs = {}
        //                $.each(data, function (k, v) {
        //                    dataInputs[k] = v.RFC;
        //                })
        //                resolve(dataInputs)
        //            })

        //            const { value: rfc } = await Swal.fire({
        //                title: '<small>Se encontraron los siguientes datos de facturación</small>',
        //                input: 'select',
        //                inputOptions: inputOptions,
        //                inputPlaceholder: 'Seleccione su RFC',
        //                showCancelButton: true,
        //            })

        //            if (rfc) {
        //                $("#LegalName").val(data[rfc].LegalName)
        //                $("#ComercialName").val(data[rfc].ComercialName)
        //                $("#RFC").val(data[rfc].RFC)
        //                $("#Street").val(data[rfc].Street)
        //                $("#ExteriorNumber").val(data[rfc].ExteriorNumber)
        //                $("#InteriorNumber").val(data[rfc].InteriorNumber)
        //                $("#Zone").val(data[rfc].Zone)
        //                $("#Zip").val(data[rfc].Zip)
        //                $("#Region").val(data[rfc].Region)
        //                $("#City").val(data[rfc].City)
        //                $("#State").val(data[rfc].State)
        //                $("#Country").val(data[rfc].Country)
        //                $("#Customer").val(data[rfc].Customer)
        //            }
        //        }
        //    });
        //})
        $(".customerText").on("click", "#newCustomer", function () {
            $(".customerText").hide();
            $(".newCustomer").fadeIn(200);
            $(".editCustomer").show()
        });
        $(".customerText").on("click", "#searchCustomer", function () {
            $(".customerText").hide();
            $(".searchCustomer").fadeIn(200);
            $(".editCustomer").show()
        });
        $("#customerDetails").on("click", ".editCustomer", function () {
            $(".customerText").fadeIn(200);
            $(".searchCustomer").hide();
            $(".newCustomer").hide();
            $(".editCustomer").hide();
        });
        $("#customerDetails").on("click", ".searchRFC", function () {
            $.ajax({
                type: "POST",
                url: "/mi-cuenta/SearchCustomers",
                data: { rfc: $("#RFCToSearch").val()},
                cache: false
            }).done(function (data) {
                $(".RFCResults").empty().append(data);
                //if (data.length > 0) {
                //    const inputOptions = new Promise((resolve) => {
                //        dataInputs = {}
                //        $.each(data, function (k, v) {
                //            dataInputs[k] = v.RFC;
                //        })
                //        resolve(dataInputs)
                //    })

                //    const { value: rfc } = await Swal.fire({
                //        title: '<small>Se encontraron los siguientes datos de facturación</small>',
                //        input: 'select',
                //        inputOptions: inputOptions,
                //        inputPlaceholder: 'Seleccione su RFC',
                //        showCancelButton: true,
                //    })

                //    if (rfc) {
                //        $("#LegalName").val(data[rfc].LegalName)
                //        $("#ComercialName").val(data[rfc].ComercialName)
                //        $("#RFC").val(data[rfc].RFC)
                //        $("#Street").val(data[rfc].Street)
                //        $("#ExteriorNumber").val(data[rfc].ExteriorNumber)
                //        $("#InteriorNumber").val(data[rfc].InteriorNumber)
                //        $("#Zone").val(data[rfc].Zone)
                //        $("#Zip").val(data[rfc].Zip)
                //        $("#Region").val(data[rfc].Region)
                //        $("#City").val(data[rfc].City)
                //        $("#State").val(data[rfc].State)
                //        $("#Country").val(data[rfc].Country)
                //        $("#Customer").val(data[rfc].Customer)
                //    }
                //}
                $("#customerDetails").on("click", ".selectCustomer", function () {

                    $.post("/mi-cuenta/SaveMyInfoCustomer", { Customer: $(this).data("customer") }, function (data) {
                        data = JSON.parse(data);
                        if (data.message == "") {
                            showMessage("Actualizado correctamente");
                        } else {
                            Notiflix.Notify.Warning(data.message)
                        }
                        showFormMyAccount("mya-info-account", $(".mya .panel"));
                    })
                })
            }).fail(function () {
                alert("¡¡Ha ocurrido un error!!");
            })
        })
    }
    function getShippingAddress(data) {
        $(".mya-shipping-address table tbody tr").remove();
        $.each(data, function (k, v) {
            var labelRed = "";
            if (v.Phone == null || v.Phone == "") {
                labelRed = "<br/><span class='txtRed'>Dirección incompleta</span><br/>"
            }
            var tr = "<tr><td>" + ((v.Principal) ? "<span class='principal'><i class='fas fa-star'></i></span> " : "") +
                ((v.Street) ? v.Street : "") +
                ((v.ExteriorNumber) ? ", No. " + v.ExteriorNumber : "") +
                ((v.InteriorNumber) ? ", Int. " + v.InteriorNumber : "") +
                ((v.Region) ? ", Colonia: " + v.Region : "") +
                labelRed +
                "</td ><td>" + v.Zip + "</td> <td><a href='#' data-id='" + v.ID + "' class='btn-rounded editar px-1'>Editar</a><a href='#' data-id='" + v.ID + "' class='btn-rounded eliminar px-1'>Eliminar</a></td></tr >"
                $(".mya-shipping-address table tbody").append(tr);
        });
    }
    function getMyOrders(data) {
        $(".mya-orders").empty();
        $(".mya-orders").append(data);
    }
    function getPendingProducts(data) {
        $(".mya-pending-products").empty();
        $(".mya-pending-products").append(data);
    }
    function fail() {
        alert("¡¡¡Error!!!");
    }
}

function attachStarHover(m) {
    // Pintar por hover las estrellas hasta la posición actual
    m.on("mouseenter", ".rating-box.calificar .rating-star", function (e) {
        var parent = $(this).closest(".rating-box");
        var index = $(this).index();
        parent.children(".rating-star").removeClass("full-star").addClass("empty-star");
        for (var i = 0; i <= index; i++) {
            parent.children(".rating-star").eq(i).removeClass("empty-star").addClass("full-star");
        }
    });
    // Al quitar hover, restaurar el estado según la selección actual (data("stars"))
    m.on("mouseleave", ".rating-box.calificar", function (e) {
        var parent = $(this);
        var sel = parent.data("stars");
        // sel guarda un índice 0-based cuando se selecciona con click; si no existe, -1
        if (isNaN(sel)) sel = -1;
        parent.children(".rating-star").removeClass("full-star").addClass("empty-star");
        if (sel >= 0) {
            for (var i = 0; i <= sel; i++) {
                parent.children(".rating-star").eq(i).removeClass("empty-star").addClass("full-star");
            }
        }
    });
}

$(document).ready(function () {
    // Manejo global para detectar expiración de sesión o devolución de la página de login
    $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
        // Si el servidor devuelve 401, redirigir inmediatamente al login
        if (jqXHR && jqXHR.status === 401) {
            window.location.href = "/iniciar-sesion";
            return;
        }
        // Fallback: si la respuesta contiene la página de login (a veces el servidor devuelve HTML de login con 200)
        var resp = (jqXHR && jqXHR.responseText) ? jqXHR.responseText : null;
        if (typeof resp === "string" && resp.indexOf("Iniciar sesión") !== -1) {
            window.location.href = "/iniciar-sesion";
            return;
        }
    });

    // Otro filtro global: comprobar HTML devuelto en peticiones que completan con 200
    $(document).ajaxComplete(function (event, xhr, settings) {
        try {
            if (xhr && xhr.status === 200) {
                var ct = (xhr.getResponseHeader && xhr.getResponseHeader('Content-Type')) || "";
                if (ct.indexOf('text/html') !== -1) {
                    var txt = xhr.responseText || "";
                    // Detectores comunes de la página de login
                    if (txt.indexOf("Iniciar sesión") !== -1 || (txt.indexOf('<form') !== -1 && txt.indexOf('name=\"User\"') !== -1)) {
                        // protegerse contra bucles: solo si la petición venía de rutas de mi-cuenta o similares
                        if (settings && settings.url && settings.url.indexOf('/mi-cuenta') !== -1) {
                            window.location.href = "/iniciar-sesion";
                        } else {
                            // si es una llamada que no es de mi-cuenta pero devuelve la página de login, igualmente redirigimos
                            window.location.href = "/iniciar-sesion";
                        }
                    }
                }
            }
        } catch (e) {
            // no bloquear por errores de parsing
            console.error("ajaxComplete session check error", e);
        }
    });

    var hash = window.location.hash;
    if (hash === "") {
        hash = "mya-info-account";
    } else {
        hash = hash.slice(1)
    }
    if (window.location.pathname == "/mi-cuenta") {
        showFormMyAccount(hash, $(".mya .panel"));
    }
    jQuery.validator.addMethod("phone", function (value, element) {
        value = value.replace(/-/g, "");
        value = value.replace(/_/g, "");
        return value.length > 6;
    }, "Formato incorrecto");

    $("#addshippingaddress #Email").inputmask({ alias: 'email' });
    $("#addshippingaddress #Phone").inputmask({
        mask: "99999999999999999999",
        showMaskOnHover: false,
        showMaskOnFocus: false,
        placeholder: ' '
    });

    /************************/
    /* Cambio de contraseña */
    /************************/

    $("#changePassword").validate({
        submitHandler: function (form) {
            AjaxPost("/mi-cuenta/changepassword", $(form).serialize(), function () {
                Swal.fire('Contraseña actualizada', 'Tu contraseña ha sido cambiada exitosamente.', 'success');
            });

            return false;
        },
        rules: {
            cpPassword: "required",
            cpPasswordConfirm: {
                equalTo: "#cpPassword"
            }
        },
        messages: {
            cpPassword: "Campo obligatorio",
            cpPasswordConfirm: {
                required: "Campo obligatorio",
                equalTo: "Las contraseñas no coinciden"
            }
        }
    });

    /****************************/
    /****************************/
    $("#addshippingaddress").validate({
        submitHandler: function (form) {
            AjaxPost("/mi-cuenta/UpdateShippingAddress", $(form).serialize(), function (data) {
                showFormMyAccount("mya-shipping-address", $(".mya .panel"));
                Swal.fire('¡Hecho!', 'Se guardó correctamente la dirección de envío.', 'success');
                $(".formShippingAddress").fadeOut("fast", function () {
                    $(".formShippingAddress form").trigger("reset");
                });
            });
            return false;
        },
        rules: {
            Phone: "phone",
            Region: "required"
        },
        messages: {
            Phone: {
                required: "Campo obligatorio"
            },
            Email: {
                required: "Campo obligatorio"
            },
            Addressee: {
                required: "Campo obligatorio"
            },
            Street: "Campo obligatorio",
            ExteriorNumber: "Campo obligatorio",
            InteriorNumber: "Campo obligatorio",
            Zone: "Campo obligatorio",
            Zip: "Campo obligatorio",
            Region: "Campo obligatorio",
            City: "Campo obligatorio",
            State: "Campo obligatorio",
            Country: "Campo obligatorio"
        }
    });

    ///////////////////////
    $(".mya-orders").on("click", "a.btn-open", function () {
        var button = $(this).children("i");
        var container = $(this).parents(".mya-order");
        container.children(".mya-order-content").stop().slideToggle()
        if (button.hasClass("fa-chevron-down")) {
            button.removeClass("fa-chevron-down").addClass("fa-chevron-up");
        } else {
            button.removeClass("fa-chevron-up").addClass("fa-chevron-down");
        }
    })
    $(".mya-orders").on("click", "a.btn-buy", function () {
        var order = $(this).data("order");
        $.post("/carrito/Repurchase", { order: order }, function (data) {
            updateShoppingCarCounter(data.quantity)
            if (data.errors.length > 0) {
                Notiflix.Notify.Warning("Algunos productos no se encuentran disponibles actualmente.")
            }
            else
            {
                Notiflix.Notify.Success("Se han agregado todos los productos al carro.")
            }
        })
    })
    $(".mya-orders").on("submit","#searchOrders", function (evt) {
        evt.preventDefault();
        $.ajax({
            type: "GET",
            url: "/mi-cuenta/MyOrders",
            data: $(this).serialize(),
            dataType: "html",
            cache: false
        }).done(function get(data) {
            $(".mya-orders").empty();
            $(".mya-orders").append(data);
            }).fail(function fail() {
                alert("¡¡¡Error!!!");
            });
    })
    $(".mya-orders").on("click", ".btn-review", function (ev) {
        ev.preventDefault();
        let order = ev.currentTarget.dataset.idorder
        let product = ev.currentTarget.dataset.idproduct;
        let obj = {
            order: order,
            detalle: (product != undefined) ? product : null
        }
        $.ajax({
            type: "GET",
            url: "/mi-cuenta/modalreview",
            data: obj,
            dataType: "html",
            cache: false
        }).done(function get(data) {
            var m = $(data);
            m.modal();
            attachStarHover(m);
            m.on($.modal.AFTER_CLOSE, function (event, modal) {
                m.remove();
            });
            m.find("textarea").each(function () {
                let textarea = $(this);
                let span = textarea.next("span.contador");
                let max = parseInt(textarea.attr("maxlength")) || 400;
                span.text("0/" + max);
            });
            m.on("keyup change focus blur", "textarea", function (ev) {
                let el = $(ev.currentTarget)
                let max = parseInt(el.attr("maxlength")) || 400;//400;
                let txt = el.val();
                if (txt.length > max) {
                    el.val(txt.substring(0, max));
                }
                //el.closest("tr").find(".rv-opinion span").text(max - txt.length);
                let span = el.next("span");
                if (!span.length) {
                    // fallback: buscar dentro del contenedor del producto
                    span = el.closest(".reviews-products-container").find(".space-y-2-custom span").first();
                }
                //span.text(max - (el.val() || "").length);
                let usados = (el.val() || "").length;
                span.text(usados + "/" + max);

                span.removeClass("warning danger");
                if (usados > max - 50) {
                    span.addClass("danger");
                } else if (usados > max - 100) {
                    span.addClass("warning");
                }
            });
            m.on("click", ".calificar .rating-star", function (e) {
                var parent = $(e.currentTarget).closest(".rating-box");
                var index = $(e.currentTarget).index();
                parent.children(".rating-star").removeClass("full-star").addClass("empty-star");
                for (var i = 0; i <= index; i++) {
                    parent.children(".rating-star").eq(i).removeClass("empty-star").addClass("full-star");
                }
                parent.data("stars",index)
            })
            m.on("click", ".guardarProducto", function (e) {
                let container = $(this).closest(".reviews-products-container")
                let obj = getReview(container)
                let textarea = container.find("textarea");
                if (textarea.length && textarea.val().length < 1) {
                    Notiflix.Notify.Warning("Agregue un comentario para poder registrar su opinión.")
                    return;
                }
                if (obj.estrellas < 1) {
                    Notiflix.Notify.Warning("Seleccione una calificación válida.")
                    return;
                }
                saveReview([obj])
            })
            function getReview(parent) {
                let estrellas = parent.find(".rating-box").data("stars") + 1;
                if (isNaN(estrellas)) {
                    estrellas = 0;
                }
                return {
                    detalle: parent.data("detalle"),
                    estrellas: estrellas,
                    comentario: parent.find("textarea").val(),
                    estatus: null,
                    mensaje: null
                }
            }
            function saveReview(param) {
                $.ajax({
                    type: "POST",
                    url: "/mi-cuenta/savereviews",
                    data: {reviews:param},
                    cache: false
                }).done(function (data) {
                    if (data.Estatus) {
                        $.each(data.Lista, function (i, v) {
                            let item = $("div[data-detalle='" + v.Detalle + "']");
                            if (v.Estatus == false) {
                                if (item.find(".mensaje").length) {
                                    item.find(".mensaje").text(v.Mensaje)
                                } else {
                                    Notiflix.Notify.Warning(v.Mensaje)
                                }
                            }
                            else {
                                //item.find(".rv-opinion").text(v.Comentario)
                                // reemplazar textarea por el texto de la opinion
                                let textarea = item.find("textarea");
                                if (textarea.length) {
                                    textarea.next("span").remove();
                                    textarea.replaceWith($("<span>").addClass("rv-text").text(v.Comentario));
                                } else {
                                    // si ya no hay textarea, intentar actualizar rv-opinion o añadirlo
                                    let rv = item.find(".rv-text");
                                    if (rv.length) {
                                        rv.text(v.Comentario);
                                    } else {
                                        item.find(".space-y-2-custom").eq(1).append($("<span>").addClass("rv-text").text(v.Comentario));
                                    }
                                }
                                item.find(".guardarProducto").remove();
                                item.find(".rating-box").removeClass("calificar")
                            }
                        })
                    }
                    else {
                        Notiflix.Notify.Warning(data.Mensaje)
                    }
                }).fail(function () {
                    Notiflix.Notify.Warning("Sucedio un error, intente de nuevo más tarde.")
                });
            }
        }).fail(function fail() {
            Notiflix.Notify.Warning("Sucedio un error, intente de nuevo más tarde.")
        });
    });

    $(".mya-pending-products").on("click", ".btn-review", function (ev) {
        ev.preventDefault();
        let order = ev.currentTarget.dataset.idorder
        let product = ev.currentTarget.dataset.idproduct;
        let obj = {
            order: order,
            detalle: (product != undefined) ? product : null
        }
        $.ajax({
            type: "GET",
            url: "/mi-cuenta/modalreview",
            data: obj,
            dataType: "html",
            cache: false
        }).done(function get(data) {
            var m = $(data);
            m.modal();
            attachStarHover(m);
            m.on($.modal.AFTER_CLOSE, function (event, modal) {
                m.remove();
            });
            m.find("textarea").each(function () {
                let textarea = $(this);
                let span = textarea.next("span.contador");
                let max = parseInt(textarea.attr("maxlength")) || 400;
                span.text("0/" + max);
            });
            m.on("keyup change focus blur", "textarea", function (ev) {
                let el = $(ev.currentTarget)
                let max = parseInt(el.attr("maxlength")) || 400;//400;
                let txt = el.val();
                if (txt.length > max) {
                    el.val(txt.substring(0, max));
                }
                //el.closest("tr").find(".rv-opinion span").text(max - txt.length);
                let span = el.next("span");
                if (!span.length) {
                    // fallback: buscar dentro del contenedor del producto
                    span = el.closest(".reviews-products-container").find(".space-y-2-custom span").first();
                }
                //span.text(max - (el.val() || "").length);
                let usados = (el.val() || "").length;
                span.text(usados + "/" + max);

                span.removeClass("warning danger");
                if (usados > max - 50) {
                    span.addClass("danger");
                } else if (usados > max - 100) {
                    span.addClass("warning");
                }
            });
            m.on("click", ".calificar .rating-star", function (e) {
                var parent = $(e.currentTarget).closest(".rating-box");
                var index = $(e.currentTarget).index();
                parent.children(".rating-star").removeClass("full-star").addClass("empty-star");
                for (var i = 0; i <= index; i++) {
                    parent.children(".rating-star").eq(i).removeClass("empty-star").addClass("full-star");
                }
                parent.data("stars", index)
            })
            m.on("click", ".guardarProducto", function (e) {
                let container = $(this).closest(".reviews-products-container")
                let obj = getReview(container)
                let textarea = container.find("textarea");
                if (textarea.length && textarea.val().length < 1) {
                    Notiflix.Notify.Warning("Agregue un comentario para poder registrar su opinión.")
                    return;
                }
                if (obj.estrellas < 1) {
                    Notiflix.Notify.Warning("Seleccione una calificación válida.")
                    return;
                }
                saveReview([obj])
            })
            function getReview(parent) {
                let estrellas = parent.find(".rating-box").data("stars") + 1;
                if (isNaN(estrellas)) {
                    estrellas = 0;
                }
                return {
                    detalle: parent.data("detalle"),
                    estrellas: estrellas,
                    comentario: parent.find("textarea").val(),
                    estatus: null,
                    mensaje: null
                }
            }
            function saveReview(param) {
                $.ajax({
                    type: "POST",
                    url: "/mi-cuenta/savereviews",
                    data: { reviews: param },
                    cache: false
                }).done(function (data) {
                    if (data.Estatus) {
                        $.each(data.Lista, function (i, v) {
                            let item = $("div[data-detalle='" + v.Detalle + "']");
                            if (v.Estatus == false) {
                                if (item.find(".mensaje").length) {
                                    item.find(".mensaje").text(v.Mensaje)
                                } else {
                                    Notiflix.Notify.Warning(v.Mensaje)
                                }
                            }
                            else {
                                //item.find(".rv-opinion").text(v.Comentario)
                                // reemplazar textarea por el texto de la opinion
                                let textarea = item.find("textarea");
                                if (textarea.length) {
                                    textarea.next("span").remove();
                                    textarea.replaceWith($("<span>").addClass("rv-text").text(v.Comentario));
                                } else {
                                    // si ya no hay textarea, intentar actualizar rv-opinion o añadirlo
                                    let rv = item.find(".rv-text");
                                    if (rv.length) {
                                        rv.text(v.Comentario);
                                    } else {
                                        item.find(".space-y-2-custom").eq(1).append($("<span>").addClass("rv-text").text(v.Comentario));
                                    }
                                }
                                item.find(".guardarProducto").remove();
                                item.find(".rating-box").removeClass("calificar")
                                location.reload();
                            }
                        })
                    }
                    else {
                        Notiflix.Notify.Warning(data.Mensaje)
                    }
                }).fail(function () {
                    Notiflix.Notify.Warning("Sucedio un error, intente de nuevo más tarde.")
                });
            }
        }).fail(function fail() {
            Notiflix.Notify.Warning("Sucedio un error, intente de nuevo más tarde.")
        });
    });

    $(".mya-orders").on("click", ".btn-tracking", function (ev) {
        ev.preventDefault();
        let order = ev.currentTarget.dataset.idorder
        //let trackingnumber = ev.currentTarget.dataset.claveras
        let obj = {
            order: order
            //trackingnumber: trackingnumber
        }
        $.ajax({
            type: "GET",
            url: "/mi-cuenta/modaltracking",
            data: obj,
            dataType: "html",
            cache: false
        }).done(function get(data) {
            var m = $(data);
            m.modal();
            m.on($.modal.AFTER_CLOSE, function (event, modal) {
                m.remove();
            });
            m.on("click", ".btn-code-copy", function (e) {
                e.preventDefault();
                var $btn = $(this);
                var contenedor = $btn.prev('.m-tracking-code');
                var texto = (contenedor && contenedor.find) ? contenedor.find('.t-code-number').text() : "";

                if (!texto) {
                    Notiflix.Notify.Warning("No se encontró el código para copiar");
                    return;
                }

                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(texto).then(function () {
                        var svg = $btn.find('svg');
                        svg.css('fill', '#4CAF50');

                        Notiflix.Notify.Success("Código copiado al portapapeles");

                        setTimeout(function () {
                            svg.css('fill', '#64748b');
                        }, 1000);
                    }).catch(function (err) {
                        console.error('Error al copiar:', err);
                        Notiflix.Notify.Failure("No se pudo copiar el código");
                    });
                } else {
                    // Fallback para navegadores antiguos
                    var $temp = $('<input>');
                    $('body').append($temp);
                    $temp.val(texto).select();
                    try {
                        document.execCommand('copy');
                        Notiflix.Notify.Success("Código copiado al portapapeles");
                    } catch (err) {
                        Notiflix.Notify.Failure("No se pudo copiar el código");
                    }
                    $temp.remove();
                }
            });
            m.on("click", ".rastrearSeguimiento", function (e) {
                e.preventDefault();
                let claverastreo = e.currentTarget.dataset.clave
                let fkEcommShippingSalesType = e.currentTarget.dataset.esstype
                if (claverastreo != null) {
                    SeguimientoCompras(claverastreo, fkEcommShippingSalesType);
                }
            })
            function SeguimientoCompras(claverastreo, fkEcommShippingSalesType) {
                $.ajax({
                    type: "GET",
                    url: "/mi-cuenta/SeguimientoCompras",
                    data: { claveRastreo: claverastreo, fkEcommShippingSalesType: fkEcommShippingSalesType },
                    success: function (result) {
                        if (result.Status) {
                            window.open(result.Data);
                        }
                        else {
                            Swal.fire('ERROR', result.Message, 'error');
                        }
                    }
                });
            }
        }).fail(function fail() {
            Notiflix.Notify.Warning("Sucedio un error, intente de nuevo más tarde.")
        });
    }) 
});

function showMessage(content) {
    if (content == "" || content == undefined) {
        content = "Mensaje vacio"
    }

    Notiflix.Notify.Success(content);
    //$(".msg-background .msg-content").text("")
    //$(".msg-background .msg-content").append(content)
    //$(".msg-background").fadeIn("fast");
    //var maxSeconds = 3
    //$(".msg-time-close").text(maxSeconds);
    //var cancel = setInterval(function () {
    //    maxSeconds--;
    //    $(".msg-time-close").text(maxSeconds);
    //    if (maxSeconds < 1) {
    //        hideMessage();
    //        clearInterval(cancel);
    //    }
    //}, 1000);
}
function hideMessage() {
    //$(".msg-background").fadeOut("fast", function () {
    //    $(".msg-background .msg-content").text("")
    //});
}

//$(".msg-close").on("click", function (evt) {
//    evt.preventDefault();
//    hideMessage();
//})
$("#loginForm").validate({
    rules: {
        User: {
            required: true,
            //email: true,
        },
        Password: "required"
    },
    messages: {
        User: {
            required: "El correo de usuario es obligatorio.",
            email: "El correo eléctronico no es valido."
        },
        Password: "Este campo es obligatorio.",
    }
})
$("#restorePasswordForm #Email").inputmask({ alias: 'email' })
$("#restorePasswordForm").validate({
    submitHandler: function (form) {
        AjaxPost("/iniciar-sesion/RestoreRequest", $(form).serialize(), function (data) {
            var type, title;
            if (data.status) {
                type = "success";
                title = "Listo";
            } else {
                type = "error";
                title = "Ocurrió un error:";
            }
            Swal.fire(title, data.message , type);
        });
        return false;
    },
    rules: {
        Email: {
            required: true,
            email: true,
        }
    },
    messages: {
        Email: {
            required: "El correo de usuario es obligatorio.",
            email: "El correo eléctronico no es valido."
        }
    }
});
if ($("#newsletter").length > 0) {
    $("#newsletter").validate({
        submitHandler: function (form) {
            $.ajax({
                type: "POST",
                url: "/newsletter",
                dataType: "json",
                data: $(form).serialize(),
            }).done(function (data) {
                data = JSON.parse(data)
                var title = ""
                var type = "";
                if (data.status) {
                    title = "Hecho"
                    type = "success"
                } else {
                    title = "Espera"
                    type = "warning"

                }
                Swal.fire({
                    title: title, text: data.mensaje, type: type, showConfirmButton: true, timer: 2000, onClose: function () {
                        setTimeout(function () {
                            $("input[name='mail']").focus();
                        }, 500);
                    }
                });
            }).fail(function (data) {
                Swal.fire({
                    title: 'Ocurrió un error:', text: data.mensaje, type: 'error', onClose: function () {
                        setTimeout(function () {
                            $("input[name='mail']").focus();
                        }, 500);
                    }
                });
            });
            return false;
        },
        rules: {
            mail: {
                email: true,
                required: true
            },
        },
        messages: {
            mail: {
                email: "Formato de email incorrecto.",
                required: "Es necesario introducir su correo electrónico."
            }
        },
        errorPlacement: function (error, element) {
            error.css("display", "block")
            error.css("fontWeight", "600")
            error.insertAfter($("#newsletter").children("input[type=submit]"));
        }
    });

    $("#newsletter input[type=email]").inputmask({ alias: 'email' });
}
$(document).on("click", ".addToCar", addToCar);
$(document).on("click", ".btn-addnew", addToCarForMessage);
$(document).on("submit", "form.co-shop-quantity", function (evt) {
    evt.preventDefault();
    var form = $(this);
    var element = this;
    $.get({
        url: form.attr("action"),
        data: form.serialize(),
        params: {
            withCredentials: true
        }
    }).done(function (data) {
        if (form.find("[name=view]").val() === "True") {
            let count = $($.parseHTML(data)).filter("#countItems").text();
            let mensaje = $($.parseHTML(data)).filter("#MessageItem").text();
            showMessage(mensaje)
            updateShoppingCarCounter(count);
            $("#shopCartAjax").html(data);
        } else {
            var container = $(element).parents(".co-item");
            if (data.Quantity == 0) {
                location.reload(true);//container.remove();
            }
            if (data.Count == 0) {
                location.reload(true);
            }
            //showMessage(data.Message)
            mostrarMensaje(data.IdProduct, data.Message, data.TituloMensaje, data.CodeProduct);
            updateShoppingCarCounter(data.Count);
            container.find("a.quantity").text(data.Quantity);
            container.find(".co-item-discount div").text(data.Discount);
            container.find(".co-item-subtotal div").text(data.Subtotal);
            $(".co-total td#BigSubtotal").text(data.BigSubtotal);
            $(".co-total td#BigDiscount").text(data.BigDiscount);
            $(".co-total td#BigTax").text(data.BigTax);
            $(".co-total td#BigTotal").text(data.BigTotal);
        }
    }).fail(fail);
})
$(document).on("submit", "form.co-shop-promotion", function (evt) {
    evt.preventDefault();
    var form = $(this);
    var element = this;

    $.get({
        url: form.attr("action"),
        data: form.serialize(),
        params: {
            withCredentials: true
        }
    }).done(function (data) {
        if (data !== false) {
            updateShoppingCarCounter(data)
            showMessage("Los productos han sido agregados a su carrito")
        } else {
            showMessage("Error al agregar la promoción.")
        }
    }).fail(function () {
        showMessage("Error al agregar la promoción.")
    });
})

$(document).on("click", "form.co-shop-quantity.desc input[type=button]", function (evt) {
    var accion = $(this).attr("value");
    var input = $(this).parent(".control").children(".quantity");
    var inputId = $(this).parent(".control").children(".Id");
    var actual = input.val()
    var id = inputId.attr("value");
    var max = input.attr("max");
    switch (accion) {
        case '-':
            actual--;
            break;
        case '+':
            actual++;
            break;
    }
    if (actual > 0 && actual <= max) {
        input.val(actual);
        //if (input.data("update")) {
        //    //actualizar el carro de compras via ajax con el id del producto
        //    $(".quantity").submit();
        //}
    }
    evt.preventDefault()
});

$(document).on("click", "form.co-shop-quantity.fixLine input[type=button]", function (evt) {
    var accion = $(this).attr("value");
    var input = $(this).parent(".control").children(".quantity");
    var inputId = $(this).parent(".control").children(".Id");
    var actual = input.val()
    var id = inputId.attr("value");
    var max = input.attr("max");
    switch (accion) {
        case '-':
            actual--;
            break;
        case '+':
            actual++;
            break;
    }
    if (actual > 0 && actual <= max) {
        input.val(actual);
        //if (input.data("update")) {
        //    //actualizar el carro de compras via ajax con el id del producto
        //    $(".quantity").submit();
        //}

        $.get({
            url: "/carrito/AddToShoppingCart",
            data: { Id: id, Quantity: actual, view: true },
            params: {
                withCredentials: true
            }
        }).done(function (data) {
            let count = $($.parseHTML(data)).filter("#countItems").text();
            let mensaje = $($.parseHTML(data)).filter("#MessageItem").text();
            showMessage(mensaje)
            updateShoppingCarCounter(count);
            $("#shopCartAjax").html(data);
        }).fail(fail);
    }
    else if (actual > max) {
        Notiflix.Notify.Warning("No se puede actualizar la cantidad del producto, el máximo de existencia es: " + max);
    }
    else {
        Notiflix.Notify.Warning("El valor de la cantidad del producto debe ser mayor a 0 o igual a 1.");
    }
    evt.preventDefault()
});


function fail() {
    showMessage("Error al agregar el producto al carro de compras")
}

function updateShoppingCarCounter(count){
    if (count > 0) {
        $(".co-count span").text(count);
        $(".co-count span").fadeIn();
    } else {
        $(".co-count span").fadeOut(0);
    }
}

function addToCar(evt) {
    evt.preventDefault();
    var link = $(this)[0];
    if (link.href == undefined) {
        link = $(this).children("a")[0];
    }
    $.get({
        url: link.href,
        params: {
            withCredentials: true
        }
    }).done(function (data) {
        updateShoppingCarCounter(data.Count);
        //showMessage(data.Message)
        mostrarMensaje(data.IdProduct, data.Message, data.TituloMensaje, data.CodeProduct);
    }).fail(fail);
}

function addToCarForMessage(evt) {
    evt.preventDefault();
    var link = $(this)[0];
    if (link.href == undefined) {
        link = $(this).children("a")[0];
    }

    $.get({
        url: link.href,
        params: {
            withCredentials: true
        }
    }).done(function (data) {
        updateShoppingCarCounter(data.Count);
        var msj = data.TituloMensaje + ' ' + data.Message;
        showMessage(msj);
    }).fail(fail);
}

$("form .buyNow").click(function () {
    $(this).closest("form").find("input[name=Button]").attr("value", "buyNow");
    //$(this).closest("form").submit();
});

function mostrarMensaje(id, mensaje, titulo, code) {
    setTimeout(function () { $(".loading").fadeIn("fast"); }, 0);
    $.get({
        url: "/carrito/recommendedproducts",
        data: { idProduct: id, mensaje: mensaje, tituloMensaje: titulo, codeProduct: code }
    }).done(function get(data) {
        $("#contenido").empty();
        $("#contenido").append(data);
        document.getElementById("sidebar").style.width = "410px";
        $("#fondo").fadeIn();
        document.getElementById("contenido").style.display = "block";
        $("body").css("overflow-y", "hidden");
    }).fail(fail);
}

function ocultarMensaje() {
    document.getElementById("sidebar").style.width = "0";
    $("#fondo").fadeOut();
    document.getElementById("contenido").style.display = "none";
    $("body").css("overflow-y", "scroll");
}

$("#fondo").click(function () {
    $("#fondo").fadeOut();
    document.getElementById("contenido").style.display = "none";
    $("body").css("overflow-y", "scroll");
});
//Start Full-Slider
$('.Full-Slider').children(".FS-Slider").on('afterChange', SlickEvents);
$('.Full-Slider').children(".FS-Slider").on('init', SlickEvents);
$('.Full-Slider').children(".FS-Slider").slick({
    dots: true,
    infinite: true,
    speed: 500,
    arrows: false,
    slidesToShow: 1,
    adaptiveHeight: true,
    autoplay: true,
    autoplaySpeed: 2000,
});

function SlickEvents() {
    //esto forza a redimencionar la barra de socialmedia a la medida del slider
    var heightSlider = $(".FS-Slider").height();
    var heightSocials = calculateHeightSocial($(".FS-SocialMedia").children("li").children("a").parent("li"));
    $(".FS-SocialMedia").children("li").children(".line").css("height", (heightSlider - heightSocials) / 2)
    function calculateHeightSocial(objects) {
        var TotalHeight = 0;
        for (var i = 0; i < objects.length; i++) {
            TotalHeight = TotalHeight + objects[0].offsetHeight;
        }
        return TotalHeight;
    }
}
$(window).resize(SlickEvents);
//end Full-Slider

// Start Slider-Images
$(".Slider-Images>div").children(".SI-Slider").slick({
    dots: false,
    infinite: true,
    speed: 500,
    arrows: true,
    slidesToShow: 5,
    adaptiveHeight: true,
    responsive: [
        {
            breakpoint: 968,
            settings: {
                slidesToShow: 4
            }
        },
        {
            breakpoint: 768,
            settings: {
                slidesToShow: 3
            }
        },
        {
            breakpoint: 480,
            settings: {
                slidesToShow: 1
            }
        }
    ]
})/*.on('setPosition', function (event, slick) {
        //Si el slider de lo mas vendido tiene diferentes tamaños se puede activar este evento para redimencionar los slides al mismo tamaño
        //slick.$slides.css('height', slick.$slider.height()+ 'px');
    })*/;
// End Slider-Images

$(".Slider-Images>div").children(".SI-Slider").on('setPosition', function () {
    $(".SI-Content").on("mouseenter", up);
    $(".SI-Content").on("mouseleave", down);
//    $(".SI-Content").off("click", "a.addToCar");
  ///  $(".SI-Content").on("click", "a.addToCar", addToCar);
});

//Start Slider lo mas vendido
$(".SI-Content").on("mouseenter", up);
$(".SI-Content").on("mouseleave", down);
$(".SI-Content").click(function (ev) {
    if (!($(ev.target).is("a") || $(ev.target).closest("a").is("a"))) {
        if ($(this).children(".SI-Face").children(".SI-ToHide").css("opacity") == "1")
            $(this).trigger("mouseenter");
        else
            $(this).trigger("mouseleave");
    }
});

function up() {
    $(this).children(".SI-Face").children(".SI-ToHide").animate({
        opacity: 0
    }, 0);
    $(this).children(".SI-ToShow").stop().animate({
        opacity: 1
    }, 200);
}
function down() {
    $(this).children(".SI-Face").children(".SI-ToHide").animate({
        opacity: 1
    }, 0);
    $(this).children(".SI-ToShow").stop().animate({
        opacity: 0
    }, 200);
}
    //End Slider lo mas vendido


//Slider proceso de compra
//$(".pp-slider").slick({
//    dots: true,
//    infinite: true,
//    speed: 500,
//    arrows: true,
//    slidesToShow: 1,
//    autoplay: true,
//    autoplaySpeed: 4000,
//    fade: true,
//    pauseOnHover: true,
//    pauseOnFocus: true,
//});
$(document).ready(function () {
    ////
    //Start opciones de paginacion
    ///start modo de visualizacion
    $(".PR-Container .ViewMode i").on("click", function () {
        var mode = $(this).data("viewmode");
        $(".PR-Container .ViewMode i").removeClass("active");
        $(this).addClass("active");
        $(".PR-Product").removeClass("PR-grid").removeClass("PR-list").addClass("PR-" + mode);
        updateQueryStringParam("ViewMode", mode)
    })
    ///end modo visualizacion

    ///Start orden
    $(".PR-Container .order").children("ul").children("li:first-child").on("click", function () {
        var element = $(this).parent("ul");
        openCollapse(element, element.children("li").height(), 100);
    });
    $(".PR-Container .order").children("ul").children("li:nth-child(n+2)").on("click", function () {
        var order = $(".PR-Container .order li.select");
        closeCollapse($(this).parent("ul"), 0, 0);
        order.data("order", $(this).data("order"));
        order.children("span").text($(this).text());
        $(".PR-Pager").data("page", 1);
        changePage();
    });
    ///End orden

    ///Start numero de resultados
    $(".PR-Container .numResults").children("ul").children("li:first-child").on("click", function () {
        var element = $(this).parent("ul");
        openCollapse(element, element.children("li").height(), 100);
    });
    $(".PR-Container .numResults").children("ul").children("li:nth-child(n+2)").on("click", function () {
        var numResult = $(".PR-Container .numResults li.select");
        closeCollapse($(this).parent("ul"), 0, 0);
        numResult.data("perpage", $(this).data("perpage"));
        numResult.children("span").text($(this).text());
        $(".PR-Pager").data("page", 1);
        changePage();
    })
    ///End numero de resultados

    //Nuevo filtro con checks
    $('#selectModels, #selectModelsMob').on('select2:select', function (e) {
        // Se dispara cuando se selecciona UNA opción.
        const dato = e.params.data;
        changePage();
    });

    $('#selectModels, #selectModelsMob').on('select2:unselect', function (e) {
        // Se dispara cuando se elimina UNA opción.
        const dato = e.params.data;
        const models = $('#selectModels').val();
        if (models.length == 0) {
            deleteParamURL('Model');
        }

        changePage();
    });

    $('#selectModels, #selectModelsMob').on('select2:clearing', function () {
        // Se dispara cuando se eliminan TODAS las opciones.
        deleteParamURL('Model');
        changePage();
    });

    $(".PR-Container .PR-Aside").children("div").children("label").children("input").on("click", function () {
        var key = Object.keys($(this).data())[0];
        var data = $(this).data(key);
        $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-category]").prop('checked', false);
        $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-distributor]").prop('checked', false);
        $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-promocion]").prop('checked', false);
        $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-destacar]").prop('checked', false);

        if (key == "promocion") {
            if (this.checked) {
                const checkboxes = document.getElementsByName("checkPromo");

                for (var checkbox of checkboxes) {
                    if (this != checkbox) {
                        checkbox.checked = false;
                    }
                }
            }
        }
        else {
            var checkboxes = null;
            if (key == "category") {
                checkboxes = document.getElementsByName("checkCategory");
                ValidarChecks(checkboxes, this);
            }
            else if (key == "distributor") {
                checkboxes = document.getElementsByName("checkBrand");
                ValidarChecks(checkboxes, this);
            }
        }

        var ids = "";
        $(".PR-Pager").data("page", 1);
        var actives = $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-" + key + "]:checked");
        for (var i = 0; i < actives.length; i++) {
            if (i != 0) {
                ids = ids + ",";
            }
            ids = ids + $(actives[i]).data(key);
        }

        const txtCont = "Varios productos";
        var isDes = $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-destacar]:checked").length == 1 ? true : false;
        if (key == "category") {
            if (actives.length >= 2) {
                const h1Element = document.getElementById('h1-toner');
                if (h1Element) {
                    if (!isDes) {
                        h1Element.textContent = txtCont;
                    }
                }
            }
        }
        else if (key == "destacar") {
            const h1Element = document.getElementById('h1-toner');
            if (h1Element) {
                if (isDes) {
                    h1Element.textContent = "Productos destacados";
                }
                else {
                    h1Element.textContent = txtCont;
                }
            }
        }

        const valores = $('#selectModels').val();
        var idModels = "";
        if (valores.length > 0) {
            valores.forEach(function (valor) {
                idModels += valor + ","
            });

            updateQueryStringParam("Model", idModels.slice(0, -1));
        } else {
            var urlPage = new URL(window.location.href), getModel = urlPage.searchParams.get('Model');
            if (getModel != null) {
                delete Params["Model"];
                updateQueryStringParam("Model", "-1");
            }
        }

        updateQueryStringParam(key[0].toUpperCase() + key.slice(1), ids)
        changePage();
    })
    //Fin de nuevo filtro

    //Apertura del panel de filtros en mobile
    $(".btn-abrir-filtros").on("click", function () {
        const panelFiltros = document.getElementById('panel-filtros-mobile');
        panelFiltros.classList.add('visible');

        $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-category]").prop('checked', false);
        $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-distributor]").prop('checked', false);
        $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-promocion]").prop('checked', false);
        $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-destacar]").prop('checked', false);
    })

    $(".btn-cerrar-filtros").on("click", function () {
        const panelFiltros = document.getElementById('panel-filtros-mobile');
        panelFiltros.classList.remove('visible');
    })

    //Filtros en panel
    $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input").on("click", function () {
        var key = Object.keys($(this).data())[0];
        var data = $(this).data(key);

        if (key == "promocion") {
            if (this.checked) {
                const checkboxes = document.getElementsByName("checkPromoMob");

                for (var checkbox of checkboxes) {
                    if (this != checkbox) {
                        checkbox.checked = false;
                    }
                }
            }
        }
        else {
            var checkboxes = null;
            if (key == "category") {
                checkboxes = document.getElementsByName("checkCategoryMob");
                ValidarChecks(checkboxes, this);
            }
            else if (key == "distributor") {
                checkboxes = document.getElementsByName("checkBrandMob");
                ValidarChecks(checkboxes, this);
            }
        }

        var ids = "";
        $(".PR-Pager").data("page", 1);
        var actives = $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-" + key + "]:checked");
        for (var i = 0; i < actives.length; i++) {
            if (i != 0) {
                ids = ids + ",";
            }
            ids = ids + $(actives[i]).data(key);
        }

        const txtCont = "Varios productos";
        var isDes = $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-destacar]:checked").length == 1 ? true : false;
        if (key == "category") {
            if (actives.length >= 2) {
                const h1Element = document.getElementById('h1-toner');
                if (h1Element) {
                    if (!isDes) {
                        h1Element.textContent = txtCont;
                    }
                }
            }
        }
        else if (key == "destacar") {
            const h1Element = document.getElementById('h1-toner');
            if (h1Element) {
                if (isDes) {
                    h1Element.textContent = "Productos destacados";
                }
                else {
                    h1Element.textContent = txtCont;
                }
            }
        }

        const valores = $('#selectModelsMob').val();
        var idModels = "";
        if (valores.length > 0) {
            valores.forEach(function (valor) {
                idModels += valor + ","
            });

            updateQueryStringParam("Model", idModels.slice(0, -1));
        } else {
            var urlPage = new URL(window.location.href), getModel = urlPage.searchParams.get('Model');
            if (getModel != null) {
                delete Params["Model"];
                updateQueryStringParam("Model", "-1");
            }
        }

        updateQueryStringParam(key[0].toUpperCase() + key.slice(1), ids)
        changePage();
    });
    //Fin del panel de filtros en mobile

    //Validar checks
    function ValidarChecks(checkboxes, elemento) {
        if (checkboxes != null) {
            if (elemento != checkboxes[0]) {
                var key2 = Object.keys($(checkboxes[0]).data())[0];
                var data2 = $(checkboxes[0]).data(key2);

                if (data2 == "-1") {
                    checkboxes[0].checked = false;
                }
            }
            else {
                for (var checkbox of checkboxes) {
                    if (elemento != checkbox) {
                        checkbox.checked = false;
                    }
                }
            }
        }
    }
    //Fin

    ///Start filtro por categorias y marca
    $(".PR-Container .PR-Aside").children("section").children("p").on("click", function () {
        if ($(this).children(".noDisplay").css("display") === "block") {
            var element = $(this).parent("section").children("ul");
            openCollapse(element, 0, 200);
        }
    })
    $(".PR-Container .PR-Aside").children("section").children("ul").children("li").on("click", function () {
        updateQueryStringParam("SearchParam", "")
        var key = Object.keys($(this).data())[0];
        var data = $(this).data(key);

        if (key == "destacar") {
            var className = $(".PR-Container .PR-Aside li[data-destacar]").attr('class');
            if (className == 'active') {
                $(".PR-Container .PR-Aside li[data-destacar]").removeClass("active");
            }
            else {
                $(".PR-Container .PR-Aside p[data-" + key + "]").parent("section").children("ul").children("li").removeClass("active") //elimina la clase active en el caso de categorías y marcas que tiene por default marcado el "TODAS"
                $(this).toggleClass("active"); //Agrega la clase active al <li> presionado
                DesactivaFiltros(true,true,false,true);
            }
        }
        else if (key == "promocion") {
            var classNameP = $(".PR-Container .PR-Aside li[data-promocion]").attr('class');
            if (classNameP == 'active') {
                $(".PR-Container .PR-Aside li[data-promocion]").removeClass("active");
                $(".PR-Container .PR-Aside li[data-promocion=" + data + "]").addClass("active");
            }
            else {
                $(".PR-Container .PR-Aside p[data-" + key + "]").parent("section").children("ul").children("li").removeClass("active")
                $(this).toggleClass("active");
                DesactivaFiltros(true, true, true, false);
            }
        }
        else {
            $(".PR-Container .PR-Aside p[data-" + key + "]").parent("section").children("ul").children("li").removeClass("active")
            $(this).toggleClass("active");
            DesactivaFiltros(false,false,true,true);
        }
        //Solo selecciona una categoria y marca
        //if (data < 1 || key == "distributor") {
            //$(".PR-Container .PR-Aside p[data-" + key + "]").parent("section").children("ul").children("li").removeClass("active")
        //} else {
        //    $(".PR-Container .PR-Aside p[data-" + key + "]").parent("section").children("ul").children("li:first-child").removeClass("active")
        //}

        //$(this).toggleClass("active");
        var actives = $(".PR-Container .PR-Aside p[data-" + key + "]").parent("section").children("ul").children("li.active");
        var ids = "";
        $(".PR-Pager").data("page", 1);

        if (key == "distributor") {
            delete Params["Model"];
            updateQueryStringParam("Model", "-1");
        }

        for (var i = 0; i < actives.length; i++) {
            if (i != 0) {
                ids = ids + ",";
            }
            ids = ids + $(actives[i]).data(key);
        }

        updateQueryStringParam(key[0].toUpperCase() + key.slice(1), ids)
        $(this).parent("ul").parent("section").children("p").data(key, ids);
        changePage();
    })
    ///End filtro por categoria y marca

    ///Start paginacion
    $(".PR-Pager ul").on("click", "li", function () {
        //var prevPage = $(".PR-Pager ul").children(":nth-child(2)");
        //var nextPage = $(".PR-Pager ul").children(":nth-last-child(2)");
        //var firstPage = $(".PR-Pager ul").children(":nth-child(1)");
        //var lastPage = $(".PR-Pager ul").children(":nth-last-child(1)");
        var selectPage = $(this).data("page");
        $(".PR-Pager").data("page", selectPage);
        //$(".PR-Pager li").removeClass("active");
        //if (prevPage[0] != $(this)[0] && nextPage[0] != $(this)[0] && lastPage[0] != $(this)[0] && firstPage[0] != $(this)[0]) {
        //    $(this).addClass("active");
        //} else {
        //    for (var i = 2; i < $(".PR-Pager li").length - 2; i++) {
        //        if (selectPage === $(".PR-Pager li:nth-child(" + (i + 1) + ")").data("page")) {
        //            $(".PR-Pager li:nth-child(" + (i + 1) + ")").addClass("active");
        //        }
        //    }
        //}
        //prevPage.data("page", ((selectPage == firstPage.data("page")) ? firstPage.data("page") : selectPage - 1));
        //nextPage.data("page", ((selectPage == lastPage.data("page")) ? lastPage.data("page") : selectPage + 1));
        changePage();
    });

    ///End paginacion
    //end opciones de paginacion
    ////
    //var stringParams = ["Page", "Order", "PerPage", "ViewMode", "Category", "Distributor", "SearchParam", "Filter"];

    var Params = {
        SearchParam: getUrlParameter("SearchParam"),
        Page: getUrlParameter("Page"),
        PerPage: getUrlParameter("PerPage"),
        Order: getUrlParameter("Order"),
        ViewMode: getUrlParameter("ViewMode"),
        Category: getUrlParameter("Category"),
        Distributor: getUrlParameter("Distributor"),
        Model: getUrlParameter("Model"),
        Destacar: getUrlParameter("Destacar"),
        Promocion: getUrlParameter("Promocion")
    };
    Params = clearParams(Params);
    var paramCount = Object.keys(Params).length;
    var load = $(".firstLoad");
    if (paramCount == 0) {
        load.remove();
    }
    $.each(Params, function (key, value) {
        paramCount--;
        switch (key) {
            case "Page":
                $(".PR-Pager").data("page", value)
                break;
            case "Order":
                var order = $(".PR-Container .order ul");
                order.children(".select").data("order", value);
                order.children(".select").children("span").text(order.children("li[data-order=" + value + "]").text());
                break;
            case "PerPage":
                var perPage = $(".PR-Container .numResults ul");
                perPage.children("li.select").data("perpage", value);
                perPage.children(".select").children("span").text(value);
                break;
            case "ViewMode":
                $(".PR-Container .ViewMode i[data-viewmode=" + value + "]").trigger("click")
                break;
            case "SearchParam":
                break;
            case "Category":
                const elementoCat = document.getElementById('panel-filtros-mobile');
                const estilosCat = window.getComputedStyle(elementoCat);

                if (estilosCat.display === 'none') {
                    $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-category]").prop('checked', false);
                    $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-category]").prop('checked', false);
                    $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-category=" + value + "]").prop('checked', true);
                }
                else {
                    $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-category]").prop('checked', false);
                    $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-category]").prop('checked', false);
                    $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-category=" + value + "]").prop('checked', true);
                }
                break;
            case "Distributor":
                const elementoDis = document.getElementById('panel-filtros-mobile');
                const estilosDis = window.getComputedStyle(elementoDis);

                if (estilosDis.display === 'none') {
                    $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-distributor]").prop('checked', false);
                    $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-distributor]").prop('checked', false);
                    $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-distributor=" + value + "]").prop('checked', true);
                }
                else {
                    $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-distributor]").prop('checked', false);
                    $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-distributor]").prop('checked', false);
                    $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-distributor=" + value + "]").prop('checked', true);
                }
                break;
            case "Destacar":
                $(".PR-Container .PR-Aside input[data-destacar], #panel-filtros-mobile input[data-destacar]").each(function (index) {
                    if (index !== 0) {
                        $(this).prop("checked", true);
                    }
                });
                break;
            case "Promocion":
                $(".PR-Container .PR-Aside input[data-promocion=" + value + "], #panel-filtros-mobile input[data-promocion=" + value + "]").each(function (index) {
                    if (index !== 0) {
                        $(this).prop("checked", true);
                    }
                });
                break;
        }
        if (paramCount < 1) {
            if (load.length > 0) {
                load.remove();
            } else {
                changePage();
            }
        }
    })
    function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    }
    function updateQueryStringParam(key, value) {

        var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
            urlQueryString = document.location.search,
            newParam = key + '=' + value,
            params = '?' + newParam;

        // If the "search" string exists, then build params from it
        if (urlQueryString) {
            var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
            var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

            if (typeof value == 'undefined' || value == null || value == '') { // Remove param if value is empty
                params = urlQueryString.replace(removeRegex, "$1");
                params = params.replace(/[&;]$/, "");

            } else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
                params = urlQueryString.replace(updateRegex, "$1" + newParam);

            } else { // Otherwise, add it to end of query string
                params = urlQueryString + '&' + newParam;
            }
        }

        // no parameter was set so we don't need the question mark
        params = params == '?' ? '' : params;

        //window.history.pushState({}, "", baseUrl + params);
        window.history.replaceState({}, "", baseUrl + params);
    }
    function changePage() {
        Params.Page = (isNaN($(".PR-Pager").data("page"))) ? 0 : ($(".PR-Pager").data("page"));
        Params.Order = $(".PR-Container .order li.select").data("order");
        Params.PerPage = $(".PR-Container .numResults li.select").data("perpage");
        Params.ViewMode = $(".PR-Container .ViewMode i.active").data("viewmode");
        if (getUrlParameter("SearchParam")) {
            Params.SearchParam = getUrlParameter("SearchParam");
            Params.Category = false
            Params.Distributor = false
            Params.Destacar = false
            Params.Promocion = false
        } else {
            var mob = window.getComputedStyle(document.querySelector('.btn-abrir-filtros')),
                idsCategory = "", idsDistributor = "", activesCategory = null;
            if (mob.display == 'none')
                activesCategory = $(".PR-Container .PR-Aside input[data-category]:checked");
            else
                activesCategory = $("#panel-filtros-mobile input[data-category]:checked");

            if (activesCategory != null) {
                for (var i = 0; i < activesCategory.length; i++) {
                    if (i != 0) {
                        idsCategory = idsCategory + ",";
                    }
                    idsCategory = idsCategory + $(activesCategory[i]).data("category");
                }
            }

            var activesDistri = $(".PR-Container .PR-Aside input[data-distributor]:checked, #panel-filtros-mobile input[data-distributor]:checked");
            if (activesDistri != null) {
                for (var i = 0; i < activesDistri.length; i++) {
                    if (i != 0) {
                        idsDistributor = idsDistributor + ",";
                    }
                    idsDistributor = idsDistributor + $(activesDistri[i]).data("distributor");
                }
            }

            var desktopDestacar = $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-destacar]:checked").data("destacar");
            var mobileDestacar = $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-destacar]:checked").data("destacar");
            var idDestacar = desktopDestacar === undefined ? mobileDestacar : desktopDestacar;

            var desktopPromo = $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-promocion]:checked").data("promocion");
            var mobilePromo = $("#panel-filtros-mobile").children("div.grupo-filtro").children("label").children("input[data-promocion]:checked").data("promocion");
            var idPromo = desktopPromo === undefined ? mobilePromo : desktopPromo;

            var models = $('#selectModels').val();
            if (models.length == 0)
                models = $('#selectModelsMob').val();

            var idModels = "";
            if (models.length > 0) {
                models.forEach(function (valor) {
                    idModels += valor + ","
                });
                idModels = idModels.slice(0, -1);
            } else {
                var urlPage = new URL(window.location.href), getModel = urlPage.searchParams.get('Model');
                if (getModel != null) {
                    idModels = getModel;
                }
            }

            Params.Category = idsCategory;//$(".PR-Container .PR-Aside p[data-category]").data("category");
            Params.Distributor = idsDistributor;//$(".PR-Container .PR-Aside p[data-distributor]").data("distributor");
            Params.Destacar = idDestacar; //$(".PR-Container .PR-Aside p[data-destacar]").data("destacar");
            Params.Promocion = idPromo;//$(".PR-Container .PR-Aside p[data-promocion]").data("promocion");
            Params.SearchParam = false;
            Params.Model = idModels;
        }
        Params = clearParams(Params);

        $.ajax({
            type: "POST",
            url: "/busqueda?" + $.param(Params, true),
            //            data: { Page: Params.page - 1, Order: Params.order, PerPage: Params.perPage, ViewMode: Params.viewMode, Category: Params.category, Distributor: Params.distributor },
            //            dataType: "json"
        }).done(success).fail(fail);
        function success(data) {
            var products = data.products;
            var pages = data.items;
            var count = data.count;
            if (count > 0) {
                $(".PR-Container .PR-Content").children("div").remove();
                $(".PR-Container .PR-Content").append(products);
                $.each(Params, function (key, value) {
                    updateQueryStringParam(key, value);
                })
                updatePager(parseInt(Params.Page), parseInt(Params.PerPage), pages)
                window.scrollTo(0, 0);
            } else {
                $(".PR-Container .PR-Content").children("div").remove();
                $(".PR-Container .PR-Content").html('<div class="notFoundResult"><img src="/images/tutorial.gif" alt="Tutorial filtros" title="Filtros tutorial" /><br /><br /><span>No se encontraron coincidencias con los filtros seleccionados.</span><br /><span>Puedes probar marcando nuevos filtros para buscar mejorar la búsqueda.</span></div>');
            }
        }
        function fail(data) {
        }
        function updatePager(actualPage, itemsPerPage, numItems) {
            var maxPage = 9;
            var numPages = Math.ceil(numItems / itemsPerPage);
            if (numPages < maxPage) {
                maxPage = numPages;
            }
            var pager = $(".PR-Pager ul");
            pager.children().remove();
            if (numPages < 2) {
                return;
            }
            pager.append('<li data-page="1"><i class="fas fa-angle-double-left"></i></li >')
            if (actualPage > 1)
                pager.append('<li data-page="' + (actualPage - 1) + '"><i class="fas fa-angle-left"></i></li >')
            else
                pager.append('<li data-page="1"><i class="fas fa-angle-left"></i></li >')
            var PageNumber = 1;
            var MiddlePage = Math.floor(maxPage / 2);
            if (actualPage > MiddlePage) {
                PageNumber = actualPage - MiddlePage;
                if ((numPages - maxPage) < PageNumber) {
                    PageNumber = numPages - maxPage + 1;
                }
            }
            for (var page = 0; page < maxPage; page++) {
                var li = document.createElement("li");
                li.setAttribute("data-page", PageNumber)
                li.innerText = PageNumber;
                if (actualPage === PageNumber) {
                    li.setAttribute("class", "active")
                }
                pager.append(li);
                PageNumber++;
            }
            if (actualPage < numPages)
                pager.append('<li data-page="' + (actualPage + 1) + '"><i class="fas fa-angle-right"></i></li >')
            else
                pager.append('<li data-page="' + numPages + '"><i class="fas fa-angle-right"></i></li >')
            pager.append('<li data-page="' + numPages + '"><i class="fas fa-angle-double-right"></i></li >')
            pager.children("li").css("marginLeft", 0)
        }

    }
    function clearParams(params) {
        var paramsReturn = {}
        $.each(params, function (key, value) {
            if (value) {
                paramsReturn[key] = value;
            }
        })
        return paramsReturn
    }

    function DesactivaFiltros(category, distributor, destacar, promotions) {
        if (category) {
            $(".PR-Container .PR-Aside p[data-category]").parent("section").children("ul").children("li").removeClass("active") //elimina el active del <li> que esté activo de las categorías
            var categoryFilter = $(".PR-Container .PR-Aside p[data-category]").parent() //Obtiene las propiedades de la etiqueta <p> de categorías
            categoryFilter.children("ul").children("li[data-category='-1']").toggleClass("active") //Activa la etiqueta <li> "TODAS" de categorías
            $(".PR-Container .PR-Aside p[data-category]").data("category", "-1"); //Establece el valor -1 al parámetro de categorías por si el valor era diferente
            updateQueryStringParam("Category", "-1") //Actualiza el valor visualizado del parámetro Category de la url
        }
        if (distributor) {
            $(".PR-Container .PR-Aside p[data-distributor]").parent("section").children("ul").children("li").removeClass("active") //elimina el active del <li> que esté activo de las marcas
            var distributorFilter = $(".PR-Container .PR-Aside p[data-distributor]").parent() //Obtiene las propiedades de la etiqueta <p> de las marcas
            distributorFilter.children("ul").children("li[data-distributor='-1']").toggleClass("active") //Activa la etiqueta <li> "TODAS" de las marcas
            $(".PR-Container .PR-Aside p[data-distributor]").data("distributor", "-1"); //Establece el valor -1 al parámetro de marcas por si el valor era diferente
        }
        if (destacar) {
            $(".PR-Container .PR-Aside p[data-destacar]").parent("section").children("ul").children("li").removeClass("active")//Elimina el active del <li> activo de productos destacados
            $(".PR-Container .PR-Aside p[data-destacar]").data("destacar", ""); //Establece un valor vacío de destacados para que no lo tome en cuenta al realizar la búsqueda de los productos
            updateQueryStringParam("destacar", "");
            delete Params["Model"];
            updateQueryStringParam("Model", "-1");
        }
        if (promotions) {
            $(".PR-Container .PR-Aside p[data-promocion]").parent("section").children("ul").children("li").removeClass("active")//Elimina el active del <li> activo en alguna promoción seleccionada
            $(".PR-Container .PR-Aside p[data-promocion]").data("promocion", ""); //Establece un valor vacío de promoción para que no lo tome en cuenta al realizar la búsqueda de los productos
            updateQueryStringParam("promocion", "");
            delete Params["Model"];
            updateQueryStringParam("Model", "-1");
        }
    }

    function deleteParamURL(param) {
        const urlParams = new URLSearchParams(window.location.search);
        urlParams.delete(param);

        const newSearch = urlParams.toString();
        const newURL = window.location.pathname + (newSearch ? '?' + newSearch : '');

        // Actualizar la URL sin recargar la página
        window.history.pushState({}, '', newURL);
    }

    function validaParamURL(r, p) {
        const url = new URL(window.location.href); // Crea un objeto URL con la ubicación de la página
        const parametro = url.searchParams.get(p); // Busca si existe el parámetro
        if (r) {
            if (parametro != null) {
                return parametro;
            }
            else {
                return null;
            }
        } else {
            if (parametro != null) {
                return true;
            } else {
                return false;
            }
        }
    }

    $(function () {
        const promocion = validaParamURL(true, 'Promocion');
        const model = validaParamURL(true, 'Model');

        if (validaParamURL(false, 'Destacar')) {
            // Si se encontró, entonces ejecuta lo siguiente (Para marcar la opción de Productos destacados en el paginado)
            const checkD = $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-destacar]");
            if (checkD.length > 0) {
                checkD[0].checked = true;
            }
        }

        if (promocion != null) {
            const checkP = $(".PR-Container .PR-Aside").children("div").children("label").children("input[data-promocion=" + promocion + "]");
            if (checkP.length > 0) {
                checkP[0].checked = true;
            }
        }

        if (model != null) {
            const mob = window.getComputedStyle(document.querySelector('.btn-abrir-filtros'));
            if (mob.display == 'none') {
                setTimeout(function () {
                    $('#selectModels').val(model).trigger('change');
                }, 1600);
            }
            else {
                setTimeout(function () {
                    $('#selectModelsMob').val(model).trigger('change');
                }, 1600);
            }
        }
    });
})

//Start vista Producto
$(".PT-Slider").slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    asNavFor: '.PT-SubSlider'
});
$(".PT-SubSlider").slick({
    slidesToShow: 3,
    slidesToScroll: 1,
    asNavFor: '.PT-Slider',
    arrows: true,
    focusOnSelect: true
});


$("body").on("click", ".a-info-product", function () {
    $("#winModalProductInfo").modal("show")
    $("#contentProductInfo").html($(this).siblings(".product-info").html());
    
});
    //End vista Producto

$(document).on("click", ".seeProductDetail", function (ev) {
    ev.preventDefault();
    let productID = ev.currentTarget.dataset.idproduct;
    let obj = {
        idProduct: productID
    }

    $.ajax({
        type: "GET",
        url: "/productDetail",
        data: obj,
        dataType: "html",
        cache: false
    }).done(function get(data) {
        var m = $(data);
        m.modal();
        m.on($.modal.AFTER_CLOSE, function (event, modal) {
            m.remove();
        });
        m.ready(function () {
            $(".PT-Slider").slick({
                autoplay: true,
                autoplaySpeed: 2000,
                slidesToShow: 1,
                slidesToScroll: 1,
                arrows: false,
                fade: true,
                asNavFor: '.PT-SubSlider'
            });
            $(".PT-SubSlider").slick({
                slidesToShow: 3,
                slidesToScroll: 1,
                asNavFor: '.PT-Slider',
                arrows: true,
                focusOnSelect: true
            });
        });
    }).fail(function fail() {
        Notiflix.Notify.Warning("Sucedio un error, intente de nuevo más tarde.")
    });
});
$("#contactForm").validate({
    submitHandler: function (form) {
        AjaxPost("/contacto", $(form).serialize(), function (data) {
            if (data.status) {
                Swal.fire('Mensaje enviado', 'Pronto nos pondremos en contacto.', 'success');
                $("#contactForm").find("button").prop("disabled", true);
            } else {
                Swal.fire('Error', data.message, 'warning');
            }
        });

        return false;
    },
    rules: {
        name: "required",
        mail: {
            email: true,
            required: true
        },
        tel: "required"
    },
    messages: {
        name: "Campo requerido.",
        mail: {
            email: "Formato de correo electronico incorrecto.",
            required: "Campo requerido."
        },
        tel: "Campo requerido."
    }
});

$(".ctc-options").on("click", "li", function (e) {
    e.preventDefault();
    $(".ctc-options li").removeClass("active");
    $(this).addClass("active");
    var tab = $(this).children("a").data("tab");
    $(".ctc-panel").hide();
    $("." + tab).show();
});
$(".ctc-options li:first-child").click();
$(document).ready(function () {
    $(".sn-thumbnail .img").on("click", "a", function (evt) {
        evt.stopPropagation();
        evt.preventDefault();
        dropSlick();
        $(".sn-full").slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: false,
            asNavFor: '.sn-thumb'
        });
        $(".sn-thumb").slick({
            slidesToShow: 3,
            slidesToScroll: 1,
            asNavFor: '.sn-full',
            arrows: true,
            focusOnSelect: true
        }); 

        var images = $(this).data("images");
        for (var i = 0; i < images.length; i++) {
            $('.sn-full').slick('slickAdd', '<div><img src="' + images[i] + '"/></div>');
            if (images.length > 1) {
                $('.sn-thumb').slick('slickAdd', '<div><img src="' + images[i] + '"/></div>');
            }
        }
        resizeSerialSlide(images.length)
        $(".sn-gallery").fadeIn();
    });
    $(".sn-modal").on("click", ".close", function () {
        $(".sn-gallery").fadeOut(300, dropSlick)
    });
    $("#sn-filterserials").on("change", "select", function () {
        var value = $(this).val()
        if ($(this).attr("id") === "mostrar") {
            var items = $(".sn-price")
            $.each(items, function (k, v) {
                if (value != "Todos") {
                    if ($(v).data("status") == value) {
                        $(v).parents(".row").fadeIn();
                    } else {
                        $(v).parents(".row").fadeOut();
                    }
                } else {
                    $(v).parents(".row").fadeIn();
                }
            });
        } else {
            $.get(window.location.href + "/series", $("#sn-filterserials").serialize(), function (data) {
                $("#sn-serials-results").children().remove();
                $("#sn-serials-results").append(data);
                $("#sn-filterserials #mostrar").val("Todos");
            })
        }
    })
    $("#sn-filterserials").on("submit", function (evt) {
        evt.preventDefault();
    })
    function dropSlick() {
        if ($(".sn-full").hasClass("slick-initialized")) {
            $(".sn-full").slick("unslick")
            $(".sn-thumb").slick("unslick")
        }
    }
    function resizeSerialSlide(count) {
        var maxh = $(window).height() - 170;
        if (count > 1) {
            var thumbnailh = Math.ceil(maxh / 5)
            var slideh = thumbnailh * 4;
            $(".sn-full img").height(slideh)
            $(".sn-thumb img").height(thumbnailh)
        } else {
            $(".sn-full img").height(maxh + 20)
        }

    }
})
function IniciarPagoConekta(publicKey) {
    const isOXXO = $("[name=paymentmethod]:checked").parent().parent().hasClass("oxxo");

    if (!isOXXO) {
        if (Conekta.getPublicKey() == null) {
            Conekta.setPublicKey(publicKey);
        }

        //Validacion de fecha mau
        var mes = $("#card_exp_month :selected").text();
        var anio = $("#card_exp_year :selected").text();

        var fechaSeleccionadaTexto = anio + "-" + mes;
        var fechaSeleccionada = new Date(fechaSeleccionadaTexto);
        var fechaActual = new Date();

        var nombrePersona = $("#creditCardForm input[name=card_name]").val();

        if (fechaSeleccionada < fechaActual) {
            Swal.fire({
                title: 'Fecha de vencimiento pasada', text: 'Por favor, introduzca una fecha de vencimiento de tarjeta válida.', type: 'warning', onClose: function () {
                    setTimeout(function () {
                        $("#card_exp_month input[name=card_exp_month]").focus();
                    }, 500);
                }
            });
            return false;
        }
        else if (nombrePersona.trim() == "") {
            Swal.fire({
                title: 'Nombre de tarjetahabiente inválido', text: 'Por favor, escribe el nombre del tarjetahabiente.', type: 'warning', onClose: function () {
                    setTimeout(function () {
                        $("#creditCardForm input[name=card_name]").focus();
                    }, 500);
                }
            });
            return false;
        }
        else if (!Conekta.card.validateNumber($("#creditCardForm input[name=card_number]").val())) {
            Swal.fire({
                title: 'Número de tarjeta inválida', text: 'Por favor, escribe un número de tarjeta válido.', type: 'warning', onClose: function () {
                    setTimeout(function () {
                        $("#creditCardForm input[name=card_number]").focus();
                    }, 500);
                }
            });
            return false;
        }
        else if (!Conekta.card.validateCVC($("#creditCardForm input[name=card_cvv]").val().trim())) {
            Swal.fire({
                title: 'Código de seguridad inválido', text: 'Por favor, escribe un código de seguridad válido.', type: 'warning', onClose: function () {
                    setTimeout(function () { $("#creditCardForm input[name=card_cvv]").focus(); }, 500);
                }
            });
            return false;
        }

        let tokenParams = {
            "card": {
                "name": $("#creditCardForm input[name=card_name]").val(),
                "number": $("#creditCardForm input[name=card_number]").val(),
                "exp_month": $("#creditCardForm select[name=card_exp_month]").val(),
                "exp_year": $("#creditCardForm select[name=card_exp_year]").val(),
                "cvc": $("#creditCardForm input[name=card_cvv]").val().trim()
            }
        };

        Conekta.Token.create(tokenParams, successResponseHandler, errorResponseHandler);
    }
    else {
        var params = ObtenerDatosCheckout();

        AjaxPostObj("/conekta", params, function (result) {
            if (result.Status) {
                window.location.href = `/conekta/info?status=true&reference=${result.Message}&oxxoInfo=${result.Data}&isOXXO=true`;
                setTimeout(function () {
                    $(".btn.co-pay, .btn.co-back").attr("disabled", "");
                    $(".loading").fadeIn("fast");
                }, 0);
                return false;
            }
            else {
                debugger;
            }
        });
    }
}

var errorResponseHandler = function (error) {
    Swal.fire({
        title: 'Ocurrió un error', text: error.message_to_purchaser, type: 'error'
    });

    $(".btn.co-pay, .btn.co-back").removeAttr("disabled");
};
$(document).ready(function () {
    $(".moreComments").on("click", ".seeMoreComments", function (ev) {
        ev.preventDefault();
        let product = ev.currentTarget.dataset.idprod;
        let starrow = 0;
        let maxrow = 5;
        let obj = {
            idProduct: product,
            startRowIndex: starrow,
            maximumRows: maxrow
        }

        $.ajax({
            type: "GET",
            url: "/searchOpinions",
            data: obj,
            dataType: "html",
            cache: false
        }).done(function get(data) {
            var m = $(data);
            m.modal();
            m.on($.modal.AFTER_CLOSE, function (event, modal) {
                m.remove();
            });
            m.on("click", ".PR-Pager-Opinions ul li", function (e) {
                var selectPage = $(this).data("page");
                $(".PR-Pager-Opinions").data("page", selectPage);
                changePageOpinions();
            })
            function clearParams(params) {
                var paramsReturn = {}
                $.each(params, function (key, value) {
                    if (value) {
                        paramsReturn[key] = value;
                    }
                })
                return paramsReturn
            }
            obj = clearParams(obj);
            function changePageOpinions() {
                obj.idProduct = (isNaN($(".PR-Pager-Opinions").data("idprod"))) ? 0 : ($(".PR-Pager-Opinions").data("idprod"));
                obj.startRowIndex = (isNaN($(".PR-Pager-Opinions").data("page"))) ? 0 : ($(".PR-Pager-Opinions").data("page"));
                obj.maximumRows = "5";

                obj = clearParams(obj);
                $.ajax({
                    type: "POST",
                    url: "/searchOpinionsPaginador",
                    data: obj
                }).done(success).fail(fail);
                function success(data) {
                    var html = data.html;
                    var totalItems = data.totalRows;
                    var count = data.count;
                    
                    if (count > 0) {
                        $(".Opinions").children("div").remove();
                        $(".Opinions").append(html);
                        updatePagerOpinions(parseInt(obj.startRowIndex), parseInt(obj.maximumRows), totalItems);
                    } else {
                        $(".Opinions").children("div").remove();
                        updatePagerOpinions(parseInt(obj.startRowIndex), parseInt(obj.maximumRows), totalItems);
                    }
                }
                function fail(data) {
                }
                function updatePagerOpinions(actualPage, itemsPerPage, numItems) {
                    var maxPage = 9;
                    var numPages = Math.ceil(numItems / itemsPerPage);
                    if (numPages < maxPage) {
                        maxPage = numPages;
                    }
                    var pager = $(".PR-Pager-Opinions ul");
                    pager.children().remove();
                    if (numPages < 2) {
                        return;
                    }
                    pager.append('<li data-page="1"><i class="fas fa-angle-double-left"></i></li >')
                    if (actualPage > 1)
                        pager.append('<li data-page="' + (actualPage - 1) + '"><i class="fas fa-angle-left"></i></li >')
                    else
                        pager.append('<li data-page="1"><i class="fas fa-angle-left"></i></li >')
                    var PageNumber = 1;
                    var MiddlePage = Math.floor(maxPage / 2);
                    if (actualPage > MiddlePage) {
                        PageNumber = actualPage - MiddlePage;
                        if ((numPages - maxPage) < PageNumber) {
                            PageNumber = numPages - maxPage + 1;
                        }
                    }
                    for (var page = 0; page < maxPage; page++) {
                        var li = document.createElement("li");
                        li.setAttribute("data-page", PageNumber)
                        li.innerText = PageNumber;
                        if (actualPage === PageNumber) {
                            li.setAttribute("class", "active")
                        }
                        pager.append(li);
                        PageNumber++;
                    }

                    if (actualPage < numPages) {
                        pager.append('<li data-page="' + (actualPage + 1) + '"><i class="fas fa-angle-right"></i></li >')
                        pager.append('<li data-page="' + numPages + '"><i class="fas fa-angle-double-right"></i></li >')
                    }
                    pager.children("li").css("marginLeft", 0)
                }
            }
        }).fail(function fail() {
            Notiflix.Notify.Warning("Sucedio un error, intente de nuevo más tarde.")
        });
    });
})
