﻿//live 
var IMIwapModule = angular.module("myApp", ['ui.router', 'oc.lazyLoad', 'utf8-base64', 'ngSanitize']);
function getQuerystringValueByName(name) {

    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");

    results = regex.exec(location.search);

    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

}

IMIwapModule.config(['$ocLazyLoadProvider', function ($ocLazyLoadProvider) {

    $ocLazyLoadProvider.config({



    });

}]);

angular.module('IMIwapModule', [

  'angularLazyImg'

]).config(['lazyImgConfigProvider', function (lazyImgConfigProvider) {

    var scrollable = document.querySelector('#scrollable');

    lazyImgConfigProvider.setOptions({

        offset: 100, // how early you want to load image (default = 100)

        errorClass: 'error', // in case of loading image failure what class should be added (default = null)

        successClass: 'success', // in case of loading image success what class should be added (default = null)

        onError: function (image) { }, // function fired on loading error

        onSuccess: function (image) { }, // function fired on loading success

        container: angular.element(scrollable) // if scrollable container is not $window then provide it here. This can also be an array of elements.

    });

}])
angular.module('IMIwapModule', [

    'angularLazyImg'

]);

var _windowUrl = window.location.href;

var _windowlanguage = "";

if (_windowUrl.indexOf("/ar/") > -1) {

    _windowlanguage = "ar";

}

else {

    _windowlanguage = "en";

}

function GetErrorMessage(_code) {

    var _erMessage = "";
    var _messages = sessionStorage.getItem("errormessages");
    if (_messages != "" && _messages != null && _messages != undefined) {
        var _errorObject = JSON.parse(_messages);

        var returnedData = $.grep(_errorObject, function (element, index) {
            return element.code == _code;
        });
        if (_windowlanguage == "ar")
            _erMessage = returnedData[0]["message_ar"];
        else
            _erMessage = returnedData[0]["message_en"];
        return _erMessage;
    }
};


//15-07-2021
IMIwapModule.directive('disallowSpaces', function () {
    return {
        restrict: 'A',

        link: function ($scope, $element) {
            $element.bind('input', function () {
                $(this).val($(this).val().replace(/ /g, ''));
            });
        }
    };
});



IMIwapModule.directive('safeChars', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            function fromUser(text) {
                if (text) {
                    var transformedInput = text.replace(/[><]/g, '');
                    if (transformedInput !== text) {
                        ngModelCtrl.$setViewValue(transformedInput);
                        ngModelCtrl.$render();
                    }
                    return transformedInput;
                }
                return undefined;
            }
            ngModelCtrl.$parsers.push(fromUser);
        }
    };
});

//20-dec-2023 sponsorship changes
IMIwapModule.directive('formChars', function () {
    function link(scope, elem, attrs, ngModel) {
        ngModel.$parsers.push(function (viewValue) {
            var reg = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
            // if view values matches regexp, update model value
            if (viewValue.match(reg)) {
                return viewValue;
            }
            // keep the model value as it is
            var transformedValue = ngModel.$modelValue;
            ngModel.$setViewValue(transformedValue);
            ngModel.$render();
            return transformedValue;
        });
    }

    return {
        restrict: 'A',
        require: 'ngModel',
        link: link
    };
});

function InvalidMsg(textbox) {
    try {
        if (_windowlanguage == 'en') {

            if (textbox.value === '') {
                textbox.setCustomValidity
                      ('Please fill out this field');
            } else if (textbox.validity.typeMismatch) {
                textbox.setCustomValidity
                      ('Please enter a valid email');
            } else {
                textbox.setCustomValidity('');
            }
        }
        else {
            if (textbox.value === '') {
                textbox.setCustomValidity
                      ('الرجاء ملء هذه الخانة');
            } else if (textbox.validity.typeMismatch) {
                textbox.setCustomValidity
                      ('يرجى إدخال بريد إلكتروني صالح');
            } else {
                textbox.setCustomValidity('');
            }
        }
        return true;
    } catch (e) { }
}

//20-dec-2023 sponsorship changes


IMIwapModule.directive('onfinishrender', function ($timeout) {

    return {

        restrict: 'A',



        link: function (scope, elm, attrs) {

            if (scope.$last === true) {

                $timeout(function () {



                    scope.$emit(attrs.onfinishrender);

                });

            }



        }

    };

});



IMIwapModule.directive('bootstrapSwitch', [

           function () {

               return {

                   restrict: 'A',

                   require: '?ngModel',

                   link: function (scope, element, attrs, ngModel) {

                       element.bootstrapSwitch();



                       element.on('switchChange.bootstrapSwitch', function (event, state) {

                           if (ngModel) {

                               scope.$apply(function () {

                                   ngModel.$setViewValue(state);

                               });

                           }

                       });



                       scope.$watch(attrs.ngModel, function (newValue, oldValue) {

                           if (newValue == true || newValue == 1) {

                               element.bootstrapSwitch('state', true, true);

                           } else {

                               element.bootstrapSwitch('state', false, true);

                           }

                       });

                   }

               };

           }

]);



IMIwapModule.directive('amountOnly', function () {

    return {

        require: 'ngModel',

        link: function (scope, element, attr, ngModelCtrl) {

            function fromUser(text) {

                if (text) {

                    var transformedInput = text.replace(/[^0-9.]/g, '');



                    if (transformedInput !== text) {

                        ngModelCtrl.$setViewValue(transformedInput);

                        ngModelCtrl.$render();

                    }

                    return transformedInput;

                }

                return undefined;

            }

            ngModelCtrl.$parsers.push(fromUser);

        }

    };

});

IMIwapModule.directive('numbersOnly', function () {

    return {

        require: 'ngModel',

        link: function (scope, element, attr, ngModelCtrl) {

            function fromUser(text) {

                if (text) {

                    var transformedInput = text.replace(/[^0-9]/g, '');



                    if (transformedInput !== text) {

                        ngModelCtrl.$setViewValue(transformedInput);

                        ngModelCtrl.$render();

                    }

                    return transformedInput;

                }

                return undefined;

            }

            ngModelCtrl.$parsers.push(fromUser);

        }

    };

});

IMIwapModule.directive('dateOnly', function () {

    return {

        require: 'ngModel',

        link: function (scope, element, attr, ngModelCtrl) {

            function fromUser(text) {

                if (text) {

                    var transformedInput = text.replace(/[^0-9/]/g, '');


                    if (transformedInput !== text) {

                        ngModelCtrl.$setViewValue(transformedInput);

                        ngModelCtrl.$render();

                    }

                    return transformedInput;

                }

                return undefined;

            }

            ngModelCtrl.$parsers.push(fromUser);

        }

    };

});

IMIwapModule.directive('validateAlphanumeric', function () {

    return {

        require: 'ngModel',

        link: function (scope, element, attr, ngModelCtrl) {

            function fromUser(text) {

                if (text) {

                    var transformedInput = text.replace(/[^0-9a-zA-Z]/g, '');



                    if (transformedInput !== text) {

                        ngModelCtrl.$setViewValue(transformedInput);

                        ngModelCtrl.$render();

                    }

                    return transformedInput;

                }

                return undefined;

            }

            ngModelCtrl.$parsers.push(fromUser);

        }

    };

});



IMIwapModule.directive('alphabetsOnly', function () {

    return {

        require: 'ngModel',

        link: function (scope, element, attr, ngModelCtrl) {

            function fromUser(text) {

                if (text) {

                    var transformedInput = text.replace(/[^a-zA-Z ]/g, '');



                    if (transformedInput !== text) {

                        ngModelCtrl.$setViewValue(transformedInput);

                        ngModelCtrl.$render();

                    }

                    return transformedInput;

                }

                return undefined;

            }

            ngModelCtrl.$parsers.push(fromUser);

        }

    };

});

IMIwapModule.directive('allowPattern', [allowPatternDirective]);



function allowPatternDirective() {

    return {

        restrict: "A",

        compile: function (tElement, tAttrs) {

            return function (scope, element, attrs) {



                element.bind("keypress", function (event) {

                    var keyCode = event.which || event.keyCode;

                    var keyCodeChar = String.fromCharCode(keyCode);




                    if (!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))) {

                        event.preventDefault();

                        return false;

                    }



                });

            };

        }

    };

}





IMIwapModule.service('civilidflagcheck', ['myAPI', function (myAPI) {





    this.getcivilid = function () {

        var civilid = "";

        if (sessionStorage.getItem("civilid") != undefined && sessionStorage.getItem("civilid") != "")

            civilid = sessionStorage.getItem("civilid");



        return civilid;

    }



    this.RatePlanType = function () {

        var RatePlanType = "";

        if (sessionStorage.getItem("RatePlanType") != undefined && sessionStorage.getItem("RatePlanType") != "")

            RatePlanType = sessionStorage.getItem("RatePlanType");



        return RatePlanType;

    }



    this.validatecivilid = function (input) {

        var civilid = "";

        var numbers = /^[0-9a-zA-Z]+$/;

        if (input == undefined || input == "" || !input.match(numbers) || input.length > 12) {

            return "false";

        }

        else

            return "true";



    }





}]);





IMIwapModule.service('labelfocus', ['myAPI', function (myAPI) {



    this.labelfocus = function (input) {



        try {

            setTimeout(function () {

                $(".mat-input").focus(function () {

                    $(this).parent().addClass("is-active is-completed");

                });

                $(".mat-input").focusout(function () {

                    if ($(this).val() === "")

                        $(this).parent().removeClass("is-completed");

                    $(this).parent().removeClass("is-active");

                });

            }, 1000);

        } catch (e) { }



    };



}]);





IMIwapModule.service('validateservice', ['myAPI', function (myAPI) {

    this.isnumber = function (input) {

        try {

            var numbers = /^[0-9]+$/;

            if (input.match(numbers)) {

                return "true";

            }

            else {

                return "false";

            }



        }

        catch (e) { }



    };





}]);





IMIwapModule.service('commonservice', ['myAPI', function (myAPI) {

    this.settokeniddetails = function () {

        try {



            var csinfo = document.getElementById("cinfo").value;





            if (csinfo != undefined && csinfo != '') {

                var updtokenid = '';

                var headermsisdn = '';

                var RatePlanType = '';

                var IDDFlag = '';



                if (csinfo != undefined && csinfo != '') {

                    var obj = csinfo.split('|');

                    updtokenid = obj[0];

                    headermsisdn = obj[1];

                    RatePlanType = obj[2];

                    IDDFlag = obj[3];



                }



                if (updtokenid != undefined && updtokenid != '') {



                    //var name = 'x-tokenid'

                    //document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';


                    sessionStorage.setItem("updtokenid", updtokenid);

                    sessionStorage.setItem("tokenid", updtokenid);



                    sessionStorage.setItem("RatePlanType", RatePlanType);

                    sessionStorage.setItem("IDDFlag", IDDFlag);

                    sessionStorage.setItem("msisdn", headermsisdn);



                    sessionStorage.setItem("paycivilidcheck", "done");



                }

            }

            else {





                var name = 'x-tokenid';

                $scope.readCookie = function (name) {



                }





                this.readCookie = function (name) {



                    var nameEQ = name + "=";

                    var ca = document.cookie.split(';');

                    for (var i = 0; i < ca.length; i++) {

                        var c = ca[i];

                        while (c.charAt(0) == ' ') {

                            c = c.substring(1, c.length);

                        }

                        if (c.indexOf(nameEQ) == 0) {

                            return c.substring(nameEQ.length, c.length);

                        }

                    }

                    return null;

                }

                var token = readCookie(name);

                if (token != undefined && token != '' && token != null) {

                    sessionStorage.setItem("tokenid", token);

                }



            }



        }

        catch (e) { }



    };



}]);


IMIwapModule.controller('changelangcontroller', function ($scope, myAPI, $http, $compile, $state) {




    $scope.readCookie = function (name) {

        var nameEQ = name + "=";

        var ca = document.cookie.split(';');

        for (var i = 0; i < ca.length; i++) {

            var c = ca[i];

            while (c.charAt(0) == ' ') {

                c = c.substring(1, c.length);

            }

            if (c.indexOf(nameEQ) == 0) {

                return c.substring(nameEQ.length, c.length);

            }

        }

        return null;

    }



    $scope.changlangurl = function (lang) {





        var name = 'langcookie';


        var lang = $scope.readCookie(name);


        if (lang == null || lang == undefined || lang == "") {

            lang = 'en';

        }





        var url = window.location.href;

        var nurl = '';

        var n = url.indexOf("/en/");

        if (n != -1) {

            nurl = url.replace('/en/', '/ar/');

        }

        else if (url.indexOf("/ar/") != -1) {

            nurl = url.replace('/ar/', '/en/');

        }

        else if (url.indexOf("/EN/") != -1) {

            nurl = url.replace('/EN/', '/ar/');

        }

        else if (url.indexOf("/AR/") != -1) {

            nurl = url.replace('/AR/', '/en/');

        }

        else if (url.indexOf("/En/") != -1) {

            nurl = url.replace('/En/', '/ar/');

        }

        else if (url.indexOf("/Ar/") != -1) {

            nurl = url.replace('/Ar/', '/en/');

        }

        window.location.href = nurl;


        return;


    }







    $scope.searchclick = function () {





        var key = document.getElementById('searchkey').value;

        $scope.searchtext = key;

        if (key == undefined || key == '') {

            return false;

        }

        document.getElementById("searchsec").style.height = "0%";



        try {




            var _windowUrl = window.location.href;

            if (_windowUrl.indexOf("/ar/") > -1) {

                var elem = "<div ng-init=\"tempid ='!TEMPID!' ;elementid='!ELEMENTID!' ;init();\" ng-controller=\"searchcontroller\"><div class=\"searchpage\"><div class=\"container\"><div class=\"col-lg-12 text-center min-heading wow fadeInRight animated\"><h1 class=\"content-title white c-font-bold\">Here's what we found</h1><h4>البحث عن \"" + key + "\" جلب النتائج التالية:</h4></div><div class=\"clearfix\"></div><div id=\"searchdatanotfound\" style=\"text-align:center\"></div><div class=\"search-sec1\" ng-repeat=\"data in searchdata\"><label>{{data.title}}</label><p>{{data.description}}Terms matched: 1-URL: <a href=\"{{data.name}}\">{{data.name}} </a></p></div></div></div><input type=\"hidden\" id=\"hdbskey\" value=\"!SKEY!\" /></div>";

            }

            else {

                var elem = "<div ng-init=\"tempid ='!TEMPID!' ;elementid='!ELEMENTID!' ;init();\" ng-controller=\"searchcontroller\"><div class=\"searchpage\"><div class=\"container\"><div class=\"col-lg-12 text-center min-heading wow fadeInRight animated\"><h1 class=\"content-title white c-font-bold\">Here's what we found</h1><h4>Your search for \"" + key + "\" fetched the following results:</h4></div><div class=\"clearfix\"></div><div id=\"searchdatanotfound\" style=\"text-align:center\"></div><div class=\"search-sec1\" ng-repeat=\"data in searchdata\"><label>{{data.title}}</label><p>{{data.description}}Terms matched: 1-URL: <a href=\"{{data.name}}\">{{data.name}} </a></p></div></div></div><input type=\"hidden\" id=\"hdbskey\" value=\"!SKEY!\" /></div>";

            }





            elem = elem.replace('!SKEY!', key);

            var temp = $compile(elem)($scope);

            document.getElementById('searchdiv').innerHTML = '';

            angular.element(document.getElementById('searchdiv')).append(temp);

        } catch (e) {



            sessionStorage.setItem("skey", key);

            location.href = 'search';

        }
    }
});

IMIwapModule.controller('quickpaycontroller', function ($scope, myAPI, $http, $compile) {

    $scope.redirectoquickpay = function () {

        location.href = 'quickpay';

    }



});
IMIwapModule.controller('myaccredirectcontroller', function ($scope, myAPI, $http, $compile) {

    $scope.redirectomyacc = function () {
        location.href = 'myaccount';
    }



});


IMIwapModule.controller('nojoomredirectcontroller', function ($scope, myAPI, $http, $compile) {

    $scope.redirectonojoom = function () {
        location.href = 'nojoomrewards';
    }



});

IMIwapModule.controller('logoutcontroller', function ($scope, myAPI, $http,
$compile) {
    $scope.logout = function () {
        var name = 'x-tokenid'
        var token = sessionStorage.getItem("tokenid");
        document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        sessionStorage.clear();
        var dataPost = { mode: "LOGOUT", "tokenid": token };
        myAPI.post("/portal/auth/logout", dataPost).then(function (resp) {
            if (resp.status == "200" && resp.data.status == "0") {
                location.href = 'login';
            }
        });
    }
});



IMIwapModule.controller('updatetokenid', function ($scope, myAPI, $http, $compile, commonservice) {



    try {



        var updtokenid = '';

        var headermsisdn = '';

        var RatePlanType = '';

        var IDDFlag = '';



        var csinfo = document.getElementById("cinfo").value;



        var pviews = document.getElementById("pviews").value;



        if (pviews != undefined && pviews != '') {

            try {



                var pairs = pviews.split('&');



                var result = {};

                pairs.forEach(function (pair) {

                    pair = pair.split('=');

                    result[pair[0]] = decodeURIComponent(pair[1] || '');

                });



                var dataPost = JSON.parse(JSON.stringify(result));





                myAPI.post("/portal/pageviews/post", dataPost).then(function (resp) {







                });





            }

            catch (e) { }

        }



        if (csinfo != undefined && csinfo != '') {

            var obj = csinfo.split('|');

            updtokenid = obj[0];

            headermsisdn = obj[1];

            RatePlanType = obj[2];

            IDDFlag = obj[3];

            try {
                commonservice.settokeniddetails();
            }
            catch (e) { }

        }





        var sesupdtokenid = updtokenid;


    } catch (e) { }





});
IMIwapModule.controller('ofootercontroller', function ($scope, myAPI, $http) {

    try {
        var dataPost = "";
        var lang = "";
        var url = window.location.href.toLowerCase();
        var n = url.indexOf("/en/");
        var n1 = url.indexOf("/ar/");
        if (n != -1) {
            lang = "en";
        }
        if (n1 != -1) {
            lang = "ar";
        }
        if (lang == null || lang == undefined || lang == "") {
            lang = 'en';
        }
        dataPost = { "actiontype": "getmenuhirerachy", "params": { "reqfrom": "portal", "menuid": "1", "lang": lang } }
        myAPI.post("/portalapis/api/collections/getmenu", dataPost).then(function (resp) {
            if (resp.status == "200") {
                $scope.menulist = resp.data.response;
            }
        });

        $scope.footerpayment = function (_type) {

            try {

                sessionStorage.setItem("footerpay", _type);

            } catch (e) { }

            location.href = 'quickpay';

        };





        $scope.qualitypolicyclick = function () {

            //alert("query");

        };







    } catch (e) { }



});

IMIwapModule.controller('ft_footercontroller', function ($scope, myAPI, $http) {

    try {
        var dataPost = "";
        var lang = "";
        var url = window.location.href.toLowerCase();
        var n = url.indexOf("/en/");
        var n1 = url.indexOf("/ar/");
        if (n != -1) {
            lang = "en";
        }
        if (n1 != -1) {
            lang = "ar";
        }
        if (lang == null || lang == undefined || lang == "") {
            lang = 'en';
        }
        dataPost = { "actiontype": "getmenuhirerachy", "params": { "reqfrom": "portal", "menuid": "52", "lang": lang } }
        myAPI.post("/portalapis/api/collections/getmenu", dataPost).then(function (resp) {
            if (resp.status == "200") {
                $scope.menulist = resp.data.response;
            }
        });

        $scope.footerpayment = function (_type) {
            try {
                sessionStorage.setItem("footerpay", _type);
            } catch (e) { }
            location.href = 'quickpay';
        };
        $scope.qualitypolicyclick = function () {

        };

    } catch (e) { }

});


IMIwapModule.controller('datalayercontroller', function ($scope, myAPI, $http, $compile, $window, $rootScope) {
    $scope.init = function () {
        try {

            var _windowUrl = window.location.href;
            var _l = "";
            var _loginornot = "";
            var _page = (_windowUrl.substring(_windowUrl.lastIndexOf('/') + 1));
            if (_windowUrl.indexOf("/ar/") > -1)
                _l = "ar";
            else
                _l = "en";

            var tokenid = sessionStorage.getItem("tokenid");
            if (tokenid != null && tokenid != "" && tokenid != undefined)
                _loginornot = "loggedIn";
            else
                _loginornot = "guest";


            try {
                var _segment = "personal";
                if ($("#h_personal").hasClass("active"))
                    _segment = "personal";
                else
                    _segment = "business";

            } catch (e) { }



            $rootScope.$on("CallActivateDataLayer", function (event, _hash, _category, _subcategory,
             _bundlename, _bundleprice) {
                $window.dataLayer.push({
                    'event': 'activate',
                    'language': _l,
                    'loginStatus': _loginornot,
                    'customerID': "" + _hash + "",
                    'segment': _segment,
                    'category': _category,
                    'subCategory': _subcategory,
                    'bundleName': _bundlename,
                    'bundleRate': _bundleprice
                });


            });



            $rootScope.$on("CallSubmitTicketDataLayer", function (event, _hash, _category, _subcategory) {
                $window.dataLayer.push({
                    'event': 'ticketSubmitted',
                    'language': _l,
                    'troubleCategory': _category,
                    'troubleSubCategory': _subcategory,
                    'loginStatus': _loginornot,
                    'customerID': "" + _hash + ""
                });
            });



            $rootScope.$on("CallBackDataLayer", function (event, _hash, _organizationsize, _industry, _solutionintrested) {
                $window.dataLayer.push({
                    'event': 'callback',
                    'language': _l,
                    'loginStatus': _loginornot,
                    'customerID': "" + _hash + "",
                    'organizationSize': _organizationsize,
                    'industrySector': _industry,
                    'solutionsInterestedIn': _solutionintrested
                });

            });


        } catch (e) { }

    };


});



IMIwapModule.controller('commoncontroller', function ($scope, myAPI, $http, $window, $compile, $location) {

    $scope.MenuRedirect = function ($event, category, page) {
        try {
            $window.gtag('event', 'Menu', {
                'event_category': category,
                'event_action': 'Click',
                'event_label': $event.currentTarget.innerHTML
            });
        } catch (e) { }
        location.href = page;
    }

    $scope.RedirectEO = function (uri) {
        try {
            var d = new Date();
            //d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000));
            d.setTime(d.getTime() + (30 * 60 * 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = "eo=1; " + expires;
        }
        catch (x) { }
        location.href = uri;

    }
    $scope.CloseEO = function () {
        sessionStorage.setItem("sesseo", "1");
        $("#eo_popup").modal('hide');
    }
    $scope.GetCookie = function (name) {

        try {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) == 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
        }
        catch (c) { }
        return null;

    }
    $scope.scrolltosection = function (id, scrollid) {

        try {

            $(window).scrollTop($('#' + scrollid).offset().top);

            var parentid = document.getElementById(id).parentElement.parentElement.id;

            $('#' + parentid + " >li").removeClass('active');

            $('#' + id).parent('li').addClass('active');



        } catch (e) { }

    };

    $scope.gotopage = function (page) {
        location.href = page;
    }

    $scope.helppopup = function (_id) {



        if (_id != undefined && _id != null && _id != '') {


            try {
                try {
                    var _helpquestion = "";
                    try {
                        _helpquestion = $("#" + _id + "_id").text().trim();
                    } catch (e) { }

                    var _windowUrl = window.location.href;
                    if (_windowUrl.indexOf("/ar/") > -1) {
                        _helpquestion = _helpquestion + '-ar';
                    }
                    else {
                        _helpquestion = _helpquestion + '-en';
                    }
                    $window.gtag('event', 'FAQ - Questions', {
                        'event_category': 'FAQ - Questions',
                        'event_action': 'click',
                        'event_label': _helpquestion
                    });
                } catch (e) { }
            }
            catch (e) {

            }



            try {

                $("#" + _id).modal("show");

            }

            catch (e) { }

        }

    }

    $scope.init = function () {

        setTimeout(function () {
            try {

                $('#demo').jplist({
                    itemsBox: '.list'
                , itemPath: 'section'
                , panelPath: '.jplist-panel'
                });

            } catch (e) { }
        }, 1000);


        $("ul.simbundlesfilterul").on("click", "li", function () {

            var _data = this.id;
            $(".jpl").css("display", "none");
            $("." + _data).css("display", "block");
        });



        //23-08-2020
        //koopid params get
        try {


            try {
                function uuidv4() {
                    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                        return v.toString(16);
                    });
                }
            } catch (e) { }

            var kuid = "";
            try {
                kuid = sessionStorage.getItem("kuid");
                if (kuid != null && kuid != undefined && kuid != "") {
                    kuid = kuid;
                } else {
                    kuid = uuidv4();
                    sessionStorage.setItem("kuid", kuid);
                }
            } catch (e) { }


            var data = {
                templateid: "99", elementid: "51", channel: "WEBPORTAL",
                deviceid: kuid
            };
            myAPI.post("/portalapis/api/koopid/get", data).then(function (resp) {
                if (resp.status == "200" && resp.data.status == "0" && resp.data.data != null) {
                    $scope.koopidparams = resp.data.data;
                    try {
                        $("#kpd_koopidtag").removeAttr("data-kpdparams");
                        var _kpdparams = "?retainsession=true&autoconfig=true&login-providerId=50000017&resize=scale&splashscreen=true&localstore=customer&trackhistory=true&uselocation=false&eparam=" + $scope.koopidparams;
                        $("#kpd_koopidtag").attr("data-kpdparams", _kpdparams);
                    } catch (e) { }



                    //20-08-2020 to open chat direct
                    try {
                        var url = location.href;
                        var pg = url.substr(url.lastIndexOf('#') + 1);
                        if (pg.indexOf("chat") > 0) {
                            $("#kpd_koopidtag").attr("data-kpdproactive", "true");
                            $("#kpd_koopidtag").attr("data-kpdproactivetimer", "5");
                        }
                    } catch (e) { }


                }
                else {

                }
            });
        } catch (e) { }


        setTimeout(function () {

            try {

                try {

                    //var _errMessages = sessionStorage.getItem("errormessages");
                    //if (_errMessages == null || _errMessages == "" || _errMessages == undefined) {

                    var _dataPost = {};

                    myAPI.post("/portalapis/api/ApiFeatures/GetErrorMessages", _dataPost).then(function (resp) {

                        if (resp.status == "200" && resp.data.data != null && resp.data.data.length > 0) {

                            $scope.errormessages = resp.data.data;
                            var _em = JSON.stringify($scope.errormessages);
                            sessionStorage.setItem("errormessages", _em);
                        }
                    });
                    //}
                    //else {
                    //    $scope.errormessages = sessionStorage.getItem("errormessages");
                    //}

                } catch (e) { }

                var url = location.href;

                var pg = url.substr(url.lastIndexOf('#') + 1);

                if (pg != undefined && pg != null) {

                    //$(window).scrollTop($('#' + pg.replace('/','')).offset().top);    

                    if (pg == "/chat") {

                        $(".left-first-section").click();

                    }

                    else {


                        try {
                            if ($("#availablepacks").length > 0) {
                                $(".panel-collapse").removeClass("in");
                                $("#bundlespacks").addClass("in");

                                if (pg.toLowerCase() == "/currentpacks") {
                                    $("#anchormycurrentpacks").removeClass("collapsed");
                                    $("#anchoravailablepacks").addClass("collapsed");
                                    $("#anchorpassportpacks").addClass("collapsed");
                                    $("#anchormycountrypacks").addClass("collapsed");
                                    $("#anchorbundlepacks").addClass("collapsed");


                                    $("#currentpacks").addClass("in");
                                    $("#availablepacks").removeClass("in");
                                    $("#roamingpacks").removeClass("in");
                                    $("#mycountrypacks").removeClass("in");
                                    $("#bundlespacks").removeClass("in");
                                }


                                if (pg.toLowerCase() == "/bundlespacks") {
                                    $("#anchormycurrentpacks").addClass("collapsed");
                                    $("#anchoravailablepacks").addClass("collapsed");
                                    $("#anchorpassportpacks").addClass("collapsed");
                                    $("#anchormycountrypacks").addClass("collapsed");
                                    $("#anchorbundlepacks").removeClass("collapsed");


                                    $("#currentpacks").removeClass("in");
                                    $("#availablepacks").removeClass("in");
                                    $("#roamingpacks").removeClass("in");
                                    $("#mycountrypacks").removeClass("in");
                                    $("#bundlespacks").addClass("in");
                                }


                                if (pg.toLowerCase() == "/availablepacks") {
                                    $("#anchormycurrentpacks").addClass("collapsed");
                                    $("#anchoravailablepacks").removeClass("collapsed");
                                    $("#anchorpassportpacks").addClass("collapsed");
                                    $("#anchormycountrypacks").addClass("collapsed");
                                    $("#anchorbundlepacks").addClass("collapsed");

                                    $("#currentpacks").removeClass("in");
                                    $("#availablepacks").addClass("in");
                                    $("#roamingpacks").removeClass("in");
                                    $("#mycountrypacks").removeClass("in");
                                    $("#bundlespacks").removeClass("in");
                                }
                                if (pg.toLowerCase() == "/roamingpacks") {
                                    $("#anchormycurrentpacks").addClass("collapsed");
                                    $("#anchoravailablepacks").addClass("collapsed");
                                    $("#anchorpassportpacks").removeClass("collapsed");
                                    $("#anchormycountrypacks").addClass("collapsed");
                                    $("#anchorbundlepacks").addClass("collapsed");

                                    $("#currentpacks").removeClass("in");
                                    $("#availablepacks").removeClass("in");
                                    $("#roamingpacks").addClass("in");
                                    $("#mycountrypacks").removeClass("in");
                                    $("#bundlespacks").removeClass("in");
                                }
                                if (pg.toLowerCase() == "/mycountrypacks") {
                                    $("#anchormycurrentpacks").addClass("collapsed");
                                    $("#anchoravailablepacks").addClass("collapsed");
                                    $("#anchorpassportpacks").addClass("collapsed");
                                    $("#anchormycountrypacks").removeClass("collapsed");
                                    $("#anchorbundlepacks").addClass("collapsed");

                                    $("#currentpacks").removeClass("in");
                                    $("#availablepacks").removeClass("in");
                                    $("#roamingpacks").removeClass("in");
                                    $("#mycountrypacks").addClass("in");
                                    $("#bundlespacks").removeClass("in");
                                }
                            }
                        } catch (e) { }


                        $(window).scrollTop($('#' + pg.replace('/', '')).offset().top);

                    }

                }

            } catch (e) { }

            try {
                var eo_click = $scope.GetCookie('eo');
                if (eo_click != null && eo_click == 1)
                { }
                else
                {
                    var sess_eo = sessionStorage.getItem('sesseo');
                    if (sess_eo != null && sess_eo == 1)
                    { }
                    else
                    {
                        $("#eo_popup").modal('show');
                    }
                }

            } catch (a) {

            }

        }, 500);

        try {

            var _windowUrl = window.location.href;
            var _l = "";
            $scope._hash = "";
            var _page = (_windowUrl.substring(_windowUrl.lastIndexOf('/') + 1));
            if (_windowUrl.indexOf("/ar/") > -1)
                _l = "ar";
            else
                _l = "en";


            try {
                var _segment = "personal";
                if ($("#h_personal").hasClass("active"))
                    _segment = "personal";
                else
                    _segment = "business";

            } catch (e) { }


            var tokenid = sessionStorage.getItem("tokenid");
            if (tokenid != null && tokenid != "" && tokenid != undefined) {
                var data = {
                    templateid: "99", elementid: "51", code: "gethash"
                };
                myAPI.post("/portalapis/api/ApiFeatures/GetFeatureData", data).then(function (resp) {
                    if (resp.status == "200" && resp.data.status == "0" && resp.data.data != null) {
                        $scope._hash = resp.data.data;
                        $window.dataLayer.push({
                            'language': _l,
                            'segment': _segment,
                            'category': _page,
                            'subCategory': '',
                            'loginStatus': 'loggedIn',
                            'customerID': "" + $scope._hash + ""
                        });
                    }
                    else {
                        $window.dataLayer.push({
                            'language': _l,
                            'segment': _segment,
                            'category': _page,
                            'subCategory': '',
                            'loginStatus': 'loggedIn',
                            'customerID': "" + $scope._hash + ""
                        });
                    }
                });
            }
            else {
                $window.dataLayer.push({
                    'language': _l,
                    'segment': _segment,
                    'category': _page,
                    'subCategory': '',
                    'loginStatus': 'guest',
                    'customerID': ""
                });
            }


        } catch (e) { }

    }



    $scope.myaccountactivationredirection = function (_title) {
        try {
            var _windowUrl = window.location.href;
            if (_windowUrl.indexOf("/ar/") > -1) {
                _title = _title + '-ar-Activate (Redirection)';
            }
            else {
                _title = _title + '-en-Activate (Redirection)';
            }
            $window.gtag('event', 'Activation - Redirection', {
                'event_category': 'Activation - Redirection',
                'event_action': 'click',
                'event_label': _title
            });
        } catch (e) { }

        location.href = "myaccount";
    };

    $scope.eshopbuyredirection = function (_title, _buyurl) {
        try {
            var _windowUrl = window.location.href;
            var _page = "";

            try {

                if (_windowUrl.indexOf("#") != -1) {
                    var _pL = (_windowUrl.split("#"));
                    var _pname = _pL[0];
                    _page = (_pname.substring(_pname.lastIndexOf('/') + 1));
                }
                else {
                    _page = (_windowUrl.substring(_windowUrl.lastIndexOf('/') + 1));
                }



                if (_page == '' || _page == undefined || _page == null) {
                    _title = _title;
                }
                else {
                    _title = _page + '-' + _title;
                }

            } catch (e) { }


            if (_windowUrl.indexOf("/ar/") > -1) {
                _title = _title + '-ar-Buy Now';
            }
            else {
                _title = _title + '-en-Buy Now';
            }
            $window.gtag('event', 'eShop Redirections', {
                'event_category': 'eShop Redirections',
                'event_action': 'click',
                'event_label': _title
            });
        } catch (e) { }

        location.href = _buyurl;
    };


    $scope.eshopbuyredirectiondatalayer = function (_data, _list) {
        try {
            var _windowUrl = window.location.href;
            var _page = "";
            var _title = "";
            var _buyurl = "";
            $scope._hash = "";
            var _l = "";
            var _loginornot = "";


            if (_windowUrl.indexOf("#") != -1) {
                var _pL = (_windowUrl.split("#"));
                var _pname = _pL[0];
                var _page = (_pname.substring(_pname.lastIndexOf('/') + 1));
            }
            else {
                var _page = (_windowUrl.substring(_windowUrl.lastIndexOf('/') + 1));
            }


            if (_windowUrl.indexOf("/ar/") > -1)
                _l = "ar";
            else
                _l = "en";

            var tokenid = sessionStorage.getItem("tokenid");
            if (tokenid != null && tokenid != "" && tokenid != undefined)
                _loginornot = "loggedIn";
            else
                _loginornot = "guest";


            try {

                if (_data != null && _data != undefined) {
                    _title = _data.title;
                    _buyurl = _data.buyurl;
                }
                else {
                    return false;
                }

                if (_page == '' || _page == undefined || _page == null) {
                    _title = _title;
                }
                else {
                    _title = _page + '-' + _title;
                }

            } catch (e) { }


            if (_windowUrl.indexOf("/ar/") > -1) {
                _title = _title + '-ar-Buy Now';
            }
            else {
                _title = _title + '-en-Buy Now';
            }
            $window.gtag('event', 'eShop Redirections', {
                'event_category': 'eShop Redirections',
                'event_action': 'click',
                'event_label': _title
            });
            try {


                try {
                    var _segment = "personal";
                    if ($("#h_personal").hasClass("active"))
                        _segment = "personal";
                    else
                        _segment = "business";

                } catch (e) { }


                var data = {
                    templateid: "99", elementid: "51", code: "gethash"
                };
                myAPI.post("/portalapis/api/ApiFeatures/GetFeatureData", data).then(function (resp) {
                    if (resp.status == "200" && resp.data.status == "0" && resp.data.data != null) {
                        $scope._hash = resp.data.data;
                        $window.dataLayer.push({
                            event: 'eec.productClick',
                            language: _l,
                            segment: _segment,
                            category: _data.category,
                            subCategory: _data.subcategory,
                            loginStatus: _loginornot,
                            customerID: "" + $scope._hash + "",
                            ecommerce: {
                                currencyCode: 'USD',
                                click: {
                                    actionField: { list: _list },
                                    products: [
                                        {
                                            name: _data.title,
                                            id: "" + _data.id + "",
                                            price: _data.amount,
                                            brand: _data.brand,
                                            category: _data.category,
                                            variant: '',
                                            position: '1'
                                        }
                                    ]
                                }
                            }
                        });
                        location.href = _buyurl + '?pg=' + _page + '&lst=' + _list;
                    }
                    else {
                        $window.dataLayer.push({
                            event: 'eec.productClick',
                            language: _l,
                            segment: _segment,
                            category: _data.category,
                            subCategory: _data.subcategory,
                            loginStatus: _loginornot,
                            customerID: "" + $scope._hash + "",
                            ecommerce: {
                                currencyCode: 'USD',
                                click: {
                                    actionField: { list: _list },
                                    products: [
                                        {
                                            name: _data.title,
                                            id: "" + _data.id + "",
                                            price: _data.amount,
                                            brand: _data.brand,
                                            category: _data.category,
                                            variant: '',
                                            position: '1'
                                        }
                                    ]
                                }
                            }
                        });
                        location.href = _buyurl + '?pg=' + _page + '&lst=' + _list;
                    }
                });
            } catch (e) { }



        } catch (e) { }


    };
    $scope.myaccountactivationdatalayer = function (_data) {
        try {
            var _windowUrl = window.location.href;
            var _l = "";
            var _title = "";
            var _loginornot = "";
            $scope._hash = "";
            var _page = (_windowUrl.substring(_windowUrl.lastIndexOf('/') + 1));
            if (_windowUrl.indexOf("/ar/") > -1)
                _l = "ar";
            else
                _l = "en";

            var tokenid = sessionStorage.getItem("tokenid");
            if (tokenid != null && tokenid != "" && tokenid != undefined)
                _loginornot = "loggedIn";
            else
                _loginornot = "guest";


            try {
                var _segment = "personal";
                if ($("#h_personal").hasClass("active"))
                    _segment = "personal";
                else
                    _segment = "business";

            } catch (e) { }


            if (_data != null && _data != undefined) {
                _title = _data.title;
            }
            else {
                return false;
            }

            if (_windowUrl.indexOf("/ar/") > -1) {
                _title = _title + '-ar-Activate (Redirection)';
            }
            else {
                _title = _title + '-en-Activate (Redirection)';
            }



            $window.gtag('event', 'Activation - Redirection', {
                'event_category': 'Activation - Redirection',
                'event_action': 'click',
                'event_label': _title
            });


            try {
                var data = {
                    templateid: "99", elementid: "51", code: "gethash"
                };
                myAPI.post("/portalapis/api/ApiFeatures/GetFeatureData", data).then(function (resp) {
                    if (resp.status == "200" && resp.data.status == "0" && resp.data.data != null) {
                        $scope._hash = resp.data.data;
                        $window.dataLayer.push({
                            'event': 'activate',
                            'language': _l,
                            'loginStatus': _loginornot,
                            'customerID': "" + $scope._hash + "",
                            'segment': _segment,
                            'category': _data.category,
                            'subCategory': _data.subcategory,
                            'bundleName': _data.bundlename,
                            'bundleRate': _data.amount,
                        });
                        location.href = "myaccount";

                    }
                    else {
                        $window.dataLayer.push({
                            'event': 'activate',
                            'language': _l,
                            'loginStatus': _loginornot,
                            'customerID': "" + $scope._hash + "",
                            'segment': _segment,
                            'category': _data.category,
                            'subCategory': _data.subcategory,
                            'bundleName': _data.bundlename,
                            'bundleRate': _data.amount,
                        });

                        location.href = "myaccount";
                    }
                });
            } catch (e) { }

        } catch (e) { }


    };



});



IMIwapModule.factory("myAPI", ['$http', '$q', function ($http, $q) {

    var tokenid = sessionStorage.getItem("tokenid");

    var childlineno = sessionStorage.getItem("childlineno");

    var langcookie = "";











    //alert(tokenid);

    if (tokenid == null || tokenid == undefined || tokenid == '') {

        tokenid = '';

    }

    if (childlineno == null || childlineno == undefined || childlineno == '') {

        childlineno = '';

    }

    if (langcookie == null || langcookie == undefined || langcookie == '') {

        langcookie = '';

    }

    var data = {



        post: httpRequest,

        get: httpgetRequest,

        postp: httpPRequest

    };

    return data;

    function httpRequest(appUrl, postData) {



        var tokenid = sessionStorage.getItem("tokenid");

        var childlineno = sessionStorage.getItem("childlineno");

        var langcookie = '';


        var url = window.location.href.toLowerCase();

        var n = url.indexOf("/en/");

        var n1 = url.indexOf("/ar/");

        if (n != -1) {

            langcookie = "en";

        }

        if (n1 != -1) {

            langcookie = "ar";

        }



        //alert(tokenid);

        if (tokenid == null || tokenid == undefined || tokenid == '') {

            tokenid = '';

        }

        if (childlineno == null || childlineno == undefined || childlineno == '') {

            childlineno = '';

        }

        if (langcookie == null || langcookie == undefined || langcookie == '') {

            langcookie = 'en';

        }



        try {

            var _TempPost = postData;

            if (_TempPost != null && _TempPost.code == "contactsearch") {

                childlineno = _TempPost.msisdn;

            }

        } catch (e) { }



        var deferred = $q.defer();

        $http({

            method: "POST",

            url: (appUrl),

            data: JSON.stringify(postData),

            headers: { 'Content-Type': ' application/json; charset=utf-8', 'chanel': 'portal', 'tokenid': tokenid, 'childlineno': childlineno, 'langcookie': langcookie },

            time: 60000

        }).success(function (resp, respstatus) {

            var result = {

                data: resp || {},

                status: respstatus

            }

            deferred.resolve(result);

        }).error(function (error, respstatus) {


            var result = {

                data: error || {},

                status: respstatus

            }

            deferred.resolve(result);

        });

        return deferred.promise;

    }

    function httpPRequest(appUrl, postData, contentType) {



        var tokenid = sessionStorage.getItem("tokenid");

        var childlineno = sessionStorage.getItem("childlineno");

        var langcookie = '';




        var url = window.location.href.toLowerCase();

        var n = url.indexOf("/en/");

        var n1 = url.indexOf("/ar/");

        if (n != -1) {

            langcookie = "en";

        }

        if (n1 != -1) {

            langcookie = "ar";

        }



        //alert(tokenid);

        if (tokenid == null || tokenid == undefined || tokenid == '') {

            tokenid = '';

        }

        if (childlineno == null || childlineno == undefined || childlineno == '') {

            childlineno = '';

        }



        if (langcookie == null || langcookie == undefined || langcookie == '') {

            langcookie = '';

        }





        var deferred = $q.defer();

        $http({

            method: "POST",

            url: (appUrl),

            data: JSON.stringify(postData),

            headers: { 'Content-Type': 'application/json; charset=utf-8', 'chanel': 'portal', 'tokenid': tokenid, 'childlineno': childlineno, 'langcookie': langcookie },

            time: 60000,

            responseType: 'arraybuffer'

        }).success(function (resp, respstatus) {

            var result = {

                data: resp || {},

                status: respstatus

            }

            deferred.resolve(result);

        }).error(function (error, respstatus) {



            var result = {

                data: error || {},

                status: respstatus

            }

            deferred.resolve(result);

        });

        return deferred.promise;

    }

    function httpgetRequest(appUrl, postData) {

        var tokenid = sessionStorage.getItem("tokenid");

        var childlineno = sessionStorage.getItem("childlineno");

        var langcookie = '';

        var name = "langcookie";

        var nameEQ = name + "=";


        var url = window.location.href.toLowerCase();

        var n = url.indexOf("/en/");

        var n1 = url.indexOf("/ar/");

        if (n != -1) {

            langcookie = "en";

        }

        if (n1 != -1) {

            langcookie = "ar";

        }



        if (tokenid == null || tokenid == undefined || tokenid == '') {

            tokenid = '';

        }

        if (childlineno == null || childlineno == undefined || childlineno == '') {

            childlineno = '';

        }

        if (langcookie == null || langcookie == undefined || langcookie == '') {

            langcookie = '';

        }

        var deferred = $q.defer();



        $http.headers.post['Content-Type'] = 'application/json; charset=utf-8';

        $http.headers.post['accesskey'] = IMIapp.getAccessKey();

        $http.headers.post['csrftoken'] = IMIapp.getCsrfKey();



        $http({

            method: "GET",

            url: IMIapp.apiUrl(appUrl),

            data: JSON.stringify(postData),

            headers: { 'Content-Type': ' application/json; charset=utf-8', 'chanel': 'portal', 'tokenid': tokenid, 'childlineno': childlineno, 'langcookie': langcookie }



        }).success(function (resp, respstatus) {

            var result = {

                data: resp || {},

                status: respstatus

            }

            deferred.resolve(result);

        }).error(function (error, respstatus) {

            if (respstatus == 401) {

                IMIapp.clearSession();

                window.location.href = IMIapp.webUrl() + "login.html";

            }

            var result = {

                data: error || {},

                status: respstatus

            }

            deferred.resolve(result);

        });

        return deferred.promise;

    }

}]);

function NotificationRegister(_notificationid) {

    var _msisdn = sessionStorage.getItem("msisdn");

    if (_msisdn != null && _msisdn != "" && _msisdn != undefined && _msisdn != "undefined") {

        _msisdn = _msisdn;

    }

    else {

        _msisdn = '';

    }

    var tokenid = sessionStorage.getItem("tokenid");

    var childlineno = sessionStorage.getItem("childlineno");

    var langcookie = '';

    var url = window.location.href.toLowerCase();

    var n = url.indexOf("/en/");

    var n1 = url.indexOf("/ar/");

    if (n != -1) {

        langcookie = "en";

    }

    if (n1 != -1) {

        langcookie = "ar";

    }


    if (tokenid == null || tokenid == undefined || tokenid == '') {

        tokenid = '';

    }

    if (childlineno == null || childlineno == undefined || childlineno == '') {

        childlineno = '';

    }

    if (langcookie == null || langcookie == undefined || langcookie == '') {

        langcookie = 'en';

    }



    console.log("msisdn->" + _msisdn);

    var dataPost = {

        templateid: "99",

        elementid: "51",

        code: "pushnotificationregister",

        msisdn: _msisdn,

        pushnotificationid: _notificationid

    };





    $.ajax({

        url: "/portalapis/api/ApiFeatures/GetFeatureData",

        type: "POST",

        data: JSON.stringify(dataPost),

        error: function () {

            //alert("Temporary error. Please try again...");

        },

        complete: function () { },

        beforeSend: function (xhr) {

            xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

            xhr.setRequestHeader('chanel', 'WEBAPP');

            xhr.setRequestHeader('tokenid', tokenid);

            xhr.setRequestHeader('langcookie', langcookie);

        },

        success: function (data) {

        }

    });

}

function scrolltosection(id, scrollid) {

    $(window).scrollTop($('#' + scrollid).offset().top);

    try {

        var parentid = document.getElementById(id).parentElement.parentElement.id;

        $('#' + parentid + " >li").removeClass('active');

        $('#' + id).parent('li').addClass('active');



    } catch (e) { }

}






IMIwapModule.run(
    function ($rootScope) {
        $rootScope.photos = new Array(100);
    }
);

IMIwapModule.service(
  'scrollAndResizeListener', function ($window, $document, $timeout) {
      var id = 0,
          listeners = {},
          scrollTimeoutId,
		  swipeTimeoutId,
		  touchstartTimeoutId,
		  touchmoveTimeoutId,
          resizeTimeoutId;

      function invokeListeners() {
          var clientHeight = $document[0].documentElement.clientHeight,
              clientWidth = $document[0].documentElement.clientWidth;

          for (var key in listeners) {
              if (listeners.hasOwnProperty(key)) {
                  listeners[key](clientHeight, clientWidth); // call listener with given arguments
              }
          }
      }


      $window.addEventListener('scroll', function () {
          // cancel previous timeout (simulates stop event)
          $timeout.cancel(scrollTimeoutId);

          // wait for 200ms and then invoke listeners (simulates stop event)
          scrollTimeoutId = $timeout(invokeListeners, 200);
      });


      $window.addEventListener('resize', function () {
          $timeout.cancel(resizeTimeoutId);
          resizeTimeoutId = $timeout(invokeListeners, 200);
      });


      $window.addEventListener('touchstart', function () {
          $timeout.cancel(touchstartTimeoutId);
          touchstartTimeoutId = $timeout(invokeListeners, 100);
      });
      $window.addEventListener('touchmove', function () {
          $timeout.cancel(touchmoveTimeoutId);
          touchmoveTimeoutId = $timeout(invokeListeners, 100);
      });
      $window.addEventListener('touchend', function () {
          $timeout.cancel(swipeTimeoutId);
          swipeTimeoutId = $timeout(invokeListeners, 100);
      });

      return {
          bindListener: function (listener) {
              var index = ++id;

              listeners[id] = listener;

              return function () {
                  delete listeners[index];
              }
          }
      };
  }
);

IMIwapModule.directive(
  'imageLazySrc', function ($document, scrollAndResizeListener) {
      return {
          restrict: 'A',
          link: function ($scope, $element, $attributes) {
              var listenerRemover;

              function isInView(clientHeight, clientWidth) {
                  // get element position
                  var imageRect = $element[0].getBoundingClientRect();

                  if (
                      (imageRect.top >= 0 && imageRect.bottom <= clientHeight)
                      &&
                      (imageRect.left >= 0 && imageRect.right <= clientWidth)
                  ) {
                      $element[0].src = $attributes.imageLazySrc; // set src attribute on element (it will load image)

                      // unbind event listeners when image src has been set
                      listenerRemover();
                  }
              }

              // bind listener
              listenerRemover = scrollAndResizeListener.bindListener(isInView);

              // unbind event listeners if element was destroyed
              // it happens when you change view, etc
              $element.on('$destroy', function () {
                  listenerRemover();
              });


              // explicitly call scroll listener (because, some images are in viewport already and we haven't scrolled yet)
              isInView(
                  $document[0].documentElement.clientHeight,
                  $document[0].documentElement.clientWidth
              );
          }
      };
  }
);

