﻿; (function($) {
    $.fn.OpportunityImageControl = function(options) {
        var defaults = {
            queryKey: 'imagepath'
        };
        var options = $.extend({}, defaults, options);

        var querysplitter = function(s) {
            var r = {};
            if (s) {
                var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
                q = q.replace(/\&$/, ''); // remove the trailing &
                jQuery.each(q.split('&'), function() {
                    var splitted = this.split('=');
                    var key = splitted[0];
                    var val = splitted[1];
                    // convert numbers
                    if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
                    // convert booleans
                    if (val == 'true') val = true;
                    if (val == 'false') val = false;
                    // ignore empty values
                    if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
                });
            }
            return r;
        };

        var thumbnailclick = function(e) {
            e.preventDefault();

            var imagepath = '';
            var query = querysplitter(this.href);
            for (var k in query) {
                if (k == options.queryKey) {
                    imagepath = query[k];
                    break;
                }
            };

            if (imagepath.length > 0) {
                var img = new Image();
                var jImg = $(img);

                jImg.hide();

                var parent = $(this).parents('.OpportunityImageControl:first').find('.OpportunityImage');
                parent.addClass('ImageLoading').empty().append(jImg);

                jImg.load(function() {
                    $(this).fadeIn();
                }).error(function() {
                }).attr('src', imagepath);
            }
        };

        return this.each(function() {
            $('.OpportunityThumbnails a', this).click(thumbnailclick);
        });
    };
})(jQuery)