﻿(function(jQuery) {
    jQuery.fn.portfolio = function(options) {
        var opts = jQuery.extend({}, jQuery.fn.portfolio.defaults, options);
        
        this.each(function(){

            var mainView = jQuery("."+opts.mainViewClass, this);
            var mainViewImg = jQuery("img", mainView);
            
            var previewImgs = jQuery("."+opts.previewViewClass+" img", this);
            previewImgs.click(function() {
                previewImgs.removeClass(opts.selectedClass);
                jQuery(this).addClass(opts.selectedClass);
                //carefully check this, should be regexp
                var newSrc = this.src.replace("/"+opts.thumbnailFilePrefix,"/");
                mainViewImg.fadeOut(opts.fadeOutInterval, function() {
                    
                    var imgPreloader = new Image()
					imgPreloader.src = newSrc;
					
					if (imgPreloader.complete) {
						mainViewImg.attr("src", newSrc);
						mainViewImg.fadeIn(opts.fadeInInterval);
					}
					else {
					   mainView.addClass(opts.loadingClass);
					   
					   jQuery(imgPreloader).unbind().bind("load", function() {
							mainViewImg.attr("src", newSrc);
							mainView.removeClass(opts.loadingClass);
                            mainViewImg.fadeIn(opts.fadeInInterval);
						});	 
					}
                    
                });
                                        
            });
            
        });
        
        
    };
    
    jQuery.fn.portfolio.defaults = {
        mainViewClass: "mainView",
        previewViewClass: "previewView",
        thumbnailFilePrefix: "preview_",
        loadingClass: "loading",
        selectedClass: "thumbselected",
        fadeInInterval:1500,
        fadeOutInterval:300 
    };
}
)(jQueryCS);

