
// jQuery Plugins //////////////////////////////////////////////////////////////////////////

// Mouse wheel Plugin ////////////////////////////////////////////////////////
(function($) {
$.fn.extend({
	mousewheel: function(f) {
		if (!f.guid) f.guid = $.event.guid++;
		if (!$.event._mwCache) $.event._mwCache = [];
		
		return this.each( function() {
			if (this._mwHandlers) return this._mwHandlers.push(f);
			else this._mwHandlers = [];
			
			this._mwHandlers.push(f);
			
			var s = this;
			
			this._mwHandler = function(e) {
				e = $.event.fix(e || window.event);
				var delta = 0, returnValue = true;
				
				if (e.wheelDelta)  delta = e.wheelDelta/120;
				if (e.detail)      delta = -e.detail/3;
				if (window.opera)  delta = -e.wheelDelta;
				
				for (var i=0; i<s._mwHandlers.length; i++)
					if (s._mwHandlers[i])
						if ( s._mwHandlers[i].call(s, e, delta) === false ) {
							returnValue = false;
							e.preventDefault();
							e.stopPropagation();
						}
				
				return returnValue;
			};
			
			if (this.addEventListener)
				if ($.browser.mozilla) this.addEventListener('DOMMouseScroll', this._mwHandler, false);
				else                   this.addEventListener('mousewheel',     this._mwHandler, false);
			else
				$.event.add(this, 'mousewheel', this._mwHandler);
			
			$.event._mwCache.push( $(this) );
		});
	},
	
	unmousewheel: function(f) {
		return this.each( function() {
			if ( f && this._mwHandlers ) {
				for (var i=0; i<this._mwHandlers.length; i++)
					if (this._mwHandlers[i] && this._mwHandlers[i].guid == f.guid)
						delete this._mwHandlers[i];
			} else {
				if (this.addEventListener)
					if ($.browser.mozilla) this.removeEventListener('DOMMouseScroll', this._mwHandler, false);
					else                   this.removeEventListener('mousewheel',     this._mwHandler, false);
				else
					$.event.remove(this, 'mousewheel', this._mwHandler);
					
				this._mwHandlers = this._mwHandler = null;
			}
		});
	}
});
// clean-up
$(window).bind('unload', function() {
    var els = $.event._mwCache || [];
	for (var i=0; i<els.length; i++)
	    els[i].unmousewheel();
});
	


// Query String Plugin ////////////////////////////////////////////////////////
jQuery.parseQstr = function( str ) {
    var q = {};
    var match = str.match(/([^?#]*)(#.*)?$/);
    if (!match) return {};
    str = match[0];
    var p = str.split(/[&;]/);
    for (var i=0; i<p.length; i++) {
        var n = p[i].split('=');
        var k = decodeURIComponent(n[0]);
        if (n.length == 2) var v = decodeURIComponent(n[1]);
        else var v = k;
        if (typeof q[k] == 'undefined') q[k] = v;
        else {
            var a = eval(q[k]);
            a.push(v);
            q[k] = a;
        }
    }
    return q;
}

jQuery.objToQstr = function ( obj ) {
    var str = '';
    $.each( obj, function(key, val) {
        str+= encodeURIComponent(key)+'='+encodeURIComponent(val) + '&';
    });
    return str.replace(/&$/,'');
}

// Centering Plugin ////////////////////////////////////////////////////////
jQuery.fn.vcenter = function() {
    return this.each( function() {
        var $obj = $(this);
        var $p = $obj.parent();
        
        var t = parseInt( ($p.height() - $obj.height()) / 2 );
        if( $obj.css('position').toLowerCase() == 'absolute' ) {
            $obj.css('top', t+'px');
        }
        else {
            $obj.css('marginTop', t+'px');
        }
        
    });
}

jQuery.fn.center = function() {
    return this.each( function() {
        var $obj = $(this);
        var $p = $obj.parent();
        
        var l = parseInt( ($p.width() - $obj.width()) / 2 );
        if( $obj.css('position').toLowerCase() == 'absolute' ) {
            $obj.css('left', l+'px');
        }
        else {
            $obj.css('margin-left', l+'px');
        }
        
    });
}


// Color Formatting Plugin//////////////////////////////////////////////////////////
// Takes color in hexadecimal notation and returns [r, g, b] 
jQuery.hex2rgb = function(color) {
    var rgb;
    color = color.replace(/^#/,'');
    if( color.length == 6 ) {
        rgb = [
            parseInt(color.substring(0,2), 16),
            parseInt(color.substring(2,4), 16), 
            parseInt(color.substring(4,6), 16)
        ];
    }
    else if( color.length == 3 ) {
        rgb = [
            parseInt(color.substring(0,1), 16),
            parseInt(color.substring(1,2), 16), 
            parseInt(color.substring(2,3), 16)
        ];
    } else {
        rgb = [0,0,0];
    }
    return rgb;
}
// Takes r, g, b and returns the hexadecimal version of a color
jQuery.rgb2html = function(R,G,B) {return $.toHex(R) + $.toHex(G) + $.toHex(B)}

// Converts a decimal number to hexadecimal
jQuery.toHex = function(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}

// Takes a color string returned by the browser and parses it into a hexadecimal color string
jQuery.colorFormat = function(color) {
    if( !color ) return;
    color = color.replace('#','');
    var returnColour = "";
    if(color != "transparent") {
        if(color.substr(0, 3) == "rgb") {
            var a = color.replace(/[^0-9|,]/g,'').split(',');
            returnColour = $.rgb2html(a[0],a[1],a[2]);            
        }        
        else if(color.length == 3) {            
            returnColour = color.substring(0, 1) + 
                    color.substring(0, 1) + 
                    color.substring(1, 2) +
                    color.substring(1, 2) +
                    color.substring(2, 3) + 
                    color.substring(2, 3);
        }        
        else {
            returnColour = color;            
        }        
    }
    else if( color == "transparent" ) {
        returnColour = 'transparent';
    }    
    return returnColour;    
}

// Rollover Plugin //////////////////////////////////////////////////////////////////////////
jQuery.rollover = {
    _get_filter : function(obj) { // handle ie6 filter
        if (!$.browser.msie) return obj;
        filter = $(obj).css('filter');
        if( filter )  return obj.filters(0);
        else return obj;
    },
    over: function(e) {
        var obj = this;
        var img = obj;
        var prop = $.data(obj, 'rollover');
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',obj)[0];        
        if( prop.saved_src ) return;
        img = $.rollover._get_filter(img);
        prop.saved_src = img.src;
        $.data(obj, 'rollover', prop);
        img.src = $.rollover.over_src(img.src);
    },
    textover : function(e) {
        var obj = this;
        var img = obj;
        var prop = $.data(obj, 'rollover');
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',obj)[0];
        if( prop.saved_src ) return;
        img = $.rollover._get_filter(img);
        prop.saved_src = img.src;
        $.data(obj, 'rollover', prop);
        img.src = $.rollover.textover_src(img.src, prop.options);
    },
    over_src: function(src) {
        return src.replace(/\.(\w+)$/, "_over.$1");
    },
    textover_src: function(src, settings ){
        var baseURL = settings.baseURL;
        var params = {};
        $.each( settings, function(k,v) {
            if( k != 'baseURL' ) params[k] = v;
        });
        var q = $.parseQstr(src);
        $.extend(q,params);
        return baseURL + '?' + $.param(q);
    },
    out : function(e) {
        var obj = this;
        var img = obj;
        var prop = $.data(obj, 'rollover');
        if( $(obj).is('.ignore') ) return;        
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',obj)[0];        
        if( prop.saved_src ) $.rollover._get_filter(img).src = prop.saved_src;
        prop.saved_src = null;
        $.data(obj, 'rollover', prop);
    }    
};
jQuery.fn.rollover = function () {
    return this.each( function(i,obj) {
        $.data(obj, 'rollover', {saved_src: null});
        $(obj).unbind('mouseover', $.rollover.over).unbind('mouseout', $.rollover.out).
            mouseover($.rollover.over).mouseout($.rollover.out);        
        $(obj).preloadImg();
    });
};
jQuery.fn.textover = function (options) {
    var defaults = {
        baseURL: webroot + 'img/textimage.php'
    }
    return this.each( function(i,obj) {
        options = $.extend({}, defaults, options || {});
        if( !options.color ) {
            var c = $(obj).addClass('hover').css('color') || '000000';
            $(obj).removeClass('hover');
            c = $.colorFormat(c.replace('#',''));
            options.color = c;
        }
        $.data(obj, 'rollover', {
            saved_src: null,
            options: options
        });
        $(obj).unbind('mouseover', $.rollover.textover).unbind('mouseout', $.rollover.out).
            mouseover($.rollover.textover).mouseout($.rollover.out);
        $(obj).preloadImg();
    });
};
jQuery.fn.rolloverUnbind = function () {
    return this.each( function(i,obj) {
        $(obj).unbind('mouseover', $.rollover.over);
        $(obj).unbind('mouseover', $.rollover.textover);
        $(obj).unbind('mouseout', $.rollover.out);        
        $.removeData(obj, 'rollover');
    });
};

// Preloads rollover images according to rollover replacement rules
jQuery.fn.preloadImg = function () {
    return this.each( function() {
        if( typeof(this.rollover) == 'undefined' || !this.rollover ) return;
        var img = this;
        if( img.tagName.toLowerCase() != 'img' ) img = $('img',this)[0];
        var preloader = new Image();
        if( img.src.search('image.php') == -1 )
            preloader.src = $.rollover.over_src(img.src);
        else
            preloader.src = $.rollover.textover_src(img.src,this.rollover.settings);   

    });
};


// Image Replacement Plugin//////////////////////////////////////////////////////////

// Uses php image generator to replace the element's text with an image
jQuery.fn.imageReplace = function (settings) {
    var settings = $.extend({},  settings);
    baseURL = webroot+'img/textimage.php';
    return this.each( function() {
        $obj = $(this);
        var text = $.trim($obj.text());
        if( text.length < 1 ) return;
       
        var options = $.extend({}, settings);
        if( !options.color ) options.color = $.colorFormat($obj.css('color')|| '000000');
        if( !options.size ) options.size = parseInt($obj.css('font-size'));
        if( $obj.css('text-transform') == 'uppercase' ) text = text.toUpperCase();
        else if( $obj.css('text-transform') == 'lowercase' ) text = text.toLowerCase();
        if( !options.align ) options.align = $obj.css('text-align');
        var option_string = '';
        $.each(options, function(key,val) {
            option_string += '&'+encodeURIComponent(key)+'='+encodeURIComponent(val);
        });        
        $obj.empty().append('<img src="'+baseURL+'?text='+encodeURIComponent(text)+ option_string + '" alt="'+text+'">');
    });
}

})(jQuery);


function get_imageframe_size() {
    var w = $(window).width();
    var h = $(window).height();
    
    if (w <= 890 ) maxwidth = 400;
    else if (w <= 1024) maxwidth = 700;
    else if (w <= 1100) maxwidth = 800;
    else if (w <= 1280) maxwidth = 900;
    else maxwidth = 1000;
    
    if (h <= 600) maxheight = 290;
    else if (h <= 768) maxheight = 480;
    else if (h <= 1024) maxheight = 640;
    else maxheight = 800;
    
    return [maxwidth, maxheight];
}


function center_page() {
    var $$ = $('.page');
    var wh = $(window).height() - 100;
    var h = $$.height();
    if( h < wh) {
        mt = ((wh - h) / 2) - 50;
        if( mt > 0 ) $$.css('padding-top', mt);
    }
}

$(function() {    
    $('#nav li a.about').imageReplace({size:10});
    $('#nav li a').imageReplace({size:10.8, wrap:16}).textover();
    $('h2').imageReplace({size:10.8});
    $('.collection-list h2').textover();

        $('#nav a img, h2 img, .image-next, .image-prev').ifixpng();

    $('.collection-list li').hover(
        function() {            
            $('h2', this).mouseover().addClass('ignore');
            $('a', this).addClass('hover');
        },
        function() {
            $('h2', this).removeClass('ignore').mouseout();
            $('a', this).removeClass('hover');
        }
    );

    $('#nav a[rel=title]').click(function() {
        $('.collection .description').hide();
        $('.collection .images').show();
        $(this).mouseover().addClass('ignore');
        $('#nav a[rel=about]').removeClass('ignore').mouseout();
    }).click(); 
    $('#nav a[rel=about]').click(function() {
        $('.collection .images').hide();
        $('.collection .description').show();
        $(this).mouseover().addClass('ignore');
        $('#nav a[rel=title]').removeClass('ignore').mouseout();
    });

    center_page();
    $(window).resize( center_page );

    $('.collection-list li').each( function( i, li) {
        if( i%2 ==0 ) $(this).css('marginRight', 0);
    })
});
