/**
 * Bind returns a function pointer, scoped to the given scope. 
 *
 * @param {Object} scope The scope for the function
 * @return {Function} The scoped method
 */
Function.prototype.bind = function(scope){
	var method = this;
	return function(){
		return method.apply(scope, arguments);
	};
};

/*
* Gallery class
*
* 
*/
function Gallery(selector) {

	this.IMAGES_PER_SCREEN = 5;
	this.imageCount = 0;	
	this.activeImageNumber = 0;
	
	// set some elemenets for referencing in other functions
	this.overlay        = $('#overlay');
	this.galleryOverlay = $('#gallery_overlay');
	this.activeCity     = null;
	this.goSend         = $('#go_send');
	this.goSuccess      = $('#go_success');
	this.goError        = $('#go_error');
	this.btnNext 		= $('#go_browser_next');
	this.btnPrev 		= $('#go_browser_prev');
	this.btnReserve     = $('#go_send_button');
	this.btnStf         = $('#go_stf_button');
	this.btnAdd         = this.galleryOverlay.find('a[rel=addRecipient]');
	this.btnSend        = this.galleryOverlay.find('a[rel=sendEmail]');
	this.browser        = $('#go_browser');
	this.canvas			= $('#go_browser_canvas');
	this.photoContainer = $('#go_photo');
	this.stfContainer   = $('#go_send');
	this.receiversList = $('#go_receivers_canvas');


	$(selector).bind("click", this.open.bind(this));
	$('#go_back_button').bind("click", this.close.bind(this));

	$('#go_stf_button').click(function () {
	    $('#go_browser').toggle();
	    $('#go_send').toggle();
	});

	this.galleryOverlay.find('a[rel=back]').bind("click", this.backToGallery.bind(this));
	this.galleryOverlay.find('a[rel=clear]').bind("click", this.clearButtonClicked.bind(this));

	this.btnNext.bind("click", this.nextButtonClicked.bind(this));
	this.btnPrev.bind("click", this.prevButtonClicked.bind(this));
	this.btnSend.bind("click", this.sendButtonClicked.bind(this));
	this.btnAdd.bind("click", this.addButtonClicked.bind(this));
	this.canvas.bind("click", this.zoomImage.bind(this));

	
    this.emailRegex = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;

    this.galleryOverlay.find('input[name=toEmail]').bind("keyup", this.validateEmail.bind(this));
}

Gallery.prototype = {
    open: function (e) {
        e.preventDefault();
        var tooltip = $(e.target).parents('div:first')
        this.activeCity = tooltip.find('h2:first').text();
        var date = $(e.target).siblings('strong').text();
        this.imageCount = this.browser.find('li').length;
        this.galleryOverlay.find('h2').text(this.activeCity + ' - ' + date);
        var w = $('body').width();
        var h = $('body').height();
        this.overlay.css('height', h + 'px');

        var a = null;
        if (e.target.nodeName == 'A') {
            a = e.target;
        } else {
            a = $(e.target).parents('a')[0];
        }
        this.photoContainer.find('img').hide(); // init to hidden photo
        this.loadImages(a.href);
    },

    close: function (e) {
        this.reset();
        this.overlay.hide();
        this.galleryOverlay.hide();
    },

    reset: function () {
        this.receiversList.empty();
        this.goError.hide();
        this.goSuccess.hide();
        this.goSend.hide();
        this.browser.show();
        this.btnReserve.show();
        this.btnStf.show();
    },

    validateEmail: function (e) {
        if (this.emailRegex.test(e.target.value)) {
            $(e.target).removeClass("error");
            return false;
        } else {
            $(e.target).addClass("error");
            return true;
        }
    },

    /*
    * load images with ajax, should just fetch a fragment of HTML <ul><li><a href="large.jpg"><img src="thumb.jpg" /></a></li>...</ul> 
    */
    loadImages: function (url) {
        var self = this;
        $.get(url, function (data) {
            self.initializedImages(data);
        });
    },

    initializedImages: function (htmlWithImages) {
        this.browser.find('#go_browser_canvas').html(htmlWithImages);
        this.imageCount = $(htmlWithImages).find('li').length;
        this.overlay.show();
        // get first photo in list and show it
        var firstImage = this.photoContainer.find('img');
        var firstImageURL = $(htmlWithImages).find("a:first").attr("href");
        firstImage.load(function (e) {
            $(this).fadeIn();
        });
        firstImage.attr("src", firstImageURL);
        this.galleryOverlay.show();
        this.scrollToImage(0);
    },

    clearButtonClicked: function (e) {
        e.preventDefault();
        this.receiversList.empty();
    },

    sendButtonClicked: function (e) {
        e.preventDefault();
        var form = $(e.target).parents("form");
        var url = form.attr("action");
        var entries = this.receiversList.find('li');

        if (entries.length == 0) {
            alert('Voeg tenminste 1 ontvanger toe aan de lijst');
            return false;
        }

        reciepients = jQuery.map(entries, function (n, i) {
            return (n.innerHTML);
        });

        data = {
            to: reciepients.join(','),
            from: form.find('input[name=fromName]').val(),
            city: this.activeCity
        }

        var self = this;

        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            success: self.sendToFriendCompleted.bind(self),
            dataType: 'json'
        });

    },

    sendToFriendCompleted: function (data) {
        this.goSend.hide();
        if (data.success == true) {
            this.receiversList.empty();
            this.goSuccess.show();
        } else {
            this.goError.show();
        }
        this.btnReserve.hide();
        this.btnStf.hide();
    },

    addButtonClicked: function (e) {
        e.preventDefault();
        var form = this.galleryOverlay.find('form').get(0);
        if ($(form).find('input.error').length > 0) {
            return false;
        }
        var r = form.toName.value + ' &lt;' + form.toEmail.value + '&gt;';
        this.receiversList.append('<li>' + r + '</li>');
    },

    nextButtonClicked: function (e) {
        e.preventDefault();
        if (this.activeImageNumber + 10 > this.imageCount - 1) {
            this.activeImageNumber = this.imageCount - this.IMAGES_PER_SCREEN;
        } else {
            this.activeImageNumber = this.activeImageNumber + this.IMAGES_PER_SCREEN;
        }
        this.scrollToImage(this.activeImageNumber);
    },

    prevButtonClicked: function (e) {
        e.preventDefault();
        if (this.activeImageNumber - this.IMAGES_PER_SCREEN < 0) {
            this.activeImageNumber = 0;
        } else {
            this.activeImageNumber = this.activeImageNumber - this.IMAGES_PER_SCREEN;
        }
        this.scrollToImage(this.activeImageNumber);
    },

    scrollToImage: function (i) {
        var exp = 'li:eq(' + i + ')';
        var li = this.browser.find(exp);
        this.canvas.scrollTo(li, 300);
    },

    zoomImage: function (e) {
        e.preventDefault();
        var a = $(e.target).parent().get(0);
        this.photoContainer.find('img').attr("src", a.href);
    },

    backToGallery: function (e) {
        this.reset();
    }

}
