/* Minification failed. Returning unminified contents.
(15,1): run-time error CSS1019: Unexpected token, found '!'
(15,2): run-time error CSS1019: Unexpected token, found 'function('
(15,12): run-time error CSS1031: Expected selector, found ')'
(15,12): run-time error CSS1025: Expected comma or open brace, found ')'
(15,2775): run-time error CSS1019: Unexpected token, found '('
(15,2782): run-time error CSS1031: Expected selector, found ')'
(15,2782): run-time error CSS1025: Expected comma or open brace, found ')'
(19,1): run-time error CSS1019: Unexpected token, found '$'
(19,2): run-time error CSS1019: Unexpected token, found '('
(19,11): run-time error CSS1031: Expected selector, found ')'
(19,11): run-time error CSS1025: Expected comma or open brace, found ')'
(21,2): run-time error CSS1019: Unexpected token, found ')'
(25,1): run-time error CSS1019: Unexpected token, found '$'
(25,2): run-time error CSS1019: Unexpected token, found '('
(25,12): run-time error CSS1031: Expected selector, found '('
(25,12): run-time error CSS1025: Expected comma or open brace, found '('
(33,2): run-time error CSS1019: Unexpected token, found ')'
(35,15): run-time error CSS1031: Expected selector, found ';'
(35,15): run-time error CSS1025: Expected comma or open brace, found ';'
(36,15): run-time error CSS1031: Expected selector, found ';'
(36,15): run-time error CSS1025: Expected comma or open brace, found ';'
(38,1): run-time error CSS1019: Unexpected token, found '$'
(38,2): run-time error CSS1019: Unexpected token, found '('
(38,12): run-time error CSS1031: Expected selector, found '('
(38,12): run-time error CSS1025: Expected comma or open brace, found '('
(59,2): run-time error CSS1019: Unexpected token, found ')'
(61,10): run-time error CSS1031: Expected selector, found 'ToastMessage('
(61,10): run-time error CSS1025: Expected comma or open brace, found 'ToastMessage('
(85,21): run-time error CSS1031: Expected selector, found '='
(85,21): run-time error CSS1025: Expected comma or open brace, found '='
(86,1): run-time error CSS1019: Unexpected token, found '$'
(86,2): run-time error CSS1019: Unexpected token, found '('
(86,11): run-time error CSS1031: Expected selector, found ')'
(86,11): run-time error CSS1025: Expected comma or open brace, found ')'
(89,2): run-time error CSS1019: Unexpected token, found ')'
(91,10): run-time error CSS1031: Expected selector, found 'GetBrowser('
(91,10): run-time error CSS1025: Expected comma or open brace, found 'GetBrowser('
(109,1): run-time error CSS1019: Unexpected token, found '$'
(109,2): run-time error CSS1019: Unexpected token, found '('
(109,11): run-time error CSS1031: Expected selector, found ')'
(109,11): run-time error CSS1025: Expected comma or open brace, found ')'
(119,2): run-time error CSS1019: Unexpected token, found ')'
(121,1): run-time error CSS1019: Unexpected token, found '$'
(121,2): run-time error CSS1019: Unexpected token, found '('
(121,11): run-time error CSS1031: Expected selector, found ')'
(121,11): run-time error CSS1025: Expected comma or open brace, found ')'
(130,2): run-time error CSS1019: Unexpected token, found ')'
(132,11): run-time error CSS1031: Expected selector, found '='
(132,11): run-time error CSS1025: Expected comma or open brace, found '='
(134,1): run-time error CSS1019: Unexpected token, found '$'
(134,2): run-time error CSS1019: Unexpected token, found '('
(134,11): run-time error CSS1031: Expected selector, found ')'
(134,11): run-time error CSS1025: Expected comma or open brace, found ')'
(144,2): run-time error CSS1019: Unexpected token, found ')'
(146,1): run-time error CSS1019: Unexpected token, found '$'
(146,2): run-time error CSS1019: Unexpected token, found '('
(146,11): run-time error CSS1031: Expected selector, found ')'
(146,11): run-time error CSS1025: Expected comma or open brace, found ')'
(149,2): run-time error CSS1019: Unexpected token, found ')'
(151,10): run-time error CSS1031: Expected selector, found 'GetNowDate('
(151,10): run-time error CSS1025: Expected comma or open brace, found 'GetNowDate('
(158,10): run-time error CSS1031: Expected selector, found 'GetQueryStringParam('
(158,10): run-time error CSS1025: Expected comma or open brace, found 'GetQueryStringParam('
(168,10): run-time error CSS1031: Expected selector, found 'ResizeGrids('
(168,10): run-time error CSS1025: Expected comma or open brace, found 'ResizeGrids('
(181,10): run-time error CSS1031: Expected selector, found 'changeJsonDateFormat('
(181,10): run-time error CSS1025: Expected comma or open brace, found 'changeJsonDateFormat('
(218,10): run-time error CSS1031: Expected selector, found 'changeDateFormat('
(218,10): run-time error CSS1025: Expected comma or open brace, found 'changeDateFormat('
(223,10): run-time error CSS1031: Expected selector, found 'changeNumberFormat('
(223,10): run-time error CSS1025: Expected comma or open brace, found 'changeNumberFormat('
(246,10): run-time error CSS1031: Expected selector, found 'parseDecimal('
(246,10): run-time error CSS1025: Expected comma or open brace, found 'parseDecimal('
(263,27): run-time error CSS1031: Expected selector, found '='
(263,27): run-time error CSS1025: Expected comma or open brace, found '='
(267,10): run-time error CSS1031: Expected selector, found 'changeCPFCNPJFormat('
(267,10): run-time error CSS1025: Expected comma or open brace, found 'changeCPFCNPJFormat('
(331,10): run-time error CSS1031: Expected selector, found 'pqDatePickerPQ('
(331,10): run-time error CSS1025: Expected comma or open brace, found 'pqDatePickerPQ('
(362,10): run-time error CSS1031: Expected selector, found 'nrReloadScripts('
(362,10): run-time error CSS1025: Expected comma or open brace, found 'nrReloadScripts('
(371,10): run-time error CSS1031: Expected selector, found 'pqFilterLayout('
(371,10): run-time error CSS1025: Expected comma or open brace, found 'pqFilterLayout('
(416,10): run-time error CSS1031: Expected selector, found 'nrSpecialDrops('
(416,10): run-time error CSS1025: Expected comma or open brace, found 'nrSpecialDrops('
(426,10): run-time error CSS1031: Expected selector, found 'RowAnchors('
(426,10): run-time error CSS1025: Expected comma or open brace, found 'RowAnchors('
(440,10): run-time error CSS1031: Expected selector, found 'Special('
(440,10): run-time error CSS1025: Expected comma or open brace, found 'Special('
(719,10): run-time error CSS1031: Expected selector, found 'NrButtonStop('
(719,10): run-time error CSS1025: Expected comma or open brace, found 'NrButtonStop('
(725,10): run-time error CSS1031: Expected selector, found 'DropSpecial('
(725,10): run-time error CSS1025: Expected comma or open brace, found 'DropSpecial('
(744,10): run-time error CSS1031: Expected selector, found 'KeyDelay('
(744,10): run-time error CSS1025: Expected comma or open brace, found 'KeyDelay('
(756,18): run-time error CSS1031: Expected selector, found '='
(756,18): run-time error CSS1025: Expected comma or open brace, found '='
(757,10): run-time error CSS1031: Expected selector, found 'DatePicker('
(757,10): run-time error CSS1025: Expected comma or open brace, found 'DatePicker('
(909,10): run-time error CSS1031: Expected selector, found 'Masks('
(909,10): run-time error CSS1025: Expected comma or open brace, found 'Masks('
(927,13): run-time error CSS1031: Expected selector, found '='
(927,13): run-time error CSS1025: Expected comma or open brace, found '='
(928,11): run-time error CSS1030: Expected identifier, found 'extend('
(928,11): run-time error CSS1031: Expected selector, found 'extend('
(928,11): run-time error CSS1025: Expected comma or open brace, found 'extend('
(943,2): run-time error CSS1019: Unexpected token, found ')'
(946,17): run-time error CSS1031: Expected selector, found ';'
(946,17): run-time error CSS1025: Expected comma or open brace, found ';'
(948,10): run-time error CSS1031: Expected selector, found 'OpenNrWindow('
(948,10): run-time error CSS1025: Expected comma or open brace, found 'OpenNrWindow('
(972,19): run-time error CSS1031: Expected selector, found '='
(972,19): run-time error CSS1025: Expected comma or open brace, found '='
(973,10): run-time error CSS1031: Expected selector, found 'ConfirmDialog('
(973,10): run-time error CSS1025: Expected comma or open brace, found 'ConfirmDialog('
(1005,19): run-time error CSS1031: Expected selector, found ';'
(1005,19): run-time error CSS1025: Expected comma or open brace, found ';'
(1007,10): run-time error CSS1031: Expected selector, found 'MouseOver('
(1007,10): run-time error CSS1025: Expected comma or open brace, found 'MouseOver('
(1018,10): run-time error CSS1031: Expected selector, found 'OpenPositionModal('
(1018,10): run-time error CSS1025: Expected comma or open brace, found 'OpenPositionModal('
(1080,10): run-time error CSS1031: Expected selector, found 'AlterFinZone('
(1080,10): run-time error CSS1025: Expected comma or open brace, found 'AlterFinZone('
(1089,10): run-time error CSS1031: Expected selector, found 'MaxLength('
(1089,10): run-time error CSS1025: Expected comma or open brace, found 'MaxLength('
(1111,10): run-time error CSS1031: Expected selector, found 'dateAddDays('
(1111,10): run-time error CSS1025: Expected comma or open brace, found 'dateAddDays('
(1122,10): run-time error CSS1031: Expected selector, found 'parseDate('
(1122,10): run-time error CSS1025: Expected comma or open brace, found 'parseDate('
(1135,10): run-time error CSS1031: Expected selector, found 'dayDiff('
(1135,10): run-time error CSS1025: Expected comma or open brace, found 'dayDiff('
(1142,10): run-time error CSS1031: Expected selector, found 'charFraction('
(1142,10): run-time error CSS1025: Expected comma or open brace, found 'charFraction('
(1169,10): run-time error CSS1031: Expected selector, found 'daysToDate('
(1169,10): run-time error CSS1025: Expected comma or open brace, found 'daysToDate('
(1186,10): run-time error CSS1031: Expected selector, found 'ToDateString('
(1186,10): run-time error CSS1025: Expected comma or open brace, found 'ToDateString('
(1201,10): run-time error CSS1031: Expected selector, found 'CloseTop('
(1201,10): run-time error CSS1025: Expected comma or open brace, found 'CloseTop('
(1205,10): run-time error CSS1031: Expected selector, found 'CloseSide('
(1205,10): run-time error CSS1025: Expected comma or open brace, found 'CloseSide('
(1212,10): run-time error CSS1031: Expected selector, found 'OpenTabZone('
(1212,10): run-time error CSS1025: Expected comma or open brace, found 'OpenTabZone('
(1222,10): run-time error CSS1031: Expected selector, found 'ChangeTab('
(1222,10): run-time error CSS1025: Expected comma or open brace, found 'ChangeTab('
(1236,10): run-time error CSS1031: Expected selector, found 'GetAnimation('
(1236,10): run-time error CSS1025: Expected comma or open brace, found 'GetAnimation('
(1261,13): run-time error CSS1031: Expected selector, found '='
(1261,13): run-time error CSS1025: Expected comma or open brace, found '='
(1262,10): run-time error CSS1031: Expected selector, found 'BlinkLine('
(1262,10): run-time error CSS1025: Expected comma or open brace, found 'BlinkLine('
(1289,10): run-time error CSS1031: Expected selector, found 'Bounce('
(1289,10): run-time error CSS1025: Expected comma or open brace, found 'Bounce('
(1363,17): run-time error CSS1031: Expected selector, found '='
(1363,17): run-time error CSS1025: Expected comma or open brace, found '='
(1364,16): run-time error CSS1031: Expected selector, found '='
(1364,16): run-time error CSS1025: Expected comma or open brace, found '='
(1366,1): run-time error CSS1019: Unexpected token, found '$'
(1366,2): run-time error CSS1019: Unexpected token, found '('
(1366,11): run-time error CSS1031: Expected selector, found ')'
(1366,11): run-time error CSS1025: Expected comma or open brace, found ')'
(1400,2): run-time error CSS1019: Unexpected token, found ')'
(1402,10): run-time error CSS1031: Expected selector, found 'ReadOnly('
(1402,10): run-time error CSS1025: Expected comma or open brace, found 'ReadOnly('
(1410,19): run-time error CSS1031: Expected selector, found '='
(1410,19): run-time error CSS1025: Expected comma or open brace, found '='
(1411,10): run-time error CSS1031: Expected selector, found 'StartForm('
(1411,10): run-time error CSS1025: Expected comma or open brace, found 'StartForm('
(1447,10): run-time error CSS1031: Expected selector, found 'BlockFields('
(1447,10): run-time error CSS1025: Expected comma or open brace, found 'BlockFields('
(1466,10): run-time error CSS1031: Expected selector, found 'DropClear('
(1466,10): run-time error CSS1025: Expected comma or open brace, found 'DropClear('
(1484,10): run-time error CSS1031: Expected selector, found 'DropData('
(1484,10): run-time error CSS1025: Expected comma or open brace, found 'DropData('
(1495,10): run-time error CSS1031: Expected selector, found 'ChangeErrorState('
(1495,10): run-time error CSS1025: Expected comma or open brace, found 'ChangeErrorState('
(1517,10): run-time error CSS1031: Expected selector, found 'CleanText('
(1517,10): run-time error CSS1025: Expected comma or open brace, found 'CleanText('
(1530,1): run-time error CSS1019: Unexpected token, found '$'
(1530,27): run-time error CSS1031: Expected selector, found '='
(1530,27): run-time error CSS1025: Expected comma or open brace, found '='
(1543,1): run-time error CSS1019: Unexpected token, found '$'
(1543,29): run-time error CSS1031: Expected selector, found '='
(1543,29): run-time error CSS1025: Expected comma or open brace, found '='
(1556,10): run-time error CSS1031: Expected selector, found 'GetTarget('
(1556,10): run-time error CSS1025: Expected comma or open brace, found 'GetTarget('
(1562,16): run-time error CSS1031: Expected selector, found '='
(1562,16): run-time error CSS1025: Expected comma or open brace, found '='
(1564,10): run-time error CSS1031: Expected selector, found 'LoadNrForm('
(1564,10): run-time error CSS1025: Expected comma or open brace, found 'LoadNrForm('
(1688,10): run-time error CSS1031: Expected selector, found 'LoadNrDrop('
(1688,10): run-time error CSS1025: Expected comma or open brace, found 'LoadNrDrop('
(1718,10): run-time error CSS1031: Expected selector, found 'SubmitNRForm('
(1718,10): run-time error CSS1025: Expected comma or open brace, found 'SubmitNRForm('
(1825,1): run-time error CSS1019: Unexpected token, found '!'
(1825,11): run-time error CSS1031: Expected selector, found '('
(1825,11): run-time error CSS1025: Expected comma or open brace, found '('
(1825,145): run-time error CSS1019: Unexpected token, found '('
(1825,155): run-time error CSS1031: Expected selector, found '('
(1825,155): run-time error CSS1025: Expected comma or open brace, found '('
(1825,5004): run-time error CSS1019: Unexpected token, found ')'
(1826,10): run-time error CSS1031: Expected selector, found 'LoadAnalyticSells('
(1826,10): run-time error CSS1025: Expected comma or open brace, found 'LoadAnalyticSells('
(1845,10): run-time error CSS1031: Expected selector, found 'LoadAnalyticPeriodLate('
(1845,10): run-time error CSS1025: Expected comma or open brace, found 'LoadAnalyticPeriodLate('
(1865,10): run-time error CSS1031: Expected selector, found 'LoadAnalyticPaymentPeriod('
(1865,10): run-time error CSS1025: Expected comma or open brace, found 'LoadAnalyticPaymentPeriod('
(1885,10): run-time error CSS1031: Expected selector, found 'LoadAnalyticProg('
(1885,10): run-time error CSS1025: Expected comma or open brace, found 'LoadAnalyticProg('
(1906,10): run-time error CSS1031: Expected selector, found 'LoadAgingData('
(1906,10): run-time error CSS1025: Expected comma or open brace, found 'LoadAgingData('
(1918,10): run-time error CSS1031: Expected selector, found 'GraphAxesConstructor('
(1918,10): run-time error CSS1025: Expected comma or open brace, found 'GraphAxesConstructor('
(2157,10): run-time error CSS1031: Expected selector, found 'GraphPieConstructor('
(2157,10): run-time error CSS1025: Expected comma or open brace, found 'GraphPieConstructor('
(2186,10): run-time error CSS1031: Expected selector, found 'graphData('
(2186,10): run-time error CSS1025: Expected comma or open brace, found 'graphData('
(2202,10): run-time error CSS1031: Expected selector, found 'graphFormat('
(2202,10): run-time error CSS1025: Expected comma or open brace, found 'graphFormat('
(2214,1): run-time error CSS1019: Unexpected token, found '$'
(2214,2): run-time error CSS1019: Unexpected token, found '('
(2214,12): run-time error CSS1031: Expected selector, found '('
(2214,12): run-time error CSS1025: Expected comma or open brace, found '('
(2217,2): run-time error CSS1019: Unexpected token, found ')'
(2219,10): run-time error CSS1031: Expected selector, found 'TerMailTo('
(2219,10): run-time error CSS1025: Expected comma or open brace, found 'TerMailTo('
(2228,10): run-time error CSS1031: Expected selector, found 'RefreshTerMail('
(2228,10): run-time error CSS1025: Expected comma or open brace, found 'RefreshTerMail('
(2232,10): run-time error CSS1031: Expected selector, found 'ExistsTerMail('
(2232,10): run-time error CSS1025: Expected comma or open brace, found 'ExistsTerMail('
(2236,10): run-time error CSS1031: Expected selector, found 'MarkTerMail('
(2236,10): run-time error CSS1025: Expected comma or open brace, found 'MarkTerMail('
(2241,10): run-time error CSS1031: Expected selector, found 'AddRemoveTerMail('
(2241,10): run-time error CSS1025: Expected comma or open brace, found 'AddRemoveTerMail('
(2268,10): run-time error CSS1031: Expected selector, found 'GetTerMails('
(2268,10): run-time error CSS1025: Expected comma or open brace, found 'GetTerMails('
(2335,10): run-time error CSS1031: Expected selector, found ';'
(2335,10): run-time error CSS1025: Expected comma or open brace, found ';'
(2336,8): run-time error CSS1031: Expected selector, found ';'
(2336,8): run-time error CSS1025: Expected comma or open brace, found ';'
(2338,10): run-time error CSS1031: Expected selector, found 'GetCategoryIcon('
(2338,10): run-time error CSS1025: Expected comma or open brace, found 'GetCategoryIcon('
(2348,10): run-time error CSS1031: Expected selector, found 'GetOccurrenceHistory('
(2348,10): run-time error CSS1025: Expected comma or open brace, found 'GetOccurrenceHistory('
(2647,11): run-time error CSS1031: Expected selector, found ';'
(2647,11): run-time error CSS1025: Expected comma or open brace, found ';'
(2648,12): run-time error CSS1031: Expected selector, found ';'
(2648,12): run-time error CSS1025: Expected comma or open brace, found ';'
(2649,11): run-time error CSS1031: Expected selector, found ';'
(2649,11): run-time error CSS1025: Expected comma or open brace, found ';'
(2650,9): run-time error CSS1031: Expected selector, found ';'
(2650,9): run-time error CSS1025: Expected comma or open brace, found ';'
(2651,9): run-time error CSS1031: Expected selector, found ';'
(2651,9): run-time error CSS1025: Expected comma or open brace, found ';'
(2653,13): run-time error CSS1031: Expected selector, found ';'
(2653,13): run-time error CSS1025: Expected comma or open brace, found ';'
(2654,13): run-time error CSS1031: Expected selector, found ';'
(2654,13): run-time error CSS1025: Expected comma or open brace, found ';'
(2656,10): run-time error CSS1031: Expected selector, found 'GetDownloadList('
(2656,10): run-time error CSS1025: Expected comma or open brace, found 'GetDownloadList('
(2802,10): run-time error CSS1031: Expected selector, found 'GetDownloadInstruments('
(2802,10): run-time error CSS1025: Expected comma or open brace, found 'GetDownloadInstruments('
(2950,10): run-time error CSS1031: Expected selector, found 'GetAttachList('
(2950,10): run-time error CSS1025: Expected comma or open brace, found 'GetAttachList('
(3048,1): run-time error CSS1019: Unexpected token, found '$'
(3048,2): run-time error CSS1019: Unexpected token, found '('
(3048,11): run-time error CSS1031: Expected selector, found ')'
(3048,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3052,2): run-time error CSS1019: Unexpected token, found ')'
(3054,15): run-time error CSS1031: Expected selector, found ';'
(3054,15): run-time error CSS1025: Expected comma or open brace, found ';'
(3055,10): run-time error CSS1031: Expected selector, found 'AlertTimer('
(3055,10): run-time error CSS1025: Expected comma or open brace, found 'AlertTimer('
(3063,10): run-time error CSS1031: Expected selector, found 'AlertPulse('
(3063,10): run-time error CSS1025: Expected comma or open brace, found 'AlertPulse('
(3072,20): run-time error CSS1031: Expected selector, found '='
(3072,20): run-time error CSS1025: Expected comma or open brace, found '='
(3073,10): run-time error CSS1031: Expected selector, found 'LoadAlerts('
(3073,10): run-time error CSS1025: Expected comma or open brace, found 'LoadAlerts('
(3109,10): run-time error CSS1031: Expected selector, found 'UpdateAlertDate('
(3109,10): run-time error CSS1025: Expected comma or open brace, found 'UpdateAlertDate('
(3120,10): run-time error CSS1031: Expected selector, found 'AlertBlock('
(3120,10): run-time error CSS1025: Expected comma or open brace, found 'AlertBlock('
(3135,10): run-time error CSS1031: Expected selector, found 'AlertClear('
(3135,10): run-time error CSS1025: Expected comma or open brace, found 'AlertClear('
(3140,1): run-time error CSS1019: Unexpected token, found '$'
(3140,2): run-time error CSS1019: Unexpected token, found '('
(3140,11): run-time error CSS1031: Expected selector, found ')'
(3140,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3143,2): run-time error CSS1019: Unexpected token, found ')'
(3145,17): run-time error CSS1031: Expected selector, found ';'
(3145,17): run-time error CSS1025: Expected comma or open brace, found ';'
(3146,10): run-time error CSS1031: Expected selector, found 'MessageTimer('
(3146,10): run-time error CSS1025: Expected comma or open brace, found 'MessageTimer('
(3154,10): run-time error CSS1031: Expected selector, found 'MessagePulse('
(3154,10): run-time error CSS1025: Expected comma or open brace, found 'MessagePulse('
(3159,21): run-time error CSS1031: Expected selector, found '='
(3159,21): run-time error CSS1025: Expected comma or open brace, found '='
(3160,10): run-time error CSS1031: Expected selector, found 'LoadTopMessages('
(3160,10): run-time error CSS1025: Expected comma or open brace, found 'LoadTopMessages('
(3201,10): run-time error CSS1031: Expected selector, found 'UpdateMessageDate('
(3201,10): run-time error CSS1025: Expected comma or open brace, found 'UpdateMessageDate('
(3212,10): run-time error CSS1031: Expected selector, found 'MessageHome('
(3212,10): run-time error CSS1025: Expected comma or open brace, found 'MessageHome('
(3227,10): run-time error CSS1031: Expected selector, found 'MessageHomeBlock('
(3227,10): run-time error CSS1025: Expected comma or open brace, found 'MessageHomeBlock('
(3242,10): run-time error CSS1031: Expected selector, found 'MessageHomeClear('
(3242,10): run-time error CSS1025: Expected comma or open brace, found 'MessageHomeClear('
(3249,10): run-time error CSS1031: Expected selector, found 'MessageClear('
(3249,10): run-time error CSS1025: Expected comma or open brace, found 'MessageClear('
(3263,1): run-time error CSS1019: Unexpected token, found '$'
(3263,2): run-time error CSS1019: Unexpected token, found '('
(3263,11): run-time error CSS1031: Expected selector, found ')'
(3263,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3266,2): run-time error CSS1019: Unexpected token, found ')'
(3268,23): run-time error CSS1031: Expected selector, found ';'
(3268,23): run-time error CSS1025: Expected comma or open brace, found ';'
(3269,10): run-time error CSS1031: Expected selector, found 'RelationIssueTimer('
(3269,10): run-time error CSS1025: Expected comma or open brace, found 'RelationIssueTimer('
(3277,10): run-time error CSS1031: Expected selector, found 'RelationIssuePulse('
(3277,10): run-time error CSS1025: Expected comma or open brace, found 'RelationIssuePulse('
(3282,10): run-time error CSS1031: Expected selector, found 'LoadTopRelationIssues('
(3282,10): run-time error CSS1025: Expected comma or open brace, found 'LoadTopRelationIssues('
(3310,10): run-time error CSS1031: Expected selector, found 'RelationIssueHome('
(3310,10): run-time error CSS1025: Expected comma or open brace, found 'RelationIssueHome('
(3325,10): run-time error CSS1031: Expected selector, found 'RelationIssueHomeBlock('
(3325,10): run-time error CSS1025: Expected comma or open brace, found 'RelationIssueHomeBlock('
(3340,10): run-time error CSS1031: Expected selector, found 'RelationIssueHomeClear('
(3340,10): run-time error CSS1025: Expected comma or open brace, found 'RelationIssueHomeClear('
(3347,10): run-time error CSS1031: Expected selector, found 'RelationIssueClear('
(3347,10): run-time error CSS1025: Expected comma or open brace, found 'RelationIssueClear('
(3360,1): run-time error CSS1019: Unexpected token, found '$'
(3360,2): run-time error CSS1019: Unexpected token, found '('
(3360,11): run-time error CSS1031: Expected selector, found ')'
(3360,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3363,2): run-time error CSS1019: Unexpected token, found ')'
(3365,14): run-time error CSS1031: Expected selector, found ';'
(3365,14): run-time error CSS1025: Expected comma or open brace, found ';'
(3366,10): run-time error CSS1031: Expected selector, found 'TodoTimer('
(3366,10): run-time error CSS1025: Expected comma or open brace, found 'TodoTimer('
(3374,10): run-time error CSS1031: Expected selector, found 'TodoPulse('
(3374,10): run-time error CSS1025: Expected comma or open brace, found 'TodoPulse('
(3381,10): run-time error CSS1031: Expected selector, found 'LoadTodo('
(3381,10): run-time error CSS1025: Expected comma or open brace, found 'LoadTodo('
(3432,10): run-time error CSS1031: Expected selector, found 'TodoToday('
(3432,10): run-time error CSS1025: Expected comma or open brace, found 'TodoToday('
(3443,10): run-time error CSS1031: Expected selector, found 'TodoHome('
(3443,10): run-time error CSS1025: Expected comma or open brace, found 'TodoHome('
(3455,10): run-time error CSS1031: Expected selector, found 'TodoClear('
(3455,10): run-time error CSS1025: Expected comma or open brace, found 'TodoClear('
(3459,10): run-time error CSS1031: Expected selector, found 'FinishDivergence('
(3459,10): run-time error CSS1025: Expected comma or open brace, found 'FinishDivergence('
(3482,1): run-time error CSS1019: Unexpected token, found '$'
(3482,2): run-time error CSS1019: Unexpected token, found '('
(3482,11): run-time error CSS1031: Expected selector, found ')'
(3482,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3487,2): run-time error CSS1019: Unexpected token, found ')'
(3489,10): run-time error CSS1031: Expected selector, found 'ShopPulse('
(3489,10): run-time error CSS1025: Expected comma or open brace, found 'ShopPulse('
(3494,10): run-time error CSS1031: Expected selector, found 'LoadShopCurrent('
(3494,10): run-time error CSS1025: Expected comma or open brace, found 'LoadShopCurrent('
(3541,10): run-time error CSS1031: Expected selector, found 'ShopHeader('
(3541,10): run-time error CSS1025: Expected comma or open brace, found 'ShopHeader('
(3554,10): run-time error CSS1031: Expected selector, found 'ShopEntryHeader('
(3554,10): run-time error CSS1025: Expected comma or open brace, found 'ShopEntryHeader('
(3574,10): run-time error CSS1031: Expected selector, found 'ShopEntryItems('
(3574,10): run-time error CSS1025: Expected comma or open brace, found 'ShopEntryItems('
(3588,10): run-time error CSS1031: Expected selector, found 'ShopHomeClear('
(3588,10): run-time error CSS1025: Expected comma or open brace, found 'ShopHomeClear('
(3594,10): run-time error CSS1031: Expected selector, found 'ShopToggleItems('
(3594,10): run-time error CSS1025: Expected comma or open brace, found 'ShopToggleItems('
(3600,10): run-time error CSS1031: Expected selector, found 'SelectStatus('
(3600,10): run-time error CSS1025: Expected comma or open brace, found 'SelectStatus('
(3618,10): run-time error CSS1031: Expected selector, found 'ShowFile('
(3618,10): run-time error CSS1025: Expected comma or open brace, found 'ShowFile('
(3678,10): run-time error CSS1031: Expected selector, found 'GetMoneyOver('
(3678,10): run-time error CSS1025: Expected comma or open brace, found 'GetMoneyOver('
(3694,10): run-time error CSS1031: Expected selector, found 'ActiveCommunication('
(3694,10): run-time error CSS1025: Expected comma or open brace, found 'ActiveCommunication('
(3711,10): run-time error CSS1031: Expected selector, found 'LogMapped('
(3711,10): run-time error CSS1025: Expected comma or open brace, found 'LogMapped('
(3721,10): run-time error CSS1031: Expected selector, found 'CurrentRelation('
(3721,10): run-time error CSS1025: Expected comma or open brace, found 'CurrentRelation('
(3744,26): run-time error CSS1031: Expected selector, found ';'
(3744,26): run-time error CSS1025: Expected comma or open brace, found ';'
(3746,1): run-time error CSS1019: Unexpected token, found '$'
(3746,2): run-time error CSS1019: Unexpected token, found '('
(3746,11): run-time error CSS1031: Expected selector, found ')'
(3746,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3779,2): run-time error CSS1019: Unexpected token, found ')'
(3781,10): run-time error CSS1031: Expected selector, found 'SaveCertificate('
(3781,10): run-time error CSS1025: Expected comma or open brace, found 'SaveCertificate('
(3784,1): run-time error CSS1019: Unexpected token, found '$'
(3784,2): run-time error CSS1019: Unexpected token, found '('
(3784,11): run-time error CSS1031: Expected selector, found ')'
(3784,11): run-time error CSS1025: Expected comma or open brace, found ')'
(3787,2): run-time error CSS1019: Unexpected token, found ')'
(3789,21): run-time error CSS1031: Expected selector, found ';'
(3789,21): run-time error CSS1025: Expected comma or open brace, found ';'
(3790,10): run-time error CSS1031: Expected selector, found 'ContactCallTimer('
(3790,10): run-time error CSS1025: Expected comma or open brace, found 'ContactCallTimer('
(3800,14): run-time error CSS1031: Expected selector, found '='
(3800,14): run-time error CSS1025: Expected comma or open brace, found '='
(3801,10): run-time error CSS1031: Expected selector, found 'ContactCallCheck('
(3801,10): run-time error CSS1025: Expected comma or open brace, found 'ContactCallCheck('
(3814,10): run-time error CSS1031: Expected selector, found 'ContactCallPulse('
(3814,10): run-time error CSS1025: Expected comma or open brace, found 'ContactCallPulse('
(3823,19): run-time error CSS1031: Expected selector, found '='
(3823,19): run-time error CSS1025: Expected comma or open brace, found '='
(3824,10): run-time error CSS1031: Expected selector, found 'ContactCallEventAlerts('
(3824,10): run-time error CSS1025: Expected comma or open brace, found 'ContactCallEventAlerts('
(3857,10): run-time error CSS1031: Expected selector, found 'ContactCallBlock('
(3857,10): run-time error CSS1025: Expected comma or open brace, found 'ContactCallBlock('
(3872,10): run-time error CSS1031: Expected selector, found 'CallClear('
(3872,10): run-time error CSS1025: Expected comma or open brace, found 'CallClear('
(3878,15): run-time error CSS1031: Expected selector, found ';'
(3878,15): run-time error CSS1025: Expected comma or open brace, found ';'
(3879,10): run-time error CSS1031: Expected selector, found 'ContactCallToggle('
(3879,10): run-time error CSS1025: Expected comma or open brace, found 'ContactCallToggle('
(3912,18): run-time error CSS1031: Expected selector, found '='
(3912,18): run-time error CSS1025: Expected comma or open brace, found '='
(3913,18): run-time error CSS1031: Expected selector, found '='
(3913,18): run-time error CSS1025: Expected comma or open brace, found '='
(3960,16): run-time error CSS1031: Expected selector, found '='
(3960,16): run-time error CSS1025: Expected comma or open brace, found '='
(3962,15): run-time error CSS1031: Expected selector, found ';'
(3962,15): run-time error CSS1025: Expected comma or open brace, found ';'
(3963,17): run-time error CSS1031: Expected selector, found ';'
(3963,17): run-time error CSS1025: Expected comma or open brace, found ';'
(3964,10): run-time error CSS1031: Expected selector, found 'ShowContactInfo('
(3964,10): run-time error CSS1025: Expected comma or open brace, found 'ShowContactInfo('
(4052,10): run-time error CSS1031: Expected selector, found 'ShowTerContactMerc('
(4052,10): run-time error CSS1025: Expected comma or open brace, found 'ShowTerContactMerc('
(4059,10): run-time error CSS1031: Expected selector, found 'SaveTerContactMercMail('
(4059,10): run-time error CSS1025: Expected comma or open brace, found 'SaveTerContactMercMail('
(4086,10): run-time error CSS1031: Expected selector, found 'ForgotMail('
(4086,10): run-time error CSS1025: Expected comma or open brace, found 'ForgotMail('
 */
// Unobtrusive Ajax support library for jQuery
// Copyright (C) Microsoft Corporation. All rights reserved.
// @version v3.2.5
// 
// Microsoft grants you the right to use these script files for the sole
// purpose of either: (i) interacting through your browser with the Microsoft
// website or online service, subject to the applicable licensing or use
// terms; or (ii) using the files as included with a Microsoft product subject
// to that product's license terms. Microsoft reserves all other rights to the
// files not expressly granted by Microsoft, whether by implication, estoppel
// or otherwise. Insofar as a script file is dual licensed under GPL,
// Microsoft neither took the code under GPL nor distributes it thereunder but
// under the terms set out in this paragraph. All notices and licenses
// below are for informational purposes only.
!function(t){function a(t,a){for(var e=window,r=(t||"").split(".");e&&r.length;)e=e[r.shift()];return"function"==typeof e?e:(a.push(t),Function.constructor.apply(null,a))}function e(t){return"GET"===t||"POST"===t}function r(t,a){e(a)||t.setRequestHeader("X-HTTP-Method-Override",a)}function n(a,e,r){var n;r.indexOf("application/x-javascript")===-1&&(n=(a.getAttribute("data-ajax-mode")||"").toUpperCase(),t(a.getAttribute("data-ajax-update")).each(function(a,r){switch(n){case"BEFORE":t(r).prepend(e);break;case"AFTER":t(r).append(e);break;case"REPLACE-WITH":t(r).replaceWith(e);break;default:t(r).html(e)}}))}function u(u,i){var o,d,c,s;o=u.getAttribute("data-ajax-confirm"),o&&!window.confirm(o)||(d=t(u.getAttribute("data-ajax-loading")),s=parseInt(u.getAttribute("data-ajax-loading-duration"),10)||0,t.extend(i,{type:u.getAttribute("data-ajax-method")||void 0,url:u.getAttribute("data-ajax-url")||void 0,cache:"true"===(u.getAttribute("data-ajax-cache")||"").toLowerCase(),beforeSend:function(t){var e;return r(t,c),e=a(u.getAttribute("data-ajax-begin"),["xhr"]).apply(u,arguments),e!==!1&&d.show(s),e},complete:function(){d.hide(s),a(u.getAttribute("data-ajax-complete"),["xhr","status"]).apply(u,arguments)},success:function(t,e,r){n(u,t,r.getResponseHeader("Content-Type")||"text/html"),a(u.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(u,arguments)},error:function(){a(u.getAttribute("data-ajax-failure"),["xhr","status","error"]).apply(u,arguments)}}),i.data.push({name:"X-Requested-With",value:"XMLHttpRequest"}),c=i.type.toUpperCase(),e(c)||(i.type="POST",i.data.push({name:"X-HTTP-Method-Override",value:c})),t.ajax(i))}function i(a){var e=t(a).data(c);return!e||!e.validate||e.validate()}var o="unobtrusiveAjaxClick",d="unobtrusiveAjaxClickTarget",c="unobtrusiveValidation";t(document).on("click","a[data-ajax=true]",function(t){t.preventDefault(),u(this,{url:this.href,type:"GET",data:[]})}),t(document).on("click","form[data-ajax=true] input[type=image]",function(a){var e=a.target.name,r=t(a.target),n=t(r.parents("form")[0]),u=r.offset();n.data(o,[{name:e+".x",value:Math.round(a.pageX-u.left)},{name:e+".y",value:Math.round(a.pageY-u.top)}]),setTimeout(function(){n.removeData(o)},0)}),t(document).on("click","form[data-ajax=true] :submit",function(a){var e=a.currentTarget.name,r=t(a.target),n=t(r.parents("form")[0]);n.data(o,e?[{name:e,value:a.currentTarget.value}]:[]),n.data(d,r),setTimeout(function(){n.removeData(o),n.removeData(d)},0)}),t(document).on("submit","form[data-ajax=true]",function(a){var e=t(this).data(o)||[],r=t(this).data(d),n=r&&(r.hasClass("cancel")||void 0!==r.attr("formnovalidate"));a.preventDefault(),(n||i(this))&&u(this,{url:this.action,type:this.method||"GET",data:e.concat(t(this).serializeArray())})})}(jQuery);
/*Biblioteca do Nota Registrada*/

//Automação
$(document).ready(function () {
    setTimeout(function () { $(window).bind("resize", function () { nrReloadScripts() }); }, 100);
});

//Controle de Sessão

$(function () {
    // Set idle time
    try {
        $(document).idleTimer(3300000);
    }
    catch (ex) {

    }
});

var idleEvents;
var oldOptions;

$(function () {
    $(document).on("idle.idleTimer", function (event, elem, obj) {
        // function you want to fire when the user goes idle

        oldOptions = toastr.options.timeOut;
        toastr.options.timeOut = false;
        toastr.warning('Você será deslogado em 5 minutos', 'Alerta de Inatividade');
        toastr.options.timeOut = oldOptions;

        idleEvents = setTimeout(function () {
            document.getElementById('logoutForm').submit()
        }, 300000)
    });

    $(document).on("active.idleTimer", function (event, elem, obj, triggerevent) {
        clearTimeout(idleEvents);
        toastr.clear();
        $('.custom-alert').fadeOut();

        toastr.success('Bom trabalho.', 'Você está de volta!');
    });
});

function ToastMessage(type, messages) {
    var messagesS = messages.split('#;')

    for (var i = 0 ; i < messagesS.length; i++) {
        message = messagesS[i];

        if (message.indexOf('</button>') != -1) {
            toastr.options.timeOut = false;
            toastr.options.extendedTimeOut = false;
        }

        switch (type) {
            case 'info': { toastr.info(message); } break;
            case 'success': { toastr.success(message); } break;
            case 'warning': { toastr.warning(message); } break;
            case 'error': { toastr.error(message); } break;
        }

        toastr.options.timeOut = oldOptions;
        toastr.options.extendedTimeOut = 1000;
    }
}

//
var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function (event) {
    currentMousePos.x = event.pageX;
    currentMousePos.y = event.pageY;
});

function GetBrowser() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return { name: 'IE', version: (tem[1] || '') };
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bOPR|Edge\/(\d+)/)
        if (tem != null) { return { name: 'Opera', version: tem[1] }; }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); }
    return {
        name: M[0],
        version: M[1]
    };
}

$(document).ready(function () {
    toastr.options = {
        "closeButton": false,
        "newestOnTop": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": true,
        "timeOut": "10000",
        "limit": 3
    }
})

$(document).on('click', function (e) {
    $('[data-toggle="popover"],[data-original-title]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            (($(this).popover('hide').data('bs.popover') || {}).inState || {}).click = false  // fix for BS 3.3.6
        }

    });
});

var start = new Date;

$(document).ready(function () {
    var date = new Date();
    $('#nrData').each(function () { $(this).text(("0" + (date.getDate())).slice(-2) + "/" + ("0" + (date.getMonth() + 1)).slice(-2) + "/" + date.getFullYear()); });
    $('#nrHora').each(function () { $(this).text(("0" + (date.getHours())).slice(-2) + ":" + ("0" + (date.getMinutes())).slice(-2)); });

    setInterval(function () {

        $('#nrData').each(function () { $(this).text(("0" + (date.getDate())).slice(-2) + "/" + ("0" + (date.getMonth() + 1)).slice(-2) + "/" + date.getFullYear()); });
        $('#nrHora').each(function () { $(this).text(("0" + (date.getHours())).slice(-2) + ":" + ("0" + (date.getMinutes())).slice(-2)); });
    }, 5000)
});

$(document).ready(function () {
    var zoom = 1 / ZoomGlobal;
    $('#fc_frame').css('zoom', zoom);
})

function GetNowDate(seconds) {
    var date = new Date();
    var text = ("0" + (date.getDate())).slice(-2) + "/" + ("0" + (date.getMonth() + 1)).slice(-2) + "/" + date.getFullYear();
    text += ' ' + ("0" + (date.getHours())).slice(-2) + ":" + ("0" + (date.getMinutes())).slice(-2) + (seconds ? ":" + ("0" + (date.getSeconds())).slice(-2) : "");
    return text;
}

function GetQueryStringParam(name) {
    var url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function ResizeGrids() {
    setTimeout(function () {
        $('.pq-grid.panel').each(function () {
            try {
                $(this).pqGrid('refreshView');
                nrReloadScripts();
            }
            catch (err) { }
        });
    }, 10);
}

/*Data Format*/
function changeJsonDateFormat(value, isShort, hasTime, onlyTime) {
    if (value != null) {
        if (jQuery.type(value) === "string") {
            if (value.indexOf("\Date(") > 0) {
                var currentTime = new Date(parseInt(value.substr(6)));
                currentTime.setMinutes(currentTime.getMinutes() + new Date().getTimezoneOffset());

                var month = currentTime.getMonth() + 1;
                var day = currentTime.getDate();
                var year = currentTime.getFullYear();

                var date = ("0" + (day)).slice(-2) + "/" + ("0" + (month)).slice(-2);
                if (!isShort)
                    date += "/" + year;
                if (hasTime) {
                    date += " " + (('' + currentTime.getHours()).length < 2 ? '0' : '') + currentTime.getHours() + ":" + (('' + currentTime.getMinutes()).length < 2 ? '0' : '') + currentTime.getMinutes();
                }
                if (onlyTime)
                    return (('' + currentTime.getHours()).length < 2 ? '0' : '') + currentTime.getHours() + ":" + (('' + currentTime.getMinutes()).length < 2 ? '0' : '') + currentTime.getMinutes();

                return date;
            }
            else {
                d1 = value ? value.split('-') : null;
                return value ? ("0" + (d1[2])).slice(-2) + '/' + ("0" + (d1[1])).slice(-2) + '/' + d1[0] : "";
            }
        }
        else {
            var month = value.getMonth() + 1;
            var day = value.getDate();
            return (('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + value.getFullYear();
        }
    }
    else
        return '';
}

function changeDateFormat(value) {
    d1 = value ? value.split('/') : null;
    return value ? d1[1] + '/' + d1[0] + '/' + d1[2] : "";
}

function changeNumberFormat(value, divisor, after, clean) {
    if (value != null) {
        var dec = parseFloat(value);
        var ret = dec.toFixed(after).replace('.', divisor);

        if (dec < 0)
            dec = dec * -1;

        if (!clean) {
            var retSplit = ret.split(divisor);

            while (retSplit[0].length > 3) {
                ret = ret.insertAt(retSplit[0].length - 3, '.');
                retSplit = ret.split('.');
            }
        }

        return ret;
    }
    else
        return '';
}

function parseDecimal(value) {
    try {
        var parcialD = value.trim().replace('R$ ', '');

        while (parcialD.indexOf('.') != -1)
            parcialD = parcialD.replace('.', '');

        if (parcialD == '')
            return 0;

        return parseFloat(parcialD.replace(',', '.'));
    }
    catch (e) {
        return 0;
    }
}

String.prototype.insertAt = function (index, string) {
    return this.substr(0, index) + string + this.substr(index);
}

function changeCPFCNPJFormat(value, standard) {
    if (value != null && value != '') {
        var text = value.toString();
        if (standard) {

            if (text.length <= 11) {
                if (text.length < 11) {
                    if (text.length == 10)
                        text = "0" + text;
                    else
                        text = Array(11 - text.length).join("0") + text;
                }
                text = text.toString().replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
            }
            else if (text.length == 13) {
                text = '0' + text.toString().replace(/(\d{1})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
            }
            else if (text.length == 14) {
                text = text.toString().replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
            }
            else if (text.length == 15) {
                text = text.toString().replace(/(\d{3})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
            }
        }
        else {
            if (text.length <= 11) {
                if (text.length < 11)
                    text = Array(11 - text.length).join("0") + text;
                text = text.toString().replace(/(\d{4})(\d{2})(\d{3})(\d{2})/, '$1-$4');
            }
            else if (text.length == 13) {
                text = '0' + text.toString().replace(/(\d{4})(\d{3})(\d{4})(\d{2})/, '$1<br /><b>$3</b>');
            }
            else if (text.length == 14) {
                text = text.toString().replace(/(\d{4})(\d{1})(\d{3})(\d{4})(\d{2})/, '$1<br /><b>$4</b>');
            }
            else if (text.length == 15) {
                text = text.toString().replace(/(\d{4})(\d{2})(\d{3})(\d{4})(\d{2})/, '$1<br /><b>$4</b>');
            }
        }
        return text;

    }
    else
        return '';
}

//filter: {
//        type: 'textbox',
//        condition: "between",
//        init: pqDatePickerPQ,
//        listeners: [{
//            'change': function (evt, ui) {

//                ui.value = changeJsonDateFormat(ui.value);
//                ui.value2 = changeJsonDateFormat(ui.value2);

//                $(this).closest(".pq-grid").pqGrid('filter', {
//                    oper: "add",
//                    data: [ui]
//                })
//            }
//        }]
//},
function pqDatePickerPQ(ui) {
    var $this = $(this);
    $this
        //.css({ zIndex: 3, position: "relative" })
        .datepicker({
            format: 'DD/MM/YYYY',
            language: 'pt-br',
            icons: {
                time: "fa fa-clock-o",
                date: "fa fa-calendar",
                up: "fa fa-arrow-up",
                down: "fa fa-arrow-down"
            }
        });
    //default From date
    var $from = $this.filter(".pq-from").datepicker("option", "defaultDate", new Date());
    //default To date
    var $to = $this.filter(".pq-to").datepicker("option", "defaultDate", new Date());

    var value = changeJsonDateFormat(ui.column.filter.value),
        value2 = changeJsonDateFormat(ui.column.filter.value2);

    $from.val(value);
    $to.val(value2);

    $from.attr('readonly', 'readonly');
    $to.attr('readonly', 'readonly');
}

/*Page Functions*/

function nrReloadScripts() {
    pqFilterLayout();
    DatePicker();
    Special();
    Masks();
    DropSpecial();
    RowAnchors();
}

function pqFilterLayout() {
    $('.pq-header-outer').each(function () {
        if ($(this).find('.pq-grid-header-search-row').length > 0) {

            //$(this).css('height', '72px');

            var $main = $(this).closest('.pq-grid');
            if ($main.prop('style')['height'] != "") {
                //$main.css('min-height', $main.css('height'));
                $main.css('max-height', (parseInt($main.css('height')) + 14) + "px");
                $main.css('height', '');
            }
        }
        else {
            //$(this).css('height', '27px');
        }
    })

    $('.pq-td-div input, .pq-td-div select').each(function () {
        if (!$(this).hasClass('form-control')) {
            $(this).addClass('form-control');
            $(this).css('padding-left', '8px');
        }
    });

    var iconDate = '<span class="input-group-addon"><i class="fa fa-calendar"></i></span>';
    $('.pq-from-to-center').each(function () { $(this).remove(); });
    $('.pq-to-div, .pq-from-div').each(function () {
        if (!$(this).hasClass('input-group')) {
            $(this).addClass('input-group').addClass('date');

            if ($(this).hasClass('pq-to-div')) {
                $(this).css('width', '57%');
                $(this).css('padding-left', '0px');
                $(this).css('float', 'left');
                $(iconDate).insertBefore($(this).children()[0]);
            }
            else {
                $(this).css('width', '43%');
                $(this).css('padding-right', '0px');
            }
        }
    });
}

function nrSpecialDrops() {
    $(".chosen-select").chosen({
        no_results_text: "Nenhum registro encontrado",
        width: "100%"
    });

    $(".chosen-select").trigger("chosen:updated");
}

//Função para pegar o RowIndx do PQgrid, de dentro do detalhe (é, grid burro)
function RowAnchors() {
    $('.rowAnchorSearch').each(function () {
        var rowIndx = '';
        var current = $(this);
        while (rowIndx == '' && current != $('<body>')) {
            current = current.parent();
            if (current.attr("pq-row-indx") != undefined) {
                rowIndx = current.attr("pq-row-indx");
            }
        }
        $(this).val(rowIndx);
    });
}

function Special() {
    $("span.pie").each(function () {
        if (!$(this).hasClass('rendered')) {
            $(this).addClass('rendered');

            var chart = $(this);
            var color = $(this).attr("clp");
            var title = $(this).attr("title");

            $(chart).peity("pie", {
                "fill": [color, "#d7d7d7"], "width": '100%', "height": 22, "title": title, "innerRadius": 10, "radius": 30
            });
        }
    });

    var timeOutFilter;
    $(".nrFilter").each(function () {
        $(this).keyup(KeyDelay(function () {
            $(this).change();
        }, 1500));
    });

    var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch-YN'));

    elems.forEach(function (html) {
        if (!html.attributes["data-switchery"]) {
            var switchery = new Switchery(html, {
                color: '#1ab394',
                secondaryColor: '#ED5565'
            });
        }
    });

    var elems2 = Array.prototype.slice.call(document.querySelectorAll('.js-switch-ON'));
    elems2.forEach(function (html) {
        if (!html.attributes["data-switchery"]) {
            var switchery = new Switchery(html, {
                color: '#1ab394',
                secondaryColor: '#1ab394'
            });
        }
    });

    var elems3 = Array.prototype.slice.call(document.querySelectorAll('.js-switch-RE'));
    elems3.forEach(function (html) {
        if (!html.attributes["data-switchery"]) {
            var switchery = new Switchery(html, {
                color: '#000000',
                secondaryColor: '#fff'
            });
        }
    });


    $('.iChecks').each(function () {
        if (!$(this).next().hasClass('iCheck-helper')) {
            var titleh = $(this).attr('titleh');
            var titlec = $(this).attr('titlec');

            var color = 'green';
            if ($(this).hasClass('blue'))
                color = 'blue';
            else if ($(this).hasClass('red'))
                color = 'red';

            $(this).iCheck({
                checkboxClass: 'icheckbox_square-' + color,
                radioClass: 'iradio_square-green',
            });

            if (titlec != undefined) {
                $(this).parent().children('ins').attr('titlec', titlec)
            }
            if (titleh != undefined) {
                $(this).parent().children('ins').attr('titleh', titleh)
            }

            $(this).on('ifChanged', function () {
                $(this).iCheck('update');
                $(this).change();
            });

            CommitICheck(this);
        }

        function CommitICheck(target) {
            if ($(target).is(':checked')) {
                $(target).iCheck('check');
            }
            else {
                $(target).iCheck('uncheck');
            }

            if ($(target).is(':disabled')) {
                $(target).iCheck('disable');
            }
            else {
                $(target).iCheck('enable');
            }
        }
    });

    if ($('.popover-content:visible').length == 0) {
        var timeOutTitle;
        $("[titleh]").each(function () {
            if ($(this).attr('data-original-title') == undefined && !$(this).is('option') && !$(this).is('select')) {
                var texto = $(this).attr('titleh');
                while (texto.indexOf('"') > -1) {
                    texto = texto.replace('"', "'");
                }

                $(this).popover({
                    trigger: 'hover',
                    content: texto.replace(/\n/g, '</br>'),
                    container: 'body',
                    placement: 'top',
                    html: true,
                }).mouseleave(function (e) {
                    timeOutTitle = setTimeout(function () {
                        $('.popover').each(function () {
                            $(this).popover('hide');
                            clearTimeout(timeOutTitle);
                        });
                    }, 800);
                }).mousedown(function (e) {
                    clearTimeout(timeOutTitle);
                    $('.popover').each(function () {
                        $(this).popover('hide');
                    });
                }).mouseenter(function (e) {
                    $('.popover').each(function () {
                        if ($(this).attr('id') == 'popoverIddle')
                            $(this).fadeOut();
                    });
                    clearTimeout(timeOutTitle);
                    //var target = $('.popover:visible');
                    //$(target).popover('show');

                    //var wid = parseInt($(target).css('width'));
                    //var hei = parseInt($(target).css('height'));

                    //var relX = (e.pageX / ZoomGlobal) - (wid / 2);
                    //var relY = (e.pageY / ZoomGlobal) - hei;

                    //$(target).css('left', relX + 'px');
                    //$(target).css('top', relY + 'px');
                });
            }
        });
        $("[titlehl]").each(function () {
            if ($(this).attr('data-original-title') == undefined && !$(this).is('option') && !$(this).is('select')) {
                var texto = $(this).attr('titlehl');
                while (texto.indexOf('"') > -1) {
                    texto = texto.replace('"', "'");
                }

                $(this).popover({
                    trigger: 'hover',
                    content: texto.replace(/\n/g, '</br>'),
                    container: 'body',
                    placement: 'left',
                    html: true,
                    offset: '45% 45%'
                }).mouseleave(function (e) {
                    timeOutTitle = setTimeout(function () {
                        $('.popover').each(function () {
                            $(this).popover('hide');
                            clearTimeout(timeOutTitle);
                        });
                    }, 800);
                }).mousedown(function (e) {
                    clearTimeout(timeOutTitle);
                    $('.popover').each(function () {
                        $(this).popover('hide');
                    });
                }).mouseenter(function (e) {
                    clearTimeout(timeOutTitle);

                    var target = $('.popover:visible');
                    $(target).popover('show');

                    var topCO = parseInt($(target).find('.arrow').css('top'));
                    var topC = topCO - ($(target).height() * 0.5);

                    $(target).find('.arrow').css('top', '50%');

                    var top = topC + parseInt($(target).css('top'));

                    $(target).css('top', top + 'px');
                    //$(target).css('left', left + 'px');                    
                });
            }
        });
        $("[titlehr]").each(function () {
            if ($(this).attr('data-original-title') == undefined && !$(this).is('option') && !$(this).is('select')) {
                var texto = $(this).attr('titlehr');
                while (texto.indexOf('"') > -1) {
                    texto = texto.replace('"', "'");
                }

                $(this).popover({
                    trigger: 'hover',
                    content: texto.replace(/\n/g, '</br>'),
                    container: 'body',
                    placement: 'right',
                    html: true,
                    offset: '45% 45%'
                }).mouseleave(function (e) {
                    timeOutTitle = setTimeout(function () {
                        $('.popover').each(function () {
                            $(this).popover('hide');
                            clearTimeout(timeOutTitle);
                        });
                    }, 800);
                }).mousedown(function (e) {
                    clearTimeout(timeOutTitle);
                    $('.popover').each(function () {
                        $(this).popover('hide');
                    });
                }).mouseenter(function (e) {
                    clearTimeout(timeOutTitle);

                    var target = $('.popover:visible');
                    $(target).popover('show');

                    var topCO = parseInt($(target).find('.arrow').css('top'));
                    var topC = topCO - ($(target).height() * 0.5);

                    $(target).find('.arrow').css('top', '50%');

                    var top = topC + parseInt($(target).css('top'));

                    $(target).css('top', top + 'px');
                    //$(target).css('left', left + 'px'); 
                });
            }
        });
        $("[titlec]").each(function () {
            if ($(this).attr('data-original-title') == undefined && !$(this).is('option') && !$(this).is('select')) {
                var texto = $(this).attr('titlec');
                $(this).removeAttr('titlec');
                $(this).popover({
                    trigger: 'click',
                    content: texto.replace(/\n/g, '</br>'),
                    container: 'body',
                    placement: 'top',
                    html: true,
                });
            }
        });
    }

    $('.nrImportant').each(function () {
        var atual = $(this);
        //$(atual).css('border', '2px solid');
        //setInterval(function () {
        //    $(atual).animate({
        //        borderColor: "white"
        //    }, 250);
        //    $(atual).animate({
        //        borderColor: "gray"
        //    }, 250);
        //}, 500);
    });

    $('.ladda-button').each(function () {
        var botao = $(this).ladda();

        botao.click(function () {
            botao.ladda('start');

            if ($(this).closest('div[class~="NRform"]').length == 0)
                setTimeout(function () {
                    botao.ladda('stop');
                }, 2000);
        });
    });
}

function NrButtonStop() {
    $('.ladda-button').each(function () {
        $(this).ladda('stop');
    });
}

function DropSpecial() {
    $('.summernote').each(function () {
        if ($(this).css('display') == 'block') {
            $(this).summernote({
                toolbar: [
                  // [groupName, [list of button]]
                  ['style', ['bold', 'italic', 'underline', 'clear']],
                  ['fontsize', ['fontsize']],
                  ['para', ['ul', 'ol', 'paragraph']],
                  ['height', ['height']]
                ]
            });
        }
    });

    $('.dropdown-toggle').dropdown();
}

//Delay
function KeyDelay(f, delay) {
    var timer = null;
    return function () {
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = window.setTimeout(function () {
            f.apply(context, args);
        },
        delay || 500);
    };
}

var EditingDateP = false;
function DatePicker() {
    var bindDatePicker = function () {
        //Somente Meses
        $("input[data-mask='99/9999']").each(function () {
            var isDoc = $(this).hasClass('financial');

            var startDate = new Date(new Date().setFullYear(new Date().getFullYear() - 10));
            var endDate = new Date(new Date().setFullYear(new Date().getFullYear() + 10));

            if (isDoc) {
                startDate = new Date();
                endDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
            }

            $(this).datepicker({
                format: 'MM yyyy',
                language: 'pt-br',
                startView: "months",
                minViewMode: "months",
                startDate: startDate,
                endDate: endDate,
                autoclose: true,
                icons: {
                    time: "fa fa-clock-o",
                    date: "fa fa-calendar",
                    up: "fa fa-arrow-up",
                    down: "fa fa-arrow-down"
                }
            });

            $(this).datepicker()
              .on("changeDate", function (e) {
                  // check if the date is correct. We can accept dd-mm-yyyy and yyyy-mm-dd.
                  // update the format if it's yyyy-mm-dd
                  if (EditingDateP) {
                      return false;
                  }

                  var dateString = parseDateName($(this).val());
                  var date = parseDate(dateString);
                  var locked = $(this).is('[readonly]')

                  if (!isValidDate(date) && locked && $(this).val().trim() != '') {
                      $(this).val($(this).attr('previous-data'));
                  }
                  else {
                      $(this).attr('previous-data', dateString);
                      $(this).datepicker('update');
                  }

              }).on("changeDate", this.onchange)
                .on("hide", function () {
                    var d = $(this).attr('previous-data').ToDate();
                    $(this).val(d.FormatDate("MMMM yyyy"));
                });

            var idD = $(this).attr('id');
            $(this).parent().click(function () { $('#' + idD).datepicker("show"); });

            var dateString = parseDateName($(this).val());
            $(this).attr('previous-data', dateString);
            $(this).prop('onchange', '').unbind('change');
        });

        //Datas completas
        $("input[data-mask='99/99/9999']").each(function () {
            var isDoc = $(this).hasClass('financial');

            var startDate = new Date(new Date().setFullYear(new Date().getFullYear() - 10));
            var endDate = new Date(new Date().setFullYear(new Date().getFullYear() + 10));

            if (isDoc) {
                startDate = new Date();
                endDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
            }

            $(this).datepicker({
                format: 'dd/mm/yyyy',
                language: 'pt',
                startDate: startDate,
                endDate: endDate,
                autoclose: true,
                icons: {
                    time: "fa fa-clock-o",
                    date: "fa fa-calendar",
                    up: "fa fa-arrow-up",
                    down: "fa fa-arrow-down"
                }
            });

            $(this).datepicker()
              .on("changeDate", function (e) {
                  // check if the date is correct. We can accept dd-mm-yyyy and yyyy-mm-dd.
                  // update the format if it's yyyy-mm-dd
                  if (EditingDateP) {
                      return false;
                  }

                  var date = parseDate($(this).val());
                  var locked = $(this).is('[readonly]')

                  if (!isValidDate(date) && locked && $(this).val().trim() != '') {
                      $(this).val($(this).attr('previous-data'));
                  }
                  else {
                      $(this).attr('previous-data', $(this).val());
                      $(this).datepicker('update');
                  }

              }).on("changeDate", this.onchange)
                .on("hide", function () {
                    $(this).val($(this).attr('previous-data'));
                });

            var idD = $(this).attr('id');
            $(this).parent().click(function () { $('#' + idD).datepicker("show"); });

            $(this).attr('previous-data', $(this).val());
            $(this).prop('onchange', '').unbind('change');
        });
    }

    var isValidDate = function (value, format) {
        format = format || false;
        // lets parse the date to the best of our knowledge
        if (format) {
            value = parseDate(value);
        }

        var timestamp = Date.parse(value);

        return isNaN(timestamp) == false;
    }

    var parseDateName = function (value) {
        var dateSplit = value.split(' ');
        var dateString = "01/" + ("0" + (monthNames.indexOf(dateSplit[0].replace('�', 'ç')) + 1)).slice(-2) + "/" + dateSplit[1];

        return dateString;
    }

    var parseDate = function (value) {
        var m = value.match(/^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/);
        if (m)
            value = m[5] + '-' + ("00" + m[3]).slice(-2) + '-' + ("00" + m[1]).slice(-2);

        return value;
    }

    bindDatePicker();
}

function Masks() {
    $('.form-control.decimal').each(function () {
        $(this).keydown(function (e) {

        });
    });

    $('input[data-mask]').each(function () {
        var valueD = $(this).val();
        $(this).inputmask({
            mask: $(this).attr('data-mask')
        })
        $(this).val(valueD);
    });
}

/*Utilities*/

var zIndexM = 3000;
jQuery.fn.extend({
    nModal: function (cmd) {
        if (cmd == 'show') {
            this.modal('show');

            var idM = this.attr('id');

            $('#' + idM).css('z-index', '');
            $('#' + idM).attr({ 'style': $('#' + idM).attr('style') + ';z-index: ' + zIndexM + ' !important' });
            zIndexM += 10;
        }
        else {
            this.modal(cmd);
        }
    },
});


var globalWindow;

function OpenNrWindow(url, width, height) {
    if (globalWindow != null) {
        if (globalWindow.closed) {
            globalWindow = null;
        }
    }

    if (globalWindow == null) {
        var oW = $(window).width(),
            oH = $(window).height();

        var wW = oW * (width / 100),
            wH = oH * (height / 100);

        var left = (oW / 2) - (wW / 2),
            top = (oH / 2) - (wH / 2);

        globalWindow = window.open(url, "popup", "title='Viewer', width=" + wW + ", height=" + wH + ", top=" + top + ", left=" + left);
    }
    else {
        globalWindow.location.href = url;
    }
}

var ConfirmationD = false;
function ConfirmDialog(title, message, eventYes) {
    ConfirmationD = false;

    var modalHtml = "<div class='modal inmodal' id='divConfirme' tabindex='-1' role='dialog' aria-hidden='true' style='display: none; padding-right: 17px;z-index: 4000 !important;'>\
                    <div class='modal-dialog modal-lg'>\
                        <div class='modal-content animated fadeIn'>\
                            <div class='modal-header' style='padding:10px;border-bottom: 0px;'>\
                                <h4 class='modal-title'>"+ title + "</h4>\
                            </div>\
                            <div class='modal-body'> " + message + "\
                            </div>\
                            <div class='modal-footer' style='border-top:0px;'>\
                                <button type='button' class='btn btn-white' data-dismiss='modal' id='divConfirmCancel'>Cancelar</button>\
                                <button type='button' class='btn btn-primary' id='divConfirmOK' >Confirmar</button>\
                            </div>\
                        </div>\
                    </div>\
                </div>";


    var modal = $(modalHtml).appendTo('body');
    $('#divConfirmCancel').click(function () { modal.modal("hide"); modal.remove() });
    $('#divConfirmOK').click(function () { ConfirmationD = true; eventYes(); modal.modal("hide"); modal.remove() });
    $('.popover').popover('hide');
    modal.modal("show");

    modal.on('hidden.bs.modal', function () {
        if (!ConfirmationD)
            $('button[type="submit"]').each(function () { if ($(this) != undefined) { $(this).ladda('stop'); } });
    })
};

var MouseOverTimer;

function MouseOver(sender, event, time) {
    MouseOverTimer = setTimeout(function () {
        event();
        clearTimeout(MouseOverTimer);
    }, time);

    $(sender).mouseleave(function () {
        clearTimeout(MouseOverTimer);
    });
}

function OpenPositionModal(origem, destino, fTop, position) {
    var tempScrollTop = $(window).scrollTop();

    var destinoM = $('#' + $(destino).attr('id') + ' .modal-content');
    var destinoD = $('#' + $(destino).attr('id') + ' .modal-dialog');

    var height = parseInt($(destinoM).css('height')) + 50;

    $(destino).css("position", "absolute");
    $(destinoM).css("position", "absolute");
    $(destinoD).css("position", "absolute");
    $(destino).css("overflow-y", "hidden");

    var windowS = $(window).scrollTop();
    var windowW = ($(window).width() / ZoomGlobal);
    var windowH = ($(window).height() / ZoomGlobal);

    var leftP = ($(origem).offset().left - ($(destinoM).width() - $(origem).width()) / 2);
    var topP = ($(origem).offset().top - ($(destinoM).height() - $(origem).height()) / 2) - windowS;

    if (position != undefined) {
        var positions = position.split(';');

        if (position.indexOf('bot') != -1) {
            topP = ($(origem).offset().top + 10) - windowS;
        }

        if (position.indexOf('right') != -1) {
            leftP = ($(origem).offset().left);
        }

        if (position.indexOf('center') != -1) {
            leftP = (windowW / 2 - ($(destinoM).width() / 2));
        }
    }

    if (leftP < 0)
        leftP = 10;

    if ((windowW - 10) < (leftP + $(destinoM).width()))
        leftP = windowW - ($(destinoM).width() + 10);

    if (fTop) {
        topP = 20;
        leftP = leftP - 70;
    }
    else if ((topP + height - windowH) > 0) {
        topP = windowH - height - 10;
    }

    $(destino).css("height", $(wrapper).height());
    $(destinoM).css("left", leftP);
    $(destinoM).css("top", (windowS / ZoomGlobal) + topP);

    $('.popover').popover('hide');
    $(destino).nModal("show");
    $(destino).css("overflow-y", "");

    $(window).scrollTop(tempScrollTop);
}

//class = " nrZone(obrigatorio) graphic(nome customizado) group1(grupo de zonas a ser controlado) "
function AlterFinZone(zone, group) {
    $(".nrZone.group" + group).each(function () {
        if ($(this).hasClass(zone))
            $(this).show();
        else
            $(this).hide();
    });
}

function MaxLength(text, max, reverse) {
    if (text == undefined)
        return '';

    if (reverse == false || reverse == undefined) {
        text = text.split('<div>')[0];

        if (text.length > max)
            return jQuery.trim(text).substring(0, max).trim() + "...";
        else
            return text;
    }
    else {
        text = text.split('<div>')[0];

        if (text.length > max)
            return "..." + jQuery.trim(text).substring(text.length - max, text.length).trim();
        else
            return text;
    }
}

function dateAddDays(date, addDays) {
    var dat = parseDate(date);
    dat.setDate(dat.getDate() + addDays);

    var month = dat.getMonth() + 1;
    var day = dat.getDate();
    var year = dat.getFullYear();

    return year + "-" + ("0" + (month)).slice(-2) + "-" + ("0" + (day)).slice(-2);
}

function parseDate(str, isBR) {
    str = str.replace('-', '/').replace('-', '/').replace('-', '/');

    if (isBR) {
        var mdy = str.split('/')
        return new Date(mdy[2], mdy[1] - 1, mdy[0]);
    }
    else {
        var mdy = str.split('/')
        return new Date(mdy[0], mdy[1] - 1, mdy[2]);
    }
}

function dayDiff(sDateA, sDateB) {
    var dateA = parseDate(sDateA);
    var dateB = parseDate(sDateB);

    return Math.round((dateB - dateA) / (1000 * 60 * 60 * 24));
}

function charFraction(sDateA, sDateB, isDiv) {
    var dateA = parseDate(sDateA);
    var dateB = parseDate(sDateB);
    var nowD = new Date();

    var dataCalc = 0;
    var dataAlt = 0;

    if (dateB.toLocaleDateString() == nowD.toLocaleDateString()) {
        return 100;
    }
    else if (dateB > nowD && !isDiv) {
        dataCalc = Math.ceil((dateB - dateA) / (1000 * 60 * 60 * 24));
        dataAlt = Math.ceil((nowD - dateA) / (1000 * 60 * 60 * 24));
    }
    else {
        dataAlt = Math.round((nowD - dateB) / (1000 * 60 * 60 * 24));
        if (!isDiv)
            dataCalc = 120;
        else
            dataCalc = 30;
    }

    dataAlt = dataAlt < 0 ? dataAlt * -1 : dataAlt;
    return Math.ceil((100 * dataAlt) / dataCalc);
}

function daysToDate(sDateB, isDiv) {
    var dateB = parseDate(sDateB);
    var nowD = new Date();

    var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds

    if (dateB.toLocaleDateString() == nowD.toLocaleDateString())
        return "0";

    var res = (nowD.getTime() - dateB.getTime()) / (oneDay);

    if (res > 0 && !isDiv)
        return '+' + Math.ceil(res);
    else
        return Math.floor(res);
}

function ToDateString(tick, interval) {
    var months = ['Jan', 'Fev', 'Mar', 'Abr', "Mai", 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
    var monthsL = ['Janeiro', 'Fevereiro', 'Março', 'Abril', "Maio", 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];

    var date = new Date(tick);

    switch (interval) {
        case "day": return date.getDate() + ' de ' + months[date.getMonth()];
        case "month": return monthsL[date.getMonth()];
        case "year": date.getYear();
    }
}

/*Zonas*/

function CloseTop() {
    $('.navbar-static-top').hide();
}

function CloseSide() {
    $('.navbar-static-side').hide();
    $('#page-wrapper').css('margin-left', '0px');
}

/*Tab Control*/

function OpenTabZone(target, modal) {
    var tempScrollTop = $(window).scrollTop();

    $('.popover').popover('hide');
    $(modal).nModal('show');
    setTimeout(function () { $(target).click(); }, 400);

    $(window).scrollTop(tempScrollTop);
}

function ChangeTab(target, sender) {
    $('.nrTab').each(function () {
        $(this).removeClass('active');
    });

    $(sender).addClass('active');

    $('.nrPanel').each(function () {
        $(this).hide();
    });

    $(target).show();
}

function GetAnimation(name) {
    switch (name) {
        case "fading-circle":
            return "<div class='sk-spinner sk-spinner-fading-circle'>\
                        <div class='sk-circle1 sk-circle'></div>\
                        <div class='sk-circle2 sk-circle'></div>\
                        <div class='sk-circle3 sk-circle'></div>\
                        <div class='sk-circle4 sk-circle'></div>\
                        <div class='sk-circle5 sk-circle'></div>\
                        <div class='sk-circle6 sk-circle'></div>\
                        <div class='sk-circle7 sk-circle'></div>\
                        <div class='sk-circle8 sk-circle'></div>\
                        <div class='sk-circle9 sk-circle'></div>\
                        <div class='sk-circle10 sk-circle'></div>\
                        <div class='sk-circle11 sk-circle'></div>\
                        <div class='sk-circle12 sk-circle'></div>\
                    </div>";
        case "chasing-dots":
            return "<div class='sk-spinner sk-spinner-chasing-dots'>\
                        <div class='sk-dot1'></div>\
                        <div class='sk-dot2'></div>'\
                    </div>";
    }
}

var anchors = [];
function BlinkLine() {
    for (var i = 0; i < anchors.length; i++) {
        var anchorT = anchors[i];

        //Quando o PQuery atualiza a linha, o objeto some, e precisa ser pego novamente
        var selector = 'div[id="' + anchorT[0].id + '"]';
        var toClone = $(selector).length > 1;

        if (toClone)
            CloneLine();

        $(selector).each(function () {
            $(this).parent().parent().css({ 'transition': '0,4s !important', 'background': '#d8e8fa' });
            $(this).parent().parent().addClass('blinkLine');
        });
    }

    setTimeout(function () {
        $('.blinkLine').each(function () {
            $(this).removeClass('blinkLine');
            $(this).css({ 'transition': '0,4s !important', 'background': '' });
        });
    }, 400);

    anchors = [];
}

function Bounce(sender) {
    $(sender).animate({
        top: -10,
    }, 200);
    $(sender).animate({
        top: 0,
    }, 100);

    $(sender).animate({
        top: -6,
    }, 100);
    $(sender).animate({
        top: 0,
    }, 100);

    $(sender).animate({
        top: -3,
    }, 100);
    $(sender).animate({
        top: 0,
    }, 100);
}
/*

Manual de Utilização da "biblioteca" para formulários assincronos

Todos os modelos devem ser construídos e validados através de DataAnnotations e herdar da classe CustomValidations (projeto NotaRegistrada.Validation)
Qualquer tipo de listagem para um dropdown, deve ser feita através de um IEnumerable<SelectListItem> que deve ter o mesmo nome da propriedade para validação
Ex: CnpjCliente => ienumCnpjCliente
Também há a necessidade de carregar os dados em ordem, logo, em caso de um combo carregar o outro, faça com que ele tenha o nome ienum1XXX, ienum2XXX, o JS irá ignorar esta configuração na hora de bater os campos, mas vai usar esta ordem como parametro
(assim é possível carregar assincronamente todos os dados através de um único Json)

O form deve conter a classe NRform

E uma cópia do código abaixo modificado com o Id do formulário e suas ações especícicas para carregar e após salvar

    @*Modal Control Zones*@
    <script>
        function FormLoad(formId, Id)
        {
            var token = $('input[name="__RequestVerificationToken"]').val();
            switch(formId)
            {
                case "contactForm":
                    {
                        LoadNrForm("@Url.Action("Contact", "Admin")", Id, formId);
                        StartForm(Id == null, formId);
                        $('#cadContato').nModal('show');
                    }break;
            }
        }

        function FormSubmit(formId)
        {
            var token = $('input[name="__RequestVerificationToken"]').val();
            switch(formId)
            {
                case "contactForm":
                    {
                        SubmitNRForm(token, "@Url.Action("Contact", "Admin")", formId);
                        RefreshRequester();
                        RefreshTerMail();
                    }break;
            }
        }
    </script>

    Em caso de lsts, o hash de divisão é #@&, e deve ser usado como padrão na abertura do model, como ex: <input type="hidden" id="lstIdProgramacao" value="@string.Join("#@&", Model.lstIdProgramacao)" />

*/

/*Validation*/

//Usado para assegurar que não teremos posts duplicados ou anomalias
var ajaxRunning = false;
var globalHash = "#@&";

$(document).ready(function () {
    var selector = '.NRform .form-control'
    var selector2 = '.NRform button[type="submit"]'
    //if (formId != null) {
    //    selector = '#' + formId + ' ' + '.form-control';
    //    selector2 = '#' + formId + ' ' + 'button[type="submit"]';
    //}

    $(selector).each(function () {
        $(this).keydown(function (e) {
            if (ajaxRunning)
                return false;

            var code = e.which; // recommended to use e.which, it's normalized across browsers
            if (code == 13) {
                var form = $(this).closest('div[class~="NRform"]');
                FormSubmit($(form).attr('id'));
                return false;
            }
        });
    })
    $(selector2).each(function () {
        $(this).addClass("ladda-button");
        $(this).attr("data-style", "zoom-in");

        $(this).click(function () {
            if (ajaxRunning)
                return false;

            var form = $(this).closest('div[class~="NRform"]')
            FormSubmit($(form).attr('id'));
            return false;
        });
    })
})

function ReadOnly(sender, target) {
    if ($(sender).is(':checked')) {
        $(target).removeAttr('readonly');
    } else {
        $(target).attr('readonly', 'readonly');
    }
}

var currentNumber = '';
function StartForm(isNew, formId) {
    BlockFields(isNew, formId);
    var selector = 'input[mask]';
    if (formId != null)
        selector = '#' + formId + ' ' + selector;

    $(selector).each(function () {
        var maskT = $(this).attr('mask');
        if (maskT == "99.999.999/9999-99") {
            $(this).val(changeCPFCNPJFormat($(this).val(), true));
            $(this).mask(maskT);
        }
        else if (maskT == "9999?9-9999") {
            $(this).mask(maskT)
            .focusout(function (event) {
                var target, phone, element;
                target = (event.currentTarget) ? event.currentTarget : event.srcElement;
                phone = target.value.replace(/\D/g, '');
                element = $(target);
                element.unmask();
                if (phone.length > 8) {
                    element.mask("99999-999?9");
                } else {
                    element.mask("9999-9999?9");
                }
            });
        }
        else
            $(this).mask(maskT);

        $(this).val($(this).val());
    });

    nrReloadScripts();
}

function BlockFields(isNew, formId) {
    var selector = '.form-control.onlyNew';
    if (formId != null)
        selector = '#' + formId + ' ' + selector;

    var saved = false;
    $(selector).each(function () {
        if (!isNew)
            saved = true;
    });

    $(selector).each(function () {
        if ((isNew || !saved) || ($(this).val() == ''))
            $(this).removeAttr("disabled");
        else
            $(this).attr("disabled", "disabled");
    });
}

function DropClear(target, optional) {
    if (optional == undefined || optional == null)
        optional = '--Selecione--'

    if (optional == false) {
        var ddlClasses = $(target);
        ddlClasses.find('option')
        .remove()
        .end();
    }
    else {
        var ddlClasses = $(target);
        ddlClasses.find('option')
        .remove()
        .end().append($('<option>').text(optional).attr('value', ''));
    }
}

function DropData(target, json, optional) {
    DropClear(target, optional);

    var ddlClasses = $(target);
    if (json.length > 0) {
        $.each(json, function () {
            ddlClasses.append($('<option>').text(this.Text).attr('value', this.Value));
        });
    }
}

function ChangeErrorState(target, hasError) {
    if (target != undefined) {
        var found = false;
        var current = $(target);
        var i = 0; //segurança
        while (!found && !current.hasClass('ibox-content') && i < 10) {
            current = current.parent();
            if (current.hasClass("form-group")) {
                found = true;

                if (hasError) {
                    if (!current.hasClass("has-error"))
                        current.addClass("has-error");
                }
                else
                    current.removeClass("has-error");
            }
            i++;
        }
    }
}

function CleanText(text) {
    while (text.indexOf('.') >= 0)
        text = text.replace('.', '');
    while (text.indexOf('/') >= 0)
        text = text.replace('/', '');
    while (text.indexOf('-') >= 0)
        text = text.replace('-', '');
    while (text.indexOf('_') >= 0)
        text = text.replace('_', '');

    return text;
}

$.prototype.FielHierarchy = function (formId) {
    var found = 0;
    var current = $(this);
    while ($(current).prop('nodeName') != $('body').prop('nodeName')) {
        current = $(current).parent();
        if ($(current).hasClass('NRform'))
            found++;
        if ($(current).attr('Id') == formId)
            break;
    }

    return found == 1;
}
$.prototype.ClearErrorState = function () {
    var formId = $(this).attr('id');

    $(this).find('.form-group.has-error').each(function () {
        if ($(this).FielHierarchy(formId))
            $(this).removeClass('has-error');
    });
    $(this).find('.field-validation-valid').each(function () {
        if ($(this).FielHierarchy(formId))
            $(this).text("");
    });
}

function GetTarget(formId, targetId) {
    return $('#' + formId + ' ' + '#' + targetId);
}

/*Ajax*/

var shadowZone = "<div id='{Id}' style='position: absolute;width:  100%;height: 100%;margin: -{margin}px;padding-top:10%;z-index: 10;background-color:  black;opacity: 0.3;'>" + GetAnimation('chasing-dots') + "</div>";

function LoadNrForm(url, id, formId, extraId) {
    var filter = GetQueryStringParam("filter");
    ajaxRunning = true;

    var margin = $('#' + formId).css('padding').replace('px', '');

    $('#' + formId).prepend(shadowZone.replace('{Id}', 'shadow' + formId).replace('{margin}', margin));

    return $.ajax({
        type: "GET",
        dataType: 'json',
        url: url,
        data: { Id: id, ajax: true, filter: filter },
        success: function (json) {
            //Primeiro vc carrega todos os DropDowns, para não dar erro com os valores
            var re = /ienum[a-zA-Z0-9]{0,}/;
            var dropSpecial = []
            var match;

            for (var i in json.data) {
                if (match = re.exec(i)) {
                    var rep = "ienum";

                    dropSpecial.push(i.replace(rep, ""));
                    DropData($('#' + i.replace(rep, "")), json.data[i]);
                }
            }
            for (var i in json.data) {
                var targetS = 'span[data-valmsg-for="' + i + '"]'

                if (formId != null)
                    targetS = '#' + formId + ' ' + targetS;
                var target = $(targetS);

                if ($(target).length > 0) {
                    $(target).text("");
                    ChangeErrorState(target, false);
                }
                ChangeErrorState(i, false);

                if (!(match = re.exec(i))) {
                    var compS = '#' + i;
                    var II = i;
                    var isDrop = false;

                    if (dropSpecial.indexOf(i) != -1) {
                        isDrop = true;
                    }

                    if (formId != null)
                        compS = '#' + formId + ' #' + II;
                    var comp = $(compS);

                    if ($(comp).hasClass("onlyValues")) {
                        if (json.data[II] == null) {
                            $(comp).closest('div[class~="form-group"]').parent().hide();
                        }
                        else {
                            $(comp).closest('div[class~="form-group"]').parent().show();
                        }
                    }

                    if ($.isArray(json.data[II])) {
                        $(comp).val(json.data[II].join(globalHash));
                    }
                    else if (isDrop) {
                        $(comp).val(json.data[II]);
                        $(comp).change();
                        $(comp).attr('selectedValue', json.data[II]);
                    }
                    else if ($(comp).attr("type") == "radio") {
                        $("input[id='" + $(comp).attr("id") + "'][value='" + json.data[II] + "']").prop("checked", true);
                    }
                    else if ($(comp).attr("type") == "checkbox") {
                        if ($(comp).hasClass('iChecks')) {
                            if (json.data[II])
                                $(comp).iCheck('check');
                            else
                                $(comp).iCheck('uncheck');
                        }
                        else {
                            $(comp).prop("checked", json.data[II]);
                            $(comp).change();
                        }
                    }
                    else {
                        if (json.data[II] != null) {
                            if (json.data[II].toString().indexOf("\Date(") > 0) {
                                $(comp).val(changeJsonDateFormat(json.data[II]));
                            }
                            else {
                                if ($(comp).hasClass("decimal"))
                                    $(comp).val(changeNumberFormat(json.data[II], ',', 2, true));
                                else
                                    $(comp).val(json.data[II]);
                            }
                        }
                        else
                            $(comp).val(json.data[II]);
                    }
                }
            }
            StartForm(id == null, formId);
            ajaxRunning = false;
        },
        error: function () {
            ajaxRunning = false;
            StartForm(id == null, formId);
            $('#shadow' + formId).remove();
        },
        complete: function () {
            $('#' + formId + ' button[type="submit"]').each(function () { if ($(this) != undefined) { $(this).ladda('stop'); } })
            $('#shadow' + formId).remove();

            try {
                AfterLoad(formId, id, extraId);
            }
            catch (err) {

            }
        }
    });
}

function LoadNrDrop(url, target, filterValue, special, optional) {
    DropClear(target);

    ajaxRunning = true;

    return $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: { filter: filterValue },
        success: function (json) {
            DropData(target, json.data, optional);

            var selected = $(target).attr('selectedValue');
            if (selected != null) {
                $(target).val(selected);
                $(target).removeAttr('selectedValue');
            }

            if (special) //Necessário referencia do "chosen"
                nrSpecialDrops();

            ajaxRunning = false;
        },
        error: function () {
            ajaxRunning = false;
        }
    });
}

function SubmitNRForm(token, url, formId) {
    ajaxRunning = true;

    $('#' + formId + ' button[type="submit"]').ladda('start');
    var formData = { __RequestVerificationToken: token };

    var selector = '.NRform input.form-control, .NRform select.form-control, .NRform input[type="hidden"], .NRform textarea.form-control'

    if (formId != null)
        selector = '#' + formId + ' input.form-control, #' + formId + ' select.form-control, #' + formId + ' input[type="hidden"], #' + formId + ' textarea.form-control'

    $(selector).each(function () {
        var value = '';
        if ($(this).hasClass('list')) {
            value = $(this).val().split(globalHash);
        }
        else if ($(this).attr("type") == "checkbox") {
            value = $(this).is(":checked");
        }
        else if ($(this).attr("type") == "radio") {
            if (formData[$(this).attr('id')] == undefined) {
                value = $("#" + $(this).attr("id") + ":checked").val();
            }
            else
                return true;
        }
        else if ($(this).attr("mask") != undefined) {
            value = CleanText($(this).val());
        }
        else if ($(this).hasClass("password")) {
            value = $(this).val();
        }
        else {
            value = $(this).val().toUpperCase();
        }

        formData[$(this).attr('id')] = value;
    });

    return $.ajax({
        type: "Post",
        dataType: 'json',
        url: url,
        data: formData,
        traditional: true,
        success: function (data) {
            $('#' + formId).ClearErrorState();
            if (data.modelValidation != null) {
                var validation = $.parseJSON(data.modelValidation);
                for (var i in validation) {
                    var item = validation[i];

                    var targetS = 'span[data-valmsg-for="' + i + '"]'

                    if (formId != null)
                        targetS = '#' + formId + ' ' + targetS;
                    var target = $(targetS);

                    if ($(target).length > 0) {
                        if (item.Errors.length > 0) {
                            $(target).text(item.Errors[0].ErrorMessage);
                            ChangeErrorState(target, true);
                        }
                        else {
                            $(target).text("");
                            ChangeErrorState(target, false);
                        }
                    }
                }
                $(".has-error div input:first").focus();
            }

            if (data.success) {
                BlockFields(false);
                toastr.success('Salvo com Sucesso');

                if (data.Id != null) {
                    var selector = '#Id';
                    if (formId != null)
                        selector = selector + ' ' + formId;
                    $("#Id").val(data.Id);
                }

                AfterSubmit(formId, data.action);
            }
            else {
                if (data.message != '')
                    toastr.error(data.message, 'Falha');
                if (data.action != '' && data.action != undefined)
                    AfterSubmit(formId, data.action);
            }
            ajaxRunning = false;
        },
        error: function () {
            ajaxRunning = false;
        },
        complete: function () {
            $('#' + formId + ' button[type="submit"]').each(function () { if ($(this) != undefined) { $(this).ladda('stop'); } })
        }
    });
}
/*
    jQuery Masked Input Plugin
    Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
    Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
    Version: 1.4.1
*/
!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : jQuery) }(function (a) { var b, c = navigator.userAgent, d = /iphone/i.test(c), e = /chrome/i.test(c), f = /android/i.test(c); a.mask = { definitions: { 9: "[0-9]", a: "[A-Za-z]", "*": "[A-Za-z0-9]" }, autoclear: !0, dataName: "rawMaskFn", placeholder: "_" }, a.fn.extend({ caret: function (a, b) { var c; if (0 !== this.length && !this.is(":hidden")) return "number" == typeof a ? (b = "number" == typeof b ? b : a, this.each(function () { this.setSelectionRange ? this.setSelectionRange(a, b) : this.createTextRange && (c = this.createTextRange(), c.collapse(!0), c.moveEnd("character", b), c.moveStart("character", a), c.select()) })) : (this[0].setSelectionRange ? (a = this[0].selectionStart, b = this[0].selectionEnd) : document.selection && document.selection.createRange && (c = document.selection.createRange(), a = 0 - c.duplicate().moveStart("character", -1e5), b = a + c.text.length), { begin: a, end: b }) }, unmask: function () { return this.trigger("unmask") }, mask: function (c, g) { var h, i, j, k, l, m, n, o; if (!c && this.length > 0) { h = a(this[0]); var p = h.data(a.mask.dataName); return p ? p() : void 0 } return g = a.extend({ autoclear: a.mask.autoclear, placeholder: a.mask.placeholder, completed: null }, g), i = a.mask.definitions, j = [], k = n = c.length, l = null, a.each(c.split(""), function (a, b) { "?" == b ? (n--, k = a) : i[b] ? (j.push(new RegExp(i[b])), null === l && (l = j.length - 1), k > a && (m = j.length - 1)) : j.push(null) }), this.trigger("unmask").each(function () { function h() { if (g.completed) { for (var a = l; m >= a; a++) if (j[a] && C[a] === p(a)) return; g.completed.call(B) } } function p(a) { return g.placeholder.charAt(a < g.placeholder.length ? a : 0) } function q(a) { for (; ++a < n && !j[a];); return a } function r(a) { for (; --a >= 0 && !j[a];); return a } function s(a, b) { var c, d; if (!(0 > a)) { for (c = a, d = q(b) ; n > c; c++) if (j[c]) { if (!(n > d && j[c].test(C[d]))) break; C[c] = C[d], C[d] = p(d), d = q(d) } z(), B.caret(Math.max(l, a)) } } function t(a) { var b, c, d, e; for (b = a, c = p(a) ; n > b; b++) if (j[b]) { if (d = q(b), e = C[b], C[b] = c, !(n > d && j[d].test(e))) break; c = e } } function u() { var a = B.val(), b = B.caret(); if (o && o.length && o.length > a.length) { for (A(!0) ; b.begin > 0 && !j[b.begin - 1];) b.begin--; if (0 === b.begin) for (; b.begin < l && !j[b.begin];) b.begin++; B.caret(b.begin, b.begin) } else { for (A(!0) ; b.begin < n && !j[b.begin];) b.begin++; B.caret(b.begin, b.begin) } h() } function v() { A(), B.val() != E && B.change() } function w(a) { if (!B.prop("readonly")) { var b, c, e, f = a.which || a.keyCode; o = B.val(), 8 === f || 46 === f || d && 127 === f ? (b = B.caret(), c = b.begin, e = b.end, e - c === 0 && (c = 46 !== f ? r(c) : e = q(c - 1), e = 46 === f ? q(e) : e), y(c, e), s(c, e - 1), a.preventDefault()) : 13 === f ? v.call(this, a) : 27 === f && (B.val(E), B.caret(0, A()), a.preventDefault()) } } function x(b) { if (!B.prop("readonly")) { var c, d, e, g = b.which || b.keyCode, i = B.caret(); if (!(b.ctrlKey || b.altKey || b.metaKey || 32 > g) && g && 13 !== g) { if (i.end - i.begin !== 0 && (y(i.begin, i.end), s(i.begin, i.end - 1)), c = q(i.begin - 1), n > c && (d = String.fromCharCode(g), j[c].test(d))) { if (t(c), C[c] = d, z(), e = q(c), f) { var k = function () { a.proxy(a.fn.caret, B, e)() }; setTimeout(k, 0) } else B.caret(e); i.begin <= m && h() } b.preventDefault() } } } function y(a, b) { var c; for (c = a; b > c && n > c; c++) j[c] && (C[c] = p(c)) } function z() { B.val(C.join("")) } function A(a) { var b, c, d, e = B.val(), f = -1; for (b = 0, d = 0; n > b; b++) if (j[b]) { for (C[b] = p(b) ; d++ < e.length;) if (c = e.charAt(d - 1), j[b].test(c)) { C[b] = c, f = b; break } if (d > e.length) { y(b + 1, n); break } } else C[b] === e.charAt(d) && d++, k > b && (f = b); return a ? z() : k > f + 1 ? g.autoclear || C.join("") === D ? (B.val() && B.val(""), y(0, n)) : z() : (z(), B.val(B.val().substring(0, f + 1))), k ? b : l } var B = a(this), C = a.map(c.split(""), function (a, b) { return "?" != a ? i[a] ? p(b) : a : void 0 }), D = C.join(""), E = B.val(); B.data(a.mask.dataName, function () { return a.map(C, function (a, b) { return j[b] && a != p(b) ? a : null }).join("") }), B.one("unmask", function () { B.off(".mask").removeData(a.mask.dataName) }).on("focus.mask", function () { if (!B.prop("readonly")) { clearTimeout(b); var a; E = B.val(), a = A(), b = setTimeout(function () { B.get(0) === document.activeElement && (z(), a == c.replace("?", "").length ? B.caret(0, a) : B.caret(a)) }, 10) } }).on("blur.mask", v).on("keydown.mask", w).on("keypress.mask", x).on("input.mask paste.mask", function () { B.prop("readonly") || setTimeout(function () { var a = A(!0); B.caret(a), h() }, 0) }), e && f && B.off("input.mask").on("input.mask", u), A() }) } }) });
function LoadAnalyticSells() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/Analytics/GetAnalyticSells",
        success: function (response) {
            var tooltipBase = "<div class='popover fade top in' role='tooltip' id='popover801489' style='display: block; width: 250px; position: absolute; top:{hh}px; left: {ww}px;'>\
                                <div class='arrow' style='left: 50%; top: 99%;'></div><h3 class='popover-title' style='display: none;'></h3>\
                                <div class='popover-content' style='text-align:left; white-space: nowrap;'><b>{0}</b><br>{1}</br>{2}</div></div>";

            GraphAxesConstructor(response, $("#AnalyticSells"), "day", tooltipBase, false, false, false, false, false, false);
        },
        error: function (response) {
            toastr.error('Gráfico com problemas, tente novamente em instantes', 'Falha!')
            return '';
        }
    });
}

function LoadAnalyticPeriodLate() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/Analytics/GetPeriodLate",
        success: function (response) {
            //content: "<b>%x</b>| Programações %s |<span>R$ %y</span>",
            var tooltipBase = "<div class='popover fade top in' role='tooltip' id='popover801489' style='display: block; width: 250px; position: absolute; top:{hh}px; left: {ww}px;'>\
                                <div class='arrow' style='left: 50%; top: 99%;'></div><h3 class='popover-title' style='display: none;'></h3>\
                                <div class='popover-content' style='text-align:left; white-space: nowrap;'><b>{0}</b><br>Valor total em atrazo</br>{2}</div></div>";

            GraphAxesConstructor(response, $("#AnalyticPeriodLate"), "day", tooltipBase, false, true, false, true, false, true);
        },
        error: function (response) {
            toastr.error('Gráfico com problemas, tente novamente em instantes', 'Falha!')
            return '';
        }
    });
}

function LoadAnalyticPaymentPeriod() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/Analytics/GetPaymentPeriod",
        success: function (response) {
            //content: "<b>%x</b>| Programações %s |<span>R$ %y</span>",
            var tooltipBase = "<div class='popover fade top in' role='tooltip' id='popover801489' style='display: block; width: 250px; position: absolute; top:{hh}px; left: {ww}px;'>\
                                <div class='arrow' style='left: 50%; top: 99%;'></div><h3 class='popover-title' style='display: none;'></h3>\
                                <div class='popover-content' style='text-align:left; white-space: nowrap;'><b>{0}</b><br>Prazo médio de recebimento</br>{2} dias</div></div>";

            GraphAxesConstructor(response, $("#AnalyticPaymentPeriod"), "day", tooltipBase, false, true, false, true, false, true);
        },
        error: function (response) {
            toastr.error('Gráfico com problemas, tente novamente em instantes', 'Falha!')
            return '';
        }
    });
}

function LoadAnalyticProg(cnpj, dtStart, dtEnd) {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/Analytics/GetAnalyticProg",
        data: { cnpj: cnpj, dtStart: dtStart, dtEnd: dtEnd },
        success: function (response) {
            //content: "<b>%x</b>| Programações %s |<span>R$ %y</span>",
            var tooltipBase = "<div class='popover fade top in' role='tooltip' id='popover801489' style='display: block; width: 250px; position: absolute; top:{hh}px; left: {ww}px;'>\
                                <div class='arrow' style='left: 50%; top: 99%;'></div><h3 class='popover-title' style='display: none;'></h3>\
                                <div class='popover-content' style='text-align:left; white-space: nowrap;'><b>{0}</b><br>Programações {1}</br>{2}</div></div>";

            GraphAxesConstructor(response, $("#AnalyticProg"), "day", tooltipBase, false, false, false, false, false, false);
        },
        error: function (response) {
            toastr.error('Gráfico com problemas, tente novamente em instantes', 'Falha!')
            return '';
        }
    });
}

function LoadAgingData(response, responsePie) {
    GraphAxesConstructor(response, $("#AgingBars"), null, null, true, false, false, true, true, false);
    GraphPieConstructor(responsePie, $("#AgingDonut"), 0.4, true);
}

//Construtor Genérico de Gráficos
//interval: "hour", "day", "month" and "year"
//tooltipbase: html
//showNumber: Aparecem números acima das barras
//hide: esconde as informações do eixo,
//XLabels: caso seja um eixo por parte, isto coloca os textos no rodapé
//stack: em caso de barras, faz com que elas se posicionem uma sobre as outras
function GraphAxesConstructor(response, target, interval, tooltipBase, showNumbers, hideX, hideY, hideLegends, xLabels, stack) {
    var dataset = [];
    var mode = "time"
    var hasRight = false;
    var columns = 0;
    var widthBar = 0;

    switch (interval) {
        case "hour": widthBar = 1 * 60 * 60 * 600; break;
        case "day": widthBar = 24 * 60 * 60 * 600; break;
        case "month": widthBar = 840 * 60 * 60 * 600; break;
        case "year": widthBar = 8400 * 60 * 60 * 600; break;
        default: { widthBar = 0.8; mode = null; } break;
    }

    var barCount = 0;
    for (var i = 0; i < response.data.length; i++) {
        var data = response.data[i];
        if (data.tipo == 'barra')
            barCount++;
    }

    for (var i = 0; i < response.data.length; i++) {
        var data = response.data[i];
        var values = graphData(data.valores);
        if (i == 0)
            columns = data.valores.length;

        if (data.yaxis > 1)
            hasRight = true;

        switch (data.tipo) {
            case 'barra':
                {
                    dataset.push({
                        label: xLabels ? null : data.eixo,
                        data: values,
                        yaxis: data.yaxis,
                        color: data.cor,
                        stack: stack,
                        bars: {
                            show: true,
                            align: "center",
                            barWidth: widthBar,
                            lineWidth: 0,
                            fill: 0.8,
                            numbers: {
                                show: showNumbers,
                                yAlign: function (y) { return y; },
                                yOffset: -6,
                                xAlign: function (x) { return x },
                                formatter: function (value) {
                                    if (value > 0) {
                                        if (data.tipoValor == "Integer") {
                                            return Math.floor(value);
                                        } else {
                                            return changeNumberFormat(value, ',', 2);
                                        }
                                    } else return '';
                                },
                                font: { size: 13, family: "'Segoe UI', 'Tahoma', 'Geneva', 'Verdana', 'sans-serif'" },
                                fontColor: '#656565'
                            }
                        }
                    });
                } break;
            case 'linha':
                {
                    dataset.push({
                        label: data.eixo,
                        data: values,
                        yaxis: data.yaxis,
                        color: data.cor,
                        lines: {
                            show: true,
                            fill: false
                        },
                    });
                } break;
            case 'linha_cheia':
                {
                    dataset.push({
                        label: data.eixo,
                        data: values,
                        yaxis: data.yaxis,
                        color: data.cor,
                        lines: {
                            lineWidth: 1,
                            show: true,
                            fill: true,
                            fillColor: {
                                colors: [{
                                    opacity: 0.2
                                }, {
                                    opacity: 0.2
                                }]
                            }
                        }
                    });
                } break;
        }
    }

    options = {};

    if (interval != null) {
        options.xaxis = {
            show: tooltipBase != null,
            mode: mode,
            tickSize: [Math.ceil(columns / 45), interval],
            tickLength: hideX || showNumbers ? 0 : null,
            axisLabelUseCanvas: true,
            axisLabelFontSizePixels: 12,
            axisLabelFontFamily: 'Arial',
            axisLabelPadding: 10,
        };
    }
    else {
        var ticks = null;
        if (xLabels) {
            ticks = [];
            for (var i = 0; i < response.data.length; i++) {
                var data = response.data[i];

                ticks.push([i + 1, data.eixo]);
            }
        }
        else
            ticks = response.data.length;

        options.xaxis = {
            show: tooltipBase != null,
            tickSize: 1,
            ticks: ticks,
            tickLength: hideX || showNumbers ? 0 : null,
            axisLabelUseCanvas: true,
            axisLabelFontSizePixels: 12,
            axisLabelFontFamily: 'Arial',
            axisLabelPadding: 10,
        };
    }

    if (hasRight) {
        options.yaxes = [{
            show: tooltipBase != null,
            position: "left",
            color: "#d5d5d5",
            tickLength: hideY ? 0 : null,
            axisLabelUseCanvas: true,
            axisLabelFontSizePixels: 12,
            axisLabelFontFamily: 'Arial',
            axisLabelPadding: 3
        }, {
            position: "right",
            show: tooltipBase != null,
            color: "#d5d5d5",
            tickLength: hideY ? 0 : null,
            axisLabelUseCanvas: true,
            axisLabelFontSizePixels: 12,
            axisLabelFontFamily: 'Arial',
            axisLabelPadding: 3
        }];
    }
    else {
        options.yaxis = {
            show: tooltipBase != null,
            position: "left",
            color: "#d5d5d5",
            tickLength: hideY ? 0 : null,
            axisLabelUseCanvas: true,
            axisLabelFontSizePixels: 12,
            axisLabelFontFamily: 'Arial',
            axisLabelPadding: 3
        };
    }

    options.legend = {
        noColumns: 1,
        labelBoxBorderColor: "#000000",
        position: "nw",
        backgroundOpacity: 0,
    };

    options.grid = {
        hoverable: true,
        borderWidth: 0
    };

    var zoomFactor = ((100 / ZoomGlobal) / 100);

    if (tooltipBase != null) {
        options.tooltip = true;
        options.tooltipOpts = {
            content: function (label, xval, yval, flotItem) {
                var atual = tooltipBase;
                var intervalD = interval;
                var xval = flotItem.datapoint[0];
                var yval = flotItem.datapoint[1];
                var dataT = response.data;

                while (atual.indexOf('{0}') != -1)
                    atual = atual.replace('{0}', ToDateString(xval, intervalD));

                while (atual.indexOf('{1}') != -1)
                    atual = atual.replace('{1}', label);

                var formatN = graphFormat(dataT, label);
                while (atual.indexOf('{2}') != -1) {

                    switch (formatN) {
                        case "Money": atual = atual.replace('{2}', "R$ " + changeNumberFormat(yval, ',', 2)); break;
                        case "Number": atual = atual.replace('{2}', changeNumberFormat(yval, ',', 2)); break;
                        case "Integer": atual = atual.replace('{2}', changeNumberFormat(yval, '', 0)); break;
                        default: atual = atual.replace('{2}', yval); break;
                    }
                }

                //position
                atual = atual.replace("\{hh\}", (((flotItem.pageY - (flotItem.pageY * ZoomGlobal))) - (110 * ZoomGlobal)) / ZoomGlobal);
                atual = atual.replace("\{ww\}", (((flotItem.pageX - (flotItem.pageX * ZoomGlobal))) - (132 * ZoomGlobal)) / ZoomGlobal);

                return atual;
            },
            defaultTheme: false
        };
    }

    var previousPoint = null, previousLabel = null;
    $(target).css('zoom', zoomFactor);
    $.plot(target, dataset, options);

    if (hideX)
        $(target).find(".flot-x-axis").detach();
    if (hideY)
        $(target).find(".flot-y-axis").detach();
    if (hideLegends)
        $(target).find(".legend").detach();
}

function GraphPieConstructor(data, target, innerRadius, hideLegends) {
    var options = {};

    options.series = {
        pie: {
            innerRadius: innerRadius != null ? innerRadius : 0,
            show: true,
        }
    }

    if (hideLegends) {
        options.legend = {
            show: false
        }
    }

    $.plot(target, data, options);
}

//function GraphSparkLine(data, target) {
//    $(target).sparkline([34, 43, 43, 35, 44, 32, 44, 52], {
//        type: 'line',
//        width: '100%',
//        height: '70',
//        lineColor: '#1ab394',
//        fillColor: "transparent"
//    });
//}

function graphData(data) {
    if (data == null)
        return [];

    var arrayR = [];

    for (var y = 0; y < data.length; y++) {
        if (jQuery.type(data[y].Key) === "string")
            arrayR.push([new Date(parseInt(data[y].Key.substr(6))), data[y].Value]);
        else
            arrayR.push([data[y].Key, data[y].Value]);
    }

    return arrayR;
}

function graphFormat(data, label) {
    for (var i = 0; i < data.length; i++) {
        var dataC = data[i];

        if (dataC.eixo == label) {
            return dataC.tipoValor;
        }
    }
    return '';
}


$(function () {
    if ($("#grid-mail-terceiro").length > 0)
        $("#grid-mail-terceiro").pqGrid(GetTerMails());
});

function TerMailTo(cnpjT, sender) {
    $("#terMailTo").nModal("show");
    setTimeout(function () {
        $('#iMailProgrammationCnpjT').val(cnpjT);
        $('#iMailInputId').val($(sender).attr('id'));
        RefreshTerMail();
    }, 500)
}

function RefreshTerMail() {
    $('#grid-mail-terceiro').pqGrid("refreshDataAndView");
}

function ExistsTerMail(email, sender) {
    return ($(sender).val().indexOf(email) > -1);
}

function MarkTerMail(email, sender) {
    senderO = $('#' + sender);
    AddRemoveTerMail(ExistsTerMail(email, senderO), email, senderO)
}

function AddRemoveTerMail(exist, email, sender) {
    if ((sender.val().match(/\;/g) || []).length > 2) {
        $('#grid-mail-terceiro').pqGrid("refresh");
        return;
    }

    if (!exist) {
        if ($(sender).val().length > 0)
            email = ';' + email;

        $(sender).val($(sender).val() + email);
    }
    else {
        $(sender).val($(sender).val().replace(email, ''));
        var val = $(sender).val();

        if (val.length > 0) {
            if (val.slice(val.length - 1, val.length) == ';')
                $(sender).val(val.slice(0, -1));
            if (val.slice(0, 1) == ';')
                $(sender).val(val.slice(1, val.length));

            $(sender).val($(sender).val().replace(';;', ';'));
        }
    }
}

function GetTerMails() {
    return {
        dataModel: {
            location: "remote",
            dataType: "JSON",
            method: "GET",
            getUrl: function () {
                var cnpjT = $('#iMailProgrammationCnpjT').val();
                if (cnpjT == '' || cnpjT == undefined)
                    cnpjT = '0';

                return {
                    url: "/Generic/GetTerContacts",
                    data: {
                        'cnpj': cnpjT
                    },
                }
            },
            getData: function (dataJSON) {
                return { data: dataJSON.data };
            }
        },
        colModel: [
            {
                title: "", editable: false, width: "10%", dataType: "string", dataIndx: 'Id',
                render: function (ui) {
                    var rowData = ui.rowData;
                    var cnpj = $('#iMailProgrammationCnpjT').val();
                    var sender = $('#iMailInputId').val();

                    var checked = (ExistsTerMail(rowData.txEmail, $('#' + sender))) ? "checked" : "";

                    return "<div class='mt10 fl'>\
                                    <div style='width:23px;float:left;'><input type='checkbox' class='iChecks' " + checked + " onchange=\"MarkTerMail('" +
                            rowData.txEmail + "','" + sender + "')\" id='chkTerMail" + rowData.Id + "' ></div></div>" +
                           "</div>";
                },
            },
            {
                title: "txNome", editable: false, dataType: "string", dataIndx: 'txNome',
                render: function (ui) {
                    var rowData = ui.rowData;
                    return rowData.txNome + ' ' + rowData.txSobrenome
                },
            },
            {
                title: "Cargo", editable: false, dataType: "string", dataIndx: 'txCargo',
            },
            {
                title: "Email", editable: false, dataType: "string", dataIndx: 'txEmail',
            },
        ],
        bootstrap: { on: true },
        hwrap: false,
        hoverMode: 'row',
        scrollModel: { pace: 'fast', autoFit: true, theme: true, },
        height: 290,
        width: '100%',
        numberCell: { show: false },
        roundCorners: false,
        stripeRows: true,
        roundCorners: false,
        rowBorders: false,
        showBottom: false,
        refresh: function () { nrReloadScripts(); },
    };
}
var gridH;
var IdP;

function GetCategoryIcon(category, size) {
    if (size == null)
        size = 35;

    if (category == null)
        category = "Manual";

    return "/Content/images/categories/" + size + "/" + category + ".png";
}

function GetOccurrenceHistory(Id, hh, location) {
    IdP = Id;

    if (hh == null)
        hh = 360; //Programação

    if (location != null && gridH != null) {
        gridH.pqGrid("refreshDataAndView");
    }
    else {
        var objH = {
            sortModel: {
                sorter: [{ dataIndx: 'dtCriacao', dir: "down" }]
            },
            dataModel: {
                location: "remote",
                dataType: "JSON",
                method: "GET",
                getUrl: function () {
                    return {
                        url: "/Generic/GetOccurrenceHistory",
                        data: {
                            idProgrammation: IdP,
                        },
                    }
                },
                getData: function (dataJSON) {
                    return { data: dataJSON.data };
                }
            },
            colModel: [
                {
                    title: "", editable: false, width: "5%", dataType: "string", dataIndx: 'Id',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        var titleT = 'titleh';
                        var content = rowData.txDadosAcao;

                        if (rowData.IdFilePreview != null) {
                            if (rowData.txComunicacao == 'CALL') {
                                titleT = 'titlec';
                                content = "<video controls src='/Generic/PlayAudio?Id=" + rowData.IdFilePreview + "' style='width:300px;height: 45px !important;'></video>";
                            }
                            else {
                                return "<img src='" + GetCategoryIcon(rowData.txCategoria) + "' " + "onclick='ShowFile(" + rowData.IdFilePreview + ")' />";
                            }
                        }

                        if (content != null) {
                            return "<img src='" + GetCategoryIcon(rowData.txCategoria) + "'" + titleT + "=\"" + content + "\" />";
                        }
                        else
                            return "<img src='" + GetCategoryIcon(rowData.txCategoria) + "' />";
                    }
                },
                {
                    title: "Data Criação", editable: false, width: "8%", dataType: "string", dataIndx: 'dtCriacao',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        return "<div class='textZone full'><div>" + changeJsonDateFormat(rowData.dtCriacaoJson) + "</div><div>" + rowData.dtCriacaoJsonHora + "</div></div>"
                    }
                },
                {
                    title: "Memo", editable: false, width: "15%", dataType: "string", dataIndx: 'txObservacao',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        if (rowData.txMotivo == null)
                            return "<div class='textZone full' titleh='" + rowData.txObservacao + "' >" + MaxLength(rowData.txObservacao, 100) + "</div>";
                        else
                            return "<div class='textZone full' titleh='" + rowData.txMotivo + "' >" + MaxLength(rowData.txMotivo, 100) + "</div>";
                    }
                },
                {
                    title: "Destinatários", editable: false, width: "5%", dataType: "string", dataIndx: 'txDestinatarios',
                    render: function (ui) {
                        var rowData = ui.rowData;
                        var contatos = '';
                        if (rowData.Contato1 != null)
                            contatos += "<b>" + rowData.Contato1.txNome + ' ' + rowData.Contato1.txSobrenome + '</b> - (' + rowData.Contato1.dddComercial + ')' + rowData.Contato1.telefoneComercial;
                        if (rowData.Contato2 != null)
                            contatos += "<br/><b>" + rowData.Contato2.txNome + ' ' + rowData.Contato2.txSobrenome + '</b> - (' + rowData.Contato2.dddComercial + ')' + rowData.Contato2.telefoneComercial;
                        if (rowData.Contato3 != null)
                            contatos += "<br/><b>" + rowData.Contato3.txNome + ' ' + rowData.Contato3.txSobrenome + '</b> - (' + rowData.Contato3.dddComercial + ')' + rowData.Contato3.telefoneComercial;

                        if (contatos != '')
                            return "<i class='fa fa-group' titleh='" + contatos + "'></i>";
                        else
                            return '';
                    }
                },
                {
                    title: "Envio", editable: false, width: "4%", dataType: "string", dataIndx: 'dtFimExecucaoJson',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        var enviado = false;
                        var nenviado = false;
                        var indefinido = false;

                        for (var i = 0; i < rowData.lstTracking.length; i++) {
                            var item = rowData.lstTracking[i];

                            if (item.stFaseExec == "Enviado")
                                enviado = true;

                            if (item.stFaseExec == "NaoEnviado")
                                nenviado = true;

                            if (item.stFaseExec == "Indefinido")
                                indefinido = true;

                        }

                        if (enviado) {
                            return "<i class='fa fa-check text-navy' style='font-size:20px'></i>";
                        }
                        else if (nenviado) {
                            return "<i class='fa fa-times text-danger' style='font-size:20px'></i>";
                        }
                        else if (indefinido) {
                            return "<i class='fa fa-question colorDisabled' style='font-size:20px'></i>";
                        }
                        else
                            return '';
                    }
                },
                {
                    title: "Entrega", editable: false, width: "4%", dataType: "string", dataIndx: 'dtFimExecucaoJson',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        var entregue = false;
                        var nentregue = false;
                        var indefinido = false;

                        for (var i = 0; i < rowData.lstTracking.length; i++) {
                            var item = rowData.lstTracking[i];

                            if (item.stFaseExec == "Entregue")
                                entregue = true;

                            if (item.stFaseExec == "NaoEntregue")
                                nentregue = true;

                            if (item.stFaseExec == "Indefinido")
                                indefinido = true;

                        }

                        if (entregue) {
                            return "<i class='fa fa-check text-navy' style='font-size:20px'></i>";
                        }
                        else if (nentregue) {
                            return "<i class='fa fa-times text-danger' style='font-size:20px'></i>";
                        }
                        else if (indefinido) {
                            return "<i class='fa fa-question colorDisabled' style='font-size:20px'></i>";
                        }
                        else
                            return '';
                    }
                },
                {
                    title: "Confirmação", editable: false, width: "6%", dataType: "string", dataIndx: 'dtFimExecucaoJson',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        var confirmacao = false;
                        var nconfirmacao = false;
                        var indefinido = false;

                        for (var i = 0; i < rowData.lstTracking.length; i++) {
                            var item = rowData.lstTracking[i];

                            if (item.stFaseExec == "Confirmado")
                                confirmacao = true;

                            if (item.stFaseExec == "NaoConfirmado")
                                nconfirmacao = true;

                            if (item.stFaseExec == "Indefinido")
                                indefinido = true;

                        }

                        if (confirmacao) {
                            return "<i class='fa fa-check text-navy' style='font-size:20px'></i>";
                        }
                        else if (nconfirmacao) {
                            return "<i class='fa fa-times text-danger' style='font-size:20px'></i>";
                        }
                        else if (indefinido) {
                            return "<i class='fa fa-question colorDisabled' style='font-size:20px'></i>";
                        }
                        else
                            return '';
                    }
                },
                {
                    title: "Tracking", editable: false, dataType: "date", width: "4%", dataIndx: 'dtUltimaAtualizacaoJson',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        var tooltip = '';

                        for (var i = 0; i < rowData.lstTracking.length; i++) {
                            var item = rowData.lstTracking[i];
                            var statusNome = ''

                            switch (item.stFaseExec) {
                                case 'NaoEnviado': statusNome = 'Não Enviado'; break;
                                case 'NãoEntregue': statusNome = 'Não Entregue'; break;
                                case 'NaoConfirmado': statusNome = 'Não Confirmado'; break;
                                default: statusNome = item.stFaseExec; break;
                            }

                            tooltip += "<tr><td>" + statusNome + "</td><td>" + changeJsonDateFormat(item.dtCriacao, false, true) + "</td></tr>"
                        }

                        if (tooltip != '') {
                            tooltip = "titleh=\"<table class='table table-striped table-bordered' style='margin-bottom:0px;'><tbody>" + tooltip + "</tbody></table>\"";
                        }

                        if (tooltip != '')
                            return "<i class='fa fa-calendar' " + tooltip + "></i>";
                        else
                            return '';
                    }
                },
                {
                    title: "Status", editable: false, dataType: "string", dataIndx: 'flConclusaoOk', width: "2%",
                    render: function (ui) {
                        var rowData = ui.rowData;
                        if (rowData.lstTracking.length > 0) {
                            if (rowData.flConclusaoOk != null) {
                                if (rowData.flConclusaoOk)
                                    return "<i class='fa fa-check text-navy' style='font-size:25px'>";
                                else
                                    return "<i class='fa fa-times' style='font-size:25px;color:red;'>";
                            }
                        }
                        return '';
                    }
                },
                {
                    title: "Data Fim", editable: false, width: "8%", dataType: "string", dataIndx: 'dtFimExecucaoJson',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        if (rowData.dtFimExecucao != null && rowData.lstTracking.length > 0)
                            return "<div class='textZone full'><div>" + changeJsonDateFormat(rowData.dtFimExecucao, false, false) + "</div><div>" + changeJsonDateFormat(rowData.dtFimExecucao, false, false, true) + "</div></div>"
                        else
                            return '';
                    }
                },
                {
                    title: "Observação", editable: false, dataType: "string", dataIndx: 'flConclusaoOk',
                    render: function (ui) {
                        var rowData = ui.rowData;
                        
                        for (var i = 0; i < rowData.lstTracking.length; i++) {
                            var item = rowData.lstTracking[i];

                            if (item.providerResult != null) {
                                if (item.providerResult.Description != null) {
                                    return "<div class='textZone full' titleh='" + item.providerResult.Description + "' >" + MaxLength(item.providerResult.Description, 60) + "</div>";
                                }
                            }
                        }
                        return '';
                    }
                },               
            ],
            bootstrap: { on: true },
            hwrap: false,
            hoverMode: 'row',
            scrollModel: { pace: 'fast', autoFit: true, theme: true, },
            height: hh,
            width: '100%',
            numberCell: { show: false },
            roundCorners: false,
            stripeRows: true,
            roundCorners: false,
            rowBorders: false,
            showBottom: false,
            refresh: function () { nrReloadScripts(); },
        };

        if (location != null) {
            gridH = $(location).pqGrid(objH);
        }
        else {
            return objH;
        }
    }
}
var gridDn;
var gridIns;
var gridAt;
var IdDn;
var IdAt;

var dtInsIni;
var dtInsFim;

function GetDownloadList(Id, hh, location) {
    IdDn = Id;

    if (hh == null)
        hh = 360; //Programação

    if (location != null && gridDn != null) {
        gridDn.pqGrid("refreshDataAndView");
    }
    else {
        var objDn = {
            filterModel: { header: true, mode: "AND" },
            sortModel: {
                sorter: [{ dataIndx: 'dtCriacaoJson', dir: "up" }]
            },
            dataModel: {
                location: "remote",
                dataType: "JSON",
                method: "GET",
                getUrl: function () {
                    return {
                        url: "/Files/GetDownloadList",
                        data: {
                            idProgrammation: IdDn,
                        },
                    }
                },
                getData: function (dataJSON) {
                    return { data: dataJSON.data };
                }
            },
            colModel: [
                {
                    title: "Arquivo", editable: false, width: "8%", dataType: "string", dataIndx: 'Id',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        if (rowData.Id != null) {
                            var url = '';

                            if (rowData.name != null) {
                                if (rowData.name.indexOf('.xml') != -1) {
                                    url = "/Files/DownloadXml?Id=" + rowData.Id + "&fileName=" + rowData.name;
                                }
                                else
                                    url = "/Files/DownloadFile?Id=" + rowData.Id + "&fileName=" + rowData.name;

                                return "<a href='" + url + "' donwload class='' onclick='setTimeout(function(){gridDn.pqGrid(\"refreshDataAndView\");},1000);' ><i class='fa fa fa-cloud-download symbol cuPO'></i></a>";
                            }
                        }
                        return '';
                    }
                },
                {
                    title: "Baixado", editable: false, width: "8%", dataType: "string", dataIndx: 'Id',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        if (rowData.Id != null) {
                            var url = '';

                            if (rowData.name != null) {
                                if (rowData.name.indexOf('.xml') == -1) {
                                    if (rowData.flDownload) {
                                        return "<div class='mt10 fl' style='width:23px !important;'><div class='nrImportant' style='width:23px;height:23px;float:left;'><input type='checkbox' class='iChecks' \
                                        titleh='Este Arquivo já foi baixado anteriormente' checked='checked' disabled='disabled' /></div></div>";
                                    }
                                    else {
                                        return "<div class='mt10 fl' style='width:23px !important;'><div style='width:23px;height:23px;float:left;'><input type='checkbox' class='iChecks' \
                                        titleh='Este Arquivo ainda não foi baixado' disabled='disabled' /></div></div>";
                                    }
                                }
                                return '';
                            }
                        }
                        return '';
                    }
                },
                {
                    title: "Tipo", editable: false, width: "10%", dataType: "string", dataIndx: 'tipoArquivoJson',
                    filter: {
                        type: "select",
                        prepend: { '': '-- Todas --' },
                        condition: 'equal',
                        listeners: ['change'],
                        options: ["BaixaBoleto", "Boleto", "BoletoCNAB", "Danfe", "Duplicata", "PagSis", "Xml"],
                    },
                },
                {
                    title: "Data", editable: false, dataType: "date", width: "20%", dataIndx: 'dtCargaJson',
                    filter: {
                        type: 'textbox',
                        condition: "between",
                        init: pqDatePickerPQ,
                        listeners: [{
                            'change': function (evt, ui) {

                                ui.value = changeDateFormat(ui.value);
                                ui.value2 = changeDateFormat(ui.value2);

                                $(this).closest(".pq-grid").pqGrid('filter', {
                                    oper: "add",
                                    data: [ui]
                                })
                            }
                        }]
                    },
                    render: function (ui) {
                        var rowData = ui.rowData;

                        return "<div class='textZone full'><div>" + changeJsonDateFormat(rowData.dtCarga, false, true) + "</div></div>"
                    }
                },
                {
                    title: "Nome", editable: false, dataType: "string", dataIndx: 'name',
                    filter: {
                        type: 'textbox',
                        condition: 'contain',
                        listeners: ['keyup'],
                    },
                },
            ],
            bootstrap: { on: true },
            hwrap: false,
            hoverMode: 'row',
            scrollModel: { pace: 'fast', autoFit: true, theme: true, },
            height: hh,
            width: '100%',
            numberCell: { show: false },
            roundCorners: false,
            stripeRows: true,
            roundCorners: false,
            rowBorders: false,
            showBottom: false,
            refresh: function () { nrReloadScripts(); },
        };

        if (location != null) {
            gridDn = $(location).pqGrid(objDn);
        }
        else {
            return objDn;
        }
    }
}

function GetDownloadInstruments(dtIni, dtFim, hh, location) {
    if ($(location).length == 0) return;

    var filter = IsSeller ? "BoletoCNAB" : "PagSis";

    dtInsIni = dtIni;
    dtInsFim = dtFim;

    if (hh == null)
        hh = 360; //Programação

    if (location != null && gridIns != null) {
        gridIns.pqGrid("refreshDataAndView");
    }
    else {
        var objDn = {
            filterModel: { header: true, mode: "AND" },
            sortModel: {
                sorter: [{ dataIndx: 'dtCriacaoJson', dir: "up" }]
            },
            dataModel: {
                location: "remote",
                dataType: "JSON",
                method: "GET",
                getUrl: function () {
                    return {
                        url: "/Files/GetDownloadList",
                        data: {
                            dtIni: dtInsIni,
                            dtFim: dtInsFim
                        },
                    }
                },
                getData: function (dataJSON) {
                    for(var i = dataJSON.data.length -1;i>=0;i--)
                    {
                        if(dataJSON.data[i].tipoArquivoJson != filter)
                            dataJSON.data.splice(i,1);
                    }                    

                    return { data: dataJSON.data };
                }
            },
            colModel: [
                {
                    title: "Arquivo", editable: false, width: "8%", dataType: "string", dataIndx: 'Id',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        if (rowData.Id != null) {
                            var url = '';

                            if (rowData.name != null) {
                                if (rowData.name.indexOf('.xml') != -1) {
                                    url = "/Files/DownloadXml?Id=" + rowData.Id + "&fileName=" + rowData.name;
                                }
                                else
                                    url = "/Files/DownloadFile?Id=" + rowData.Id + "&fileName=" + rowData.name;

                                var cell = "<a href='" + url + "' donwload class='' onclick='setTimeout(function(){gridIns.pqGrid(\"refreshDataAndView\");},1000);' titleh='Baixar documento'><i class='fa fa-cloud-download symbol cuPO'></i></a>";

                                if (!IsSeller) {
                                    cell += "<a class='ml10' onclick='DeletePaymentFile(" + rowData.Id + ")' titleh='Cancelar documento'><i class='fa fa-times symbol cuPO text-danger'></i></a>";
                                }

                                return cell;
                            }
                        }
                        return '';
                    }
                },
                {
                    title: "Baixado", editable: false, width: "8%", dataType: "string", dataIndx: 'Id',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        if (rowData.Id != null) {
                            var url = '';

                            if (rowData.name != null) {
                                if (rowData.name.indexOf('.xml') == -1) {
                                    if (rowData.flDownload) {
                                        var userD = rowData.txUsuarioNome == null ? rowData.txUsuarioEmail : rowData.txUsuarioNome + rowData.txUsuarioSobrenome;

                                        return "<div class='mt10 fl' style='width:23px !important;'><div class='nrImportant' style='width:23px;height:23px;float:left;'><input type='checkbox' class='iChecks' \
                                        titleh='Este Arquivo já foi baixado antes<br/><br/>data: " + changeJsonDateFormat(rowData.dtDownload, false, true) + "<br/>por: " + userD + "' checked='checked' disabled='disabled' /></div></div>";
                                    }
                                    else {
                                        return "<div class='mt10 fl' style='width:23px !important;'><div style='width:23px;height:23px;float:left;'><input type='checkbox' class='iChecks' \
                                        titleh='Este Arquivo ainda não foi baixado' disabled='disabled' /></div></div>";
                                    }
                                }
                                return '';
                            }
                        }
                        return '';
                    }
                },
                {
                    title: "Tipo", editable: false, width: "10%", dataType: "string", dataIndx: 'tipoArquivoJson',
                    filter: {
                        type: "select",
                        condition: 'equal',
                        listeners: ['change'],
                        options: [filter],
                    },
                },
                {
                    title: "Data de geração", editable: false, dataType: "date", width: "20%", dataIndx: 'dtCargaJson',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        return "<div class='textZone full'><div>" + changeJsonDateFormat(rowData.dtCarga, false, true) + "</div></div>"
                    }
                },
                {
                    title: "Nome", editable: false, dataType: "string", dataIndx: 'name',
                    filter: {
                        type: 'textbox',
                        condition: 'contain',
                        listeners: ['keyup'],
                    },
                },
            ],
            bootstrap: { on: true },
            hwrap: false,
            hoverMode: 'row',
            scrollModel: { pace: 'fast', autoFit: true, theme: true, },
            height: hh,
            width: '100%',
            numberCell: { show: false },
            roundCorners: false,
            stripeRows: true,
            roundCorners: false,
            rowBorders: false,
            showBottom: false,
            refresh: function () { nrReloadScripts(); },
        };

        if (location != null) {
            gridIns = $(location).pqGrid(objDn);
        }
        else {
            return objDn;
        }
    }
}

function GetAttachList(Id, hh, location) {
    IdAt = Id;

    if (hh == null)
        hh = 360; //Programação

    if (location != null && gridAt != null) {
        gridAt.pqGrid("refreshDataAndView");
    }
    else {
        var objAt = {
            filterModel: { header: true, mode: "AND" },
            sortModel: {
                sorter: [{ dataIndx: 'dtCriacaoJson', dir: "up" }]
            },
            dataModel: {
                location: "remote",
                dataType: "JSON",
                method: "GET",
                getUrl: function () {
                    return {
                        url: "/Files/GetAttachList",
                        data: {
                            idProcesso: IdAt,
                        },
                    }
                },
                getData: function (dataJSON) {
                    return { data: dataJSON.data };
                }
            },
            colModel: [
                {
                    title: "Arquivo", editable: false, width: "8%", dataType: "string", dataIndx: 'Id',
                    render: function (ui) {
                        var rowData = ui.rowData;

                        if (rowData.Id != null) {
                            var url = "/Files/DownloadFile?Id=" + rowData.Id + "&fileName=" + rowData.name;

                            return "<a href='" + url + "' donwload class=''><i class='fa fa-download symbol cuPO'></i></a>";
                        }
                        return '';
                    }
                },
                {
                    title: "Data", editable: false, dataType: "date", width: "25%", dataIndx: 'dtCargaJson',
                    filter: {
                        type: 'textbox',
                        condition: "between",
                        init: pqDatePickerPQ,
                        listeners: [{
                            'change': function (evt, ui) {

                                ui.value = changeDateFormat(ui.value);
                                ui.value2 = changeDateFormat(ui.value2);

                                $(this).closest(".pq-grid").pqGrid('filter', {
                                    oper: "add",
                                    data: [ui]
                                })
                            }
                        }]
                    },
                },
                {

                    title: "Nome", editable: false, dataType: "string", dataIndx: 'name',
                    filter: {
                        type: 'textbox',
                        condition: 'contain',
                        listeners: ['keyup'],
                    },
                },
            ],
            bootstrap: { on: true },
            hwrap: false,
            hoverMode: 'row',
            scrollModel: { pace: 'fast', autoFit: true, theme: true, },
            height: hh,
            width: '100%',
            numberCell: { show: false },
            roundCorners: false,
            stripeRows: true,
            roundCorners: false,
            rowBorders: false,
            showBottom: false,
            refresh: function () { nrReloadScripts(); },
        };

        if (location != null) {
            gridAt = $(location).pqGrid(objAt);
        }
        else {
            return objAt;
        }
    }
}
$(document).ready(function () {
    AlertPulse();
    GetMoneyOver();
    AlertTimer();
});

var alertEvent;
function AlertTimer() {
    alertEvent = setTimeout(function () {
        AlertPulse();
        clearTimeout(alertEvent);
        AlertTimer();
    }, 60000)
}

function AlertPulse() {
    if ($('#alertList').length > -1) {
        if (!$('#alertList').is(':visible')) {
            LoadAlerts();
            DropSpecial();
        }
    }
}

var alertingActive = false;
function LoadAlerts() {
    if (!alertingActive) {
        alertingActive = true;

        if (xlogs) {
            $.ajax({
                url: "/Generic/GetAlerts",
                type: 'POST',
                dataType: 'json',
                data: { type: 'Divergencia' },
                success: function (json) {
                    var alerts = json.data;
                    AlertClear();

                    if (alerts.length > 0) {
                        var newAlerts = 0;
                        for (var i = 0; i < alerts.length; i++) {
                            var item = alerts[i];

                            AlertBlock(item, i);
                            if (item.isNew)
                                newAlerts++;
                        }

                        if (newAlerts > 0)
                            $('#alertSpan').text(newAlerts);
                    }
                },
                complete: function () {
                    alertingActive = false;
                }
            });
        }
    }
}

function UpdateAlertDate() {
    $('#alertSpan').text('');
    $.ajax({
        url: "/Generic/UpdateAlertDate",
        type: 'POST',
        dataType: 'json',
        success: function (json) {
        }
    });
}

function AlertBlock(item, i) {
    if (i > 0)
        $('#alertList').append("<li class='divider'></li>");

    var string = "<li> \
            <a href='/Incoming/Search?search="+ item.nrCode + "'> \
                <div> \
                    <i class='fa fa-bell fa-fw "+ (item.isNew ? "text-danger" : "") + "'></i> " + item.nrCode + "<br/>" + item.txAlerta + " \
                </div> \
            </a> \
        </li>"

    $('#alertList').append(string);
}

function AlertClear() {
    $('#alertSpan').text('');
    $('#alertList').empty();
}
/// <reference path="messages.js" />
$(document).ready(function () {
    MessagePulse();
    MessageTimer();
});

var messageEvent;
function MessageTimer() {
    messageEvent = setTimeout(function () {
        MessagePulse();
        clearTimeout(messageEvent);
        MessageTimer();
    }, 60000)
}

function MessagePulse() {
    LoadTopMessages();
    DropSpecial();
}

var messagingActive = false;
function LoadTopMessages() {
    if (!messagingActive) {
        messagingActive = true;

        if (xlogs) {
            $.ajax({
                url: "/Generic/GetMessages",
                type: 'POST',
                dataType: 'json',
                data: { type: 'Divergencia' },
                success: function (json) {
                    var messages = json.data;
                    MessageHomeClear();

                    if (messages.length > 0) {
                        var newMessages = 0;
                        for (var i = 0; i < messages.length; i++) {
                            var item = messages[i];

                            if ($('#homeMessages').length > 0)
                                MessageHomeBlock(item, i);

                            MessageHome(item, i);

                            if (item.isNew)
                                newMessages++;
                        }
                        if (newMessages > 0)
                            $('#messageSpan').text(newMessages);

                        MessageClear();
                    }
                },
                complete: function () {
                    messagingActive = false;
                }
            });
        }
    }
}

function UpdateMessageDate() {
    $('#alertSpan').text('');
    $.ajax({
        url: "/Generic/UpdateMessageDate",
        type: 'POST',
        dataType: 'json',
        success: function (json) {
        }
    });
}

function MessageHome(item, i) {
    if (i > 0)
        $('#messageList').append("<li class='divider'></li>");

    var string = "<li> \
            <a href='/Incoming/Search?search="+ item.nrCode + "'> \
                <div> \
                    <i class='fa fa-bell fa-fw " + (item.isNew ? "text-danger" : "") + "'></i> " + item.nrCode + "<br/><div class='nrMessage'>" + item.txMessage + "</div> \
                </div> \
            </a> \
        </li>"

    $('#messageList').append(string);
}

function MessageHomeBlock(item, i) {

    var string = "<div class='feed-element'>\
                        <div>\
                            <a href='/Incoming/Search?search=" + item.nrCode + "' style='color:inherit;'> \
                                <strong>"+ item.txUsuario + "</strong>\
                                <div class='nrMessage'>"+ item.txMessage + "</div>\
                                <small class='text-muted'>" + changeJsonDateFormat(item.dtCriacao, false, true) + "</small>\
                            </a> \
                        </div>\
                    </div>";

    $('#homeMessages').append(string);
}

function MessageHomeClear() {
    $('#homeMessageCount').text('');
    $('#homeMessages').empty();
    $('#messageSpan').text('');
    $('#messageList').empty();
}

function MessageClear() {
    $(".nrMessage").each(function () {
        var text = ''
        $(this).find('span').each(function () {
            text += $(this).text();
        })

        $(this).find('span').remove();

        if (text != '')
            $(this).text(text);
    })
}
/// <reference path="relationIssues.js" />
$(document).ready(function () {
    RelationIssuePulse();
    RelationIssueTimer();
});

var relationIssueEvent;
function RelationIssueTimer() {
    relationIssueEvent = setTimeout(function () {
        RelationIssueTimer();
        clearTimeout(relationIssueEvent);
        RelationIssuePulse();
    }, 60000)
}

function RelationIssuePulse() {
    LoadTopRelationIssues();
    DropSpecial();
}

function LoadTopRelationIssues() {
    $.ajax({
        url: "/Generic/GetRelationIssues",
        type: 'POST',
        dataType: 'json',
        success: function (json) {
            var relationIssues = json.data;
            RelationIssueHomeClear();

            if (relationIssues.length > 0) {
                $('#aRelIssue').show();
                $('#relationIssueSpan').text(relationIssues.length);

                for (var i = 0; i < relationIssues.length; i++) {
                    var item = relationIssues[i];
                    if ($('#homeRelationIssues').length > 0)
                        RelationIssueHomeBlock(item, i);

                    RelationIssueHome(item, i);
                }
                RelationIssueClear();
            }
            else
                $('#aRelIssue').hide();
        }
    });
}

function RelationIssueHome(item, i) {
    if (i > 0)
        $('#relationIssueList').append("<li class='divider'></li>");

    var string = "<li> \
            <a href='/Aging/Client?cnpj=" + item.cnpjCpf + "'> \
                <div> \
                     <i class='fa fa-exclamation-triangle text-danger fa-fw'></i><strong class='ml10'>" + "Falta de contato para comunicações" + "</strong><br/><div class='nrRelationIssue'>" + changeCPFCNPJFormat(item.cnpjCpf, true) + "<br/>" + item.razaoSocial + "</div> \
                </div> \
            </a> \
        </li>"

    $('#relationIssueList').append(string);
}

function RelationIssueHomeBlock(item, i) {

    var string = "<div class='feed-element'>\
                        <div>\
                            <a href='/Incoming/Search?search=" + item.nrCode + "' style='color:inherit;'> \
                                <strong>"+ item.txUsuario + "</strong>\
                                <div class='nrRelationIssue'>"+ item.txRelationIssue + "</div>\
                                <small class='text-muted'>" + changeJsonDateFormat(item.dtCriacao, false, true) + "</small>\
                            </a> \
                        </div>\
                    </div>";

    $('#homeRelationIssues').append(string);
}

function RelationIssueHomeClear() {
    $('#homeRelationIssueCount').text('');
    $('#homeRelationIssues').empty();
    $('#relationIssueSpan').text('');
    $('#relationIssueList').empty();
}

function RelationIssueClear() {
    $(".nrRelationIssue").each(function () {
        var text = ''
        $(this).find('span').each(function () {
            text += $(this).text();
        })

        $(this).find('span').remove();

        if (text != '')
            $(this).text(text);
    })
}
$(document).ready(function () {
    TodoPulse();
    TodoTimer();
});

var todoEvent;
function TodoTimer() {
    todoEvent = setTimeout(function () {
        TodoTimer();
        clearTimeout(todoEvent);
        TodoPulse();
    }, 60000)
}

function TodoPulse() {
    if ($('#TodoList').length > -1) {
        LoadTodo();
        DropSpecial();
    }
}

function LoadTodo() {
    if (xlogs) {
        $.ajax({
            url: "/Incoming/GetDivergenceList",
            type: 'POST',
            dataType: 'json',
            data: { chkEmAberto: true, chkFinalizada: false },
            success: function (json) {
                var todo = json.data;
                TodoClear();

                if (todo == null) return false;

                if (todo.length > 0) {
                    for (var i = 0; i < todo.length; i++) {
                        var item = todo[i];

                        TodoHome(item, i);
                    }
                }
            }
        });

        var date = new Date();
        var dateText = ("0" + (date.getDate())).slice(-2) + "/" + ("0" + (date.getMonth() + 1)).slice(-2) + "/" + date.getFullYear();

        if ($('#TodoToday').length > 0) {
            $.ajax({
                url: "/Home/GetProgrammationList",
                type: 'POST',
                dataType: 'json',
                data: {
                    'dtStart': null, 'dtEnd': dateText,
                },
                success: function (json) {
                    var todo = json.data;
                    $('#TodoToday').empty();

                    if (todo.length > 0) {
                        for (var i = 0; i < todo.length; i++) {
                            var item = todo[i];

                            TodoToday(item, i);
                        }
                    }
                }
            });
        }
    }
}

function TodoToday(item, i) {
    var string = "<tr>\
                        <td><small>"+ item.statusJson + "</small></td>\
                        <td><i class='fa fa-calendar'></i> " + changeJsonDateFormat(item.dtPgtoAtualizadoJson, false, false) + "</td>\
                        <td><a href='/Incoming/Search?search=" + item.nrCode + "' style='color:inherit;'><b>" + item.nrCode + "</b></a></td>\
                        <td class='text-navy' style='text-align:right'> " + changeNumberFormat(item.vlLiquidoAtualizado, ',', 2) + "</td>\
                    </tr>";

    $('#TodoToday').append(string);
}

function TodoHome(item, i) {
    //if (i > 0)
    //    $('#TodoList').append("<li class='divider'></li>");

    var string = "<li>\
                        <a class='check-link cuPO' onclick='FinishDivergence("+ item.Id + ")'><i class='fa fa-square-o' id='todoS" + item.Id + "'></i> </a>\
                        <a href='/Incoming/Search?search=" + item.nrCode + "' style='color:inherit;'><span class='m-l-xs' id=todoL" + item.Id + "><b>" + item.nrCode + "</b> " + item.txMotivo + "</span></a>\
                      </li>";

    $('#TodoList').append(string);
}

function TodoClear() {
    $('#TodoList').empty();
}

function FinishDivergence(IdOc) {
    $('#todoS' + IdOc).removeClass('fa-square-o');
    $('#todoS' + IdOc).addClass('fa-check-square');
    $('#todoL' + IdOc).addClass('todo-completed');
    //$.ajax({
    //    type: "Post",
    //    dataType: 'json',
    //    url: "Financial/FinishDivergence",
    //    data: { Id: IdOc },
    //    success: function (response) {
    //        if (response.success) {
    //            $('#grid_motivoEscolha').pqGrid("refreshDataAndView");
    //            toastr.success('Sucesso');
    //        }
    //        else {
    //            toastr.error(response.message, 'Falha');
    //        }
    //    },
    //    error: function () {
    //        toastr.error(response.message, 'Falha');
    //    }
    //});
}
$(document).ready(function () {
    ShopPulse();
    setInterval(function () {
        ShopPulse();
    }, 60000)
});

function ShopPulse() {
    if (!$('#right-sidebar').hasClass('sidebar-open'))
        LoadShopCurrent();
}

function LoadShopCurrent() {
    $.ajax({
        url: "/Generic/GetLastTransactions",
        type: 'POST',
        dataType: 'json',
        data: { type: 'Divergencia' },
        success: function (json) {
            var data = json.data;
            var ultimoIdTransacao = 0;
            var ultimoIdServico = 0;
            var quantidade = 0;

            ShopHomeClear();

            if (data.length > 0) {
                $('#ShopSpan').text(data.length);

                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    var subItems = item.nrCode != "";

                    if (ultimoIdTransacao != item.IdTransacao) {
                        ultimoIdTransacao = item.IdTransacao;
                        ShopHeader(item, i);

                        if (daysToDate(item.dtTransacaoJson, true) == 0 && item.statusJson == "Efetivado") {
                            $('#sidebarNr').addClass('text-info');
                        }
                    }
                    if (ultimoIdServico != item.IdServico) {
                        ultimoIdServico = item.IdServico;
                        quantidade = 0;
                        for (var z = 0; z < data.length; z++) {
                            if (data[z].IdServico == ultimoIdServico)
                                quantidade++;
                        }
                        ShopEntryHeader(item, quantidade, subItems);
                    }
                    if (subItems)
                        ShopEntryItems(item, i);
                }
                $('#homeShopCount').text(data.length + " itens");
            }
        }
    });
}

function ShopHeader(item, i) {
    var string = "<div class='sidebar-message' style='background:#fff'>\
                        <div class='media-body'>\
                            <div style='float:left;'><span>Pedido: </span><strong>" + item.IdTransacao + "</strong>\
                            <br>\
                            <small class='text-muted'>" + changeJsonDateFormat(item.dtTransacao, false, true) + "</small></div>\
                            <div style='float:right;'><span>Valor Total: </span><strong>" + changeNumberFormat(item.vlTransacao, ',', 2) + "</strong></div>\
                        </div>\
                    </div>";

    $('#shopList').append(string);
}

function ShopEntryHeader(item, contagem, subItems) {
    var string = "<div class='sidebar-message' style='background:#f9f9f9'>\
                        <a href='#'>\
                            <div class='pull-left text-center'>\
                                <img alt='image' src='/Content/images/categories/35/" + item.txCategoria + ".png'>\
                                <div class='m-t-xs' style='float: left;margin: 10px 5px;'>\
                                    " + (subItems ? ("<i class='fa fa-plus text-info' onclick='ShopToggleItems(" + item.IdTransacao + ", " + item.IdServico + ")'></i>") : "") + "\
                                </div>\
                            </div>\
                            <div class='media-body'>\
                                " + item.txNomeServico + "\
                                <br>\
                                <small class='text-muted'>"+ contagem + " unidade(s)</small>\
                            </div>\
                        </a>\
                    </div>";

    $('#shopList').append(string);
}

function ShopEntryItems(item, i) {
    var string = "<div class='sidebar-message serv" + item.IdTransacao + "-" + item.IdServico + "' style='display:none;background:#f9f9f9' >\
                        <a href='/Incoming/Search?search=" + item.nrCode + "'>\
                            <div class='media-body'>\
                                "+ item.nrCode + "\
                                <br>" +
                                SelectStatus(item.statusJson) +
                            "</div>\
                        </a>\
                    </div>";

    $('#shopList').append(string);
}

function ShopHomeClear() {
    $('#homeShopCount').text('');
    $('#shopSpan').text('');
    $('#shopList').empty();
}

function ShopToggleItems(IdTransacao, IdServico) {
    $(".serv" + IdTransacao + "-" + IdServico).each(function () {
        $(this).toggle();
    });
}

function SelectStatus(status) {
    switch (status) {
        case "Aguardando":
            {
                return '<button class="btn btn-warning" data-style="expand-right" style="padding:0px 5px;">Aguardando Aprovação</button>';
            } break;
        case "Erro":
            {
                return '<button class="btn btn-danger" data-style="expand-right" style="padding:0px 5px;">Erro na Aprovação</button>';
            } break;
        default:
            {
                return '<button class="btn btn-success" data-style="expand-right" style="padding:0px 5px;">Aprovado</button>';
            }
    }
}
/*Generic Actions*/

function ShowFile(Id, IdReferencia, tipo) {
    if (Id == null) {
        if (IdReferencia != undefined && IdReferencia != null) {
            var urlG = "";
            switch (tipo) {
                case 'danfe': urlG = "/Artfacts/GenerateDanfe"; break;
                case 'duplicata': {
                    if (IsSeller != undefined && IsSeller) {
                        urlG = "/Artfacts/GenerateDuplicata";
                    }
                    else {
                        toastr.warning('Nenhum Arquivo', 'Oops!');
                        return;
                    }
                } break;
                default: {
                    toastr.warning('Nenhum Arquivo', 'Oops!');
                    return;
                }
            }
            $.ajax({
                type: "GET",
                url: urlG,
                data: { Id: IdReferencia, Id: IdReferencia },
                success: function (response) {
                    if (response.success) {
                        toastr.info(response.message);
                    }
                    else
                        ToastMessage('warning', response.message);
                },
                error: function (response) {
                    toastr.error('Ocorreu algum erro inexperado, tente novamente em instantes')
                }
            });
        }
        else {
            toastr.warning('Nenhum Arquivo', 'Oops!');
            return;
        }
    }
    else {
        $.ajax({
            type: "GET",
            url: "/Files/Arquivo",
            data: { Id: Id },
            success: function (response) {
                if (response != "") {
                    OpenNrWindow("/Files/Arquivo?Id=" + Id, 60, 90);
                } else {
                    toastr.warning('Nenhum Arquivo pode ser aberto', 'Oops!')
                }
            },
            error: function (response) {
                toastr.error('Ocorreu algum erro inexperado, tente novamente em instantes')
            }
        });
    }
}

function GetMoneyOver() {
    if (xlogs) {
        $.ajax({
            type: "Get",
            dataType: 'json',
            url: "/Generic/GetCreditOver",
            success: function (response) {
                $('#saldoLogin').text("R$ " + changeNumberFormat(response.data.vlSaldo, ',', 2));
            },
            error: function (response) {
                toastr.error('Não foi possível sincronizar o Saldo');
            }
        });
    }
}

function ActiveCommunication(cnpj) {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/Admin/ChangeComunication",
        data: { cnpj: cnpj, flCom: true },
        success: function (response) {
            if (response.success) {
                toastr.success('Comunicação ativada')
            }
        },
        error: function (response) {
            toastr.error(response.message);
        }
    });
}

function LogMapped(idModulo, idPagina, idFuncao, idProcesso, idProgramacao) {
    $.ajax({
        type: "POST",
        url: "/Generic/LogMappedAction",
        data: { idModulo: idModulo, idPagina: idPagina, idFuncao: idFuncao, idProcesso: idProcesso, idProgramacao: idProgramacao },
        success: function () {
        },
    });
}

function CurrentRelation(cnpjA, cnpjB, target1, target2) {
    $.ajax({
        type: "POST",
        url: "/Aging/CurrentRelation",
        data: { cnpjA: cnpjA, cnpjB: cnpjB },
        success: function (response) {
            if (response.data != null) {
                if (response.data.length > 0) {
                    for (var i = 0; i <= response.data.length; i++) {
                        if (i == 0)
                            $(target1).text(changeNumberFormat(response.data[i], ",", 2));
                        if (i == 1)
                            $(target2).text(changeNumberFormat(response.data[i], ",", 2));
                    }
                }
                else {
                    $(target1).text("0,00");
                    $(target2).text("0,00");
                }
            }
        },
    });
}
var zoneUploadCertificate;

$(document).ready(function () {
    $('#upload_certificate').dropzone({
        parallelUploads: 1,
        maxFiles: 1,
        paramName: "files",
        autoProcessQueue: false,
        createImageThumbnails: false,

        // Dropzone settings
        init: function () {
            zoneUploadCertificate = this;

            this.on("processing", function (file) {
                var senha = $('#txtCertificatePassword').val();
                this.options.url = "Admin/UploadCertificate?senha=" + senha;
            });

            this.on("complete", function (data) {
                var response = JSON.parse(data.xhr.responseText);

                if (response.success) {
                    this.removeAllFiles();
                    toastr.success('Salvo com Sucesso');
                    $('#certificateForm').modal('hide');
                }
                else {
                    this.removeAllFiles();
                    toastr.error(response.message, 'Falha');
                }
            });
        }

    });
});

function SaveCertificate() {
    zoneUploadCertificate.processQueue();
}
$(document).ready(function () {
    ContactCallPulse();
    ContactCallTimer();
});

var contactCallEvent;
function ContactCallTimer() {
    contactCallEvent = setTimeout(function () {
        ContactCallPulse();
        clearTimeout(contactCallEvent);
        ContactCallTimer();

        ContactCallCheck();
    }, 3000)
}

var ringCont = 0;
function ContactCallCheck() {
    if ($('#callIcon').is(':visible')) {
        if ($('#iContactInfo').length == 0 || !$('#iContactInfo').is(':visible')) {
            Bounce($('#callIcon'));

            if (ringCont < 2) {
                ringCont++
                document.getElementById('ringCall').play();
            }
        }
    }
}

function ContactCallPulse() {
    if ($('#callList').length > -1) {
        if (!$('#callList').is(':visible')) {
            ContactCallEventAlerts();
            DropSpecial();
        }
    }
}

var callingActive = false;
function ContactCallEventAlerts() {
    if (!callingActive) {
        callingActive = true;

        $.ajax({
            url: "/Generic/GetCalls",
            type: 'GET',
            dataType: 'json',
            success: function (json) {
                var calls = json.data;
                CallClear();

                if (calls.length > 0) {
                    $('#callIcon').show();
                    $('#callSpan').text(calls.length);

                    for (var i = 0; i < calls.length; i++) {
                        var item = calls[i];

                        ContactCallBlock(item, i);
                    }
                }
                else {
                    ringCont = 0;
                }
            },
            complete: function (json) {
                callingActive = false;
            }
        })
    }
}

function ContactCallBlock(item, i) {
    if (i > 0)
        $('#callList').append("<li class='divider'></li>");

    var string = "<li> \
            <a class='cuPO' onclick='ShowContactInfo(null,\""+ item.chave + "\")'> \
                <div> \
                    <i class='fa fa-phone fa-fw' style='font-size:24px;'></i><b>" + item.ContatoOrigem.Empresa.razaoSocial + "</b><br/><b>" + item.ContatoOrigem.txNome + " " + item.ContatoOrigem.txSobrenome + "<br/>\
                </div> \
            </a> \
        </li>"

    $('#callList').append(string);
}

function CallClear() {
    $('#callIcon').hide();
    $('#callSpan').text('');
    $('#callList').empty();
}

var callRoomId;
function ContactCallToggle() {
    if ($('#frameCall').attr('src') == '') {
        $.ajax({
            url: "/Generic/StartCall",
            type: 'POST',
            dataType: 'json',
            data: { idContato: ContatoAtual },
            success: function (json) {
                if (json.data != null) {
                    callRoomId = json.data.chave;
                    $('#frameCall').attr('src', "https://tokbox.com/embed/embed/ot-embed.js?embedId=13861234-911b-4403-bf27-20abc30e221b&room=" + json.data.chave + "&iframe=true");
                    $('#callVideoLink').addClass('text-danger');
                }
            }
        });
    }
    else {
        $.ajax({
            url: "/Generic/CloseCall",
            type: 'POST',
            dataType: 'json',
            data: { chave: callRoomId },
            success: function (json) {
                toastr.info('Ligação encerrada');
            }
        });
        callRoomId = '';

        $('#frameCall').attr('src', '');
        $('#callVideoLink').removeClass('text-danger');
    }
}

var ContatoAtual = 0;
var ContactModel = "<div class='modal inmodal' id='iContactInfo' tabindex='-1' role='dialog' aria-hidden='true' style='display: none; padding-right: 17px;z-index: 4000 !important;'>\
                        <div class='modal-dialog modal-lg' >\
                            <div class='modal-content animated fadeIn fl' style='width: 450px; background: #2F4050;z-index: 4001; !important;' >\
                                <div class='modal-header' style='background:#f3f3f4;padding:0px;border-radius: 5px 5px 0px 0px;'>\
                                    <button type='button mr5' class='close' data-dismiss='modal' ><span aria-hidden='true'>×</span><span class='sr-only'>Close</span></button>\
                                    <img src='/Content/images/NotaRegistrada_LogoP.png' style='width:30px;float:left;'/>\
                                </div>\
                                <div class='col-md-12 mt10 mb20' style='color:#f3f3f4;font-size:11px;'>\
                                    <div class='fa fa-user fl' style='font-size: 50px;padding:0px;background-color: white;color:darkgrey;border-radius: 30px;padding: 5px 10px; width:62px'></div>\
                                                                    <div class='col-md-10 fr'><b>{nome}</b></div>\
                                                                    <div class='col-md-10 fr'><a href='/Aging/Client?cnpj={cnpj}' target='_blank' style='color:white;'>{empresa}<span class='fa fa-external-link ml10'></span></a></div>\
                                                                    <div class='col-md-10 fr mb10'><b>{cargo}</b></div>\
                                                                    <div class='col-md-10 fr'><i class='fa fa-phone mr10'></i><b>{telefone}</b></div>\
                                                                    <div class='col-md-10 fr mt5'><a href='mailto:{email}' target='_blank' style='color:white;'><i class='fa fa-envelope mr10'></i>{email}</a></div>\
                                                                    <div class='col-md-2 fr'>\
                                                                        <a href='{linkedin}' target='_blank'><img src='/Content/images/footer/icone_linkedin.png' style='width:16px;' /></a>\
                                                                        <a href='' target='_blank'><img src='/Content/images/footer/icone_twitter.png' style='width:16px;' /></a>\
                                                                    </div>\
                                </div>\
                                <div class='col-md-12 fl mb0' style='background:#f3f3f4;padding:10px;display:{display};'>\
                                    <div class='col-md-2'>\
                                        <a><spam class='fa fa-photo' id='callVideoLink' style='font-size:34px;' onclick='ContactCallToggle()'></spam></a>\
                                    </div>\
                                    <div class='col-md-2'>\
                                        <a><spam class='fa fa-link' style='font-size:34px;'></spam></a>\
                                    </div>\
                                    <div class='col-md-2'>\
                                        <a><spam class='fa fa-user' style='font-size:34px;'></spam></a>\
                                    </div>\
                                    <div class='col-md-2'>\
                                        <a><spam class='fa fa-history' style='font-size:34px;'></spam></a>\
                                    </div>\
                                    <div class='col-md-2'>\
                                        <a><spam class='fa fa-file-text' style='font-size:34px;'></spam></a>\
                                    </div>\
                                    <div class='col-md-2'>\
                                        <a><spam class='fa fa-align-justify' style='font-size:34px;'></spam></a>\
                                    </div>\
                                </div>\
                                <div class='col-md-12 fl mb20 mlm15' style='display:{display};'>\
                                    <input type='hidden' id='hdfCallId' />\
                                    <iframe id='frameCall' src='{ROOMIDNR}' width=448 height=360 allow='microphone; camera' style='overflow:hidden;border:none;'></iframe>\
                                </div>\
                            </div>\
                        </div>\
                     </div>";

var processing = false;

var previousId;
var previousRoom;
function ShowContactInfo(Id, roomId) {
    if (previousId == Id && roomId == previousRoom) {
        $('#iContactInfo').nModal('show');
        return;
    }

    previousId = Id;
    previousRoom = roomId;

    if (!processing) {
        $('#iContactInfo').remove();
        processing = true;

        //Removendo lixo anterior
        var old = $('body #contactPop');
        if ($(old).length > 0)
            $(old).remove();

        var model = '';

        var modalContact = '';

        $.ajax({
            type: "Post",
            dataType: 'json',
            url: "/Generic/GetContact",
            data: { Id: Id, token: roomId },
            success: function (response) {
                if (response.data != null) {
                    var data = response.data;

                    model = ContactModel;
                    model = model.replace("\{nome\}", data.txNome + ' ' + data.txSobrenome);
                    model = model.replace("\{empresa\}", data.Empresa.razaoSocial);
                    model = model.replace("\{cnpj\}", data.IdCnpj);
                    model = model.replace("\{cargo\}", data.txCargo);

                    ContatoAtual = data.IdUser;
                    if (ContatoAtual != null) {
                        model = model.replace('{display}', 'block').replace('{display}', 'block');
                    }
                    else {
                        model = model.replace('{display}', 'none').replace('{display}', 'none');
                    }

                    if (data.ddd != '') {
                        model = model.replace("\{telefone\}", "(" + data.dddComercial + ") " + data.telefoneComercial.substring(0, data.telefoneComercial.length - 5) + '-' + data.telefoneComercial.substring(data.telefoneComercial.length - 5), 4);
                    }
                    else
                        model = model.replace("\{telefone\}", '');

                    model = model.replace("\{email\}", data.txEmail).replace("\{email\}", data.txEmail);
                    model = model.replace("\{linkedin\}", data.linkedin);
                }
                else {
                    model = ContactModel;
                }

                if (roomId != undefined && roomId != null) {
                    callRoomId = roomId;

                    roomId = "https://tokbox.com/embed/embed/ot-embed.js?embedId=13861234-911b-4403-bf27-20abc30e221b&room=" + roomId + "&iframe=true";
                    model = model.replace("\{ROOMIDNR\}", roomId);
                }
                else {
                    callRoomId = null;
                    model = model.replace("\{ROOMIDNR\}", '');
                }

                $('body').append(model);

                modalContact = $('#iContactInfo');
            },
            error: function () {
                toastr.error(response.message, 'Falha');
            },
            complete: function () {
                processing = false;
                $(modalContact).nModal('show');

                if (callRoomId != null) {
                    $('#callVideoLink').addClass('text-danger');
                }
            }
        });
    }
}

function ShowTerContactMerc(cnpj, email) {
    $('#txContatoMercCnpj').val(cnpj);
    $('#txContatoMercMail').val(email);

    $('#iContatoMercMail').nModal('show');
}

function SaveTerContactMercMail(sender) {
    var cnpj = $('#txContatoMercCnpj').val();
    var email = $('#txContatoMercMail').val();

    if (email != '') {
        $.ajax({
            type: "Post",
            dataType: 'json',
            url: "/Admin/ContactMercMail",
            data: { cnpj: cnpj, email: email },
            success: function (response) {
                if (response.success) {
                    toastr.success('Email mecânico salvo com sucesso');
                    $('#iContatoMercMail').nModal('hide');
                }
                else {
                    toastr.warning(response.message);
                }
            },
            error: function () {
                toastr.error('Falha');
            }
        });
    }
}


function ForgotMail(email) {
    if (email == '') {
        toastr.error("Preencha um e-mail", 'Falha');
    }
    else {
        $.ajax({
            type: "Get",
            dataType: 'json',
            url: "/Account/Forgot",
            data: { email: email },
            success: function (response) {
                toastr.success(response.message);
            },
            error: function () {
                toastr.error('Tente novamente em instantes');
            }
        });
    }
}
