/* vim:set ts=4 sw=4 nowrap expandtab: */

(function(window) {

/* piepenmoker namespace */
var _ns = {};

_ns.TeaserCarousel = function(elem, images, currentPipeId) {
    /* what index in the teaser list has the currently selected pipe? */
    var getStart = function() {
        var tstart = 0;
        for (var i = 0; i < images.length; i++) {
            if (images[i] == currentPipeId) {
                tstart = i - 2;
                if (tstart < 1) {
                    tstart = 1;
                }
                break;
            }
        }
        return tstart;
    };
    var carousel = null;
    if (images.length > 0) {
        /* no carousel when there are no images/pipes */
        var options = {
            vertical: true,
            start: getStart(),
            scroll: 3,
            visible: 8
        };
        $(elem).show();
        carousel = $(elem).jcarousel(options);
    }
    return carousel;
};

_ns.PreviewCarousel = function(elem, images, nrVisible) {
    var obj = {};
    obj.tc = null;
    obj.pos = 1;
    obj.tstart = 1;
    obj.nrVisible = nrVisible;
    obj.threshold = Math.floor(obj.nrVisible / 2);
    obj.images = images;

    var centerImage = function(width) {
        var w = 770;
        if (width > w) {
            $("#imagecontainer").css('width', w + 'px');
            $("#imagecontainer").css('paddingLeft', 0 + 'px');
        } else {
            alignmentPx = ((w - width)/2);
            $("#imagecontainer").css('width', (w - alignmentPx) + 'px');
            $("#imagecontainer").css('paddingLeft', alignmentPx + 'px');
        }   
    };

    /* add the 'selected' class to the new image and remove it from all others. */
    obj.setSelected = function(ofs) {
        $("[id|=imgpreview]").removeClass("selected");
        $("#imgpreview-"+ofs).addClass("selected");
    };

    /* hide the currently displayed image and show the anim gif for loading */
    obj.setLoading = function() {
        /* only hide the imageview object instead of removing it now,
         * so that the box remains and only the image disappears.*/
        $("#imageview").css('visibility', 'hidden');
        $("#loader").addClass('loading');
    }

    /* load and display the image with the given offset */
    obj.load = function(offset) {
        /* get the proper image with the given offset from the array,
         * take into account wrapping/overflow of the offset value */
        var newoffset = offset;
        if (offset >= obj.images.length)
            newoffset = 0;
        if (offset < 0)
            newoffset = obj.images.length - 1;
        var newimg = obj.images[newoffset];

        /* do the actual loading and switching of the image */
        obj.switchImage(newimg, newoffset+1);
    }

    /* scroll the carousel in such a way that the selected image is always in the 
     * center, if possible */
    obj.scroll = function(offset) {
        if (obj.tc.size(undefined) > obj.nrVisible) {
            visibleItemClicked = (offset - obj.pos) + 1;

            if (visibleItemClicked > obj.nrVisible - obj.threshold) {
                /* move to the right */
                obj.pos += obj.threshold - (obj.nrVisible - visibleItemClicked);
            }
            if (visibleItemClicked <= obj.threshold && obj.pos > 1) {
                /* move to the left */
                obj.pos -= (obj.threshold - visibleItemClicked) + 1;
            }
            obj.tc.scroll(obj.pos, true);
        }
    };

    /* do the actual loading of the new image src and replacing the old image */
    obj.loadImage = function(src, width, height, offset) {
        var img = new Image();

        /* on click, load the next image */
        $(img).click(function() {
            obj.load(offset);
        });

        /* after loading, hide anim gif, center and fade in new image  */
        $(img).load(function() {
            $(img).hide();
            /* remove the old (hidden) image and add the new one */
            $('#loader').empty();
            $('#loader').removeClass('loading');
            $('#loader').append(img);
            centerImage(width);
            $(img).fadeIn();
        });

        /* set image attributes */
        $(img).attr('id', 'imageview');
        $(img).attr('style', 'cursor: pointer;');
        $(img).attr('src', src);
        $(img).attr('width', width);
        $(img).attr('height', height);
    };

    /* hide the currently displayed image and then start loading the new one */
    obj.switchImage = function(img, offset) {
        obj.setLoading(offset);
        obj.setSelected(offset);
        obj.scroll(offset);
        obj.loadImage(img.src, img.width, img.height, offset);
    };

    return obj;
};

window.writeMailAddr = function(tld, domain, user) {
    var addr = user + "@" + domain + "." + tld;
    document.writeln(addr);
};

_ns.toggleTerms = function() {
    $("#terms").toggle();
    $("#showterms").toggle();
    $("#hideterms").toggle();
};

_ns.videoStat = function() {
    var img = new Image();
    $(img).attr('src', '/static/images/stats/video.gif?'+(new Date().getTime()));
};

_ns.pipeViewStat = function(id, name, sold) {
    var img = new Image();
    url = '/static/images/stats/pipe?s=' + id + '/' + name + '/' + sold;
    url = url + "&ts=" + (new Date().getTime());
    $(img).attr('src', url);
};

_ns.getPageScroll = function() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
};

_ns.setLang = function(lang) {
    var path_comps = window.location.pathname.substring(1).split('/');
    path_comps[0] = lang;
    var newpath = "/" + path_comps.join("/");
    window.location.pathname = newpath;
};

_ns.pipedetails = function(
    pipeimages,
    teasers,
    pipeId
){
    var obj = {};

    obj.previewCarousel = _ns.PreviewCarousel(
        "#imgpreviewcarousel", pipeimages, 5);
    obj.teaserCarousel = _ns.TeaserCarousel(
        "#teasercarousel", teasers, pipeId);

    obj.setup = function() {
        /* click handlers on the img preview links*/
        $("[id|=imgpreviewlink]").click(function(){
            var imgIndex = $(this).attr('id').split('-')[1];
            obj.previewCarousel.load(imgIndex-1);
        });

        $("#imgpreviewcarousel").show();
        $("#imgpreviewcarousel").jcarousel({
            start: obj.previewCarousel.pos,
            scroll: 1,
            visible: obj.previewCarousel.nrVisible,
            initCallback:function(carousel) {
                obj.previewCarousel.tc = carousel;
                $("#imgpreview-1").addClass('selected');
            }
        });

        /* load first image */
        obj.previewCarousel.load(0);
        $(window).unbind('resize');

        $('#foto_tab').click(function(){
            $('#pipevideos').hide();
            $('#pipeimages').show();
            $('#video_tab span').removeClass('selected');
            $('#foto_tab span').addClass('selected');
        });
        if ($("#youtube_object").length > 0) { 
            $('#video_tab span').removeClass('inactive');
            $('#video_tab').click(function(){
                $('#pipeimages').hide();
                $('#pipevideos').show();
                $('#video_tab span').addClass('selected');
                $('#foto_tab span').removeClass('selected');
                _ns.videoStat();
            });
        }
    };
    return obj;
};

window.Piepenmoker = _ns;

})(window);


