﻿var logs="";
var isReady = false;
var hasDebugLogDiv = true;
function debugLog(message) {
    if (window.console != null) {
        window.console.log(message);
    }
    if (hasDebugLogDiv) {
        if (!isReady) {
            logs = logs + message + "<br/>";
        }
        else {

            $("#debugText").before(message + "<br/>").appendTo($("#DivDebugLog"));
        }
    }

}
$(document).ready(function () {
    isReady = true;
    hasDebugLogDiv = ($("#debugText").length == 1);
    if (hasDebugLogDiv) {
        debugLog(logs);
    }
    logs = null;
});

function Board(){
    this.scale = 1;
    this.layoutBoard = function () {
        var board = $("#boardRoot");

        var w = board.width();
        var h = board.height();
        var actualWidth = $(window).width();
        var actualHeight = $(window).height();
        actualHeight -= 30; //toolbar

        var r = w / actualWidth;
        var r2 = h / actualHeight;
        var dx;
        var dy;
        if (r2 > r) {
            r = 1 / r2;
            dy = 0;

            dx = ((actualWidth - (w * r)) / 2) / r;


        }
        else {
            r = 1 / r;
            dx = 0;
            dy = ((actualHeight - (h * r)) / 2) / r;
        }
        dy -= 30; //toolbar
        if (dy < 0) dy = 0;
        scale = r;

        var transform =
    "translate(-" + (w / 2) + "px,-" + (h / 2) + "px) " +
        "scale(" + r + ", " + r + ") " +
            "translate(" + ((w / 2) + dx) + "px," + ((h / 2) + dy) + "px)";

        cssSandpaper.setTransform(board.get(0), transform);

        FixImageSize($("#pageBackground").get(0), false, 0, null);

    };
};


//wire up the root board
var board = new Board();
$(window).resize(board.layoutBoard);
$(document).ready(board.layoutBoard);


//---- utility

// Image scaling - begin
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {

    var result = { width: 0, height: 0, fScaleToTargetWidth: true };

    if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
        return result;
    }

    // scale to the target width
    var scaleX1 = targetwidth;
    var scaleY1 = (srcheight * targetwidth) / srcwidth;

    // scale to the target height
    var scaleX2 = (srcwidth * targetheight) / srcheight;
    var scaleY2 = targetheight;

    // now figure out which one we should use
    var fScaleOnWidth = (scaleX2 > targetwidth);
    if (fScaleOnWidth) {
        fScaleOnWidth = fLetterBox;
    }
    else {
        fScaleOnWidth = !fLetterBox;
    }

    if (fScaleOnWidth) {
        result.width = Math.floor(scaleX1);
        result.height = Math.floor(scaleY1);
        result.fScaleToTargetWidth = true;
    }
    else {
        result.width = Math.floor(scaleX2);
        result.height = Math.floor(scaleY2);
        result.fScaleToTargetWidth = false;
    }
    result.targetleft = Math.floor((targetwidth - result.width) / 2);
    result.targettop = Math.floor((targetheight - result.height) / 2);

    return result;
}

function OnImageLoad2(evt, uniform, margin, hostDiv) {
    var img = evt.currentTarget;
    FixImageSize(img, uniform, margin, hostDiv);
}

function OnImageLoad(evt, uniform, margin) {
    var img = evt.currentTarget;
    FixImageSize(img, uniform, margin, null);

}

function FixImageSize(img, uniform, margin, hostDiv) {
    // what's the size of this image and it's parent
    var w = $(img).get(0).naturalWidth; //.width();
    var h = $(img).get(0).naturalHeight; //.height();
    
    if(w==0 && h==0) {
        $(img).load(function () { FixImageSize(img, uniform, margin, hostDiv) });
        return;
        //debugLog("0 height image");
    }
   
    var tw = $(img).parent().width() - margin * 2;
    var th = $(img).parent().height() - margin * 2;
    // compute the new size and offsets
    var result = ScaleImage(w, h, tw, th, uniform);

    // adjust the image coordinates and size
    img.width = result.width;
    img.height = result.height;
    if (hostDiv != null) {
        $(hostDiv).css("width", result.width);
        $(hostDiv).css("height", result.height);
        $(hostDiv).css("left", result.targetleft + margin);
        $(hostDiv).css("top", result.targettop + margin);
    }
    else {
        $(img).css("left", result.targetleft + margin);
        $(img).css("top", result.targettop + margin);

    }

}

//function DoImageReizes() {
//    $(".imgResize").each(function (idx) { FixImageSize(this, false, 0, null); });
//}
//$(document).ready(DoImageReizes);

function CenterTarget(target, bH, bV) {
    if (bV) {
        var h = $(target).height();
        var th = $(target).parent().height();
        var voffset = (th - h) / 2;
        $(target).css("top", voffset);
        $(target).css("height", h);
    }
    if (bH) {
        var w = $(target).width();
        var tw = $(target).parent().width();
        var hoffset = (tw - w) / 2;
        $(target).css("left", hoffset);
        $(target).css("width", w);
    }
}
// Image scaling - end


//board rotator start

(function ($) {
    $.fn.brdRotator = function (options) {
        var opts = $.extend({}, $.fn.brdRotator.defaults, options);

        var selectedClass = opts.slideSelectedCLass.substring(1);
        var curIdx = 0;
        var timer;

        var target = this;
        var elSlideContainer = this.find(opts.slidesClass);
        var slides = elSlideContainer.children(opts.slideClass);
        var mxSlides = slides.length;

        var elPrev = this.find(opts.prev);
        var elNext = this.find(opts.next);

        var animateSlide = function (dur, i) {
            elSlideContainer.children().css({
                overflow: "hidden"
            });

            elSlideContainer.animate({
                marginLeft: "-" + (i * elSlideContainer.find(":first-child").width() + "px")
            },
                opts.duration * (dur),
                opts.easing,
                function () {
                    elSlideContainer.children().css({
                        overflow: "hidden"
                    });
                }
			);

        };

        slides.each(function (i) {
            $(this).click(function () {
                setTimer();
                if (elSlideContainer.is(":not(:animated)")) {
                    slides.removeClass(selectedClass);
                    $(this).addClass(selectedClass);
                    var dur = Math.abs(curIdx - i);
                    animateSlide(dur, i);
                    curIdx = i;
                }
            });

        });

        var elWrapper = opts.slideWrapper;
       
        elSlideContainer.before('<div class="' + opts.slideWrapper.substring(1) + '"></div>').appendTo(elWrapper);
        elWrapper = this.find(opts.slideWrapper);

        slides.eq(curIdx).addClass(selectedClass);

        var scale = function (w, h, actualWidth, actualHeight,margin) {
            var result = { scale: 0, dx: 0, dy: 0, transform: "" };
            var r = w / (actualWidth - (margin * 2));
            var r2 = h / (actualHeight - (margin * 2));
            var dx;
            var dy;
            if (r2 > r) {
                r = 1 / r2;
            }
            else {
                r = 1 / r;
            }
            dx = ((actualWidth - (w * r)) / 2) / r;
            dy = ((actualHeight - (h * r)) / 2) / r;
          
           
            result.scale = r;
            result.dx = dx;
            result.dy = dy;
            
            result.transform =
                "translate(-" + (w / 2) + "px,-" + (h / 2) + "px) " +
                    "scale(" + r + ", " + r + ") " +
                        "translate(" + ((w / 2) + dx) + "px," + ((h / 2) + dy) + "px)";

            return result;
        };


        var resize = function (x) {
             debugLog(
                " width:" + target.width() +
                    "height:" + target.height()
            );
            elWrapper.css({
                position: "relative",
                width: target.width() + "px",
                height: target.height() + "px",
                overflow: "hidden"
            });


            elSlideContainer.css({
                position: "relative",
                width: elWrapper.width() * slides.length + "px",
                height: elWrapper.height() + "px",
                overflow: "hidden"
            });

            elSlideContainer.children().css({
                position: "relative",
                "float": "left",
                overflow: "hidden"
            });
           
            elSlideContainer.children().each(
                function (idx) {
                    var item = $(this);
                    
                    var child = item.children();
                 
                    var result = scale(
                        child.width(),
                        child.height(),
                        elWrapper.width(),
                        elWrapper.height(),
                        10);
                    item.css({
                        width: elWrapper.width() + "px",
                        height: elWrapper.height() + "px"
                    });
                  
                    cssSandpaper.setTransform(child.get(0), result.transform);

                });



            elSlideContainer.css({
                marginLeft: "-" + (curIdx * elSlideContainer.find(":eq(0)").width() + "px")
            });

        }; // sets initial size

    
       

        var showNav = function () {
            elNext.css("display", "block");
            elPrev.css("display", "block");
            target.addClass("brdRotatorHovered");
           

        };
        var hideNav = function () {
            elNext.css("display", "none");
            elPrev.css("display", "none");
        
            target.removeClass("brdRotatorHovered");
        };


        var movePrev = function (x) {
            if(x!=null) x.stopPropagation();

            if (elSlideContainer.is(":not(:animated)")) {
                var dur = 1;
                if (curIdx > 0)
                    curIdx--;
                else {
                    curIdx = mxSlides - 1;
                    dur = curIdx;
                }
                slides.removeClass(selectedClass);
                animateSlide(dur, curIdx);
                slides.eq(curIdx).addClass(selectedClass);
            }
        };
        var moveNext = function (x) {
            if(x!=null) x.stopPropagation();
            if (elSlideContainer.is(":not(:animated)")) {
                var dur = 1;
                if (curIdx < mxSlides - 1)
                    curIdx++;
                else {
                    curIdx = 0;
                    dur = mxSlides - 1;
                }
                slides.removeClass(selectedClass);
                animateSlide(dur, curIdx);
                slides.eq(curIdx).addClass(selectedClass);
            }
        };
        var setTimer = function () {
            var duration = slides.eq(curIdx).children().attr("data-duration");
            if (duration == null || duration == 0) duration = opts.rotationDuration;
            if(isNaN(duration) || duration==0) duration = 5;
            
            if ((opts.auto) == true) {
                if (timer != null)
                    clearInterval(timer);
                timer = setInterval(function () {
                    moveNext();
                    hideNav();
                    setTimer(); //reset interval
                }, duration*1000);
            }
        };
        var stopTimer = function () {
            clearInterval(timer);
        };
        
        resize();
        setTimer();
        hideNav();

        elWrapper.mouseover(showNav);
        elWrapper.click(showNav);
        elSlideContainer.hover(stopTimer, setTimer);
        elNext.hover(stopTimer, setTimer);
        elNext.click(moveNext);
        elPrev.hover(stopTimer, setTimer);
        elPrev.click(movePrev);
        elSlideContainer.css("display","block");
    };


    $.fn.brdRotator.defaults = {
        slidesClass: ".brdRotatorSlides",
        slideClass: ".brdRotatorSlide",
        slideSelectedCLass: ".brdRotatorSlideSelected",  // just pure text, no sign
        slideWrapper: ".brdRotatorWrapper", // must be id, use # sign
        auto: true,
        easing: "swing",
        duration: 400,
        width: "100%",
        prev: ".brdRotatorPrev",
        next: ".brdRotatorNext",
        rotationDuration: 5
    };


})(jQuery);
//board rotator end


