$(function () {

    $('textarea.code').click(function () {
        this.focus();
        this.select();
    });
    
	
	function identify_proper_wallpaper_resolution() {

	    var dimensions = {},
			size;

		if (screen.width == 1366 && screen.height == 768) {
			size = {width: 1365, height: 768};
		} else {
			size = {width: screen.width, height: screen.height};
		}

		var id = size.width + 'x' + size.height;	

	    if ($('#d-' + id).length > 0) {
	        $('#d-' + id).addClass('default');
	        $('a.wallpaper').attr('href', $('#d-' + id + ' a').attr('href'));
	    } else {
	        $('.dimensions li').each(function () {
	            var width, height, ratio;
	            if (matches = this.id.match(/d-(\d+)x(\d+)/)) {
	                width = parseInt(matches[1]);
	                height = parseInt(matches[2])
	                ratio = (width / height).toFixed(2);
	                if (typeof dimensions[ratio] == 'undefined') {
	                    dimensions[ratio] = [];
	                }
	                dimensions[ratio].push({width: width, height: height});
	            }
	        });
	        var res = proper_size_for(size);
			if (res) {
				id = res.width + 'x' + res.height;
	            $('#d-' + id).addClass('default');
	            $('a.wallpaper').attr('href', $('#d-' + id + ' a').attr('href'));
	        }
	    }

		function proper_size_for(size) {

			function find_in(size, sizes) {
	    		var i;
	    		for (i = 0; i < sizes.length; i++) {
	    			if (size.width <= sizes[i].width && size.height <= sizes[i].height) {
	    				return sizes[i];
	    			}
	    		}
	    		return null;
			}

			var res,
				ratio = (size.width / size.height).toFixed(2);

			if (typeof dimensions[ratio] != 'undefined') {
			    if (res = find_in(size, dimensions[ratio])) {
			        return res;
			    }
			}

			var max = null;

			for (rt in dimensions) {
			    var sizes = dimensions[rt];
			    if (rt != ratio && (res = find_in(size, sizes))) {
			        return res;
				}
			    var last = sizes[sizes.length - 1];
				if (null == max) {
			        max = last;
			    } else if (max.width < last.width || max.height < last.height) {
			        max = last;
			    }
			}

			return max;
		}
		
	} // function identify_proper_wallpaper_resolution
	
	identify_proper_wallpaper_resolution();
    
});
