$(document).ready(loadData);

/*Loading XML file*/
function loadData() {
    $.ajax({
        type: "GET",
        url: "data/data.xml",
        dataType: "xml",
        success: parseData
    });
}

/* Declaring Global Variables */
var galleryItems = [];  //Array that contains the elements from our gallery
var startItem = 0;  //the start item
var activePageIndex = 1;    //the page that we are at
var itemsPerPage = 12;  //number of items shown on one page
var itemActiveIndex = null; 
var galleryMode = "paging"; // paging | slide
var pages; //number of gallery pages

/* Parsing the loaded XML file */
function parseData(xmldata) {
    //reversing the order of gallery items
    galleryItems = $($.makeArray($(xmldata).find("Item[id]")).reverse());

    goToPage(activePageIndex); //setting the start page
    
    //when clicked on Slideshow Image -> move to the next Gallery Image
    $("#imageHolder").click(function() {goNext();})
   
    //appending keydown events on the document
    $(document).keydown(function(event) {
        /*
        If the component is in Paging Mode -> the L & R arrows of the keyboard manipulate gallery pages
        In Slide Mode -> they move to Next and Previous Gallery elements
        ESC key is enabled only in Slide Mode
        */
        //the key is Next Arrow
        if (event.keyCode == '39' || event.keyCode == '54') {
            if (galleryMode == "paging") {
                var targetPage = (activePageIndex + 1) > pages ? 1 : (activePageIndex + 1);
                goToPage(targetPage);
            }
            else if (galleryMode == "slide") {
                goNext();
            }
        }
        // the key is Prev Arrow
        else if (event.keyCode == '37' || event.keyCode == '52') {
            if (galleryMode == "paging") {

                var targetPage = (activePageIndex - 1) < 1 ? pages : (activePageIndex - 1);
                goToPage(targetPage);

            }
            else if (galleryMode == "slide") {
                goPrev();
            }
        }
        //the key is ESC & it changes Slide Mode with Paging Mode
        else if (event.keyCode == '27' && galleryMode == "slide") {
            endSlideShow();
        }
    });

}

/* Dividing the Gallery into pages from 12 elements */
function goToPage(pageIndex) {
    activePageIndex = pageIndex;    //setting the pageIndex
    $("#ul_gallery").empty();   //empty the container from elements
    buildPager($(galleryItems).length, pageIndex);  //building the pager
    startItem = ((pageIndex) * itemsPerPage) - itemsPerPage;    //finding the start item

    // Slicing 12 elements from the gallery and appending them into the container
    $(galleryItems).slice(startItem, startItem + itemsPerPage).each(
            function(i, o) {
                var priceValue = ($(this).attr("price"))?$(this).attr("price") + currencyCode:"";
                $("#ul_gallery").append("<li><a href=\"javascript:void(0);\" onclick=\"openSlideShow(" + (i + startItem) + "); \"><img src=\"images/" + $(this).attr("id") + "thumb.jpg\" alt=\"\" width=\"111\" height=\"72\" /></a><div>" + priceValue + "</div></li>");
            }
        );
    $("#ul_gallery li:first-child a:first-child").focus();  //setting the focus on the first element of every page
}

/* Creating the pager and appending it to the document */
/*  << < 1 2 -3- 4 5 6 7 8 9  > >>  */
function buildPager(total, pageIndex) {

    $("#pager").empty(); //emptying the pager container
    /*calculate the remainder from the division between all elements 
    and the number of elements shown on a single page*/
    var modN = (total % itemsPerPage); 
    pages = parseInt((total / itemsPerPage)) +  ( modN > 0?1:0 ); //calculating the number of gallery pages

	/* Staring the Pager Creation */
	
	//Left Part: << <
	if(pageIndex > 1 ){
	    $("#pager").append("<li><a class=\"pn\" href=\"javascript:goToPage(1);void(0);\">&laquo;</a></li>");
	    $("#pager").append("<li><a class=\"pn\" href=\"javascript:goToPage(" + (pageIndex - 1) + ");void(0);\">&lsaquo;</a></li>");
	}
    
    //Center part: 1 2 3 ... n
	for(var i=1; i<=pages; i++){
		if(pageIndex == i){
			$("#pager").append("<li class=\"active\">" +i+ "</li>");
		} else {
			$("#pager").append("<li><a href=\"javascript:goToPage(" + i + ");void(0);\">" +i+ "</a></li>");
		}		
	}
	
	//Right Part: > >>
	if(pageIndex < pages ){
	    $("#pager").append("<li><a class=\"pn\" href=\"javascript:goToPage(" + (pageIndex + 1) + ");void(0);\">&rsaquo;</a></li>");

	    $("#pager").append("<li><a class=\"pn\" href=\"javascript:goToPage(" + pages + ");void(0);\">&raquo;</a></li>");
	}
}

/* Starting the Slideshow */
function openSlideShow(itemIndex) {

    galleryMode = "slide";//defining the gallery mode -> slide | paging
    itemActiveIndex = itemIndex;//setting the value of itemIndex
    galleryItem = galleryItems[itemIndex];//which item to visualize in the slideshow
    
    /* Loading the Slideshow Image */
    $("#itemImage").hide();//hidding the old image
    $("#itemImage").attr("src", "images/" + ($(galleryItem).attr("id")) + ".jpg");//loading the new image
    $("#itemImage").load(function() { $(this).show(); }); //showing the loaded data
    //displaying the Number of the present Image
    $("#number").text("No." + " " + ($(galleryItem).attr("id"))); 
    //displaying the price of the present Image
    $("#price").text(($(galleryItem).attr("price")) ? $(galleryItem).attr("price") + currencyCode : "");
   
   /* Showing the Slideshow into the document*/
    $("#slideShow").show();
}

/* Going to the Previous Slideshow Element */
function goPrev() {
    //decreasing the active GalleryItem Index
    itemActiveIndex--;
     
    if (itemActiveIndex < 0) {
        itemActiveIndex = $(galleryItems).length - 1;
    }


    if (!((itemActiveIndex >= startItem) && (itemActiveIndex <= startItem + itemsPerPage-1))) {
       goToPage(parseInt(itemActiveIndex / itemsPerPage) + 1);
    }
    //visualizing the changes in the Slideshow
    openSlideShow(itemActiveIndex);
}

/* Going to the Next Slideshow Element */
function goNext() {
    //increasing the active GalleryItem Index
    itemActiveIndex++;
    
    if (itemActiveIndex == $(galleryItems).length) {
        itemActiveIndex = 0;
    }

    if (!((itemActiveIndex >= startItem) && (itemActiveIndex <= startItem + itemsPerPage-1))) {
       goToPage(parseInt(itemActiveIndex / itemsPerPage) + 1);
    }
    //visualizing the changes in the Slideshow
    openSlideShow(itemActiveIndex);
}

// End the slideshow 
function endSlideShow() {
    $("#slideShow").hide(); //closing the Slideshow
    galleryMode = "paging"; //switching to Paging GalleryMode
}
