var photoCache= new Array();
var photoShown= new Array();
var intCurLeft = 0;
var intCurRight = 1;
var curButtonsDivTop = 0;
var curButtonsDivLeft = 0;
var curSpreadDivTop = 0;
var curSpreadDivLeft = 0;
var buttonsDiv = null;
var preLoadPhotos = 4;
var activeDivName = "";
var imgLoading = "images/loading.jpg";
var imgBlank = "images/blank.jpg";
var imgError = "images/error.gif";
var imgDummy = "images/0x0.jpg";
var curNavDiv = 'CoverNavigationDiv';
var curSrcDiv = 'CoverSrcDiv';
var originalWidth = 0;
var originalHeight = 0;

$(document).ready(function() {
                                originalWidth = (pagesPerContent > 1) ? $('#photoLeft').width() : $('#photoPrint').width();
                                originalHeight = (pagesPerContent > 1) ? $('#photoLeft').height() : $('#photoPrint').height();
                                });

// Disable landing page
var timer = null;
var bDHTML = (document.getElementById || document.all || document.layers);

function IsNotRealPicture(objectClicked) {
    return (objectClicked.indexOf("ViewImage") == -1 && (objectClicked.indexOf(imgBlank) != -1 || objectClicked.indexOf(imgLoading) != -1 || objectClicked.indexOf(insideBackCoverImage) || objectClicked.indexOf(insideFrontCoverImage) != -1)) ? 1 : 0; 
}

function ShowDiv(mode) {
    switch (mode) {
        case 0:
            intCurLeft = 0;
            intCurRight = 1;

            if (!showFrontCover) { ShowDiv(1); ShowPhoto(0); return; }
            if (pageCount > 1) $('#' + curNavDiv).fadeOut("slow", function () { $('#CoverNavigationDiv').fadeIn("slow"); });
            $('#' + curSrcDiv).fadeOut("slow", function () { $('#CoverSrcDiv').fadeIn("slow") });
            curNavDiv = 'CoverNavigationDiv';
            curSrcDiv = 'CoverSrcDiv';
            if (pageCount <= 1) {
                $('#ProjectFooterDiv').css('margin-top', '15px');
            }
            break;
        case 1:
            $('#' + curNavDiv).fadeOut("slow", function () { $('#' + mainNavigationDiv).fadeIn("slow"); });
            $('#' + curSrcDiv).fadeOut("slow", function () { $('#' + mainContentDiv).fadeIn("slow") });
            curNavDiv = mainNavigationDiv;
            curSrcDiv = mainContentDiv;

            break;
        case 2:
            $('#' + curNavDiv).fadeOut("slow", function() {$('#BackNavigationDiv').fadeIn("slow");});
            $('#' + curSrcDiv).fadeOut("slow", function() {$('#BackSrcDiv').fadeIn("slow")});
            curNavDiv = 'BackNavigationDiv';
            curSrcDiv = 'BackSrcDiv';
            break;
    }
    
}

function HideZoom()
{
    activeDivName = "";
    $.unblockUI();
}

function ZoomPicture(objectClicked) {
    activeDivName = "#ZoomPictureDiv";
	if (IsNotRealPicture(objectClicked.src) == 1) return;
	$('#zoomPicture').attr('src', objectClicked.src);
    $.blockUI({message: $('#ZoomPictureDiv'),
                            css: {cursor: 'auto'}
              });
}

function ZoomPictureByID(idClicked) {
    activeDivName = "#ZoomPictureDiv";
    if (IsNotRealPicture($(idClicked).attr('src')) == 1) return;
    $('#zoomPicture').attr('src', $(idClicked).attr('src'));

    $('#zoomPicture').load(function () {
        var imageWidth = $('#zoomPicture').attr("naturalWidth");
        if (typeof imageWidth == "undefined") imageWidth = $('#zoomPicture').attr('width');
        var imageHeight = $('#zoomPicture').attr("naturalHeight");
        if (typeof imageHeight == "undefined") imageHeight = $('#zoomPicture').attr('height');

        $('#ZoomPictureDiv').width(imageWidth);
        $('#ZoomPictureDiv').height(imageHeight);
        //$('#ZoomPictureDiv').css('margin-left', ($('#zoomPicture').attr("naturalWidth")/-2.0));

        var leftMove = $('#zoomPicture').attr("naturalWidth") * 1.0;
        if (leftMove > $(window).width())
            leftMove = "-50%";
        else
            leftMove = leftMove / (-2.0);

        $.blockUI.defaults.css = {};
        $.blockUI({ message: $('#ZoomPictureDiv'),
            centerY: false,
            centerX: false,
            css: { cursor: 'auto', top: '0px', left: '50%', position: 'absolute', width: imageWidth, border: 'none', height: 'auto', 'margin-left': leftMove }
        });
    });

}

function GetPhoto(ind, preLoad)
{
    if (ind<0 || ind > pageCount || preLoad < 0) return;
    
    var imageID = ((ind%2) == 0) ? '#photoLeftA' : '#photoRightA';
    
    LoadImage(imageID, ind, function() { GetPhoto(ind+1, preLoad-1); });
    
//    $.ajax({
//         url: 'photoList[ind]',
//          success: function () {
//			photoCache[ind]= new Image();
//			photoCache[ind].src = photoList[ind];
//            GetPhoto(ind+1, preLoad-1);
//          },
//          error: function () {
//			photoCache[ind]= new Image();
//			photoCache[ind].src = imgError;
//            GetPhoto(ind, preLoad);
//          }
//        });  
}


function LoadImage(pSelector, srcIndex, pCallback)
{
    var loader = $(pSelector);
    LoadThisImage(loader, srcIndex, pCallback);
}


function LoadThisImage(loader, srcIndex, pCallback)
{
//    image_src = loader.attr('src');
    var src = photoList[srcIndex];

    $(loader).fadeTo("slow", 0.30,
                    function () {
                        $(loader).attr('src', imgLoading);
                        $(loader).fadeTo("slow", 1,
                                                function () {
                                                    var img = new Image();
                                                    // image onload
                                                    $(img).load(function () {
                                                        photoCache[srcIndex] = new Image();
                                                        photoCache[srcIndex].src = photoList[srcIndex];
                                                        if (photoList[intCurLeft] == src || photoList[intCurRight] == src) {
                                                            $(loader).fadeTo("slow", 0.10,
                                                                                function () {
//                                                                                    $(loader).attr('width', wellWidth);
//                                                                                    $(loader).attr('height', wellHeight);
                                                                                    $(loader).attr('src', src);
                                                                                    $(loader).fadeTo("slow", 1, function () { SetImageSize(); });
                                                                                });
                                                        }
                                                    }).error(function () { $(loader).attr('src', imgError); }).attr('src', src);
                                                });
                    });
}

function ShowPhoto(curPhoto) {

    if (pagesPerContent > 1) {
        ShowSinglePhoto(curPhoto, "photoLeft", "pageNumberLeft");
        ShowSinglePhoto(curPhoto + 1, "photoRight", "pageNumberRight");
    } else {
        ShowSinglePhoto(curPhoto, "photoPrint", "printPageNumber");
        SetImageSize();
        $('#photoPrint').attr('style', '-moz-box-shadow: 3px 3px 4px #000;-webkit-box-shadow: 3px 3px 4px #000;box-shadow: 3px 3px 4px #000;-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color=\'#000000\')";	filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color=\'#000000\');');
    }
}

function SetImageSize() {
    if (pagesPerContent > 1) return;

    var imageWidth = $('#photoPrint').attr("naturalWidth");
    if (typeof imageWidth == "undefined") imageWidth = $('#photoPrint').attr('width');
    var imageHeight = $('#photoPrint').attr("naturalHeight");
    if (typeof imageHeight == "undefined") imageHeight = $('#photoPrint').attr('height');
    var aspectRatio = imageHeight / imageWidth;
    var newWidth = 0;
    var newHeight = 0;

    if (aspectRatio > 1) {
        $('#PrintSrcDiv').width(400 / aspectRatio + 10);
        $('#PrintSrcDiv').height(410);
        $('#photoPrint').width(400 / aspectRatio);
        $('#photoPrint').height(400);
    } else {
        $('#PrintSrcDiv').height(400 * aspectRatio + 10);
        $('#PrintSrcDiv').width(410);
        $('#photoPrint').width(400);
        $('#photoPrint').height(400 * aspectRatio);
    }
    //alert(imageHeight + ' ' + originalHeight + ' ' + $('#photoPrint').height());
}

function ShowPageNumber(pageNumberName, curPhoto)
{    
    var nPageNumber = curPhoto;

    $('#' + pageNumberName).html("<font class=\"orderLabelRow\">" + (((nPageNumber == 0 && showFrontCover) || curPhoto > pageCount) ? " " : nPageNumber) + "</font>");
}

function ShowSinglePhoto(curPhoto, imgName, pageNumberName)
{
//	if (curPhoto != intCurLeft && intCurRight != curPhoto) {
//	    return;
//	}

    // Get photo img element from html 
    var olObject = document.getElementById(imgName);
    $('#' + imgName).stop();
	ShowPageNumber(pageNumberName, curPhoto);
	// Image is already being shown
	if (olObject.src == photoList[curPhoto]) return;

    // Not a valid page, show a blank one
    if (curPhoto > pageCount) {
        $('#' + imgName).attr('src', insideBackCoverImage);
        return;
    }

    // Image is not cached. Load it and show a loading gif in the meantime
    if (!photoCache[curPhoto]) {
        LoadThisImage(((pagesPerContent > 1) ? '#' + imgName : '#photoPrint'), curPhoto);
		return;
	}

    
//	if (photoCache[curPhoto] && photoCache[curPhoto].src.slice(-1*imgError.length) == imgError) {
//		ShowPageNumber(pageNumberName, curPhoto);
//        LoadThisImage('#' + imgName, curPhoto);
//		return;
//	}

	photoShown[curPhoto] = 1;

	olObject.photoIndex = curPhoto;
	
	var loader = '#' + imgName;
	$(loader).fadeTo("slow", 0.30,
                    function () {
                        $(loader).attr('src', photoList[curPhoto]);
                        $(loader).fadeTo("slow", 1, function () { SetImageSize(); });
                    });	
//    $(loader)
//        .fadeTo("slow", 0.30)
//        .attr('src', photoList[curPhoto])
//        .fadeOut(20000);

    
}

function SetPreview(page) {
  ShowDiv(1);
  intCurLeft = page;
  intCurRight = page+1;
  ShowPhoto(page);
}

function ViewAgain()
{
  
     GetPhoto(0, preLoadPhotos);
	 ShowPhoto(0);
  
}

function NextPhoto() {
	photoShown[intCurLeft] = 0;
	photoShown[intCurRight] = 0;

	intCurLeft += pagesPerContent;
	intCurRight = intCurLeft + 1;

	if ((pagesPerContent == 1 && intCurLeft >= pageCount) || (intCurLeft > pageCount)) {
	    ShowDiv((showBackCover) ? 2 : 0);
		return;
	}

	ShowPhoto(intCurLeft);
}

function PrevPhoto()
{
	photoShown[intCurLeft] = 0;
	photoShown[intCurRight] = 0;

	intCurLeft -= 2;
	
	if (intCurLeft< 0) {
	    ShowDiv(0);
	    return;
	}
	
//	intCurLeft = pageCount - ((pageCount % 2 == 0) ? 2 : 1);
    intCurRight = intCurLeft + 1;

    ShowPhoto(intCurLeft);
}

function FlipPage(evt)
{
	evt = (evt) ? evt : ((window.event) ? window.event : "");
	var x = (evt.pageX) ? evt.pageX : ((evt.x) ? evt.x : 228);
	if (x > 227) {
		nextPhoto();
	} else {
		prevPhoto();
	}
}

function ChangeButtonAppearance(button, imgName)
{
	button.src= imgName;
}

var prevScroll = 0;

$(window).scroll(function () { 
    if (activeDivName == "") {
        prevScroll = 0;
        return;
    }

    var menuYloc = null;

    var position = $(activeDivName).position();
    menuYloc = position.top;
    var mainPosition = $('#ProjectContentDiv').position();

    if ($(document).scrollTop() > prevScroll) {
	    offset = menuYloc-$(document).scrollTop()+"px";
    } else {
        if ($(document).scrollTop() <= 0)
            offset = "0px";
        else
	        offset = menuYloc+$(document).scrollTop()+"px";
    }
    
    prevScroll = $(document).scrollTop();
	$(activeDivName).animate({top:offset},{duration:100,queue:false});
});


