	$(document).ready(function(){
		function calc_ads(trackEvent){
			if(typeof trackEvent == "undefined"){ trackEvent = true; }
			// vars
				max_height = 15;
				min_height = 1;
				max_cols = 5;
			// get budget
				var budget = parseFloat($("#ad_budget").val());
				if (budget > 0){}else {return false;}
				$.log("budget = %s",budget);
			// get rate
				var rate = parseFloat($("#ad_rate").val());
				if (rate > 0){}else {return false;}
				$.log("rate = %s",rate);
			// calculate column inches
				var ci = Math.floor( budget * 2 / rate )/2;
				$.log("column inches = %s",ci);
				if (ci < min_height){ return false;}
			// check columns
				var ads = [];
				for (c=1; c<=max_cols; c++){
					var h = Math.floor( ci * 2 / c )/2;
					// impose max height
						if (h > max_height) {
							if (h > max_height + 2 && c<5) {
								h = 0;
							} else {
								h = max_height;
							}
						}
					// cancel if less than min height
						if(h<min_height){h = 0;}
					// cancel if too wide
						if(c>=4 && h<2){h=0;}
					// add to list
						if(h>0){
							// log
							$.log("%s column max = %s",c,h);				
							// add to list
								var ad = {
									width: c,
									height: h
								};
								ads.push(ad);
						}
				}
			// compose ads
			var ads_html = "";
			$.each(ads,function(k,v){
				var cssh = v.height * 10;
				var cssw = v.width * 20;
				var cost = "$" + Math.round(rate * v.height * v.width);
				ads_html += "				<div class='virtual_ad'>";
				ads_html += "					<div class='page'>";
				ads_html += "						<img src='ad_calc/ad_back.gif' alt=''/>";
				ads_html += "						<img class='ad_img' style=\"height: " + cssh + "px; width: " + cssw + "px;\" src='ad_calc/ad_1c.gif' title='' alt=''/>";
				ads_html += "					</div>";
				ads_html += "					<div class='size'>" + v.width + " col. x " + v.height + "\"</div>";
				ads_html += "					<div class='cost'>" + cost + "</div>";
				ads_html += "				</div>";
			});
			$("#ad_page_list").html(ads_html);
			// show ads
			$.log(ads);
			// Google Analytics event tracking
			if (trackEvent) {
				$.log("tracking GA event");
				pageTracker._trackEvent("Ad Size Calculator", "Calculate", budget);
			}
		}
		// bind button click
		
		$("#btn_show_ads").click(function(){
			calc_ads();
		});
		// bind enter key press
		$("#ad_budget").keypress(function(e){
			if (e.which == 13){ calc_ads();}
		});
		// bind rate list change
		$("#ad_rate").change(function(e){
			calc_ads();
		});
		
		// trigger calc
		$(window).load(function(){
			calc_ads(false);
		});
	});