/*
 Front Search
 * */

$(function() {
    
    bindResultsMouseover();
    if (typeof queryobj === "object" && queryobj) {
        scrollLoad(queryobj);
    }
    $(".update-ids").click(function(e){
    	var visited_ids = $("#visited_ids").val();
    	if(visited_ids==""){
    		$("#visited_ids").val(parseInt($(this).attr("data-id")));
    	}
    	else{
    		$("#visited_ids").val( visited_ids + "," + $(this).attr("data-id") );
    	}
    });
    
    var visited_ids = $("#visited_ids").val().split(',');
    $.each($(".notice-image"), function(i, e){
    	var im = $(e);
    	var a_par = im.parent();
    	if(visited_ids.indexOf(a_par.attr("data-id"))>=0){
    		im.addClass("visited");
    	}
    });
    
    // Check if a dom element is the current viewport
    // el is dom element, not jquery object
    function isElementInViewport(el) {
        var rect = el.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
            );
    }
    var myTimeOut = false;
    function startTimeOut(){
    	myTimeOut = setInterval(function(){ testIfLastLiInViewport() }, 3000);
    }
    function testIfLastLiInViewport(){
    	var el = $($(".results ul")[0]).children().last()[0];
    	if ( isElementInViewport(el) ) {
            // Last li is visible, so we have to call next page manually
        	if (typeof queryobj === "object" && queryobj) {
        		$(window).trigger("scroll.ajaxload");
            }
        }
    	else{
    		clearInterval(myTimeOut);
    	}
    }
    
    if (window.addEventListener) {
        //addEventListener('DOMContentLoaded', testIfLastLiInViewport(), false); 
        addEventListener('load', startTimeOut(), false); 
        //addEventListener('scroll', testIfLastLiInViewport(), false); 
        //addEventListener('resize', testIfLastLiInViewport(), false); 
    } else if (window.attachEvent)  {
        //attachEvent('DOMContentLoaded', testIfLastLiInViewport());
        attachEvent('load', startTimeOut());
        //attachEvent('scroll', testIfLastLiInViewport());
        //attachEvent('resize', testIfLastLiInViewport());
    }
});