Index: /other-projects/nz-flag-design/trunk/main-form/choose-canvas.html
===================================================================
--- /other-projects/nz-flag-design/trunk/main-form/choose-canvas.html	(revision 29804)
+++ /other-projects/nz-flag-design/trunk/main-form/choose-canvas.html	(revision 29805)
@@ -51,24 +51,318 @@
     <script src="../similarity-2d/flag-processing.js"></script>
 
-    <script src="choose-canvas.js" />
-      
-    <!-- css for choose-palette -->
-<!--
-    <style>
-        .ui-slider-track {
-            background-color: #ECECEC;
-        }
-        .ui-slider-handle {
-            background-color: #a05a2c; /* used to be #E7924B; */
-        }
-    </style>
--->
-
-    <script>
+    <scriptXXX src="choose-canvas.js" />
+
+    <script type="text/javascript">
         // Flag settings - used to initialise the svg canvas to the user's preferences
         var flagCanvasSettings = { backgroundColor: "#000066", width: 800, height: 400 };
 
+
+// Variable for the currently selected flag ratio
+var currentRatio = null;
+
+var aspectRatios = null;
+var aspectMaxRatio = 0;
+
+function calcMaxRatio(aspect_ratio_data)
+{
+    // work out the maximum ratio      
+    var max_ratio = 0;
+
+    $.each(aspect_ratio_data, function(key, ratio_table) {
+        var ratio_array = key.split(":");
+        var ratio_x = ratio_array[0];
+        var ratio_y = ratio_array[1];
+        var ratio = ratio_y / ratio_x;
+	
+        if (ratio > max_ratio) {
+            max_ratio = ratio;
+        }
+    });
+
+    return max_ratio;
+}
+
+function calcCompleteWidth(aspect_ratio_data,scale)
+{
+    // work out the maximum ratio      
+    var max_width = 0;
+
+    $.each(aspect_ratio_data, function(key, ratio_table) {
+        var ratio_array = key.split(":");
+        var ratio_x = ratio_array[0];
+        var ratio_y = ratio_array[1];
+        var ratio = ratio_y / ratio_x;
+	
+	max_width += (scale*ratio);
+    });
+
+    return max_width;
+}
+
+
+function scaledDivsFitInPage(aspect_ratio_data, scale_to_height, num_of_rows_allowed, la_x_dim)
+{
+    var divs_fit = true;
+
+    var row = 1;
+    var total_row_width = 0;
+    var total_height = 0;
+
+    $.each(aspect_ratio_data, function(key, ratio_table) {
+        var ratio_array = key.split(":");
+        var ratio_x = ratio_array[0];
+        var ratio_y = ratio_array[1];
+        var ratio = ratio_y / ratio_x;
+	
+	var scaled_div_width = scale_to_height*ratio;
+	if (total_row_width + scaled_div_width > la_x_dim) {
+	    // this div doesn't fit on the current row 
+	    // => start a new row
+	    total_row_width = scaled_div_width;
+	    row++;
+
+	    if (row>num_of_rows_allowed) {
+		// blow out!
+		divs_fit = false;
+		return false; // jquery.each equivalent to 'break'
+	    }
+	}
+	else {
+	    total_row_width += scaled_div_width;
+	    row++;
+	}
+    });
+
+    return divs_fit;
+}
+
+
+function calcScaleToHeight(aspectRatios,la_x_dim,la_y_dim) 
+{
+    // determine scale factor so divs max out (as in, filling in the page) based la_y_dim height, 
+
+    var num_of_rows_allowed = 1;
+    var scale_to_height = la_y_dim; // optimized version of true calcuation, la_y_dim / num_of_rows_allowed;
+
+    //var div_width  = complete_width_100 * (div_height/100)
+    
+    var num_flag_bins = aspectRatios.length;
+    
+    while (!scaledDivsFitInPage(aspectRatios,scale_to_height,num_of_rows_allowed,la_x_dim)) {
+	    
+	num_of_rows_allowed++;
+	
+	if (num_of_rows_allowed>num_flag_bins) {
+	    // needing more rows than there are flag bins is an indication that things
+	    // just don't fit, and so will need to use a scroll bar.
+	    // Exiting at this point will naturally achieve this
+	    break;
+	}
+
+	scale_to_height = la_y_dim/num_of_rows_allowed;
+	
+	// if get to here, then need 
+	
+    }
+
+    console.log("**** num_of_rows = " + num_of_rows_allowed + ", scale to height = " + scale_to_height);
+    return scale_to_height;
+}
+
+
+$(function() {
+    $.getJSON( "../similarity-2d/flag-aspect-ratios-json.jsp", function(data) {
+
+        aspectRatios = data;
+	
+        //var scale_to_y_dim = 130;
+	
+        // express scale_to_y_dim to use relative to height of window
+	
+	var window_height = $(window).height();
+	var div_top = $('#aspect-ratio-div').offset().top + 20;
+
+        var la_y_dim = (div_top>0) ? window_height - div_top : window_height * 0.6;
+	var la_x_dim = $(window).width() * 0.7;
+
+        //var scale_to_y_dim = la_y_dim/4;
+	
+        //console.log("*** scale to y dim = " + la_y_dim);
+	
+        //alert("scale_to_y_dim = " + scale_to_y_dim);
+
+
+        aspectMaxRatio = calcMaxRatio(aspectRatios);
+	//var complete_width_100 = calcCompleteWidth(aspectRatios,100); // as if every aspect ratio bin is scaled to 100 pixels high
+
+	
+	scale_to_y_dim = calcScaleToHeight(aspectRatios,la_x_dim,la_y_dim);
+
+
+        var items = [];
+	
+	
+        $.each(data, function(key, ratio_table) {
+            var freq = ratio_table.freq;
+            var ratio_array = key.split(":");
+            var ratio_x = ratio_array[0];
+            var ratio_y = ratio_array[1];
+            var ratio = ratio_y / ratio_x;
+	    
+            var ratioScale = aspectMaxRatio/ratio;
+	    
+            var x_dim = Math.round(scale_to_y_dim * ratioScale);
+            var y_dim = scale_to_y_dim;
+	    
+            var innertext = "<div style='font-size: 180%;'>"+freq + " countries, " + key + "</div>";
+            
+            var flags = [];
+	    
+            var nz_prioritized_flags = ratio_table.flags.sort();
+	    
+            // Promote NZ flag to start of array, but otherwise keep sorted
+            var p = nz_prioritized_flags.length-1;
+            var found_nz = false;
+	    
+            while (p>0) {                
+                var curr;
+                var curr_title;
+		
+                if (!found_nz) {
+                    curr = ratio_table.flags[p];
+                    curr_title = curr.replace(/^.*\//,"").replace(/\.(.*?)$/,"");
+                }
+		
+                if (curr_title == "nz") {
+                    found_nz = true;
+
+                    // swap with adjacent cell
+                    var tmp_m1 = nz_prioritized_flags[p-1];
+                    nz_prioritized_flags[p-1] = curr;
+                    nz_prioritized_flags[p] = tmp_m1;
+                }
+                p--;
+            }
+	    
+            $.each(nz_prioritized_flags, function(index, flag_filename) {                
+                var title = flag_filename.replace(/^.*\//,"").replace(/\.(.*?)$/,"");
+		
+                flags.push("<img src='../similarity-2d/"+flag_filename+"' id='aspect-ratio-"+ title +"' style='height: 70px; padding: 3px; ' title='" + title.toUpperCase() + "'/>");
+            });
+	    
+            innertext += flags.join("");
+	    
+            var ratio_id = "ratio-" + key.replace(":","_");
+            if (found_nz) {
+                currentRatio = ratio_id;
+            }
+	    
+            var id = " id='" + ratio_id + "'";
+	    
+            var style = "style='width:" + x_dim + "px; height:" + y_dim + "px;";
+            if (found_nz) {
+                style += "border-color:white; border-width:4px;"
+            }
+	    
+            style += " overflow-y:scroll;";
+            style += "'";
+	    
+            var onclick = " onclick='updateCanvasDimensions("+ratio_y + "," + ratio_x + ")'";
+	    
+            items.push( "<div class='ratioDiv'" + id + style + onclick + ">"+ innertext + "</div>" );
+	    
+        });
+	
+        $('#aspect-ratio-div').append("<div class='centredDiv' style='width: 100%'>"+items.join("\n")+"</div>");
+	
+	
+        // now change the flag tooltip labels into their country names
+        $.getJSON( "../similarity-2d/iso-3166-keyed-by-alpha-2-countrycodes.json", function(data) {
+	    
+            $.each( data, function( iso2_key, country_name ) {
+		var $img = $('#aspect-ratio-'+iso2_key.toLowerCase());
+		var title = $img.attr("title") + ": " + country_name;
+		$img.attr("title",title);
+            }
+          )
+		});
+	
+    });
+});
+
+
+
+$(window).resize(function() {
+    console.log("choose-canvas resize()");
+
+    //console.log("*** aspect ratio div position top = " + $('#aspect-ratio-div').position().top);
+    
+    var window_height = $(window).height();
+    var div_top = $('#aspect-ratio-div').offset().top + 20;
+
+    //var top = 0;
+    
+    var la_y_dim = window_height - div_top;
+    var la_x_dim = $(window).width() * 0.7;
+
+    var scale_to_y_dim = calcScaleToHeight(aspectRatios,la_x_dim,la_y_dim);
+
+    // (top==0) ? la_y_dim/4 : la_y_dim/2.8;
+    
+    //console.log("*** scale to y dim = " + la_y_dim);
+    
+    $.each(aspectRatios, function(key, ratio_table) {
+        var freq = ratio_table.freq;
+        var ratio_array = key.split(":");
+        var ratio_x = ratio_array[0];
+        var ratio_y = ratio_array[1];
+        var ratio = ratio_y / ratio_x;
+	
+        var ratioScale = aspectMaxRatio/ratio;
+	
+        var x_dim = Math.round(scale_to_y_dim * ratioScale);
+        var y_dim = scale_to_y_dim;
+
+        var ratio_id = "ratio-" + key.replace(":","_");
+	
+        //console.log("*** ratio_id = " + ratio_id + " xdim = " + x_dim + ", ydim = " + y_dim);
+	
+        $('#'+ratio_id).css("width",x_dim + "px");
+        $('#'+ratio_id).css("height",y_dim + "px");
+	
+	
+    });
+});
+
+
+
+function updateCanvasDimensions(height, width) {
+    
+    // Show feedback by highlighting the chosen square
+    document.getElementById(currentRatio).style.borderColor = 'black';
+                document.getElementById(currentRatio).style.borderWidth = '1px';
+    currentRatio = "ratio-" + width + "_" + height;
+    document.getElementById(currentRatio).style.borderColor = 'white';
+    document.getElementById(currentRatio).style.borderWidth = '4px';
+    
+    // Changing the value of sizeConstant will change the
+    //  size of the svg canvas without affecting the 
+    //  width/height ratios
+    
+    var sizeConstant = 400;
+    
+    var h = sizeConstant;
+    var w = (sizeConstant / height) * width;                
+    
+    if (typeof flagCanvasSettings !== 'undefined') {
+        flagCanvasSettings.width = w;
+        flagCanvasSettings.height = h;
+    }                               
+}
+
+
+
     </script>
-      
+            
     <title>Canvas Size</title>
 
Index: /other-projects/nz-flag-design/trunk/main-form/choose-canvas.js
===================================================================
--- /other-projects/nz-flag-design/trunk/main-form/choose-canvas.js	(revision 29804)
+++ /other-projects/nz-flag-design/trunk/main-form/choose-canvas.js	(revision 29805)
@@ -1,2 +1,3 @@
+
 // Variable for the currently selected flag ratio
 var currentRatio = null;
Index: /other-projects/nz-flag-design/trunk/main-form/iterative-design.html
===================================================================
--- /other-projects/nz-flag-design/trunk/main-form/iterative-design.html	(revision 29804)
+++ /other-projects/nz-flag-design/trunk/main-form/iterative-design.html	(revision 29805)
@@ -7,4 +7,7 @@
 	<!-- jQuery -->
 	<script src="lib/jquery-1.11.1.min.js"></script>
+
+	<script src="../similarity-2d/js-lib/Colour.js"></script>
+	<script src="../similarity-2d/flag-processing.js"></script>
 
         <title>Iterative Design</title>	
@@ -94,6 +97,7 @@
 
                         // Look up jsession id; if not present fall back to use a timestamp
-                        //var jsession_id = $.cookie('JSESSIONID') || new Date().getTime();
-                        var jsession_id = $.cookie('JSESSIONID') + "-" + new Date().getTime();
+                        var jsession_id = $.cookie('JSESSIONID') || new Date().getTime();
+                        //var jsession_id = $.cookie('JSESSIONID') + "-" + new Date().getTime(); // quick hack for summer scholarship presentation day
+
                         console.log("jsession id = " + jsession_id);
                         var imageFilename = "flag-" + jsession_id + ".png";
@@ -195,4 +199,31 @@
 
 
+		function rankFlags() {
+		  // First compute colour histogram for user drawn flag
+		  var imageCanvas = document.getElementById('export_canvas');
+		  var context = imageCanvas.getContext('2d');
+		  var imageData = context.getImageData(0,0, imageCanvas.width, imageCanvas.height);
+
+		  var outputArray = createHSLHistogramFromCanvasData(imageData,imageCanvas.width,imageCanvas.height,16);
+
+		  // Now compare this colour histogram with the stored ones, updating the progress bar as we go
+
+		  var $iframe = $('#similarity-2d-iframe').contents();
+
+		  var $flagArea     = $iframe.find('#flagArea');
+		  var $progressArea = $iframe.find('#progressArea');
+                  var $progressBar  = $iframe.find('#progressBar');
+
+         	  $progressArea.find('span:first').text("Calculating flag similarity");
+	          $progressArea.slideDown();
+
+		  calcSimilarityValues(outputArray, $flagArea,$progressArea,$progressBar);
+		  
+		  // And finally reorder them based on this
+		  sortFlagsBySimilarityValue($iframe)
+
+	          $progressArea.slideUp();
+		}
+
                 function activateAccordion() {
                     console.log("activateAccordion()");
@@ -212,4 +243,11 @@
                                     console.log("onTriggerSlide: this = " + this);
                                     console.log("onTriggerSlide: id = " + this[0].id);
+                                    if (this[0].id == "similarity-2d-div") {
+                                        console.log("Triggering flag similarity comparison");
+                                        savePNGAsFile("PNG",null);
+
+		                        setTimeout(rankFlags, 1000);
+
+                                    }
                                     if (this[0].id == "render-3d-div") {
                                         console.log("Triggering SVG-Editor exportPNG()");
@@ -248,10 +286,11 @@
                     var la_y_dim = $(window).height() * 0.67;
 
-                    $('#side-by-side')
-                    .liteAccordion('resize', {
-                        containerWidth  : la_x_dim,
-                        containerHeight : la_y_dim
-                    });
-
+		    if ($('#side-by-side').liteAccordion) {
+                      $('#side-by-side')
+                      .liteAccordion('resize', {
+                          containerWidth  : la_x_dim,
+                          containerHeight : la_y_dim
+                      });
+		    }
                 });
 
