var Monbi = {
    cloudItemCount: 0,
    initialWelcomeHeight: 0,
    zoomHashPrefix: "zoom-",
    oldIE: $('html').hasClass('ie7') || $('html').hasClass('ie8'),
    init: function () {
        var self = this;

        if ($('#reference-list').length) {
            $('#reference-list .fade').fadeTo(0, .3);
            $('#reference-list').fadeIn('fast');
            $('#reference-list li').bind('mouseover', function () {
                $('.fade', this).stop().fadeTo('fast', 1);
            }).bind('mouseleave', function () {
                $('.fade', this).stop().fadeTo('fast', .3);
            });
        }

        if ($('#cart').length) {
            self.initCart();
        }

        if ($('.thumb-list').length) {
            self.initReportage();
        }

        if ($('form').length) {
        	$('form').validate();
        }

        // init menu clicks
        $('#menu-open').click(function (e) {
            e.preventDefault();
            $(this).fadeOut('fast', function () {
                $('#menu-close').fadeIn('fast');
            });
            $('#menu').fadeIn();
        });

        $('#menu-close').click(function (e) {
            e.preventDefault();
            $(this).fadeOut('fast', function () {
                $('#menu-open').fadeIn('fast');
            });
            $('#menu').fadeOut();
        });

        // init the cloud
        try {
            self.cloudItemCount = parseInt($('#cloud').data('itemcount'));
        } catch (e) {
            self.cloudItemCount = 0;
        }
        self.updateCloudUI();

        // init photo-roll
        if ($('#photo-roll').length) {
            self.initPhotoRoll();
        }

        // init welcome box AFTER photo roll so key left and right events move the photoroll
        if ($('#welcome').length) {
            self.initWelcomeBox();
        }
    },

    addToCloud: function (cart_url, reportage_id, picture_id) {
        // add cloud/basket logic
        this.cloudItemCount++;
        
        $.ajax({
			type: 'POST',
			url: cart_url,
			data: 'action=add&reportage_id=' + reportage_id + '&picture_id=' + picture_id
		});
        
        // update ui
        this.updateCloudUI();
        return true;
    },
    removeFromCloud: function (cart_url, reportage_id, picture_id) {
        // add cloud/basket logic
        this.cloudItemCount = Math.max(0, --this.cloudItemCount);
        
        $.ajax({
			type: 'POST',
			url: cart_url,
			data: 'action=delete&reportage_id=' + reportage_id + '&picture_id=' + picture_id
		});

        // update ui
        this.updateCloudUI();
        return true;
    },
    removeFromCart: function (cart_url, reportage_id, picture_id) {
        // add cloud/basket logic
        this.cloudItemCount = Math.max(0, --this.cloudItemCount);
        
        $.ajax({
			type: 'POST',
			url: cart_url,
			data: 'action=delete&reportage_id=' + reportage_id + '&picture_id=' + picture_id
		});
        
        $('div.reportage-' + reportage_id + ' ul.thumb-list li.picture-' + picture_id).fadeOut();
        
        // update item count
        var item_count = $('li.reportage-' + reportage_id + ' a.icon-delete-rep').data('itemcount');
        item_count--;
        
        if(item_count <= 0){
        	$('.reportage-' + reportage_id).fadeOut();
        }else{
        	$('.reportage-' + reportage_id + ' a.icon-delete-rep').data('itemcount', item_count);
        	$('.reportage-' + reportage_id + ' span.item-count').html(item_count);
        }
        
        if(this.cloudItemCount <= 0){
        	$('#feedback').html('Uw wolk is leeg.');
        	$('#send-order').fadeOut();
        }

        // update ui
        this.updateCloudUI();
        return true;
    },
    removeRepFromCart: function (cart_url, reportage_id, item_count) {
        // add cloud/basket logic
        this.cloudItemCount = Math.max(this.cloudItemCount - item_count);
        
        $.ajax({
			type: 'POST',
			url: cart_url,
			data: 'action=rep&reportage_id=' + reportage_id
		});
        
        $('.reportage-' + reportage_id).fadeOut();
        
        if(this.cloudItemCount <= 0){
        	$('#feedback').html('Uw wolk is leeg.');
        	$('#send-order').fadeOut();
        }

        // update ui
        this.updateCloudUI();
        return true;
    },
    updateCloudUI: function () {
        $('#cloud').toggleClass('full', this.cloudItemCount > 0);
        $('#cloud span').html(this.cloudItemCount > 0 ? this.cloudItemCount : '');
    },

    initPhotoRoll: function () {
        var self = this;
        // hover = mouseenter & mouseleave // adding mouseover trigger with the pageload
        $('#photo-roll .item').bind('mouseenter mouseover', function () {
            $(this).find('.icons .btn').fadeTo('fast', .4);
            $(this).siblings().children('.overlay').stop().fadeTo('fast', .4);
        }).bind('mouseleave', function () {
            $(this).find('.icons .btn').hide();
            $(this).siblings().children('.overlay').stop().fadeOut('fast', 0);
            $(this).find('.box').removeClass('is-open').fadeOut('fast');
        }).prepend('<div class="overlay">');

        // fix for IE7/8 where half of the infolayer (.box) disappears behind the next .item - not fixable in pure css with z-index
        $('#photo-roll .item').each(function (idx, item) {
            $(item).css('z-index', $(item).css('z-index') - idx);
        });
        
        $('#photo-roll .item img').click(function () {
        	var href = $(this).parents('.item').find('a.icon-detail').attr('href');
        	if(href == undefined){
        		href = $(this).parents('.item').find('a.icon-zoom').attr('href');
        		self.showZoom(href);
                return false;
        	}else{
    			window.location = href;
        	}
        });

        $('#photo-roll .icon-info').each(function (ixd, item) {
            var $img = $(item).parents('.item').find('img');
            var title = $img.attr('title');
            var text = $(item).html();
            if (title != '' || text != '') {
                var $infoLayer = $('<div class="box"><div class="top"></div><div class="cnt"></div></div>');
                if (title != '') $('.cnt', $infoLayer).append('<h1>' + title + '</h1>');
                if (text != '') $('.cnt', $infoLayer).append('<p>' + text + '</p>');
                $(this).parents('.item').prepend($infoLayer);
                $img.attr('title', '');
            }
            else {
                $(this).addClass('hidden');
            }
        });

        self.initZoom();

        $(document).keydown(function (e) {
            if (e.keyCode == 27 || e.keyCode == 13 || e.keyCode == 32) {
                self.removeZoom();
            }
        });

        $(window).resize(function () {
            self.positionPhotoRoll();
        });

        // make the arrow a bit more visible by putting a white overlay over the images
        $('#photo-roll .browse').hover(function () {
            $('#photo-roll').find('.overlay').stop().fadeTo('fast', .4);
        }, function () {
            $('#photo-roll').find('.overlay').stop().fadeTo('fast', 0);
        });

        $('#photo-roll .icon-info').click(function () {
            var $item = $(this).parents('.item'),
                    $info = $item.find('.box');

            if ($info.hasClass('is-open')) {
                $info.removeClass('is-open').fadeOut('fast');
            }
            else {
                newPosition = $(this).offset().left - $item.offset().left + $(this).width() / 2;
                $info.css('left', newPosition).addClass('is-open').fadeIn('fast'); //.mouseleave(function () { $(this).fadeOut('fast') });
            }
        });

        self.positionPhotoRoll();
        $('#photo-roll .scrollable').scrollable();
        $(window).resize(function (e) { self.positionPhotoRoll(); });

        // check if there is a hash for permalink zoom
        if (document.location.hash) {
            var h = document.location.hash.slice(1);
            // check beginning
            if (h.indexOf(self.zoomHashPrefix) === 0) {
                // extra data
                var imgUrl = h.substr(self.zoomHashPrefix.length);
                self.loadZoomFromUrl(decodeURIComponent(imgUrl));
            }
        }
    },
    positionPhotoRoll: function () {
        var topOffset = ($(document).height() - $('#photo-roll').height()) / 2;
        var minOffset = $('header').height();
        if ($(window).height() < 600) {
            // 110 pas beter in 1024x786 resolutie
            // marge van 600 is in de window
            minOffset = 110;
        }
        $('#photo-roll').css('top', Math.max(minOffset, topOffset));
        $('#photo-roll').fadeIn();
    },

    initZoom: function () {
        var self = this;
        $('a.icon-zoom').click(function (e) {
            self.showZoom($(this).attr('href'));
            return false;
        });

        $(window).resize(function () {
            var $img = $('#zoom-img');
            if ($img.length) {
                $img.scaleAndPostion();
                $('#zoom-close').css('top', ($(window).height() - $('#zoom-close').height()) / 2);
            }
        });
    },
    showZoom: function (imgUrl) {
        var self = this;
        var $zoom = $('<div id="zoom-layer"><a id="zoom-close" /></div>');
        $zoom.prependTo('body').fadeIn('fast');

        var $img = $('<img id="zoom-img" />');
        $img.appendTo($zoom).imagesLoaded(function () {
            $img.data('dim', { width: $img.width(), height: $img.height() }).scaleAndPostion().fadeIn('fast');
        }).attr('src', imgUrl);


        $('#zoom-close').click(function () {
            self.removeZoom();
        }).css('top', ($(window).height() - $('#zoom-close').height()) / 2);

        // adding image url - could also be an ID
        document.location.hash = "#" + self.zoomHashPrefix + encodeURIComponent(imgUrl);
    },
    removeZoom: function () {
        $('#zoom-layer, #zoom-img').fadeOut('fast', function () {
            $(this).remove();
            document.location.hash = '';
        });

    },
    loadZoomFromUrl: function (imgUrl) {
        // check if image still exists
        //window.log(imgUrl);
        var self = this;
        if ($("a[href='" + imgUrl + "']").length) {
            self.showZoom(imgUrl);
        }
    },

    initWelcomeBox: function () {
        var self = this;
        $('#welcome').draggable({ handle: '.box' });
        if ($('#welcome .item').length > 1) {
            $('#welcome .browse').removeClass('hidden');
            $('#welcome').scrollable({ next: '.next0', prev: '.prev0' });
        }

        this.initialWelcomeHeight = $('#welcome .cnt').height();
        $('#welcome').find('.close').click(function () {
            $(this).toggleClass('closed');
            if ($(this).hasClass('closed')) {
                $('#welcome .cnt, #welcome .scrollable').animate({ height: '18px' }, 'fast');
                $('#welcome .browse').fadeTo('fast', 0);
            }
            else {
                $('#welcome .cnt, #welcome .scrollable').animate({ height: self.initialWelcomeHeight }, 'fast');
                $('#welcome .browse').fadeTo('fast', 1);
            }
        });

        $(window).keydown(function (e) {
            if (e.keyCode == 27) {
                $('#welcome').find('.close').click();
            }
        });
    },

    initReportage: function () {
        var self = this;
        $('.thumb-list li').hover(function () {
            $('.icons', this).stop().fadeTo('fast', 1);
        }, function () {
            $('.icons', this).stop().fadeTo('fast', 0);
        }).prepend('<div class="overlay-cloud"></div><div class="overlay-white"></div>');

        $('.thumb-list .icon-cloud').click(function () {
            var reportage_id = $(this).data('reportage_id');
            var picture_id = $(this).data('picture_id');
            var cart_url = $(this).data('cart_url');
            if ($(this).parents('li').toggleClass('in-cloud').hasClass('in-cloud')) {
                self.addToCloud(cart_url, reportage_id, picture_id);
            }
            else {
                self.removeFromCloud(cart_url, reportage_id, picture_id);
            }
        });
        self.initZoom();
        $('#reportage').fadeIn();
    },

    initCart: function () {
        var self = this;

        $('.thumb-list .icon-delete-pic').click(function () {
            var reportage_id = $(this).data('reportage_id');
            var picture_id = $(this).data('picture_id');
            var cart_url = $(this).data('cart_url');
            self.removeFromCart(cart_url, reportage_id, picture_id);
        });

        $('.icon-delete-rep').click(function () {
            var reportage_id = $(this).data('reportage_id');
            var cart_url = $(this).data('cart_url');
            var item_count = $(this).data('itemcount');
            self.removeRepFromCart(cart_url, reportage_id, item_count);
        });
    }
}

$.fn.scaleAndPostion = function () {
    var elems = this.filter('img');
    elems.each(function () {
        var $img = $(this),
            imgHeight = $img.data('dim').height,
            imgWidth = $img.data('dim').width,
            marginVert = parseInt($img.css('marginTop')) * 2,
            maxHeight = $(window).height() - marginVert,
            maxWidth = $(window).width() - marginVert;

        //window.log('imgHeight: ' + imgHeight + ' - imgWidth: ' + imgWidth + ' - marginVert: ' + marginVert + ' - maxHeight: ' + maxHeight + ' - maxWidth: ' + maxWidth);

        if (imgHeight > maxHeight) {
            imgWidth = Math.floor(imgWidth * maxHeight / imgHeight);
            imgHeight = maxHeight;
            //window.log('Max Height reached: ' + maxHeight + ' resizing at ' + imgWidth + 'x' + imgHeight);
        }

        if (imgWidth > maxWidth) {
            imgHeight = Math.floor(imgHeight * maxWidth / imgWidth);
            imgWidth = maxWidth;
            //window.log('Max Width reached: ' + maxWidth + ' resizing at ' + imgWidth + 'x' + imgHeight);
        }

        var topOffset = ($(window).height() - imgHeight - marginVert) / 2
        $img.css({ width: imgWidth, height: imgHeight, top: topOffset });
    });
    return this;
};

$(document).ready(function(){
	$('img').live("contextmenu",function(e){
		alert("(c) Al het beeldmateriaal en foto's op deze pagina en website zijn eigendom van Caroline Monbailliu en auteursrechtelijk beschermd door LOE bvba en mogen niet zonder hun uitdrukkelijke toestemming op een of andere wijze gebruikt worden.");
	});
	Monbi.init();
});
