﻿var getGetGalleryImagesUrl = "../Services/GalleryService.asmx/GetGalleryImages";
var validatePromoCodeUrl = "../Services/GalleryService.asmx/VerifyPromoCode";
var selectedIndex = 0;
var thumbnailViewport = 500;
var thumbnailCombinedLength = 0;
var offset = 54;
var currentPhotoSet;
var noImageUrl = '/Shared/images/gallery/NoImage.jpg';

$(document).ready(function () {
    _loadhover();
    try {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    } catch (e) { }

});

function EndRequestHandler(sender, args) {
    showWaitMessage(false, null, ".jqrygallerycontainer");
    showWaitMessage(false, null, ".jqrygalleryimagecontainer");
}


function addingToCart() {
    showWaitMessage(true, "Adding picture to cart...", ".jqrygalleryimagecontainer");
}

function loadGalleryImages(albumId, galleryTitle) {
    showWaitMessage(true, "Loading gallery...", ".jqrygallerycontainer");
    //get the photos
    var jsonObjectArray = new Array();
    jsonObjectArray.push(new dataRequestObject(name = "albumId", value = albumId, dataType = "string"));
    jsonObjectArray.push(new dataRequestObject(name = "googleCompanyName", value = GalleryVars.companyName, dataType = "string"));
    jsonObjectArray.push(new dataRequestObject(name = "username", value = GalleryVars.userName, dataType = "string"));

    try {
        $.ajax({
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            url: getGetGalleryImagesUrl,
            data: buildJSONDataRequest(jsonObjectArray),
            dataType: 'json',
            success: function (result, status) {
                try {
                    //alert("f");
                    //clear out the existing images
                    $(".jqryimagepreviewtable tr").html('');

                    //set the gallery title
                    $(".jqrygallerytitle").html(galleryTitle);
                    $(".jqryhdncurrentgallerytitle").val(galleryTitle);

                    //create the new image rows
                    currentPhotoSet = result.d;
                    var html = parseTemplate($("#gallerytmpl").html(), { data: currentPhotoSet });
                    $(html).appendTo(".jqryimagepreviewtable tr");

                    setupGalleryViewer();

                    //show the slide
                    $("#divGallerylist").slideUp(1000, function () {
                        $("#divMainContainer").slideDown(1000);
                    });
                } catch (e) {
                    showAlert("Unable to load pictures for gallery " + galleryTitle, true, 'jqrygallerycontainer');
                    showGalleryMenu();
                }
                showWaitMessage(false, null, ".jqrygallerycontainer");
            },
            error: function (xhr, textStatus, errorThrown) {
                // typically only one of textStatus or errorThrown 
                // will have info
                showAlert(xhr.responseText, true, 'jqrygallerycontainer');
                showGalleryMenu();
            }

        });
    } catch (e) {
        showAlert(e.message, true, 'jqrygallerycontainer');
        showGalleryMenu();
    }
}


function _loadhover() {
    $(".galleryframe2").hover(
      function () {
          $(this).removeClass("galleryframe2color");
          $(this).addClass("galleryframe2coloron");
      },
      function () {
          $(this).removeClass("galleryframe2coloron");
          $(this).addClass("galleryframe2color");
      }
    );
}

function showGalleryMenu() {
    try {
        $("#divMainContainer").slideUp(1000, function () {
            $("#divGallerylist").slideDown(1000);

            $(".jqryhdncurrentgalleryid").val('');
            $(".jqryhdncurrentslideid").val('');
            $(".jqryhdncurrentslidetitle").val('');
        });
    } catch (e) {
    }
}

function _findPhoto(photoId) {
    var selectPhoto = null;
    //look up image in collection
    for (var i = 0; i < currentPhotoSet.length; i++) {
        if (currentPhotoSet[i].Photo.Id == photoId) {
            selectPhoto = currentPhotoSet[i];
            break;
        }
    }
    return selectPhoto;
}

function _setupNavigationArrows(selectedIndex) {

    if (selectedIndex > 0 && thumbnailCombinedLength > thumbnailViewport) {
        $(".jqryarrowleft").show();
    } else {
        $(".jqryarrowleft").hide();
    }

    if (thumbnailCombinedLength > thumbnailViewport && selectedIndex < currentPhotoSet.length - 1) {
        $(".jqryarrowright").show();
    } else {
        $(".jqryarrowright").hide();
    }
}

function setSelectedImage(cellobj, itemindex, photoId, albumId, photoTitle) {
    try {

        var selectPhoto = _findPhoto(photoId);

        _dimThumbnails();
        $(cellobj).addClass("selected");
        selectedIndex = itemindex;

        _setupNavigationArrows(selectedIndex);

        var cleanPhotoTitle = _cleanPhotoTitle(photoTitle);
        $(".jqrymainimage").fadeOut({ duration: 500, easing: 'easeOutSine', complete: function () {
            $(".jqryloading").show();
            $(".jqrymainimage").attr("src", selectPhoto.Thumbnails[1].Url).load(function () {
                $(".jqryloading").hide();

                //set up lightbox url
                $(".jqryhrefmainimage").attr("href", selectPhoto.Thumbnails[2].Url);
                $(".jqryhrefmainimage").attr("title", cleanPhotoTitle);

                _setAddToCartFields(selectPhoto.Photo.AlbumId, selectPhoto.Photo.Id, selectPhoto.Photo.PhotoTitle);

                $(".jqrymainimage").fadeIn({ duration: 1000, easing: 'easeInOutQuint', complete: function () { } });

            });
        }
        });
    } catch (e) {
        $(".jqrymainimage").attr("src", noImageUrl).load(function () {
            $(".jqryloading").hide();
        });
    }

}

function resetSelectedThumbnail() {
    $(".jqryimagepreviewtable tr td.selected").removeClass('selected');
}

function _dimThumbnails() {
    resetSelectedThumbnail();
    $(".jqryimagepreviewtable tr td").each(function () {
        $(this).opacityrollover();
    });
}


function _cleanPhotoTitle(title) {
    return title.substring(0, title.indexOf("."));
}

function _setAddToCartFields(albumId, slideId, slideTitle) {

    $(".jqryhdncurrentgalleryid").val(albumId);
    $(".jqryhdncurrentslideid").val(slideId);
    $(".jqryhdncurrentslidetitle").val(slideTitle);
}


function setupGalleryViewer() {

    thumbnailCombinedLength = (currentPhotoSet.length * currentPhotoSet[0].Thumbnails[0].Width + (4 * currentPhotoSet.length));
    thumbnailViewport = parseInt($(".jqrypreviewcontainer").css("width"));

    $(".jqryimagepreviewtable tr td").each(function () {
        if ($(this).attr("id") == currentPhotoSet[0].Photo.Id) {
            selectedIndex = 0;
            _setupNavigationArrows(selectedIndex);

            $(this).addClass('selected');

            var cleanPhotoTitle = _cleanPhotoTitle(currentPhotoSet[0].Photo.PhotoTitle);
            $(".jqrymainimage").attr("src", currentPhotoSet[0].Thumbnails[1].Url);
            $(".jqryhrefmainimage").attr("href", currentPhotoSet[0].Thumbnails[2].Url);
            $(".jqryhrefmainimage").attr("title", cleanPhotoTitle);

            _setAddToCartFields(currentPhotoSet[0].Photo.AlbumId, currentPhotoSet[0].Photo.Id, currentPhotoSet[0].Photo.PhotoTitle);


        } else {
            //reset the thumbnails
            $(this).opacityrollover();
        }
    });

    $(".jqryhrefmainimage").fancybox();

}


/*=============================================================================================================*/
/* Thumbnail Navigation */
/*=============================================================================================================*/
function _moveToImage(selectedIndex) {

    var id = currentPhotoSet[selectedIndex].Photo.Id;
    var title = currentPhotoSet[selectedIndex].Photo.PhotoTitle;
    var albumid = currentPhotoSet[selectedIndex].Photo.AlbumId;
    var obj = $(".jqryimagepreviewtable tr td[id=" + id + "]");
    setSelectedImage(obj, selectedIndex, id, albumid, title)
}



function moveLeft(ele) {

    if (selectedIndex > 0) {
        selectedIndex -= 1;
        _moveToImage(selectedIndex);
    }

    var left = parseInt($(".jqryimagepreviewtable").css("left"));
    var imageCountInViewport = parseInt(thumbnailViewport / offset);
    var maxOffsetCount = currentPhotoSet.length - imageCountInViewport;
    var maxScroll = maxOffsetCount * offset * -1;
    // selectedIndex <= maxOffsetCount lets me know its a valid change
    // left < 0 lets me know that we have actually hidden some slides off the screen
    // (selectedIndex * offset *-1) > left lets me know what left is supposed to be for that selected index is in fact bigger than the current left amount. This handles selecting a thumb by picture that is below
    //the threshold of scrollable pics and then using the arrow to go back to the left more and not have the offset skip indexs and rest back to left=0
    if (selectedIndex <= maxOffsetCount && left < 0 && (selectedIndex * offset * -1) > left) {
        $(".jqryimagepreviewtable").css("left", left + offset);
    }


}

function moveRight(ele) {


    if (selectedIndex < currentPhotoSet.length - 1) {
        selectedIndex += 1;
        _moveToImage(selectedIndex);
    }

    var left = parseInt($(".jqryimagepreviewtable").css("left"));
    var imageCountInViewport = parseInt(thumbnailViewport / offset);
    var maxOffsetCount = currentPhotoSet.length - imageCountInViewport;
    var maxScroll = maxOffsetCount * offset * -1;
    if (selectedIndex >= imageCountInViewport && left > maxScroll) {
        $(".jqryimagepreviewtable").css("left", left - offset);
    }

}

