var images;
var currentCategoryId = 0;
var currentSetNumber = 1;
var currentImageIndex = 1;
var firstImageIndex = 0;
var lastImageIndex = 0;
var imageThumbSetSize;
var imageThumbColumns;
var showThumbPrev;
var showThumbNext;

$(document).ready(function () {

    //add thumb nav click events
    $(".imageThumbNext")
        .attr("title", "more images")
        .click(
            function () { imageThumbDisplay(currentSetNumber + 1, false); })
        .hover(
            function () { $(this).addClass("imageThumbNextHover") },
            function () { $(this).removeClass("imageThumbNextHover") });
    $(".imageThumbPrev")
        .attr("title", "previous images")
        .click(
            function () { imageThumbDisplay(currentSetNumber - 1, false); })
        .hover(
            function () { $(this).addClass("imageThumbPrevHover") },
            function () { $(this).removeClass("imageThumbPrevHover") });
    $(".imageSlideShow")
        .click(
            function () { imageSlideShowToggle(); false })
        .hover(
            function () { imageSlideShowMouseover(); },
            function () { imageSlideShowMouseout(); }
            );

    //clicking image shows next image, stop slide show
    $(".image2")
        .click(function () {
            if (imageSlideShowPlay) {
                imageSlideShowToggle();
            } else {
                imageNext();
            }
        });

    //window resize
    $(window).resize(function () {
        imageViewerSize();
    });

    //get categories and images
    artistImageCategoryGet();
    artistImageGet();

    //add mouseover title to images
    $(".image2").attr("title", "click to see next image");

    //add mouseover/mouseout for thumbnail group
    $(".imageThumbSet, .imageThumbContainer, .imageThumbContainerBackground, .imageThumb, .imageThumbFrame, .imageThumbHighlight, .imageThumbNext, .imageThumbPrev")
        .mouseover(function () { thumbSetMouseOver(); });
    $(".imageThumbSet, .imageThumb, .imageThumbFrame, .imageThumbHighlight, .imageThumbNext, .imageThumbPrev")
        .mouseout(function () { thumbSetMouseOver(); });
    $(".imageThumbContainer, .imageThumbContainerBackground")
        .mouseout(function () { thumbSetMouseOut(); });
});

function imageViewerOpen() {
    viewerOpen();
    imageViewerSize();
    $(".imageViewer").fadeIn(500);
}

function imageViewerSize() {
    imageThumbSetSize = parseInt(($(".viewer").width() - 10) / siteSettings.imageThumbSize);
    imageThumbColumns = imageThumbSetSize;
    $(".imageThumbContainer").width($(".viewer").width());
    $(".imageThumbContainerBackground").width($(".viewer").width() + 10);
}

function imageViewerClose() {
    thumbChanging = false;
    if ($(".imageViewer").is(":visible")) $(".imageViewer").fadeOut(500);
}

function artistImageCategoryGet() {
    $.ajax({
        type: "POST",
        url: "default.aspx/artistImageCategoryGet",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            //set array for common use
            categories = result.d;
        },
        error: function (xhr) {
            var sError = eval("(" + xhr.responseText + ")");
            alert("(ajax error)" + sError.Message + sError.StackTrace + sError.StackTrace);
        }
    });
}

function artistImageGet() {
    $.ajax({
        type: "POST",
        url: "default.aspx/artistImageGet",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            //set array for common use
            images = result.d;
        },
        error: function (xhr) {
            var sError = eval("(" + xhr.responseText + ")");
            alert("(ajax error)" + sError.Message + sError.StackTrace + sError.StackTrace);
        }
    });
}

function imageThumbDisplay(setNumber, showFirstImage) {
    //set current set
    currentSetNumber = setNumber;

    //if show first image, clear all image settings
    if (showFirstImage) {
        $(".image1, .image2, .imageBorder")
            .hide()
	        .css("width", "0px")
	        .css("height", "0px")
            .css("top", (($(".viewer").height() - siteSettings.imageThumbSize - 10) / 2) + "px")
            .css("left", $(".viewer").width() / 2 + "px")
	        .css("background-image", "");

        $(".imageTitle").html("");
        $(".imageDesc").html("");
    }

    //clear thumb set
    $(".imageThumbSet").html("").css("margin-left", "0px");
    $(".imageThumbPrev").hide();
    $(".imageThumbNext").hide();
    showThumbNext = false;
    showThumbPrev = false;

    //show thumb background
    overThumbs = true;
    thumbBackgroundShow();

    //loop through images
    var timeDelay = 200;
    var thumbNumber = 0;
    $.each(images, function (index, image) {

        //if image is in category
        if (image.categoryId == currentCategoryId) {
            thumbNumber += 1;

            //get first and last image
            if (thumbNumber == 1) firstImageIndex = index;
            lastImageIndex = index;

            //add thumb
            if (thumbNumber > setNumber * imageThumbSetSize - imageThumbSetSize && thumbNumber <= setNumber * imageThumbSetSize) {
                timeDelay += 100;
                imageThumbAdd(index, timeDelay);
            }

            //show prev button
            if (thumbNumber == setNumber * imageThumbSetSize - imageThumbSetSize) {
                showThumbPrev = true;
                $(".imageThumbPrev")
                    .css("bottom", ((siteSettings.imageThumbSize - $(".imageThumbNext").height() + 10) / 2) + "px")
                    .fadeIn(500);
                $(".imageThumbSet")
                    .css("margin-left", $(".imageThumbNext").width() + "px", timeDelay);
            }
        }
    });

    //show next button
    if (thumbNumber >= setNumber * imageThumbSetSize + 1) {
        showThumbNext = true;
        $(".imageThumbNext")
            .css("left", (imageThumbSetSize * siteSettings.imageThumbSize) + 5 + "px")
            .css("bottom", ((siteSettings.imageThumbSize - $(".imageThumbNext").height() + 10) / 2) + "px")
            .delay(timeDelay)
            .fadeIn(500);
    }

    //show first image
    if (showFirstImage) {
        setTimeout(function () { imageShow(firstImageIndex); }, timeDelay);
    }

    //add mouseover to all thumbs
    $(".imageThumb")
        .hover(
            function () { imageThumbMouseover($(this)); },
            function () { imageThumbMouseout($(this)); });

    //if show first image, pause, then hide thumbnails
    if (showFirstImage) {
        overThumbs = false;
        setTimeout(function () {
            thumbBackgroundHide();
        }, timeDelay + 6000);
    }
}

function imageThumbAdd(index, timeDelay) {
    //add thumb to set
    $(".imageThumbSet")
        .html($(".imageThumbSet").html() +
		    "<div id=\"imageThumbFrame" + index + "\" class=\"imageThumbFrame\"><div id=\"image" + index + "\" class=\"imageThumb\" style=\"background-image:url(" + encodeURIComponent(images[index].thumbFile) + ");\"></div></div>");
    $("#imageThumbFrame" + index)
        .attr("title", images[index].title);

    //hide image;
    $("#image" + index).hide();

    //fadein thumb and add click event
    setTimeout(function () {
        $("#image" + index).fadeIn(500);
        $("#image" + index).click(function () { imageThumbClick(index); });
    }, timeDelay);
}

function imageThumbMouseover(obj) {
    $(obj).stop(true, true).switchClass("imageThumb", "imageThumbHighlight", 200);
}

function imageThumbMouseout(obj) {
    $(obj).stop(true, true).switchClass("imageThumbHighlight", "imageThumb", 200);
}

function imageCategoryThumbMouseover(obj) {
    $(obj).stop(true, true).switchClass("imageCategoryThumb", "imageCategoryThumbHighlight", 200);
}

function imageCategoryThumbMouseout(obj) {
    $(obj).stop(true, true).switchClass("imageCategoryThumbHighlight", "imageCategoryThumb", 200);
}

function imageThumbClick(index) {
    if (imageSlideShowPlay) imageSlideShowToggle();
    imageShow(index)
}

var imageChanging = false;
function imageShow(index) {
    //do not do if image is currently changing
    if (imageChanging) return;

    //highlight thumb
    $.each(images, function (index, image) {
        if ($("#image" + index).hasClass("imageThumbSelectedHighlight")) {
            $("#image" + index).stop(true, true).switchClass("imageThumbSelectedHighlight", "imageThumb", 200);
        }
    });
    $("#image" + index).stop(true, true).switchClass("imageThumb", "imageThumbSelectedHighlight", 200);

    //add this image (and next) to cache
    $(".imageCache").html("<img id=\"img" + index + "\" class=\"imageCacheImage\" src=\"" + images[index].file + "\" />" +
        "<img id=\"img" + nextImageIndex() + "\" class=\"imageCacheImage\" src=\"" + images[nextImageIndex()].file + "\" />");

    //wait until image is loaded in cache
    $("#img" + index).load(function () {
        //set image info
        currentImageIndex = index;

        //get image size
        $(".imageCache").show(); //will not work in IE if cache is hidden
        var imageWidth = this.width;
        var imageHeight = this.height;
        $(".imageCache").hide();

        //lock image changing
        imageChanging = true;
        setTimeout(function () { imageChanging = false }, 500);

        //get sizes (default slideshow)
        var thumbHeight = $(".imageThumbContainer").height();
        var viewerHeight = $(".viewer").height();
        var viewerWidth = $(".viewer").width();
        var imageTop = ((viewerHeight - imageHeight) / 2) + 4;
        var imageLeft = (viewerWidth - imageWidth) * (2 / 5);

        //set oversizes
        if (imageHeight > viewerHeight - 22) {
            imageHeight = viewerHeight - 22;
            imageTop = 14;
        }

        //display image detail
        $(".imageTitle")
            .hide()
            .html(images[index].title)
            .fadeIn(500);
        $(".imageDesc")
            .hide()
            .html(images[index].description)
            .fadeIn(500);
        $(".imageDetail")
            .show()
            .height(viewerHeight - 22)
            .animate({
                top: 14,
                width: viewerWidth - imageWidth - imageLeft - 40
            }, 500);

        //image2 (front), hide, set size and background, then fade in
        $(".image2")
            .hide()
	        .css("width", imageWidth)
	        .css("height", imageHeight)
            .css("top", imageTop + "px")
            .css("left", imageLeft + "px")
	        .css("background-image", "url(" + encodeURIComponent(images[index].file) + ")")
	        .fadeIn(500);

        //image1 (back), set size
        $(".image1")
            .show()
            .animate({
                width: imageWidth,
                height: imageHeight,
                top: imageTop,
                left: imageLeft
            }, 500);
        //then change background after image2 fades in
        setTimeout(function () {
            $(".image1").css("background-image", "url(" + encodeURIComponent(images[index].file) + ")");
        }, 500);

        //image border, set size
        $(".imageBorder")
            .hide()
	        .css("width", imageWidth + siteSettings.imageBorderWidth * 2)
	        .css("height", imageHeight + siteSettings.imageBorderWidth * 2)
            .css("top", imageTop - siteSettings.imageBorderWidth - 1 + "px")
            .css("left", imageLeft - siteSettings.imageBorderWidth - 1 + "px")
            .fadeIn(500);
    })
}

function imageCategoryDisplay(pageTitle) {
    var timeDelay = 0;
    var prevParentCategory = "";
    var menuHtml = "";
    var groupCount = 0

    menuHtml += "<div class=\"imageCategoryGroup\">";

    //loop through categories
    $.each(categories, function (index, category) {
        //count categories
        groupCount += 1;

        //add parent
        if (category.parentName != prevParentCategory) {
            if (index > 1) menuHtml += "</div><div class=\"imageCategoryGroup\">";
            menuHtml += "<div class=\"imageCategoryGroupTitle\">" + category.parentName + "</div>";
        }

        //add category
        menuHtml +=
			"<div id=\"divImageCategory" + index + "\" class=\"imageCategory\"><span>" + category.title +
			"</span><div class=\"imageCategoryThumb\" style=\"background:url(" + encodeURIComponent(category.thumbFile) + ");\"></div></div>";

        prevParentCategory = category.parentName;
    });

    menuHtml += "</div>";

    //insert menu into content
    contentAdd(pageTitle, menuHtml, null, null, null, null);

    //set height and width of content
    var groupRows =
        parseInt(
            parseInt($(".contentWindow").css("width").replace("px", "")) /
            (parseInt($(".imageCategory").css("margin-right").replace("px", "")) +
            parseInt($(".imageCategory").css("width").replace("px", "")))
        );

    $(".contentColumn1")
        .css("width", $(".contentWindow").css("width"))
        .css("height",
            Math.round(groupCount / groupRows) * (
            parseInt($(".imageCategory").css("height").replace("px", "")) +
            parseInt($(".imageCategory").css("margin-bottom").replace("px", ""))
            ) + "px");

    //hide categories
    $(".imageCategory").hide();

    //fadein and add click event to categories
    $.each(categories, function (index, category) {
        timeDelay += 200;
        setTimeout(function () {
            $("#divImageCategory" + index).fadeIn(500);
            $("#divImageCategory" + index).click(function () { imageCategoryClick(category); });
        }, timeDelay);
    });

    //add mouseover to all category thumbs
    $(".imageCategoryThumb")
        .hover(
            function () { imageCategoryThumbMouseover($(this)); },
            function () { imageCategoryThumbMouseout($(this)); });
}

function imageCategoryClick(category) {
    imageViewerOpen();
    $(".imageCategoryTitle").html(category.title);
    currentCategoryId = category.id;

    //display thumbnails
    imageThumbDisplay(1, true);
}

var imageSlideShowPlay = false;
function imageSlideShowToggle() {
    $(".imageSlideShow").hide();

    if (imageSlideShowPlay) {
        imageSlideShowPlay = false;
        $(".imageSlideShow")
            .attr("title", "start slide show")
            .removeClass("imageSlideShowHover")
            .removeClass("imageSlideShowStop")
            .removeClass("imageSlideShowStopHover");
    } else {
        imageSlideShowPlay = true;
        imageSlideShow();
        $(".imageSlideShow")
            .attr("title", "stop slide show")
            .addClass("imageSlideShowStop");
    }

    $(".imageSlideShow").fadeIn(500);
}

function imageSlideShowMouseover() {
    if (imageSlideShowPlay) {
        $(".imageSlideShow").addClass("imageSlideShowStopHover");
    } else {
        $(".imageSlideShow").addClass("imageSlideShowHover");
    }
}

function imageSlideShowMouseout() {
    if (imageSlideShowPlay) {
        $(".imageSlideShow").removeClass("imageSlideShowStopHover");
    } else {
        $(".imageSlideShow").removeClass("imageSlideShowHover");
    }
}

function imageSlideShow() {
    if (imageSlideShowPlay) {
        //show next thumb
        imageNext();

        //continue slide show
        setTimeout(function () {
            imageSlideShow();
        }, 5000);
    }
}

function nextImageIndex() {
    var index = parseInt(currentImageIndex) + 1
    if (index > lastImageIndex) index = firstImageIndex;
    return index;
}

function imageNext() {
    //do not do if image is currently changing
    if (imageChanging) return;

    //if needed, go to next/first thumb set
    var timeDelay = 0;
    if ($(".imageViewer").is(":visible")) {
        if (nextImageIndex() >= firstImageIndex + (imageThumbColumns * currentSetNumber)) {
            $(".imageThumbNext").click();
            timeDelay = 500;
        } else if (nextImageIndex() == firstImageIndex && $(".imageThumbNext").is(":visible")) {
            imageThumbDisplay(1);
            timeDelay = 500;
        }
    }

    //show image
    setTimeout(function () {
        imageShow(nextImageIndex());
    }, timeDelay);
}

function contentSlideShow(categoryId) {

    //set current category and image
    currentCategoryId = categoryId;
    currentImageIndex = 0;

    //show content slide show
    $(".contentSlideShow").show();

    //loop through images
    var thumbNumber = 0;
    $.each(images, function (index, image) {

        //if image is in category
        if (image.categoryId == currentCategoryId) {
            thumbNumber += 1;

            //get first and last image
            if (thumbNumber == 1) firstImageIndex = index;
            lastImageIndex = index;
        }
    });

    //start slide show
    imageSlideShowToggle();
}

var overThumbs = false;
function thumbSetMouseOver() {
    overThumbs = true;
    thumbBackgroundShow();
}

function thumbSetMouseOut() {
    overThumbs = false;
    setTimeout(function () {
        thumbBackgroundHide();
    }, 2000);
}

var thumbTransition = false;
function thumbBackgroundShow() {
    //if already in transition, stop
    if (thumbTransition) return;

    //if not over thumbnails, stop
    if (!overThumbs) return;

    //if already showing, stop
    if ($(".imageThumbSet").is(":visible") && $(".imageThumbContainerBackground").is(":visible")) return;

    //set transition to block other actions
    thumbTransition = true;
    setTimeout(function () { thumbTransition = false }, 1000);

    //show thumbs
    $(".imageThumbContainerBackground")
        .show()
        .animate({
            height: (imageThumbSetSize * siteSettings.imageThumbSize / imageThumbColumns) + 10
        }, 500);
    $(".imageThumbSet").delay(500).fadeIn(500);
    if (showThumbNext) $(".imageThumbNext").delay(250).fadeIn(250);
    if (showThumbPrev) $(".imageThumbPrev").delay(250).fadeIn(250);
}

function thumbBackgroundHide() {
    //if already in transition, stop
    if (thumbTransition) return;

    //if already not showing, stop
    if (!$(".imageThumbSet").is(":visible")) return;

    //if over thumbnails, stop
    if (overThumbs) return;

    //set transition to block other actions
    thumbTransition = true;
    setTimeout(function () { thumbTransition = false }, 1000);

    //set container size for mousever
    $(".imageThumbContainer").height($(".imageThumbContainer").height());
    $(".imageThumbContainer").width($(".imageThumbContainer").width());

    //hide thumbs
    $(".imageThumbContainerBackground")
        .delay(250)
        .animate({ height: 0 }, 500);
    $(".imageThumbSet, .imageThumbNext, .imageThumbPrev")
        .fadeOut(500);
}

//var thumbChanging = false;
//function thumbChangeDisplay() {
//    if (!thumbChanging) return;

//    //change thumb display
//    if (overThumbs) {
//        thumbBackgroundShow();
//    } else {
//        thumbBackgroundHide();
//    }

//    //run again
//    if ($(".imageViewer").is(":visible")) {
//        setTimeout(function () {
//            thumbChangeDisplay()
//        }, 600);
//    }
//}

