
$( window ).resize(function() {
    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    
    $("#front-magnify").text( (parseFloat($("#img-front").width()) / parseFloat( $("#front-magnify").attr("ori") )).toFixed(2) );
    $("#top-magnify").text( (parseFloat($("#img-top").width()) / parseFloat( $("#top-magnify").attr("ori") )).toFixed(2) );
    $("#left-magnify").text( (parseFloat($("#img-left").width()) / parseFloat( $("#left-magnify").attr("ori") )).toFixed(2) );

    var zoomConfig = {
	zoomWindowPosition: 'demo-container',
	zoomWindowHeight: h,
	zoomWindowWidth: (w / 3.0),
	borderSize: 0
    };
    $('.zoomContainer').remove();
    $('.zoomWindowContainer').remove();
        
    if ($("#hoverMode").is(':checked')) {
        if (parseInt(w) > 1200) {
            $("#img-front").ezPlus(zoomConfig);
            $("#img-top").ezPlus(zoomConfig);
            $("#img-left").ezPlus(zoomConfig);
	    $(".info-text").text("Roll over to zoom and click to open fullscreen view");
        } else {
	    $(".info-text").text("Click to open fullscreen view");
        }
    } else {
	$('.zoomContainer').remove();
	$('.zoomWindowContainer').remove();
    }
});

var glob_width;
var glob_height;
var glob_elem;
var glob_id;

/*
 * This function catches the events fired during ESC key press
 */
if (document.addEventListener)
{
    document.addEventListener('webkitfullscreenchange', exitHandler, false);
    document.addEventListener('mozfullscreenchange', exitHandler, false);
    document.addEventListener('fullscreenchange', exitHandler, false);
    document.addEventListener('MSFullscreenChange', exitHandler, false);
}
function exitHandler() {
    if (document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement !== null) {
        if (!document.fullscreenElement && !document.mozFullScreenElement &&
            !document.webkitFullscreenElement && !document.msFullscreenElement) {
            $(glob_elem).css("width", "");
            $(glob_elem).css("height", "");
            //console.log(glob_elem, glob_id);
            $(glob_elem).css("background-color", "white");
            $(glob_elem).css("color", "#000");
            $("#"+glob_id).width('100%');
            $("#"+glob_id).height("100%");
            $("#slider-" + glob_id.split("-")[1]).css("margin-top", "0px");
	    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
		    
	    var zoomConfig = {
		zoomWindowPosition: 'demo-container',
		zoomWindowHeight: h,
		zoomWindowWidth: (w / 3.0),
		borderSize: 0
	    };
	    $('.zoomContainer').remove();
	    $('.zoomWindowContainer').remove();
            if ($("#hoverMode").is(':checked')) {
	        if (parseInt(w) > 1200) {
		    $("#img-front").ezPlus(zoomConfig);
		    $("#img-top").ezPlus(zoomConfig);
		    $("#img-left").ezPlus(zoomConfig);
	        }
            } else {
	        $('.zoomContainer').remove();
 	        $('.zoomWindowContainer').remove();
            }
      

            $("#front-magnify").text( (parseFloat( $("#front-magnify").attr("screen"))  / parseFloat( $("#front-magnify").attr("ori") )).toFixed(2) );
            $("#top-magnify").text( (parseFloat( $("#top-magnify").attr("screen"))  / parseFloat( $("#top-magnify").attr("ori") )).toFixed(2) );
            $("#left-magnify").text( (parseFloat( $("#left-magnify").attr("screen"))  / parseFloat( $("#left-magnify").attr("ori") )).toFixed(2) );
            $(".info-text").show();
        }
    }
}


/**
 * Click handler to enter fullscreen mode
 */
document.getElementById("leftFS").addEventListener("click", function() {
    var container = $("#photowrapper-left");
    if (!document.fullscreenElement && !document.mozFullScreenElement &&
        !document.webkitFullscreenElement && !document.msFullscreenElement) {
        //console.log(this.id);
        glob_id = "img-left";
        glob_width = $("#photowrapper-left > img").width();
        glob_height = $("#photowrapper-left > img").height();
        glob_elem = $("#photowrapper-left")[0];
    }
    toggleFullscreen(container[0], "img-left");
});

document.getElementById("topFS").addEventListener("click", function() {
    var container = $("#photowrapper-top");
    if (!document.fullscreenElement && !document.mozFullScreenElement &&
        !document.webkitFullscreenElement && !document.msFullscreenElement) { 
        glob_id = "img-top";
        glob_width = $("#photowrapper-top > img").width();
        glob_height = $("#photowrapper-top > img").height();
        glob_elem = $("#photowrapper-top")[0];
    }
    toggleFullscreen(container[0], "img-top");
});

document.getElementById("frontFS").addEventListener("click", function() {
    var container = $("#photowrapper-front");
    if (!document.fullscreenElement && !document.mozFullScreenElement &&
        !document.webkitFullscreenElement && !document.msFullscreenElement) { 
        glob_id = "img-front";
        glob_width = $("#photowrapper-front > img").width();
        glob_height = $("#photowrapper-front > img").height();
        glob_elem = $("#photowrapper-front")[0];
    }
    toggleFullscreen(container[0], "img-front");
});


function toggleFullscreen(elem, _id) {
    elem = elem || document.documentElement;

    //console.log("ID: "+_id);
    var ori_width = glob_width
    var ori_height = glob_height;
      
    var fs_scale;
    var myRatio;
    if (window.devicePixelRatio < 1) {
        myRatio = 1.0;
    } else {
        myRatio = 2.0;
    }
        
    //$("#"+_id).css('width', 'auto')
    //$("#"+_id).css('height', 'auto')

    if (!document.fullscreenElement && !document.mozFullScreenElement &&
      !document.webkitFullscreenElement && !document.msFullscreenElement) { 
        //newWidth = screen.width * (1/ myRatio);
        //newHeight = screen.width * (ori_height/ori_width) * (1/ myRatio);

        newWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	newHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        
        $(".info-text").hide();

        //newHeight = screen.height * (1/myRatio);
        //newWidth = screen.height * (ori_width/ori_height) * (1/myRatio);
 
        // NTJ: Goes into fullscreen mode
        //console.log("Entering fullscreen mode!"); 
        //$("#"+_id).removeAttr('width');
        //$("#"+_id).height("80%");
        
        
        $("#"+_id).removeAttr('height');
        $("#"+_id).removeAttr('width');
        //$("#"+_id).width("100%");
      
        photowrapper = "#photowrapper-" + _id.split("-")[1]; 

        $(photowrapper).css("height", (newHeight)+"px");
        $(photowrapper).css("width", (newWidth)+"px");
        
        //$("#"+_id).width(newWidth+"px");
        if ( (_id.split("-")[1] == "top") || (_id.split("-")[1] == "left") ) {
          //$(photowrapper).css("width", "100%");
          //$("#"+_id).width("100%");
            $("#"+_id).width((newWidth-100)+"px");
            $("#"+_id).height("auto");
            $("#slider-" + _id.split("-")[1]).css("margin-top", "100px");
        } else {
            $("#"+_id).width("auto");
            $("#"+_id).height((newHeight-100)+"px");
        }

        $(elem).css("background-color", "black");
        $(elem).css("color", "#ccc");

        if (elem.requestFullscreen) {
             elem.requestFullscreen();
        } else if (elem.msRequestFullscreen) {
            elem.msRequestFullscreen();
        } else if (elem.mozRequestFullScreen) {
            elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
            elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
        }

 
        $("#front-magnify").text( (parseFloat($("#img-front").width()) / parseFloat( $("#front-magnify").attr("ori") )).toFixed(2) );
        $("#top-magnify").text( (parseFloat($("#img-top").width()) / parseFloat( $("#top-magnify").attr("ori") )).toFixed(2) );
        $("#left-magnify").text( (parseFloat($("#img-left").width()) / parseFloat( $("#left-magnify").attr("ori") )).toFixed(2) );
        
    } else {
      $(".info-text").show();
      //console.log("Leaving the fullscreen mode");
      $("#slider-" + _id.split("-")[1]).css("margin-top", "0px");
      $(photowrapper).css("width", "100%");
      $(photowrapper).css("height", "100%");
      $("#"+_id).width('100%');
      $("#"+_id).height("100%");
      //$(elem).css("width", "100%");
      $(elem).css("background-color", "white");
      $(elem).css("color", "#000");
        

    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	    
    var zoomConfig = {
	zoomWindowPosition: 'demo-container',
	zoomWindowHeight: h,
	zoomWindowWidth: (w / 3.0),
	borderSize: 0
    };

	    $('.zoomContainer').remove();
	    $('.zoomWindowContainer').remove();
            if ($("#hoverMode").is(':checked')) {
	        if (parseInt(w) > 1200) {
		    $("#img-front").ezPlus(zoomConfig);
		    $("#img-top").ezPlus(zoomConfig);
		    $("#img-left").ezPlus(zoomConfig);
	        }
            } else {
	        $('.zoomContainer').remove();
 	        $('.zoomWindowContainer').remove();
            }

        $("#front-magnify").text( (parseFloat( $("#front-magnify").attr("screen"))  / parseFloat( $("#front-magnify").attr("ori") )).toFixed(2) );
        $("#top-magnify").text( (parseFloat( $("#top-magnify").attr("screen"))  / parseFloat( $("#top-magnify").attr("ori") )).toFixed(2) );
        $("#left-magnify").text( (parseFloat( $("#left-magnify").attr("screen"))  / parseFloat( $("#left-magnify").attr("ori") )).toFixed(2) );
      

      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }

    
    }

}


$(function() {

    /**
     *  Logic for dropdown filter box and 
     *  pagination navigation
     */
    $("#hoverMode").click(function() {
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        var zoomConfig = {
	    zoomWindowPosition: 'demo-container',
	    zoomWindowHeight: h,
	    zoomWindowWidth: (w / 3.0),
	    borderSize: 0
        };
                     
        if($("#hoverMode").is(':checked')) {
	    if (parseInt(w) > 1200) {
	        $("#img-front").ezPlus(zoomConfig);
		$("#img-top").ezPlus(zoomConfig);
		$("#img-left").ezPlus(zoomConfig);
            }
        } else {
	    $('.zoomContainer').remove();
            $('.zoomWindowContainer').remove();
        }
    });

    $("#pagination-demo").hide();
    $("#filter-dropdown").hide();

    $("#dataBtn").click(function() {
        $("#pagination-demo").toggle();
        $("#filter-dropdown").toggle();
    });
    
    $("#overviewBtn").click(function() {
        $("#pagination-demo").hide();
        $("#filter-dropdown").hide();
    });


    Handlebars.registerHelper('if_eq', function(a, b, opts) {
        if (a == b) {
            return opts.fn(this);
        } else {
            return opts.inverse(this);
        }
    });

    $( ".download" ).click(function(e) {
        //console.log("clicked download");
        var did = $(this).attr("data-name").trim();
        //console.log(did);
        e.preventDefault();  //stop the browser from following
        window.location.href = 'download?did=' + did;
    });

    $('#pagination-demo').twbsPagination({
        totalPages: 6,
        visiblePages: 6,
        onPageClick: function (event, page) {
            //console.log('Page ' + page);
            var filter_type = $('#filterType').find(":selected").val();
            var target_url = "getpage?page="+page+"&type="+filter_type;
            $.ajax({
                url: target_url,
                type: 'GET',
                success: function (response) {
                    console.log("Success.", response);

                    /*
                    // First set of values
                    $("#front-number").text( response["data"][0][5]);
                    $("#top-number").text( response["data"][0][4]);
                    $("#left-number").text( response["data"][0][3]);
        
		    $('#slider-front').slider("option", "max", response["data"][0][5]);
		    $('#slider-top').slider("option", "max", response["data"][0][4]);
		    $('#slider-left').slider("option", "max", response["data"][0][3]);

		    $("#img-front").attr("src", "img?name="+response["data"][0][0]+"&type=front&counter="+ parseInt(response["data"][0][5]/2).toString() );
                    $("#img-front").data("zoom-image", "img?name="+response["data"][0][0]+"&type=front&counter="+ parseInt(response["data"][0][5]/2).toString() );
		    $("#img-top").attr("src", "img?name="+response["data"][0][0]+"&type=top&counter="+ parseInt(response["data"][0][4]/2).toString());
                    $("#img-top").data("zoom-image", "img?name="+response["data"][0][0]+"&type=top&counter="+ parseInt(response["data"][0][4]/2).toString());
		    $("#img-left").attr("src", "img?name="+response["data"][0][0]+"&type=left&counter="+ parseInt(response["data"][0][3]/2).toString());
                    $("#img-left").data("zoom-image", "img?name="+response["data"][0][0]+"&type=left&counter="+ parseInt(response["data"][0][3]/2).toString());

		    $("#slider-front").slider('value', parseInt(response["data"][0][5]/2) );
		    $("#slider-top").slider('value', parseInt(response["data"][0][4]/2) );
		    $("#slider-left").slider('value', parseInt(response["data"][0][3]/2) );
                    */

		    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
		    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			    
		    var zoomConfig = {
			zoomWindowPosition: 'demo-container',
			zoomWindowHeight: h,
			zoomWindowWidth: (w / 3.0),
			borderSize: 0
                    };

	                
                    $('.zoomContainer').remove();
                    $('.zoomWindowContainer').remove();

                    if ($("#hoverMode").is(':checked')) {
		        if (parseInt(w) > 1200) {
			    $("#img-front").ezPlus(zoomConfig);
			    $("#img-top").ezPlus(zoomConfig);
			    $("#img-left").ezPlus(zoomConfig);
		            $(".info-text").text("Roll over to zoom and click to open fullscreen view");
                        } else {
		            $(".info-text").text("Click to open fullscreen view");
                        }
                    } else {
                        $('.zoomContainer').remove();
                        $('.zoomWindowContainer').remove();
                    }
 
                    
                    //$("#front-magnify").text( (parseFloat($("#img-front").width()) / parseFloat(response["data"][0][9])).toFixed(2) );
                    $("#front-magnify").attr( "ori", (parseFloat(response["data"][0][9])).toFixed(2) );
                    $("#front-magnify").attr( "screen", (parseFloat($("#img-front").width())).toFixed(2) );
                    //$("#top-magnify").text( (parseFloat($("#img-top").width()) / parseFloat(response["data"][0][8])).toFixed(2) );
                    $("#top-magnify").attr( "ori", (parseFloat(response["data"][0][8])).toFixed(2) );
                    $("#top-magnify").attr( "screen", (parseFloat($("#img-top").width())).toFixed(2) );
                    //$("#left-magnify").text( (parseFloat($("#img-left").width()) / parseFloat(response["data"][0][7])).toFixed(2) );
                    $("#left-magnify").attr( "ori", (parseFloat(response["data"][0][7])).toFixed(2) );
                    $("#left-magnify").attr( "screen", (parseFloat($("#img-left").width())).toFixed(2) );

                    for (var i = 0; i< 10; i++) {
                        // Automatically show the first item
                        // disabled based on the review
                        //if (i == 0) {
                        //    $("#sidebar-list > li:nth-child("+(i+1)+") > ul").collapse("show");
                        //} else {
                        //    $("#sidebar-list > li:nth-child("+(i+1)+") > ul").collapse("hide");
                        //}
                        $("#sidebar-list > li:nth-child("+(i+1)+") > ul").collapse("hide");

                        if (typeof response["data"][i] == 'undefined') {
                            $("#sidebar-list > li:nth-child("+(i+1)+")").hide();
                        } else {
                            var title;
                            var collection = "unknown";
                            title = response["data"][i][0]; 
                         
                            if (title.indexOf("NMB") !== -1) {
                                collection = "Natural History Museum of Basel";
                            } else  if (title.indexOf("NRM-PZ") !== -1) {
                                collection = "Swedish Museum of Natural History";
                            }

                            $("#sidebar-list > li:nth-child("+(i+1)+") > a").attr("data-dim", "["+response["data"][i][3]+","+response["data"][i][4]+","+response["data"][i][5]+","+response["data"][i][7]+","+response["data"][i][8]+","+response["data"][i][9]+"]");
                            var photo_html = "<img width='100%' src='img?name="+title+";type=photo'>";
                            var volren_html = "<img width='100%' src='img?name="+title+";type=volren'>";
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(1) > td:nth-child(3)").html(photo_html); 
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(2) > td:nth-child(3)").html(volren_html); 
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(4) > td:nth-child(3)").html(collection); 
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(6) > td:nth-child(3) > button").attr("data-name", response["data"][i][0]);

                            //#sidebar-list > li.active > ul > table > tbody > tr:nth-child(5) > td:nth-child(3)
                            $("#sidebar-list > li:nth-child("+(i+1)+")").show();

                            var tmp = "";                            
                            var species_type = "unknown";
                            var first_species_type = "unknown";
                            for (item in response["data"][i][1]) {
                                if (response["data"][i][1][item]["type"] == "holo") {
                                    tmp += " <span>"+response["data"][i][1][item]["text"].toLowerCase()+"</span>";
                                } else if (response["data"][i][1][item]["type"] == "i") {
                                    tmp += "<i>"+response["data"][i][1][item]["text"]+"</i>"
                                    species_type = "<i>" + response["data"][i][1][item]["text"] + "</i>";
                                    if (i == 0) {
                                        first_species_type = "<i>" + response["data"][i][1][item]["text"] + "</i>";
                                        //console.log(first_species_type);
                                        //$("#header-name").html( response["data"][0][0] + "\xa0\xa0\xa0\xa0" + first_species_type);
                                    }
                                } else {
                                    tmp += response["data"][i][1][item]["text"]
                                }
                            }
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(3) > td:nth-child(3)").html(tmp); 

                            // FIRST HEADER

                            title += "\xa0\xa0\xa0\xa0";
                            title += species_type;
                            for (item in response["data"][i][1]) {
                                if (response["data"][i][1][item]["type"] == "holo") {
                                    title += "&nbsp;&nbsp;<span class='label label-danger'>HOLOTYPE</span>";
                                }
                            }
                            $("#sidebar-list > li:nth-child("+(i+1)+") > a").html(title);

                            var size = "";
                            size = response["data"][i][2] + "&nbsp;&nbsp;GB";                   
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(5) > td:nth-child(3)").html(size);                    
 
                        }
                   
                    }
                },
                error: function () {
                    console.log("Error.")
                }
            }); 
        }
    });

    $(".data-pil").click(function() {
        $("#info-general").hide();
        $("#slider-front").slider("enable");
        $("#slider-top").slider("enable");
        $("#slider-left").slider("enable");
       
        $("#header-name").html( $(this).html());

        var selected_data = $(this).text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];
        var dimension = JSON.parse($(this).attr("data-dim"));
        $("#front-number").text(dimension[2]);
        $("#top-number").text(dimension[1]);
        $("#left-number").text(dimension[0]);
                    

        $('#slider-front').slider("option", "max", dimension[2]);
        $('#slider-top').slider("option", "max", dimension[1]);
        $('#slider-left').slider("option", "max", dimension[0]);

        $("#img-front").attr("src", "img?name="+selected_data+"&type=front&counter="+ parseInt((dimension[2]/2)-1).toString() );
        $("#img-front").data("zoom-image", "img?name="+selected_data+"&type=front&counter="+ parseInt((dimension[2]/2)-1).toString() );
        $("#slider-front").slider('value', parseInt(dimension[2]/2));
        $("#front-current-number").val(parseInt(dimension[2]/2));
        $("#img-top").attr("src", "img?name="+selected_data+"&type=top&counter="+ parseInt((dimension[1]/2)-1).toString());
        $("#img-top").data("zoom-image", "img?name="+selected_data+"&type=top&counter="+ parseInt((dimension[1]/2)-1).toString());
        $("#slider-top").slider('value',parseInt(dimension[1]/2));
        $("#top-current-number").val(parseInt(dimension[1]/2));
        $("#img-left").attr("src", "img?name="+selected_data+"&type=left&counter="+ parseInt((dimension[0]/2)-1).toString());
        $("#img-left").data("zoom-image", "img?name="+selected_data+"&type=left&counter="+ parseInt((dimension[0]/2)-1).toString());
        $("#slider-left").slider('value',parseInt(dimension[0]/2));
        $("#left-current-number").val(parseInt(dimension[0]/2));

        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            
        var zoomConfig = {
            zoomWindowPosition: 'demo-container',
            //zoomWindowHeight: h,
            zoomWindowHeight: (w / 3.0) - 50.0,
            zoomWindowWidth: (w / 3.0) - 50.0,
            zoomType: "lens",
            borderSize: 0
        };

        $('.zoomContainer').remove();
        $('.zoomWindowContainer').remove();
        if ($("#hoverMode").is(':checked')) {
            if (parseInt(w) > 1200) {
                $("#img-front").ezPlus(zoomConfig);
                $("#img-top").ezPlus(zoomConfig);
                $("#img-left").ezPlus(zoomConfig);
            }
        } else {
	    $('.zoomContainer').remove();
	    $('.zoomWindowContainer').remove();
        }
        $("#front-magnify").text( (parseFloat($("#img-front").width()) / parseFloat(dimension[5])).toFixed(2) );
        $("#top-magnify").text( (parseFloat($("#img-top").width()) / parseFloat(dimension[4])).toFixed(2) );
        $("#left-magnify").text( (parseFloat($("#img-left").width()) / parseFloat(dimension[3])).toFixed(2) );

    });

    /**
     * Text field updates 
     **/
    $( "#front-current-number" ).change(function() {
        var current_value = $("#front-current-number").val();
        var upper_limit = $("#front-number").text();
        if (current_value < 1 || current_value > upper_limit) {
            return;
        } 
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-front").attr("src", "img?name="+selected_data+"&type=front&counter="+current_value);
        $("#front-current-number").val(current_value);
        $("#slider-front").slider('value', current_value);
    });
    
    $( "#top-current-number" ).change(function() {
        var current_value = $("#top-current-number").val();
        var upper_limit = $("#top-number").text();
        if (current_value < 1 || current_value > upper_limit) {
            return;
        } 
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-top").attr("src", "img?name="+selected_data+"&type=top&counter="+current_value);
        $("#top-current-number").val(current_value);
        $("#slider-top").slider('value', current_value);
    });
    
    $( "#left-current-number" ).change(function() {
        var current_value = $("#left-current-number").val();
        var upper_limit = $("#left-number").text();
        if (current_value < 1 || current_value > upper_limit) {
            return;
        } 
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-left").attr("src", "img?name="+selected_data+"&type=left&counter="+current_value);
        $("#left-current-number").val(current_value);
        $("#slider-left").slider('value', current_value);
    });
    
    $( "#front-current-number" ).change(function() {
        var current_value = $("#front-current-number").val();
        var upper_limit = $("#front-number").text();
        if (current_value < 1 || current_value > upper_limit) {
            return;
        } 
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-front").attr("src", "img?name="+selected_data+"&type=front&counter="+current_value);
        $("#front-current-number").val(current_value);
    });
    
    /**
     * Up Down button counter 
     **/
    $("#front-down-counter").click(function() {
        var current_value = $("#front-current-number").val();
        if (current_value <= 1) {
            return;
        } else {
            current_value -= 1;
        }
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-front").attr("src", "img?name="+selected_data+"&type=front&counter="+current_value);
        $("#front-current-number").val(current_value);
            
        var imageUrl = "img?name="+selected_data+"&type=front&counter="+current_value;    
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

	var zoomConfig = {
            zoomWindowPosition: 'demo-container',
	    zoomWindowHeight: h,
	    zoomWindowWidth: (w / 3.0),
	    borderSize: 0
	};

        var zoomImage = $('#img-front');
        $('#img-front-zoomContainer').remove();
        // Reinitialize EZ
	if (parseInt(w) > 1200) {
            zoomImage.attr('src', imageUrl);
            zoomImage.data('zoom-image', imageUrl);
            if ($("#hoverMode").is(':checked')) {
                zoomImage.ezPlus(zoomConfig);
            }
	}

    });

    $("#front-up-counter").click(function() {
        var current_value = parseInt($("#front-current-number").val());
        var upper_limit = $("#front-number").text();
        if (current_value >= upper_limit) {
            return;
        } else {
            current_value += 1;
        }
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];
        
        $("#img-front").attr("src", "img?name="+selected_data+"&type=front&counter="+current_value);
        $("#front-current-number").val(current_value);
        
        var imageUrl = "img?name="+selected_data+"&type=front&counter="+current_value;    
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

	var zoomConfig = {
            zoomWindowPosition: 'demo-container',
	    zoomWindowHeight: h,
	    zoomWindowWidth: (w / 3.0),
	    borderSize: 0
	};

        var zoomImage = $('#img-front');
        $('#img-front-zoomContainer').remove();
        // Reinitialize EZ
	if (parseInt(w) > 1200) {
            zoomImage.attr('src', imageUrl);
            zoomImage.data('zoom-image', imageUrl);
            if ($("#hoverMode").is(':checked')) {
                zoomImage.ezPlus(zoomConfig);
            }
	}
    });
    
    $("#top-down-counter").click(function() {
        var current_value = $("#top-current-number").val();
        if (current_value <= 1) {
            return;
        } else {
            current_value -= 1;
        }
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-top").attr("src", "img?name="+selected_data+"&type=top&counter="+current_value);
        $("#top-current-number").val(current_value);
        
        var imageUrl = "img?name="+selected_data+"&type=top&counter="+current_value;    
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

	var zoomConfig = {
            zoomWindowPosition: 'demo-container',
	    zoomWindowHeight: h,
	    zoomWindowWidth: (w / 3.0),
	    borderSize: 0
	};

        var zoomImage = $('#img-top');
        $('#img-top-zoomContainer').remove();
        // Reinitialize EZ
	if (parseInt(w) > 1200) {
            zoomImage.attr('src', imageUrl);
            zoomImage.data('zoom-image', imageUrl);
            if ($("#hoverMode").is(':checked')) {
                zoomImage.ezPlus(zoomConfig);
            }
	}
    });

    $("#top-up-counter").click(function() {
        var current_value = parseInt($("#top-current-number").val());
        var upper_limit = $("#top-number").text();
        if (current_value >= upper_limit) {
            return;
        } else {
            current_value += 1;
        }
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];
        
        $("#img-top").attr("src", "img?name="+selected_data+"&type=top&counter="+current_value);
        $("#top-current-number").val(current_value);
        
        var imageUrl = "img?name="+selected_data+"&type=top&counter="+current_value;    
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

	var zoomConfig = {
            zoomWindowPosition: 'demo-container',
	    zoomWindowHeight: h,
	    zoomWindowWidth: (w / 3.0),
	    borderSize: 0
	};

        var zoomImage = $('#img-top');
        $('#img-top-zoomContainer').remove();
        // Reinitialize EZ
	if (parseInt(w) > 1200) {
            zoomImage.attr('src', imageUrl);
            zoomImage.data('zoom-image', imageUrl);
            if ($("#hoverMode").is(':checked')) {
                zoomImage.ezPlus(zoomConfig);
            }
	}
    });
    
    $("#left-down-counter").click(function() {
        var current_value = $("#left-current-number").val();
        if (current_value <= 1) {
            return;
        } else {
            current_value -= 1;
        }
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-left").attr("src", "img?name="+selected_data+"&type=left&counter="+current_value);
        $("#left-current-number").val(current_value);
        
        var imageUrl = "img?name="+selected_data+"&type=left&counter="+current_value;    
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

	var zoomConfig = {
            zoomWindowPosition: 'demo-container',
	    zoomWindowHeight: h,
	    zoomWindowWidth: (w / 3.0),
	    borderSize: 0
	};

        var zoomImage = $('#img-left');
        $('#img-left-zoomContainer').remove();
        // Reinitialize EZ
	if (parseInt(w) > 1200) {
            zoomImage.attr('src', imageUrl);
            zoomImage.data('zoom-image', imageUrl);
            if ($("#hoverMode").is(':checked')) {
                zoomImage.ezPlus(zoomConfig);
            }
	}
    });

    $("#left-up-counter").click(function() {
        var current_value = parseInt($("#left-current-number").val());
        var upper_limit = $("#left-number").text();
        if (current_value >= upper_limit) {
            return;
        } else {
            current_value += 1;
        }
        var selected_data = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
        selected_data = selected_data[0] + " " + selected_data[1];

        $("#img-left").attr("src", "img?name="+selected_data+"&type=left&counter="+current_value);
        $("#left-current-number").val(current_value);
        var imageUrl = "img?name="+selected_data+"&type=left&counter="+current_value;    
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

	var zoomConfig = {
            zoomWindowPosition: 'demo-container',
	    zoomWindowHeight: h,
	    zoomWindowWidth: (w / 3.0),
	    borderSize: 0
	};

        var zoomImage = $('#img-left');
        $('#img-left-zoomContainer').remove();
        // Reinitialize EZ
	if (parseInt(w) > 1200) {
            zoomImage.attr('src', imageUrl);
            zoomImage.data('zoom-image', imageUrl);
            if ($("#hoverMode").is(':checked')) {
                zoomImage.ezPlus(zoomConfig);
            }
	}
    });

    $("#slider-front").slider({
        range: "max",
        min: 1,
        max: parseInt($("#front-number").text()),
        value: 1553,
        stop: function(event, ui) {
            var name = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
            name = name[0] + " " + name[1];
            
            var imageUrl = "img?name="+name+"&type=front&counter="+(ui.value-1);
            var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            
            $("#img-front").attr("src", "img?name="+name+"&type=front&counter="+(ui.value-1));
            var zoomConfig = {
                zoomWindowPosition: 'demo-container',
                zoomWindowHeight: h,
                zoomWindowWidth: (w / 3.0) - 50.0,
                borderSize: 0
            };

            var zoomImage = $('#img-front');
            $('#img-front-zoomContainer').remove();
            //$('.zoomWindowContainer').remove();
            //$('.zoomContainer').remove();
            // Reinitialize EZ
	    if (parseInt(w) > 1200) {
                zoomImage.attr('src', imageUrl);
                zoomImage.data('zoom-image', imageUrl);
                if ($("#hoverMode").is(':checked')) {
                    zoomImage.ezPlus(zoomConfig);
                }
                //$("#img-top").ezPlus(zoomConfig);
                //$("#img-left").ezPlus(zoomConfig);
	    }

	},
        slide: function( event, ui ) {
            var name = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
            name = name[0] + " " + name[1];
            $("#img-front").attr("src", "img?name="+name+"&type=front-resized&counter="+(ui.value-1));
            $("#front-current-number").val(ui.value);
        }
    });

    $("#slider-top").slider({
        range: "max",
        min: 1,
        max: parseInt($("#top-number").text()),
        value: 645,
        stop: function(event, ui) {
            var name = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
            name = name[0] + " " + name[1];
            var imageUrl = "img?name="+name+"&type=top&counter="+(ui.value-1);
            var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            
            $("#img-top").attr("src", "img?name="+name+"&type=top&counter="+(ui.value-1));
            var zoomConfig = {
                zoomWindowPosition: 'demo-container',
                zoomWindowHeight: h,
                zoomWindowWidth: (w / 3.0),
                borderSize: 0
            };

            var zoomImage = $('#img-top');
            $('#img-top-zoomContainer').remove();
            //$('.zoomWindowContainer').remove();
            //$('.zoomContainer').remove();
            // Reinitialize EZ
	    if (parseInt(w) > 1200) {
                zoomImage.attr('src', imageUrl);
                zoomImage.data('zoom-image', imageUrl);
                if ($("#hoverMode").is(':checked')) {
                    zoomImage.ezPlus(zoomConfig);
                }
	    }
        },
        slide: function( event, ui ) {
            var name = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
            name = name[0] + " " + name[1];
            $("#img-top").attr("src", "img?name="+name+"&type=top-resized&counter="+(ui.value-1));
            $("#top-current-number").val(ui.value);
        }
    });

    $("#slider-left").slider({
        range: "max",
        min: 1,
        max: parseInt($("#left-number").text()),
        value: 580,
        stop: function(event, ui) {
            var name = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
            name = name[0] + " " + name[1];
            var imageUrl = "img?name="+name+"&type=left&counter="+(ui.value-1);
            var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            
            $("#img-left").attr("src", "img?name="+name+"&type=left&counter="+(ui.value-1));
            var zoomConfig = {
                zoomWindowPosition: 'demo-container',
                zoomWindowHeight: h,
                zoomWindowWidth: (w / 3.0),
                borderSize: 0
            };

            var zoomImage = $('#img-left');
            $('#img-left-zoomContainer').remove();
            //$('.zoomWindowContainer').remove();
            //$('.zoomContainer').remove();
            // Reinitialize EZ
	    if (parseInt(w) > 1200) {
                zoomImage.attr('src', imageUrl);
                zoomImage.data('zoom-image', imageUrl);
                if ($("#hoverMode").is(':checked')) {
                    zoomImage.ezPlus(zoomConfig);
                }
	    }
        },
        slide: function( event, ui ) {
            var name = $("#header-name").text().split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
            name = name[0] + " " + name[1];
            $("#img-left").attr("src", "img?name="+name+"&type=left-resized&counter="+(ui.value-1));
            $("#left-current-number").val(ui.value);
        }
    });
    
    //$("#slider-front").slider("disable");
    //$("#slider-top").slider("disable");
    //$("#slider-left").slider("disable");


    //remember to listen for the image's load event before assigning a source
    $("#img-front").on('load', function(){
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        if ($("#hoverMode").is(':checked')) {
	    if (parseInt(w) > 1200) {
                $("#img-front").ezPlus({
                    zoomWindowPosition: 'demo-container',
                    zoomWindowHeight: h,
                    zoomWindowWidth: (w / 3.0),
                    borderSize: 0
                });
            }
        }   
    });
    
    $("#img-top").on('load', function(){
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        if ($("#hoverMode").is(':checked')) {
	if (parseInt(w) > 1200) { 
            $("#img-top").ezPlus({
                zoomWindowPosition: 'demo-container',
                zoomWindowHeight: h,
                zoomWindowWidth: (w / 3.0),
                borderSize: 0
            });
        }
        }
    });
    
    $("#img-left").on('load', function(){
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        if ($("#hoverMode").is(':checked')) {
	if (parseInt(w) > 1200) { 
            $("#img-left").ezPlus({
                zoomWindowPosition: 'demo-container',
                zoomWindowHeight: h,
                zoomWindowWidth: (w / 3.0),
                borderSize: 0
            });
        }
        }
    });


    $('#filterType').on('change', function() {
        //console.log(this.value);
        page = 1
        var filter_type = $('#filterType').find(":selected").val();
        var target_url = "getpage?page="+page+"&type="+filter_type;
        $.ajax({
            url: target_url,
            type: 'GET',
            success: function (response) {
                console.log("Success.", response);
                $("#pagination-demo").twbsPagination('destroy');
                $('#pagination-demo').twbsPagination({
	            totalPages: response["total_pages"],
	            visiblePages: 6,
	            onPageClick: function (event, page) {
            var filter_type = $('#filterType').find(":selected").val();
            var target_url = "getpage?page="+page+"&type="+filter_type;
            $.ajax({
                url: target_url,
                type: 'GET',
                success: function (response) {
                    console.log("Success.", response);
                    /*
                    $("#front-number").text( response["data"][0][5]);
                    $("#top-number").text( response["data"][0][4]);
                    $("#left-number").text( response["data"][0][3]);
        
		    $('#slider-front').slider("option", "max", response["data"][0][5]);
		    $('#slider-top').slider("option", "max", response["data"][0][4]);
		    $('#slider-left').slider("option", "max", response["data"][0][3]);

		    $("#img-front").attr("src", "img?name="+response["data"][0][0]+"&type=front-resized&counter=0");
                    $("#img-front").data("zoom-image", "img?name="+response["data"][0][0]+"&type=front&counter=0");
		    $("#img-top").attr("src", "img?name="+response["data"][0][0]+"&type=top-resized&counter=0");
                    $("#img-top").data("zoom-image", "img?name="+response["data"][0][0]+"&type=top&counter=0");
		    $("#img-left").attr("src", "img?name="+response["data"][0][0]+"&type=left-resized&counter=0");
                    $("#img-left").data("zoom-image", "img?name="+response["data"][0][0]+"&type=left&counter=0");
                    */
		    $("#slider-front").slider('value', 1);
		    $("#slider-top").slider('value', 1);
		    $("#slider-left").slider('value', 1);
        
		    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
		    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			    
		    var zoomConfig = {
			zoomWindowPosition: 'demo-container',
			zoomWindowHeight: h,
			zoomWindowWidth: (w / 3.0),
			borderSize: 0
                    };
		    $('.zoomContainer').remove();
		    $('.zoomWindowContainer').remove();
                    if ($("#hoverMode").is(':checked')) {
		        if (parseInt(w) > 1200) {
			    $("#img-front").ezPlus(zoomConfig);
			    $("#img-top").ezPlus(zoomConfig);
			    $("#img-left").ezPlus(zoomConfig);
		            $(".info-text").text("Roll over to zoom and click to open fullscreen view");
                        } else {
		            $(".info-text").text("Click to open fullscreen view");
                        }
                    } else {
	                $('.zoomContainer').remove();
	                $('.zoomWindowContainer').remove();
                    }
          
                    
                    //$("#front-magnify").text( (parseFloat($("#img-front").width()) / parseFloat(response["data"][0][9])).toFixed(2) );
                    $("#front-magnify").attr( "ori", (parseFloat(response["data"][0][9])).toFixed(2) );
                    $("#front-magnify").attr( "screen", (parseFloat($("#img-front").width())).toFixed(2) );
                    //$("#top-magnify").text( (parseFloat($("#img-top").width()) / parseFloat(response["data"][0][8])).toFixed(2) );
                    $("#top-magnify").attr( "ori", (parseFloat(response["data"][0][8])).toFixed(2) );
                    $("#top-magnify").attr( "screen", (parseFloat($("#img-top").width())).toFixed(2) );
                    //$("#left-magnify").text( (parseFloat($("#img-left").width()) / parseFloat(response["data"][0][7])).toFixed(2) );
                    $("#left-magnify").attr( "ori", (parseFloat(response["data"][0][7])).toFixed(2) );
                    $("#left-magnify").attr( "screen", (parseFloat($("#img-left").width())).toFixed(2) );
i
                    for (var i = 0; i< 10; i++) {
                        //if (i == 0) {
                        //    $("#sidebar-list > li:nth-child("+(i+1)+") > ul").collapse("show");
                        //} else {
                        //    $("#sidebar-list > li:nth-child("+(i+1)+") > ul").collapse("hide");
                        //}
                        $("#sidebar-list > li:nth-child("+(i+1)+") > ul").collapse("hide");

                        if (typeof response["data"][i] == 'undefined') {
                            $("#sidebar-list > li:nth-child("+(i+1)+")").hide();
                        } else {
                            var title;
                            
                            var collection = "unknown";
                            title = response["data"][i][0]; 
                            //console.log(title);                        
                            if (title.indexOf("NMB") !== -1) {
                                collection = "Natural History Museum of Basel";
                            } else  if (title.indexOf("NRM-PZ") !== -1) {
                                collection = "Swedish Museum of Natural History";
                            }

                            $("#sidebar-list > li:nth-child("+(i+1)+") > a").attr("data-dim", "["+response["data"][i][3]+","+response["data"][i][4]+","+response["data"][i][5]+","+response["data"][i][7]+","+response["data"][i][8]+","+response["data"][i][9]+"]");
                            var photo_html = "<img width='100%' src='img?name="+title+";type=photo'>";
                            var volren_html = "<img width='100%' src='img?name="+title+";type=volren'>";
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(1) > td:nth-child(3)").html(photo_html); 
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(2) > td:nth-child(3)").html(volren_html); 
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(4) > td:nth-child(3)").html(collection); 
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(6) > td:nth-child(3) > button").attr("data-name", response["data"][i][0]);

                            $("#sidebar-list > li:nth-child("+(i+1)+")").show();

                            var tmp = "";                            
                            var species_type = "unknown";
                            //var first_species_type = "unknown";
                            for (item in response["data"][i][1]) {
                                if (response["data"][i][1][item]["type"] == "holo") {
                                    tmp += " <span>"+response["data"][i][1][item]["text"].toLowerCase()+"</span>";
                                } else if (response["data"][i][1][item]["type"] == "i") {
                                    tmp += "<i>"+response["data"][i][1][item]["text"]+"</i>"
                                    species_type = "<i>" + response["data"][i][1][item]["text"] + "</i>";
                                    if (i == 0) {
                                        first_species_type = "<i>" + response["data"][i][1][item]["text"] + "</i>";
                                    }
                                } else {
                                    tmp += response["data"][i][1][item]["text"]
                                }
                            }
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(3) > td:nth-child(3)").html(tmp); 

                            //$("#header-name").html( response["data"][0][0] + "\xa0\xa0\xa0\xa0" + first_species_type);

                            title += "\xa0\xa0\xa0\xa0";
                            title += species_type;
                            for (item in response["data"][i][1]) {
                                if (response["data"][i][1][item]["type"] == "holo") {
                                    title += "&nbsp;&nbsp;<span class='label label-danger'>HOLOTYPE</span>";
                                }
                            }
                            $("#sidebar-list > li:nth-child("+(i+1)+") > a").html(title);

                            var size = "";
                            size = response["data"][i][2] + "&nbsp;&nbsp;GB";                   
                            $("#sidebar-list > li:nth-child("+(i+1)+") > ul > table > tbody > tr:nth-child(5) > td:nth-child(3)").html(size); 
                        }
                   
                    }
                },
                error: function () {
                    console.log("Error.")
                }
            }); 
	            
                    }
                });
            },
            error: function () {
                console.log("Error.")
            }
        });
        /*
        $("#pagination-demo").twbsPagination('destroy');
        $('#pagination-demo').twbsPagination({
	    totalPages: 35,
	    visiblePages: 7,
	    onPageClick: function (event, page) {
	        console.log('Page ' + page);
	    }
        });
        */
    });

});
