﻿;(function () {
	angular.module('gbFilters', [])
		.filter('utc', function () {
			return function (val) {
				if (val !== undefined && val.length > 16) {
					return val.substring(0, 16)
				}
				return val;
			}
    })
    .filter('urlEncode', [function () {
      return window.encodeURIComponent;
    }])
	.filter('cut', function () {
		return function (value, wordwise, max, tail) {
			if (!value) return '';

			max = parseInt(max, 10);
			if (!max) return value;
			if (value.length <= max) return value;

			value = value.substr(0, max);
			if (wordwise) {
				var lastspace = value.lastIndexOf(' ');
				if (lastspace !== -1) {
					//Also remove . and , so its gives a cleaner result.
					if (value.charAt(lastspace - 1) === '.' || value.charAt(lastspace - 1) === ',') {
						lastspace = lastspace - 1;
					}
					value = value.substr(0, lastspace);
				}
			}

			return value + (tail);
		};
	})
	.filter('cRoundAbs', ['$global','$filter',function ($global, $filter) {
		return function (input, factor) {
			if (input == 0 || isNaN(input)) return $filter('getLabel')("lblNA");      
			var dec = 0;
			if (factor == 1) {
				input = input / 1000;
				dec = 3;
			}
			else if (factor == -1)
			{ input = input * 1000; dec = 0; }
			else {
				input = input;
				dec = 0;
			}
			if (input < 0) {
				return '(' + parseFloat(Math.abs(input)).toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ')';
			} else
				return parseFloat(input).toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		};
	}])
	.filter('cRound', function ($filter) {
		return function (input, factor) {
			if (input === 0 || isNaN(input)) return 'N/A';
			return cRound(input, factor);
		};
	})
	.filter('cRoundAbsViewBy', ['$global', '$filter', function ($global, $filter) {
		return function (input, factor, cobj, rowobj, datesArray, $index, $last, viewBy, orderBy) {
			if (viewBy === 'csp') {        
				if (isNaN(input) || cobj.ViewVal === 0 || isNaN(cobj.ViewVal)) return $filter('getLabel')("lblNA");
				input = (parseFloat(input) / parseFloat(cobj.ViewVal)) * (100);
				var retVal = $filter('WNOrDecPlace')(input, 2, 'lblNA');
				return retVal === $filter('getLabel')("lblNA") ? $filter('getLabel')("lblNA") : $filter('suffix')(retVal, '%');
			}
			else if (viewBy === 'csf') {
				if (isNaN(input) || cobj.ViewVal === 0 || isNaN(cobj.ViewVal)) return $filter('getLabel')("lblNA");
				input = (parseFloat(input) / parseFloat(cobj.ViewVal));
				return $filter('WNOrDec')(input, 2);
			}
			else if (viewBy === 'haa') {
				if (isNaN(input)) return $filter('getLabel')("lblNA");
				return $filter('cRoundAbs')(parseFloat(input) - parseFloat(cobj.PrevVal), 2);
			}
			else if (viewBy === 'hap') {
				if (isNaN(input) || input === 0 || cobj === null || cobj.PrevVal === 0) return $filter('getLabel')("lblNA");
				var retVal = $filter('WNOrDecPlace')(((parseFloat(input) / parseFloat(cobj.PrevVal)) - 1) * 100, 2, 'lblNA');
				return retVal === $filter('getLabel')("lblNA") ? $filter('getLabel')("lblNA") : $filter('suffix')(retVal, '%');
			}
			else {

				if (input === 0 || isNaN(input)) return $filter('getLabel')("lblNA");

				if (cobj.Ratio === 'Tier 1 Capital adequacy ratio' || cobj.Ratio === 'Total Capital adequacy ratio') {
					return input + '%'
				}
				var dec = 0;
				
				if (factor === 1) {
					input = input / 1000;
					//dec = 3;
				}
				else if (factor === -1)
				{ input = input * 1000; dec = 0; }
				else { input = input; dec = Math.abs(input) > 10000 ? 0 : 2; }
				dec = dec > 0 && parseInt(input) === input ? 0 : dec;
				if (input < 0) {          
					return '(' + parseFloat(Math.abs(input)).toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ')';
				} else {         
					return parseFloat(input).toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
				}
			}

		};
	}])
	.filter('cRoundAbsViewByErrorClass', ['$filter', function ($filter) {
		return function (input, factor, cobj, rowobj, datesArray, $index, $last, viewBy, orderBy) {

			if (viewBy === 'csp') {
				if (isNaN(input) || cobj.ViewVal === 0 || isNaN(cobj.ViewVal)) return '';
				input = (parseFloat(input) / parseFloat(cobj.ViewVal)) * (100);
				if (parseInt(input) < 0)
					return "clr-red-cus";
				else
					return '';
			}
			else if (viewBy === 'csf') {
				if (isNaN(input) || cobj.ViewVal === 0 || isNaN(cobj.ViewVal)) return '';
				input = (parseFloat(input) / parseFloat(cobj.ViewVal));
				if (parseInt(input) < 0)
					return "clr-red-cus";
				else
					return '';
			}
			else if (viewBy === 'haa') {
				if (isNaN(input) || input === 0 || cobj === null || cobj.PrevVal === null) return '';
				var temp = parseFloat(input) - parseFloat(cobj.PrevVal);
				if (parseFloat(temp) < 0)
					return "clr-red-cus";
				else
					return '';
			}
			else if (viewBy === 'hap') {
				if (isNaN(input) || input === 0 || cobj === null || cobj.PrevVal === null) return '';
				if (parseFloat(((parseFloat(input) / parseFloat(cobj.PrevVal)) - 1) * 100) < 0)
					return 'clr-red-cus';
				else
					return '';
			} else {
				if (input === 0 || isNaN(input)) return '';
				if (input < 0)
					return "clr-red-cus";
				else
					return '';
			}
		};
	}])
	.filter('setDecimal',['$filter', function ($filter) {
		return function (input, places) {
			if (isNaN(input)) return input;
			// If we want 1 decimal place, we want to mult/div by 10
			// If we want 2 decimal places, we want to mult/div by 100, etc
			// So use the following to create that factor
			var factor = "1" + Array(+(places > 0 && places + 1)).join("0");
			return Math.round(input * factor) / factor;
		};
	}])
	.filter('filterRatioDate',['$filter', function ($filter) {
		return function (input, ratio, dateElem, dataarray) {

			dataarray.map(function (v, i) {
				if (parseInt(v.AsofDate.slice(6, -2)) === dateElem && v.Ratio === ratio) {
					input = v.Value;
					return true;
				}
			});
			return input;
		};
	}])
	.filter('WNOrDec',['$filter', function ($filter) {
		return function (input, places) {
			if (input === null) return null;
			if (isNaN(input)) return input;
			var output;
			places = places === undefined ? 2 : places;
			if (Number(Math.abs(input)) > 10000)
				output= $filter('number')(input,0);
			else
				output = $filter('number')(input, places);      
			if (Math.abs(input) > 0 && (parseFloat(output) === 0.00 || parseFloat(output) === 0.0 || parseFloat(output) === 0))
				output = $filter('number')(input, ++places);

			if (Math.abs(input) > 0 && (parseFloat(output) === 0.00 || parseFloat(output) === 0.0 || parseFloat(output) === 0))
				output = $filter('number')(input, ++places);

			return output;
		};
	}])
    .filter('WNOrDecPlace', ['$global', '$filter',  function ($global,$filter) {
		return function (input, places, placeholder) {
			if (isNaN(input) || input === undefined || input === null || parseFloat(input) === 0) return $filter('getLabel')(placeholder);
			places = places === undefined ? 2 : places;
			if (Number(Math.abs(input)) > 10000)
				return $filter('number')(input,0);        
			else
				return $filter('number')(input, places);
		};
	}])
    .filter('Abbr', ['$filter',  function ($filter) {
		return function (input, places) {
			if (isNaN(input)) return input;
			if (input === null) { return null; }
			if (input === 0) { return '0'; }
			places = (!places || places < 0) ? 0 : places;	
			var b = (input).toPrecision(2).split("e"),
					k = b.length === 1 ? 0 : Math.floor(Math.min(b[1].slice(1), 14) / 3),
					c = k < 1 ? input.toFixed(0 + places) : (input / Math.pow(10, k * 3)).toFixed(places),
					d = c < 0 ? c : Math.abs(c),
          e = d + ['', $filter('getLabel')('lblThousandAbbr'), $filter('getLabel')('lblMillionAbbr'), $filter('getLabel')('lblBillionAbbr'), $filter('getLabel')('lblTrillionAbbr')][k];
			return e;
		};
	}])
    .filter('AbbrOrWNOrDec', ['$filter', function ($filter) {
			return function (input, places) {
				if (isNaN(input)) return input;
				if (input === null) { return null; }
				if (input === 0) { return '0'; }
				if(Math.abs(Number(input))>10000){

				places = (!places || places < 0) ? 0 : places;
				var b = (input).toPrecision(2).split("e"),
						k = b.length === 1 ? 0 : Math.floor(Math.min(b[1].slice(1), 14) / 3),
						c = k < 1 ? input.toFixed(0 + places) : (input / Math.pow(10, k * 3)).toFixed(places),
						d = c < 0 ? c : Math.abs(c),
            e = d + ['', $filter('getLabel')('lblThousandAbbr'), $filter('getLabel')('lblMillionAbbr'), $filter('getLabel')('lblBillionAbbr'), $filter('getLabel')('lblTrillionAbbr')][k];
				return e;
			}else
			    return $filter('WNOrDec')(input,places);
			};
    }])
    .filter('AbbrOrWNOrDecAuto', ['$filter',  function ($filter) {
      return function (input, places) {
        if (isNaN(input)) return input;
        if (input === null) { return null; }
        if (input === 0) { return '0'; }
        let retVal = 0;
        let firstRet = $filter('AbbrOrWNOrDec')(input,1);
        let secondRet = $filter('AbbrOrWNOrDec')(input, 2);
        let thirdRet = $filter('AbbrOrWNOrDec')(input, 3);
        if (parseFloat(thirdRet) === parseFloat(secondRet))
          retVal = secondRet;
        else if (parseFloat(secondRet) === parseFloat(firstRet))
          retVal = firstRet;
        else
          retVal = thirdRet;

        return retVal;

      };
    }])
    .filter("allowWhiteSpace", ['$sce',  function ($sce) {
      return function (message) {
        message = message || '';
        // Need to trust as HTML to allow &nbsp; as HTML entity
        return $sce.trustAsHtml(message.replace(/\s/g, '&nbsp;'));
      }
    }])
    .filter('newsLimitWithReadMore', ['$filter', function ($filter) {
		return function (input, limit, obj) {
			var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
			var reg = new RegExp('(?=[' + trimmable + '])');
			var words = input.split(reg);
      var count = 0;
      
			var html= words.filter(function (word) {
				count += word.length;
				return count <= limit;
			}).join('') + ' <a class="pull-right cursor-pointer" href="' + $filter('getURL')(obj.Detail_Url) + '">'+ $filter('getLabel')('lblReadMore')+'</a>';
     
      return escape(html);
		};
	}])
    .filter('limitText', ['$filter',  function ($filter) {
		return function (input, limit, obj) {

			var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
			var reg = new RegExp('(?=[' + trimmable + '])');
			var words = input.split(reg);
			var count = 0;
			return words.filter(function (word) {
				count += word.length;
				return count <= limit;
			}).join('') + '....';


		};
	}])
    .filter('successclass', ['$filter', function ($filter) {
		return function (input, dec) {
			var val = parseFloat(input);
			return val > 0 ? 'clr-green-cus' : val < 0 ? 'clr-red-cus' : 'clr-gray-cus';
		};
    }])
    .filter('gettrendimage', ['$filter', function ($filter) {
      return function (input,path) {
        var val = parseInt(input);
        var today = new Date();
        return val > 0 ? path + 'market-up.png?' + today.getMilliseconds() : val < 0 ? path + 'market-down.png?' + today.getMilliseconds() : '';
      };
    }])
	.filter('badgeclass',['$filter', function ($filter) {
		return function (input, dec) {
			var val = parseFloat(input);
			return val === 0 ? 'clr-gray-cus' : val > 0 ? 'badge-pas' : 'badge-nag';
		};
	}])
    .filter('negativeclass', ['$filter', function ($filter) {
		return function (input, viewBy) {
			if (parseInt(input) < 0)
				return "clr-red-cus";
			else
				return '';
		};
	}])
    .filter('valuationFtr', ['$filter', function ($filter) {
		return function (input) {
			if (input === null || isNaN(input)) return '';
			input = parseFloat(input);
			if (input === 0)
				return '<i class="fa fa-circle grey"></i>';
			if (input > 0)
				return '<i class="fa fa-circle green"></i>';
			if (input < 0)
				return '<i class="fa fa-circle red"></i>';


		}
	}])
    .filter('successhtml', ['$filter',  function ($filter) {
		return function (input, dec) {
			var val = Number(input);
			if (val === 0) {
				return "";
			}
			else if (val > 0) {
				return "<i class='fa fa-arrow-circle-up price-change clr-green-cus'></i>";
			}
			else {
				return "<i class='fa fa-arrow-circle-down price-change clr-red-cus'></i>";
			}
		};
	}])
    .filter('trim', ['$filter',  function ($filter) {
		return function (value) {
			if (!angular.isString(value)) {
				return value;
			}
			return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
		};
	}])

    .filter('unique', ['$filter',  function ($filter) {

		return function (items, filterOn) {

			if (filterOn === false) {
				return items;
			}

			if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
				var hashCheck = {}, newItems = [];

				var extractValueToCompare = function (item) {
					if (angular.isObject(item) && angular.isString(filterOn)) {
						return item[filterOn];
					} else {
						return item;
					}
				};

				angular.forEach(items, function (item) {
					var valueToCheck, isDuplicate = false;

					for (var i = 0; i < newItems.length; i++) {
						if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
							isDuplicate = true;
							break;
						}
					}
					if (!isDuplicate) {
						newItems.push(item);
					}

				});
				items = newItems;
			}
			return items;
		};
	}])
    .filter("cReverse", ['$filter',  function ($filter) {
		return function (items, flag) {
			if (flag === -1)
				return items.slice().reverse(); // Create a copy of the array and reverse the order of the items
			else items;
		};
	}])
    .filter('pe', ['$filter',  function ($filter, $global) {
		return function (input, places) {
			if (input === null || input === undefined || isNaN(input)) return '-';
			input = parseFloat(input);
			places = isNaN(places) || places == null ? 2 : places;
			if (input < 0)
				return $filter('getLabel')("lblNM");
			else if (input == 0 || input == null || input == undefined)
				return $filter('getLabel')("lblNA");
			else
				return $filter('WNOrDec')(input, places);
		};
	}])
    .filter('nmFtr', ['$global', '$filter', function ($global,$filter ) {
		return function (input, places) {
			if (input === null || input === undefined || isNaN(input)) return '-';
			input = parseFloat(input);
			places = isNaN(places) || places == null ? 2 : places;
			if (input === 0)
				return $filter('getLabel')("lblNM");
			else
				return $filter('WNOrDec')(input, places);
		};
	}])
    .filter('suffix', ['$global', '$filter', function ($global, $filter) {
		return function (input, suffix) {
      suffix = suffix === null ? '' : suffix;
      if (Math.abs(parseFloat(input)) > 0)
        return input + suffix;
      else if (input === null || input === undefined || parseFloat(input) === 0 || input === "N/A" || input === $filter('getLabel')("lblNA")) return input;
      else
			return Number(lang)===1? input +suffix: input +' '+ suffix;
		}
	}])
    .filter('monthNumber',['$filter', function ($filter) {
		return function (value) {
			if (parseInt(lang) === 1) {
				var monthNames = { "January": '01', "February": '02', "March": '03', "April": '04', "May": '05', "June": '06', "July": '07', "August": '08', "September": '09', "October": '10', "November": '11', "December": '12' };
				return monthNames[value];
			} else {
				var monthNames = { 'يناير': "01", 'فبراير': "02", 'مارس': "03", 'إبريل': "04", 'مايو': "05", 'يونيو/يونية': "06", 'يوليو/يولية': "07", 'أغسطس': "08", 'سبتمبر': "09", 'أكتوبر': "10", 'نوفمبر': "11", 'ديسمبر': "12" };
				return monthNames[value];
			}
		};
	}])
    .filter('alphabetNumber', ['$filter', function ($filter) {
		return function (value) {
			var Aphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
			value -= 1;
			return Aphabet[value];
		};
	}])
    .filter('ytyFilter', ['$filter', function ($filter) {
		return function (year, ratio, title, summaryData, years) {

			var endYear = year
			var prevYear = years.map(function (v) { return v === year - 1 ? v : undefined }).clean();

			var closeValue = summaryData.map(function (v) {
				return v.Year == endYear && v.Ratio == ratio && v.Title == title ? v.Value : undefined;
			}).clean();
			var prevClose = summaryData.map(function (v) {
				return v.Year == prevYear && v.Ratio == ratio && v.Title == title ? v.Value : undefined;
			}).clean();
			if (closeValue > 0 && prevClose > 0)
				return parseFloat(((closeValue / prevClose) - 1) * 100);
			else
				return 0;
		}
	}])
    .filter('ytyAvgFilter', ['$filter',function ($filter) {
		return function (input, dobj) {

			var tobj = dobj.map(function (elem) { return elem.yty == 0 ? undefined : elem; }).clean();
			if (dobj.length !== tobj.length) {
				return 0;
			}
			var avg = dobj.reduce(function (p, c, i, a) {
				if (isNaN(c.yty))
					return p;
				else
					return p + (c.yty / a.length)
			}, 0);

			return avg;
		}
	}])
    .filter('dateCorrection', ['$filter', function ($filter) {
		return function (date) {
			if (date != undefined) {
				return date.slice(6, -2);
			}
		};
	}])
	.filter('abs', function () {
		return function (val) {
			return Math.abs(val);
		}
	})
    .filter('getMTypeID', ['$filter', function ($filter) {
		return function (val) {
			var type;
			switch (val) {
				case 1:
					type = $filter('getLabel')("lblBoardofDirectors");
					break;
				case 2:
					type = $filter('getLabel')("lblGeneralAssembly");
					break;
				case 3:
					type = $filter('getLabel')("lblExtraOrdinary");
					break;
				case 4:
					type = $filter('getLabel')("lblCashDividend");
					break;
			}
			return type;
		}
	}])
	.filter('ValueCheck', function () {
		return function (val) {
			if (val > 0) {
				return "badge-pas"
			} else if (val < 0) {
				return "badge-nag"
			} else {
				return ""
			}
		}
	})
	.filter('gbdate', ['$filter', function ($filter) {
		return function (input, place) {
			if (input === undefined) return place;;

			if (isNaN(input) && input.indexOf('Date') !== -1)
				input = parseInt(input.replace(/\/Date\((.*?)\)\//gi, "$1"));
			return $filter('date')(input, 'dd/MM/yyyy');
		}
        }])
    .filter('gbfulldate', ['$filter', function ($filter) {
        return function (input, place) {
            if (input === undefined) return place;;

            if (isNaN(input) && input.indexOf('Date') !== -1)
                input = parseInt(input.replace(/\/Date\((.*?)\)\//gi, "$1"));
            return $filter('date')(input, 'dd/MM/yyyy h:mm a');
        }
    }])
    .filter('NAFtr', ['$global','$filter', function ($global, $filter) {
		return function (input, places, postFix) {
			postFix = postFix == undefined ? '' : postFix;
			places = places == undefined ? 0 : places;
			if (parseFloat(input) == 0 || input == null)
				return $filter('getLabel')('lblNA');
			else
				input = input.toFixed(places).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
			return input + '' + postFix;
		}
	}])
    .filter('place', ['$filter', function ($filter) {
		return function (input, places, postFix) {
			postFix = postFix == undefined ? '' : postFix;
			places = places == undefined ? 0 : places;
			if (isNaN(input) || input == undefined | input == "" || input == null || !$.isNumeric(input))
				return postFix;
			else
				input = parseFloat(input) !== 0 ? $filter('number')(input, places) : '';
			return input;
		}
    }])
    .filter('replace', ['$filter', function ($filter) {
      return function (input, compare, postFix) {
        if (parseFloat(input) > 0)
          return input;
        else if (input === compare)
          return postFix;
        
      }
    }])
    .filter('gbadmindate', ['$filter', function ($filter) {
            return function (input, place) {
                if (input === undefined) return place;;

                if (isNaN(input) && input.indexOf('Date') !== -1)
                    input = parseInt(input.replace(/\/Date\((.*?)\)\//gi, "$1"));
                return $filter('date')(input, 'MM/dd/yyyy');
            }
        }])
	.factory("interceptors", [function () {
		return {
			// if beforeSend is defined call it
			'request': function (request) {
				if (request.beforeSend)
					request.beforeSend();
				return request;
			},
			// if complete is defined call it
			'response': function (response) {
				if (response.config.complete)
					response.config.complete(response);
				return response;
			}
		};

	}])
    .filter('highlightStripHTML', ['$sce', function ($sce) {
		return function (text, phrase) {
			if (phrase) text = text.replace(/<(?:.|\n)*?>/gm, '').slice(0, 295).replace(new RegExp('(' + phrase + ')', 'gi'),
					'<span class="highlighted">$1</span>')
			return $sce.trustAsHtml(text + "...")
		}
	}])
    .filter('highlight', ['$sce', function ($sce) {
		return function (text, phrase) {
			if (phrase) text = text.replace(new RegExp('(' + phrase + ')', 'gi'),
					'<span class="highlighted">$1</span>')
			return $sce.trustAsHtml(text)
		}
	}])
    .filter('getLabel', ['$global', '$filter', function ( $global,$filter) {
		var cached = {};
		return function (input) {
 
			if (input in cached) {
				return cached[input];
			}else{
				cached= $global.getAllResources();
			}
			return cached[input]===undefined? input: cached[input];
		}
	}])
    .filter('filterRecords',['$filter',function ($filter) {
		return function (arr, field) {
			return $.grep(arr, function (elem) { return elem[field] > 0; }).length > 0;
		}

	}])
    .filter('getURL', ['$global', '$filter', function ($global,$filter ) {
		return function (url) {
			if (url === undefined) return;    
			if (parseInt(lang) == 2 && url.startsWith('/ar/'))
				return url;
			else if (parseInt(lang) == 2 && !url.startsWith('/ar/')) {
				url = siteRoot + (url.indexOf('/') === 0 ? url.replaceAt(0, '') : url);
			}
			else if (parseInt(lang) == 1 && url.startsWith('/ar/')) {
				url = siteRoot + url.replace('/ar/', '');
			}
			else
				url = url;

			return url.replace("//", "/").replace(/\--/g, '-');     
		}
	}])
    .filter('getCompanyURL', ['$global', '$filter', function ($global, $filter) {
			return function (url) {
				if (url === undefined) return;
				var returl = $filter('getURL')(url);
				var replaceString= "aname="+aname + "&searchText"
				returl= returl.replace("searchText", replaceString);        
				return returl;
			}
		}])
    .filter('getFundURL', ['$global', '$filter', function ($global, $filter) {
			return function (url) {
				if (url === undefined) return;
				var returl = $filter('getURL')(url);
				var replaceString = "searchText"
				returl = returl.replace("searchText", replaceString);
				return returl;
			}
		}])
    .filter('getLabel1', ['$filter', '$http',  function ($filter, $http) {
		var cached = {};
		var url = siteRoot + 'home/GBLabel/?input=';
		function detailsFilter(input) {
			if (input) {
				if (input in cached) {
					return typeof cached[input].then !== 'function' ? cached[input] : undefined;
				} else {
					cached[input] = $http({
						method: 'GET',
						url: url + input
					}).success(function (info) {
						cached[input] = info;
					});
				}
			}
		}
		detailsFilter.$stateful = true;
		return detailsFilter;
	}])
    .filter('getMesssage', ['$filter', '$http',  function ($filter, $http) {
		var cached = {};
		var url = siteRoot + 'home/GetMessage/?input=';
		function detailsFilter(input) {
			if (input) {
				if (input in cached) {
					return typeof cached[input].then !== 'function' ?
						cached[input] : undefined;
				} else {
					cached[input] = $http({
						method: 'GET',
						url: url + input
					}).success(function (info) {

						cached[input] = info;
					});
				}
			}
		}
		detailsFilter.$stateful = true;
		return detailsFilter;
	}])
    .filter('grabWord', ['$filter', function ($filter) {
		return function (input) {
			if (input === undefined || input === null || input.length == 0) return;
			var temp = input.split(' ');
			input = '<span>' + temp[0] + '</span>' + input.substr(temp[0].length);
			return input;
		}
	}])
    .filter('scoreCardHtml', ['$global', '$filter', function ($global, $filter) {
		return function (input, paramP, direction, meaningful) {
			
			if (input === undefined || paramP === undefined) return;
			var scor_active = 'scor_active';
			if (Number(meaningful) > 0 && (input < 0 || input >= 100))
				scor_active = '';

			var clsDirection = Number(direction) === 0 ? "pull-left" : "pull-right";
			var directionClass = Number(direction) === 0 ? "ltr" : "rtl";
			var cls = paramP.Item1 === 'Q1' ? scor_active : '';
			var rangeText = $filter('getLabel')("lblQuintileRange")

			var output = "<a class='tooltips q1 " + clsDirection + " " + cls + "' href='javascript:;'><span>"
									+ "<strong>" + rangeText + "</strong><br />"
									+ '<ul class="' + directionClass + '"><li>' + $filter('number')(paramP.Item2, 2) + '</li><li>' + " - " + '</li><li>' + $filter('number')(paramP.Item4, 2)
									+ "</li></ul></span></a>";
			cls = paramP.Item1 === 'Q2' ? scor_active : '';
			output += "<a class='tooltips q2 " + clsDirection + " " + cls + "' href='javascript:;'><span>"
									+ "<strong>" + rangeText + "</strong><br />"
									+ '<ul class="' + directionClass + '"><li>' + $filter('number')(paramP.Item4, 2) + '</li><li>' + " - " + '</li><li>' + $filter('number')(paramP.Item5, 2)
									+ "</li></ul></span></a>";

			cls = paramP.Item1 === 'Q3' ? scor_active : '';
			output += "<a class='tooltips q3 " + clsDirection + " " + cls + "' href='javascript:;'><span>"
									+ "<strong>" + rangeText + "</strong><br />"
									+ '<ul class="' + directionClass + '"><li>' + $filter('number')(paramP.Item5, 2) + '</li><li>' + " - " + '</li><li>' + $filter('number')(paramP.Item6, 2)
								 + "</li></ul></span></a>";
			cls = paramP.Item1 === 'Q4' ? scor_active : '';
			output += "<a class='tooltips q4 " + clsDirection + " " + cls + "' href='javascript:;'><span>"
									+ "<strong>" + rangeText + "</strong><br />"
									+ '<ul class="' + directionClass + '"><li>' + $filter('number')(paramP.Item6, 2) + '</li><li>' + " - " + '</li><li>' + $filter('number')(paramP.Item7, 2)
									+ "</li></ul></span></a>";
			cls = paramP.Item1 === 'Q5' ? scor_active : '';
			output += "<a class='tooltips q5 " + clsDirection +" " + cls + "' href='javascript:;'><span>"
									+ "<strong>" + rangeText + "</strong><br />"
									+ '<ul class="' + directionClass + '"><li>' + $filter('number')(paramP.Item7, 2) + '</li><li>' + " - " + '</li><li>' + $filter('number')(paramP.Item3, 2)
									+ "</li></ul></span></a>";
			return output;
		}
    }])
    .filter('printScoreCardHtml', ['$filter', '$global',  function ($filter, $global) {
      return function (input, paramP, direction, meaningful) {

        if (input === undefined || paramP === undefined) return;
        let scor_active = 'active';
        if (Number(meaningful) > 0 && (input < 0 || input >= 100))
          scor_active = '';

        let clsDirection = Number(direction) === 0 ? "pull-left" : "pull-right";
        let directionClass = Number(direction) === 0 ? "ltr" : "rtl";
        let cls = paramP.Item1 === 'Q1' ? scor_active : '';
        let imgSrc = paramP.Item1 === 'Q1' ? '/Content/Theme/images/blue_box.png' : '/Content/Theme/images/grey_box.png';
       
        let output = "<a class='q1 " +clsDirection + " " + cls + "'><img src='"+imgSrc+"' width='10' height='10' alt='' /></a>";

        cls = paramP.Item1 === 'Q2' ? scor_active : '';
        imgSrc = paramP.Item1 === 'Q2' ? '/Content/Theme/images/blue_box.png' : '/Content/Theme/images/grey_box.png';
        output += "<a class='q2 " + clsDirection + " " + cls + "'><img src='" + imgSrc + "' width='10' height='10' alt='' /></a>";

        cls = paramP.Item1 === 'Q3' ? scor_active : '';
        imgSrc = paramP.Item1 === 'Q3' ? '/Content/Theme/images/blue_box.png' : '/Content/Theme/images/grey_box.png';
        output += "<a class='q3 " + clsDirection + " " + cls + "'><img src='" + imgSrc + "' width='10' height='10' alt='' /></a>";

        cls = paramP.Item1 === 'Q4' ? scor_active : '';
        imgSrc = paramP.Item1 === 'Q4' ? '/Content/Theme/images/blue_box.png' : '/Content/Theme/images/grey_box.png';
        output += "<a class='q4 " + clsDirection + " " + cls + "'><img src='" + imgSrc + "' width='10' height='10' alt='' /></a>";

        cls = paramP.Item1 === 'Q5' ? scor_active : '';
        imgSrc = paramP.Item1 === 'Q5' ? '/Content/Theme/images/blue_box.png' : '/Content/Theme/images/grey_box.png';
        output += "<a class='q5 " + clsDirection + " " + cls + "'><img src='" + imgSrc + "' width='10' height='10' alt='' /></a>";
        return output;
      }
    }])
	.filter('utcdate', ['$filter', '$locale', function ($filter, $locale) {

		return function (input, format) {
			if (!angular.isDefined(format)) {
				format = $locale['DATETIME_FORMATS']['medium'];
			}

			var date = new Date(input);
			var d = new Date()
			var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
			return $filter('date')(_utc, format)
		};
	}])
	.filter('gbdateInt',['$filter', function ($filter) {
		return function (input) {
			if (input === undefined) return input;
			return parseInt(input.replace(/\/Date\((.*?)\)\//gi, "$1"));
		}
	}])
    .filter('financialDate', ['$filter',  function ($filter) {
		return function (input, type) {
			if (input == null) return '';
			if (type === '4') {

				var month = $filter('date')(input, 'MM');
				var year = $filter('date')(input, 'yy');
				return parseInt(month) === 3 ? 'Q1 ' + year : (parseInt(month) === 6 ? 'Q2 ' + year : parseInt(month) === 9 ? 'Q3 ' + year : parseInt(month) === 12 ? 'Q4 ' + year : '');
			} else {
				return $filter('date')(input, 'yyyy');
			}
		}
	}])
    .filter('EarningWatchChangeCal', ['$filter',  function ($filter) {
		return function (currVal, prevVal) {
			if (currVal === undefined || currVal <= 0 || prevVal === undefined || prevVal <= 0)
				return $filter('getLabel')("lblNA");
			else {
				return $filter('number')((currVal / prevVal - 1) * 100, 2) + '%';
			}
		}
	}])
    .filter('EarningWatchChangeClass', ['$filter',  function ($filter) {
		return function (currVal, prevVal) {
			if (currVal === undefined || currVal <= 0 || prevVal === undefined || prevVal <= 0)
				return '';
			else {

				var val = (currVal / prevVal - 1) * 100;
				return val > 0 ? 'clr-green-cus' : val < 0 ? 'clr-red-cus' : 'clr-gray-cus';
			}
		}
	}])
	.filter('empty', function () {
		var bar;
		return function (obj) {
			if (obj === null || obj === undefined || obj.length === 0) return true;
			for (bar in obj) {
				if (obj.hasOwnProperty(bar)) {
					return false;
				}
			}
			return true;
		};
	})
    .filter('replace', ['$filter',  function ($filter) {
		return function (input, value, replacer) {
			return (parseFloat(input) === parseFloat(value) || input === undefined) ? replacer : input;
		};
	}])
    .filter('subtotal', ['$filter',  function ($filter) {
		return function (items, index) {
			var subTotal = 0;
			for (var i = 0; i <= index; i++) {
				subTotal += (items[i].CashAdd - items[i].CashSub);
			}
			return $filter('WNOrDec')(subTotal, 2);
		}
		}])    
    .filter('totalByColum', ['$filter',  function ($filter) {
			return function (items, colum) {
				var subTotal = 0;
				for (var i = 0; i < items.length; i++) {
					subTotal += parseFloat(items[i][column]);
				}
				return $filter('WNOrDec')(subTotal, 2);
			}
		}])   
    .filter('haveValues', ['$filter',  function ($filter) {
		return function (obj, field) {
			if ($filter('empty')(obj)) return false;
			var items = $.grep(obj, function (elem) {
				return elem[field];
			});
			items = items !== null && items.length ? $.map(items, function (elem) { return Math.abs(parseFloat(elem)) !== '0'; }) : null;
			return items === null;
		}

	}])
    .filter("watchListClass", ['$filter',  function ($filter) {
		return function (input, title, t) {
			if (input === null || isNaN(input)) return '';
			input = parseFloat(input);

			if ((title === 'Stock Price' || title === 'Momentum' || title === 'growth') && t !== 'Price') {
				return $filter('successclass')(input);
			} else
				return '';
		}
 	}])
    .filter("watchListSuffix", ['$filter',  function ($filter) {
		return function (input, title, t, suffix) {
			if ((title === 'Stock Price' || title === 'Momentum' || title === 'growth') && t !== 'Price') {
        return parseFloat(input) === 0 ? '-' : $filter('suffix')($filter('WNOrDec')(input, 2), suffix?suffix:'');
			}
			return $filter('WNOrDecPlace')(input, 2, '-');
		}

	}])
    .filter('setLabel', ['$filter',  function ($filter) {
		return function (input) {
			return 'lbl' + input.replaceAll(' ', '');
		}
	}])
    .filter('maxDateFtr', ['$filter',  function ($filter) {
		return function (input, field) {
			if (input === undefined) return;
			var maxDate = $.map(input, (elem) => { return parseInt(elem[field].slice(6, -2)); }).reduce(function (a, b) { return a > b ? a : b; });
			return $filter('gbdate')(maxDate);
		}
	}])
    .filter('authHtml', ['$filter',  function ($filter) {
		return function (typeId) {           
			var url = $filter('getURL')("authuser/" + typeId);
				return "<a href=" + url + " class=\"auth-notallowed\"><i class='fa fa-lock fa-2x'></i></a>";     
		}
	}])
    .filter('checkAuth', ['$http','$rootScope','$timeout',  function ($http,$rootScope,$timeout) {
		var cached = {},min=0,max=100000000, key= Math.floor(Math.random() * (max - min)) + min;
		function detailsFilter(typeId) {    
			if (key) {
				if (key in cached) {
					// avoid returning a promise!
					return typeof cached[key].then !== 'function' ?
						Number(cached[key])>= Number(typeId) : false;
				} else {
					cached[key] = $http({
						method: 'POST',
						url: '/common/checkAuth',
					}).success(function (info) {
						cached[key] = info;           
					});
				}
			}
		}
		detailsFilter.$stateful = true;
		return detailsFilter;
	}])
    .filter('authLink', ['$filter',  function ($filter) {
			return function (typeId) {
			var url = "authuser/" + (Number(typeId) > 0 ? typeId : "");     
				return $filter('getURL')(url);     
		}
	}])
    .filter('isLoggedIn', ['$http', '$rootScope', '$timeout',  function ($http, $rootScope, $timeout) {
		var cached = {}, min = 0, max = 100000000, key = Math.floor(Math.random() * (max - min)) + min;
		function detailsFilter() {
			if (key) {
				if (key in cached) {          
					return typeof cached[key].then !== 'function' ?
						Number(cached[key]) !==0 : false;
				} else {
					cached[key] = $http({
						method: 'POST',
						url: '/common/checkAuth',
					}).success(function (info) {
						cached[key] = info;
					});
				}
			}
		}
		detailsFilter.$stateful = true;
		return detailsFilter;
	}])
    .filter('filterCount', ['$filter',  function ($filter) {
		return function (collection, value) {
			var count = 0;
			for (var prop in collection) {
				if(Number(collection[prop])!==value)
					count++;
				
			}
			return count;
		}
    }])
    .filter('toThousand', ['$filter',  function ($filter) {
      return function (input) {
        return parseFloat(input) * 1000;
      }
    }])
    .filter('toMillion', ['$filter',  function ($filter) {
      return function (input) {
        return parseFloat(input) * 1000000;
      }
    }])
    .filter('toBillion', ['$filter',  function ($filter) {
      return function (input) {
        return parseFloat(input) * 1000000000;
      }
    }])
    .filter('startFrom', function () {
      return function (input, start) {
        start = +start; //parse to int
        return input.slice(start);
      }
    })
	;
		function cRound(input,factor) { 
				var dec = 0;
				if (factor == 1) {
						input = input / 1000;
						dec = 3;
				}
				else if (factor == -1)
				{ input = input * 1000; dec = 0; }
				else {
						input = input;
						dec = 0;
				}
				return parseFloat(input).toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		}
		function WNOrDec(input, places) {
				places = places == undefined ? 2 : places;
				if (isNaN(input) || Number(input == 0)) return 'N/A';
				if (Number(Math.abs(input)) > 100000)
						return input.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
				else
						return input.toFixed(places).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		}
		function cRoundAbs(input, factor) {
				if (input == 0 || isNaN(input)) return 'N/A';
				var dec = 0;
				if (factor == 1) {
						input = input / 1000;
						dec = 3;
				}
				else if (factor == -1)
				{ input = input * 1000; dec = 0; }
				else {
						input = input;
						dec = 0;
				}
				if (input < 0) {
						return '(' + parseFloat(Math.abs(input)).toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ')';
				} else

						return parseFloat(input).toFixed(dec).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		}
})();
