var didScroll = false;
// window.onscroll = doThisStuffOnScroll;
window.addEventListener('scroll', doThisStuffOnScroll);

function doThisStuffOnScroll() {
    didScroll = true;
}

window.scrollTasks = [];
var scrollTicks = 0;
setInterval(function() {
    scrollTicks++;
    if(didScroll) {
        didScroll = false;
        var task, l = window.scrollTasks.length;
        while(l--){
            task = window.scrollTasks[l];
            if(task && task.task(scrollTicks) && task.once){
                window.scrollTasks[l] = false;
            }
        }
    }
}, 250);

window.scrollTasks.push({task: function(){
    window.lazyLoad(200);
}});

window.Util = {
    getOffsetTop:function(ele){
        var t = 0;
        while(typeof ele !== 'undefined' && ele !== null){
            if(ele.offsetTop){
                t = ele.offsetTop;
                break;
            } else {
                ele = ele.parentNode;
            }
        }
        return t;
    },
    addFBScripts: function(){
        window.fbAsyncInit = function() {
            FB.init({
                appId      : '254831554917492',
                xfbml      : true,
                version    : 'v2.7'
              });
          };

          (function(d, s, id){
              var js, fjs = d.getElementsByTagName(s)[0];
              if (d.getElementById(id)) {return;}
              js = d.createElement(s); js.id = id;
              js.src = "//connect.facebook.net/en_US/sdk.js";
              fjs.parentNode.insertBefore(js, fjs);
          }(document, 'script', 'facebook-jssdk'));
    },
    detectMobile: function () {
        return ( navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)
        )
    },
    fireEvent: function (el, etype){
        if (el.fireEvent) {
            el.fireEvent('on' + etype);
        } else {
            var evObj = document.createEvent('Events');
            evObj.initEvent(etype, true, false);
            el.dispatchEvent(evObj);
        }
    },
    loadScript: function(path, a, m){
        (function(d, o, p, a, m){
            a=d.createElement(o),
            m=d.getElementsByTagName(o)[0];
            a.async=1;a.src=p;
            m.parentNode.insertBefore(a,m)
        })(document, 'script', path);
    },
    loadCss: function(path){
        var l = document.createElement("link");
        l.setAttribute("rel", "stylesheet");
        l.setAttribute("type", "text/css");
        l.setAttribute("href", path);
        document.getElementsByTagName("head")[0].appendChild(l);
    },
    loadYoutubeJs: function(){
        if(typeof window.parseYoutube !== 'function'){
            Util.loadScript('/assets/js/youtube.js');
        }else{
            window.parseYoutube();
        }

    },
    isIn: function(ele,threshold){
        if(ele === null || ele === undefined){ return false;}
        threshold = threshold || 0;
        var _top = Util.getOffsetTop(ele), wh = window.innerHeight,
        element_height = ele.height || 0;
        return ((threshold + pageYOffset + wh) >= _top) && (pageYOffset <= (_top + element_height + threshold))
    }

}
window.lazyLoad = function(threshold) {

    var threshold = threshold || 0;
    var images = document.getElementsByClassName('lazyImg');
    if(images.length){

        for(var i = 0, len =images.length; i < len; i++ ){

            var img = images[i];

			if(typeof img === 'undefined'){
				continue;
			}

            if(Util.isIn(img, threshold)){
                var pw = img.clientWidth || img.parentNode.clientWidth || 0;
                var dpr = (window.devicePixelRatio || 1);
                pw = Math.ceil(pw*dpr);



                if(pw){
                    pw = pw - pw % 10 + 10;
    				var source = img.getAttribute("data-src");

    				if(source.indexOf('wbcdn.in/assets/img/uploads/') !== -1 && source.match(/\.jpg/)){
                        source = source.replace('assets/img/uploads/',  'assets/img/uploads/cache/').replace('.jpg', '_'+pw+'_.jpg').replace('http://','https://');
    				} else if(source.indexOf('mywb.in') !== -1){
                        source = source.replace('.jpg', '_'+pw+'_.jpg').replace('http://', 'https://');
                    }

    				img.src= source;

    				img.onload = function(){
                        this.className = this.className.replace('lazyImg', 'lazy-loaded');
    				}

    				img.onerror = function(){
                        this.src = 'https://wbcdn.in/assets/img/uploads/mywb/error-image-generic.png';
                        this.className = this.className.replace('lazyImg', 'lazy-loaded');
                        if(console){
                            console.log('image failed to load', source);
                        }
    				}
    			}
            }
		}
	}
}

window.trackEvent = function(c, a, l, v, i){

    if(typeof ga === 'function'){
        ga('send', 'event', c, a, l,{ nonInteraction: !i });
    }
}

var _addAdSense = function(){
    (function(i,s,o,g,a,m){
        a=s.createElement(o);
        m=s.getElementsByTagName(o)[0];
        a.async=1;
        a.src=g;m.parentNode.insertBefore(a,m);
        try {

            (adsbygoogle = window.adsbygoogle || []).push({
              google_ad_client: "ca-pub-2578812880681048",
              enable_page_level_ads: true
            });
        } catch (e) {
            //if(console) {console.log('Exception in _addAdSense function')}
        }

    })(window,document,'script','//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js');
}

var _addFBPixel = function(){
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
    n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
    document,'script','https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '1900645363533801'); // Insert your pixel ID here.
    fbq('track', 'PageView');
}

window.onload = function(){

    if('serviceWorker' in navigator){

        navigator.serviceWorker.getRegistrations().then(function(registrations) {
            
            for(let registration of registrations) {
                registration.unregister()
            } 

            // navigator.serviceWorker.register('/sw.js').then(function(reg){
            //     if(console){
            //         console.log('SW regsitered', reg);
            //     }
            // }, function(err){
            //     if(console){
            //         console.log('SW regsiter failed!!', err);
            //     }
            // })
        });

        
    }

    window.lazyLoad();
    setTimeout(function(){
        trackEvent('user', 'stay', document.title, 1, true);
    },30000);

    var commentBox = document.getElementById('cmtBox');
    if(commentBox !== null){
        console.log("commentBox Exists");
        window.scrollTasks.push({task: function(ticks){
            if(Util.isIn(commentBox, 300)){
                console.log("Adding FB scripts");
                Util.addFBScripts();
                return true;
            }
        }, once: true})
    }

    if(window.IS_LIVE) {
        window.scrollTasks.push({task: function(ticks){
            if( ticks > 8 && pageYOffset > 100 ){
                _addAdSense();
                _addFBPixel();
                return true;
            }
        }, once: true});
    }

    var youtubEmbeds = document.getElementsByClassName('youtube');
    if(youtubEmbeds.length){
        window.scrollTasks.push({task: function(ticks){
            if(ticks > 20 && Util.isIn(youtubEmbeds[0], 300)){
                Util.loadYoutubeJs();
                return true;
            }
        }, once: true});

    }
}

window.IS_ONLINE = true;

window.ononline = function(){

    window.IS_ONLINE = true;
    var errDiv = document.getElementById('errordiv');
    if(errDiv !== null){
        errDiv.style.display = 'none';
        errDiv.innerHTML = '';
    }


}
window.onoffline = function(){

    window.IS_ONLINE = false;
    var errDiv = document.getElementById('errordiv');
    if(errDiv !== null){
        errDiv.style.display = 'block';
        errDiv.innerHTML = 'No Network Connection';
    }
}

const toggleAccordion = function () {
    var collapsed_class = 'collapsed';
    var parentNode = this.parentNode;
    console.log(parentNode.className);
    toggleClass(parentNode, collapsed_class);
}

window.handleAccordions = function(){
    
    var toggleClass = function(node, classname) {
        var curr_class_name = node.className;
        if (curr_class_name.indexOf(classname) === -1) {
            node.className = (curr_class_name + ' ' + classname);
        } else {
            node.className = (curr_class_name.replace(` ${classname}`, ''));
        }
    }

    
    var collapsed_class = 'collapsed';
    var container_class = 'js-accordion-container';
    var head_class = 'js-accordion-head';
    var body_class = 'js-accordion-body';

    let heads = document.getElementsByClassName(head_class);
    // console.log({heads})
    for (var i = 0, l = heads.length; i < l; i++){
        var head = heads[i];
        head.addEventListener('click', toggleAccordion, false);
    }
}
handleAccordions();

// Function to scroll the element into view
function scrollToHashElement() {
  const hash = window.location.hash;
  console.log("hash", hash);
  if (hash) {
    setTimeout(function(){
        const element = document.querySelector(hash);
        if (element) {
            console.log(element)
            element.scrollIntoView({ behavior: 'smooth' });
         } else { console.log('element with hash id not found')}

     }, 1000);
  }
}

/**
 * add callbacks like this
 * window.onPageLoadScripts.push({
 *  name: 'load google maps',
 *  cb: function(){ initMap() }
 * })
 */
window.onPageLoadScripts = [];
window.registerOnPageLoadScripts = function (name, cb) {
    if (onPageLoadScripts.findIndex(sc => sc.name === name) === -1) {
        onPageLoadScripts.push({ name, cb });
    }
}
//playMainTextareaTypingAnimation();
window.playAnimation = function () {
    const preLoadElements = document.querySelectorAll(".pre-load");
    preLoadElements.forEach(function (ele) {
      ele.className = ele.className.replace("pre-animation", "post-animation");
    });
}

window.applyAnimationClass = function(ele, event_name, add){
    console.log(typeof window, ' <<<<<<<<<<');
    const attr = ele.getAttribute('data-animations'); 
    console.log({attr});
    if(attr){
        const arr = attr.split(' ');
        const animation_attr = arr.find(a => a.indexOf(event_name) !== -1);
        if(typeof animation_attr === 'string'){
            const class_name = animation_attr.split('|')[0];
            if(add){
                addClass(ele, class_name);
            } else {
                removeClass(ele, class_name);
            }
            
        }
    }
    
    
}

const observer = new IntersectionObserver(function(entries){
    console.log(entries);
    entries.forEach(function(entry){
        setTimeout(function(){
            window.applyAnimationClass(entry.target, 'SCROLL_INTO_VIEW', entry.isIntersecting);
        }, 60);
    })
})
window.attachAnimationTriggerHandlers = function(){
    const animatableElements = document.querySelectorAll(".js-animatable.js-scroll_into_view");
    animatableElements.forEach(function(ele){
        observer.observe(ele);
    });
};
registerOnPageLoadScripts('attachAnimationTriggerHandlers', attachAnimationTriggerHandlers);

window.executeOnloadScripts = function () {
    scrollToHashElement();
    playAnimation();
    handleAccordions();
    window.onPageLoadScripts.map(function (sc) {
        console.log('running:', sc.name);
        sc.cb();
    })
}


window.handleHashLinks = function () {
    var hash_links = document.getElementsByClassName('hash-link');
    // console.log("handleHashLinks called ==>", { hash_links })
    for(var i =0, l = hash_links.length; i < l;i++){
        hash_links[i].addEventListener('click', function (event){
            event.preventDefault();
            event.stopPropagation();
            var href_str = this.href;
            var href_parts = href_str.split('#');
            if(href_parts.length ===2){
                var id_str = href_parts[1];
                console.log({ id_str });
                let ele = document.getElementById(id_str);
                var rect = ele.getBoundingClientRect();
                window.scrollTo({ top: (rect.top + window.scrollY), left: 0, behavior: 'smooth'});
                
                console.log(rect);

            }
            
            // return false;
        }, false)
    }

    
}
setTimeout(() => {
    handleHashLinks();
}, 2000);
executeOnloadScripts();


var addClass = function (node, classname) {
    var curr_class_name = node.className;
    var class_arr = (curr_class_name || '').split(' ');
    var index = class_arr.indexOf(classname)
    if (index === -1) {
        class_arr.push(classname);
        node.className = class_arr.join(' ');
    }
    
}

var removeClass = function (node, classname) {
    var curr_class_name = node.className;
    var class_arr = (curr_class_name || '').split(' ');
    var index = class_arr.indexOf(classname)
    if (index === -1) {
        // skip
    } else {
        class_arr.splice(index, 1);
        node.className = class_arr.join(' ');
    }
    
}
var toggleClass = function (node, classname) {
    var curr_class_name = node.className;
    var class_arr = (curr_class_name || '').split(' ');
    var index = class_arr.indexOf(classname)
    if (index === -1) {
        class_arr.push(classname);
    } else {
        class_arr.splice(index, 1);
    }
    node.className = class_arr.join(' ');
}

const toggleElement = function () {
    let classes = this.className.split(' ');
    let toggle_class = classes.find(c => c.indexOf('toggle-') === 0);
    let _id = toggle_class.split('-')[1];
    let node = document.getElementById(_id);
    if(node){
        toggleClass(node, 'display-none');
    }
    
}


window.handleTogglers = function () {
    var _class = 'js-toggle';
    let togglers = document.getElementsByClassName(_class);
    for (var i = 0, l = togglers.length; i < l; i++) {
        var toggler = togglers[i];
        toggler.addEventListener('click', toggleElement);
    }
}
setTimeout(function(){
    handleTogglers();
}, 1000);
