$.fn.mlspinFeed = function(cb){
		var url = "http://saldane.com/~koryakm/mlspin.pl?callback=?";
		var aid = "G9500060";
		var $this = $(this);
		var speed = 5000;
		var fadeSpeed = "normal";
		
		var stuff = [];
		var current = 0;
		var focus = false;
		
		if($this.length == 0) return $this;
		
		var mouseover = function(e){
			var ui = e.data.item;
			ui.status.removeClass("ui-icon-play").addClass("ui-icon-pause");
			focus = true;	
		};
		var mouseout = function(e){
			var ui = e.data.item;
			ui.status.addClass("ui-icon-play").removeClass("ui-icon-pause");
			focus = false;	
		}
		var fader = function(){
			if(!focus){
				stuff[current].ui.body.hide();
				current ++;
				current = (current >= stuff.length)? 0 : current;
				stuff[current].ui.body.fadeIn(fadeSpeed);
				cb();
			}
		}
		var getData = function(opt){
			var base = "http://idx.mlspin.com/";
			var that = {};
			that.url = base + opt.link[0];
			that.id = opt.text[0];
			that.address = opt.text[1];
			that.desc = opt.text[3];
			that.price = opt.text[4];
			that.ui = {};
			
			if(opt.text[5]){
				that.pics = parseInt(opt.text[5],10);
			}
			that.img = base + "/photo/photo.aspx?mls="+that.id+"&w=174&h=150";
			var img = new Image();
			img.src = that.img;
			that.baseUrl = base;
			var wrap = function(h){
				return "<a href='javascript:iframe(\""+base+"details.asp?mls="+that.id+"&aid="+aid+"\", 1000);'>"+h+"</img></a>";
			}
			
			that.ui.body = $("<div class='mlspin' style='display:none'><div>");
			that.ui.img = $("<div class='img'>"+wrap("<img style='width:95%;' src='"+that.img+"'></img>")+"</div>");
			that.ui.address = $("<div class='address'>"+that.address+"</div>");
	//		that.ui.desc = $("<div class='desc'>"+that.desc+"</div>");
			that.ui.price = $("<span class='price'>"+that.price+"</span>");

			var html = [];
			if(that.pics) { html.push("<div class='pics'>"); }
			for(var i = 0; (i < that.pics && i < 3); i ++){
				img.src = base+"/photo/photo.aspx?w=64&h=48&mls="+that.id+"&n="+i;
				html.push("<span class='thumb' >"+wrap("<img src='"+base+"/photo/photo.aspx?w=64&h=48&mls="+that.id+"&n="+i+"'></img>")+"</span>");				
			}
			if(that.pics) { html.push("</div>"); }
			that.ui.pics = html.join("");
			that.ui.status = $("<div class='status ui-icon ui-icon-play'></div>");
			//construct the html
			that.ui.body.append(that.ui.img).append(that.ui.address).append(that.ui.price).append(that.ui.status).append(that.ui.pics);			
			
			that.ui.body.bind("mouseover", {"item": that.ui}, mouseover).bind("mouseout", {"item": that.ui}, mouseout);
			that.ui.body.tooltip({ 
					track: true, 
					delay: 0, 
					showURL: false, 
					fade: 250,
					bodyHandler: function(){
						return that.desc;
					}
			});

			return that;
		}
		
		$.getJSON(url, function(data){
			$.each(data, function(i,n){
				var d = getData(this);
				$this.append(d.ui.body);
				stuff.push(d);
			});
			cb();
			var f = function(){
				fader();
				setTimeout(f, speed);
			};
			f();
		});
		
		
	}

$.fn.ajaxLinks = function(){
	var $this = $(this);
	
	$("a[href^=/ajax/]").click(function(){
		$("#main-iframe").hide();
		$("#col1-content").show();
		var href = $(this).attr("href");
		var name = $(this).attr("name");
		var $click = $(this);
		$this.load(href, function(){
			$("#col1").height("100%"); 
			$slideMenu.select(name);
			$("#col1, #col2").equalizeCols();
		});
		
		return false;
	});
};


 
(function($) {
	$.fn.equalizeCols = function(minHeight){
		var height = 0;
		var reset = $.browser.msie ? "1%" : "auto";
		minHeight = minHeight || 400;
  
  	
		return this
			.css("height", reset)
			.each(function() {
				if(minHeight){
					height = Math.max(Math.max(height, this.offsetHeight), minHeight);
				} else {
					height = Math.max(height, this.offsetHeight);
				}
			})
			.css("height", height)
			.each(function() {
				var h = this.offsetHeight;
				if (h > height) {
					$(this).css("height", height - (h - height));
				}; 
			});
			
	};
	$.fn.mainMenu = function(){
		var height = 0;
		var reset = $.browser.msie ? "1%" : "auto";
		var $this = $(this);
		var pageWidth = $this.width();
		var len = $this.length;
		var itemWidth = Math.floor(pageWidth / (len)) - 1;
		var offset = pageWidth - (itemWidth * len);
		$this.css("width", itemWidth);
		$($this.get(len - 1)).css({"width": (itemWidth + offset)});

		$this.find("li")
			.css("height", reset)
			.each(function() {
				height = Math.max(height, this.offsetHeight);
		}).css({"height": height}).children("a").css({backgroundPosition: "-20px "+height+"px"}).mouseover(function(){
				$(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:500})
		}).mouseout(function(){
				$(this).stop().animate({backgroundPosition:"(40px "+height+"px)"}, {duration:400, complete:function(){
					$(this).css({backgroundPosition: "-20px "+height+"px"});
				}});
		}).each(function() {
			var h = this.offsetHeight;
			if (h > height) {
				$(this).css({"height": height - (h - height)} );
			}; 
		});		
		return this;
	};
	
	$.fn.slideMenu = function(config){
		var config = config || {};
		var padOut = config.padOut || 15;
		var padIn = config.padIn || 0;
		var speed = config.speed || 2;
		var time = config.time || 150;
		var selected = config.selected || "";
		
		var $sel = $("<div></div>");
		var nameToItem = {};
		var timer = 0;
		$(this).find("li").each(function(){
			timer = (timer / speed + time);
			var $this = $(this);
			
			
			
				$this.css("margin-left","-180px");
				$this.animate({ marginLeft: "0" }, timer);
				$this.animate({ marginLeft: "15px" }, timer);
				$this.animate({ marginLeft: "0" }, timer);
				if($(this).find("a").attr("name") === selected){
					$sel = $this;
					$sel.css("padding-left", padOut);	
				}
			
			
		});
		$(this).find("a").each(function(){
			var $this = $(this);
			var name = $(this).attr("name");
			$this.hover(function(){
				if(name !== selected){
					$(this).parent().animate({ paddingLeft: padOut }, 150);
				}
			},function(){
				if(name !== selected){
					$(this).parent().animate({ paddingLeft: padIn }, 150);
				}
			});
			
			if($.fn.corner){
				$this.corner("tr br");
			}
			nameToItem[name] = $this;
		}).click(function(){
			var name = $(this).attr("name");
			if(selected !== name){
				$sel.animate({ paddingLeft: padIn }, 150);
				select(name);
			}
		});
		var select = function(it){
			var item = (typeof it === "string")? nameToItem[it] : it;
			if(item){
				$sel = item.parent();
				selected = item.attr("name");
				$sel.css("padding-left", padOut);	
			}
		}
		this.select = select;
		window["$slideMenu"] = this;
	};
	
	$.fn.nytArticles = function(conf){
			var q = conf.q || "news";
			var key = conf.key ;
			var num = conf.numArticles || 3;
			var callback = conf.callback || function(){};
			
			var jsonpProxyUrl = "http://saldane.com/~saldane/jsonp_wrapper.pl?callback=?&uri=";
			var nytUrl = "http://api.nytimes.com/svc/search/v1/article?query="+q+"&order=newest&jsoncallback=?&api-key="+key+"&fields=abstract,small_image,small_image_url,small_image_height,small_image_width,title,url,lead_paragraph,body";
			var url = jsonpProxyUrl + encodeURIComponent(nytUrl);
			
			
			var parent = $(this);
			parent.empty();
			
			$.getJSON(url, function(data){
				for(var i = 0; i < num && i < data.total; i++){
					var elem = $("<div class='nytArticle'></div>");
				//	console.log(data.results);
					var art = data.results[i];
					if(art.small_image){
							elem.append("<div class='nytImage'><img src='"+art.small_image_url+"'></img></div>");
					}
					var text = art.abstract || art.lead_paragraph || art.body;
					elem.append("<div class='nytTitle'>"+art.title+"</div><div class='nytText'>"+text+"</div><a href='"+art.url+"' class='nytUrl' target='_top'>... read more at nyt.com</a>");					
					parent.append(elem);
				}
				callback();
			});
	};
	$.fn.visualTourFeed = function(conf){
		var pages = conf.pages || 3;
		var speed = conf.speed || "normal";
		var fadeSpeed = conf.fadeSpeed || 5000;
		
		var jsonpUrl = "http://saldane.com/~koryakm/helloworld.pl?pages="+pages+"&callback=?";
		var div = $(this);
		
		var current = 0;
		var fader = function(data){
			data[current].$block.hide(); //todo: fadeout like the plugin
			current ++;
			current = (current >= data.length)? 0 : current;
			data[current].$block.fadeIn(speed);
			
		}
		$.getJSON(jsonpUrl, function(data){			
			$.each(data, function(i,n){
				var block = $("<div style='display:none'></div>");
				block.append("<img class='faderImg' style='width:95%;' src='"+this.img+"'></img>");
				block.append("<div class='faderTitle'>"+this.title1+"</div>");
				block.append("<div class='faderTitle'>"+this.title2+"</div>");
				block.append("<div class='faderDesc'>"+this.desc2+"</div>");
				data[i].$block = block;
				div.append(block);
			});
			var f = function(){
				fader(data);
				setTimeout(f, fadeSpeed);
			};
			setTimeout(f, fadeSpeed);
			
		});

	}
	$.fn.compareTowns = function(){
		$this = $(this);
		$this.append("ZIP code 1:<input id='zip1' value=''/><br/>ZIP Code 2:<input id='zip2' /><br/>");
		var button = $("<input type='button' value='Compare'></input>");
		button.click(function(){
			var z1 = $("#zip1").val() || "00000";
			var z2 = $("#zip2").val() || "00000";
			//TODO: validation
			$this.empty().append('<iframe id="cominfoframe" width="95%" height="720px" style="border:0 none;" src="http://saldane.com/~koryakm/compareTowns.pl?zip1='+z1+'&zip2='+z2+'"></iframe>');
			$("#col1, #col2").equalizeCols();
		});
		this.append(button);
		return this;
	}
	
})(jQuery);

var iframe = function(url, height){
	
	$("#main-iframe").show();
	$("#col1-content").hide();
	if($("#main-iframe").length){
		$("#main-iframe")[0].src=url;
		$("#col1, #col2").equalizeCols();
		if(height){
			$("#main-iframe").height(height);
		}
	}
}

var resizeMainMenu = function(){
	var pageWidth = $("#main-menu").width();
	var items = $("#main-menu li");
	var itemWidth = Math.floor(pageWidth / (items.length)) - 1;
	var offset = pageWidth - (itemWidth * (items.length)) - 1 ;
	items.css("width", itemWidth);
	$(items.get(items.length - 1)).css({"width": (itemWidth + offset)});
}


$(function(){
	resizeMainMenu();
	
	$("#col1-content").show();
	$("#main-menu").mainMenu();
	$("#col1-content").ajaxLinks();
	$("#portfolio").mlspinFeed(function(){
			$("#col1, #col2").equalizeCols();
	});
	$("#col1, #col2").equalizeCols();
	
	$("#footer").empty().load("/ajax/footer.htm", function(){
		//do nothing yet.
	});
});