/* sni-living - Mon, 06 Sep 2010 20:43:54 -0400 */

if( typeof(SNI.Living) == "undefined" ) {
	SNI.Living = {};
}

if( typeof(SNI.Living.GlobalInit) == "undefined" ) { SNI.Living.GlobalInit = {}; };

SNI.Living.GlobalInit = {
	extLink: function() {
		$('a.ext').click(function() {
			window.open(this.href);
			return false;
		});
	}

};/**
 * Living-ads.js
 *
 * requires core ads functionality from sni-global.js
 * requires mdManager (uses mdManager within functions, but not during load)
 */


function FoodAd(adtype, adsize, pos, keywords) {
	if(pos < 0 || pos == undefined) {pos = 1;}
	if(keywords == undefined) { keywords = ""; }
	
	var ad = new DartAd();
	ad.setUrl("http://"+SNI.Ads._adServerHostname+"/js.ng/");
	
	if (adtype== 'BIGBOX' && pos == 5) {
		ad.addParameter("adtype", 'BIGBOX');
	} else {
		ad.addParameter("adtype", adtype );
	}
	
	if (adtype== 'LEADERBOARD') {
		ad.addParameter("Params.styles", "SNI_LEADERBOARD"); //tells ad server to wrap with div.ad-ldr
	}
		
	ad.addParameter("adsize", adsize);
	ad.addParameter("PagePos", pos);

	if( keywords != "" ) {
		var words = keywords.split(" ");
		for(i=0; i < words.length; i++) {
			ad.addParameter("keyword", words[i]);
		}
	}
	
	writeAd(ad);
}


function writeAd(ad){
	if (typeof adRestrictionManager != 'undefined') {
		ad.useIframe = adRestrictionManager.isIframe(ad, mdManager);
		if( adRestrictionManager.isActive(ad, mdManager) != false) {
			adManager.createAd(ad);
		}
	} else {
		adManager.createAd(ad);
	}	
}


//Recipe Ad
function RecipeAd (pos, adtype, pnames, pvals) {
	if(pos < 0 || pos == undefined) {pos = 1;}
			
	var ad = new DartAd();
	
	if (pos == 1 && adtype == 'GOOGLE') {pos = 2;}
	
	ad.setUrl("http://"+SNI.Ads._adServerHostname+"/js.ng/");
	ad.addParameter("PagePos", pos);
	// ad.addParameter("Params.styles", "trace");
	
	if (adtype != "" &&  adtype != undefined)
	 { 
       ad.addParameter("adtype", adtype);
	 } else {
	  	if(pos == 5) {
  			ad.addParameter("adtype", 'BIGBOX');
		}
	 }
	 
	var paramNames = pnames.split(" ");
	var paramVals = pvals.split(" ");
	
	for(i = 0; i < paramNames.length; i++) {
		ad.addParameter(paramNames[i], paramVals[i]);
	}

	writeAd(ad);
}


function LeaderboardAd(pos) {
	if(pos < 0 || pos == undefined || pos=='') {pos = 1;}
	FoodAd('LEADERBOARD', '468x60',  pos);
}


function PushdownAd(pos) {
	if(pos < 0 || pos == undefined) {pos = 1;}
	FoodAd('PUSHDOWN', '', pos);
}


function GoogleBixboxAd(pos) {
	// Food GOOGLE BIG BOX 300x250 adtag
	if(pos < 0 || pos == undefined) {pos = 1;}
	FoodAd('GOOGLE_BIGBOX', '', pos);
}


function GoogleLeaderboardAd(pos) {
	// Food GOOGLE HORIZONTAL RECTANGLE 630x132 adtag
	if(pos < 0 || pos == undefined) {pos = 1;}
	FoodAd('GOOGLE_LEADERBOARD', '', pos);
}


function BigboxAd(pos, keywords) {
	if(pos < 0 || pos == undefined) {pos = 1;}
	FoodAd('BIGBOX', '', pos, keywords);
}


function SuperstitialAd(pos) {
	if(pos < 0 || pos == undefined) {pos = 1;}
	FoodAd('SUPERSTITIAL', '', pos);
}


/*
function WDSearchAd(adtype, pos, keywords) {
	if(pos < 0 || pos == undefined) {pos = 1;}
			
	var ad = new DartAd();
	
	ad.setUrl("http://"+SNI.Ads._adServerHostname+"/js.ng/");
	ad.addParameter("adtype", adtype);
	ad.addParameter("adsize", "");
	ad.addParameter("PagePos", pos);
	// ad.addParameter("Params.styles", "trace");
	
	var words = keywords.split(" ");
	for(i = 0; i < words.length; i++) {
		ad.addParameter("keyword", words[i]);
	}
	writeAd(ad);
}

*/


//Video PreRoll & Overlay Ad functions for Maven, Pickle
function VideoPlayerAd(adtype, adsize, pos) {
	var ad = new AdUrl();
	
	ad.setUrl("http://"+SNI.Ads._adServerHostname+"/html.ng/");
	if (adtype != '') {	ad.addParameter("adtype", adtype); }
	if (adsize != '') { ad.addParameter("adsize", adsize); }
	if (!pos || pos=='') { pos = 1; }
	ad.addParameter("PagePos", pos);
	ad.useFeature("tile");
	writeAd(ad);

   return ad.buildExpandedUrl();
}


// Video Player Ad Integration
// The video player will make calls to the following javascript functions to 
//    1. Get a Dart ad tag url for PRE_ROLL and OVERLAY ads.
//--Wrapper function which the video player calls to get a preroll ad tag url -->
function getDartEnterpriseUrl(adtype,pos){
   		adtype = adtype.toUpperCase();
   		var strUrl = VideoPlayerAd(adtype,'', pos);
   		return strUrl;
}

function setDartEnterpriseBanner(adType, sync_banner) {
	if (adType == 'LEADERBOARD') {
	  if($("#leaderboard").length > 0) {
			boxW = 728;
			boxH = 90;
			$("#leaderboard").html("<iframe src='" + sync_banner + "\' width=\'" + boxW + "\' height=\'" + boxH + "\'" + "frameborder='0' scrolling='no' marginheight='0' marginwidth='0'></iframe>");
		}
	} else { // assumes adType == 'BIGBOX' or should
		if($("#bigbox").length > 0) {
			boxW = 300;
			boxH = 250;
			if (sync_banner.indexOf("336x850") > -1) {
				boxW = 336;
				boxH = 850;
			} else if (sync_banner.indexOf("300x600") > -1)	{
				boxW = 300;
				boxH = 600;
			}
			$("#bigbox").html("<iframe src='" + sync_banner + "\' width=\'" + boxW + "\' height=\'" + boxH + "\'" + "frameborder='0' scrolling='no' marginheight='0' marginwidth='0'></iframe>");
		}
	}
	return;
} 

// multiple sponsor logo tag
function MultiLogoAd(adtype,logoNum) {
	var ad = new DartAd();
	if (logoNum == undefined || logoNum == '' || logoNum > 4 || logoNum < 1) { logoNum = 4; }
	if (adtype == undefined || adtype == '') { adtype = 'LOGO';	}
	ad.setUrl("http://"+SNI.Ads._adServerHostname+"/snDigitalLogo"+logoNum+".html?");
	ad.addParameter("adtype", adtype );
	ad.addParameter("PagePos", 1 );
	if (logoNum > 0) {
		writeAd(ad);
		$(document).ready( function() {
			if ($(".sponsor-multi-logo a img").length > 0) {
				$(".sponsor-multi-logo").prepend("<em>Sponsored by:</em>");
			}
		});
	}
}


//==ENDECA Functions Begin ===============================================================
//functions added at the request of Amy Thomason for the Endeca recipe search

function WDGuidedNavSearchAds(adtype, pos, keywords, filters, pageNo) {
	var ad = new DartAd();
	if(pos < 0 || pos == undefined) {
		pos = 1;
	}
	if(pageNo > 0 && pageNo != undefined) {
	   ad.addParameter("Page", pageNo);
	}
	ad.setUrl("http://"+SNI.Ads._adServerHostname+"/js.ng/");
	ad.addParameter("adtype", adtype);
	ad.addParameter("adsize", "");
	ad.addParameter("PagePos", pos);
	// ad.addParameter("Params.styles", "trace");
	var words = keywords.split(" ");
	for(i = 0; i < words.length; i++) {
		ad.addParameter("keyword", words[i]);
	}
	var words = filters.split(" ");
	for(i = 0; i < words.length; i++) {
		ad.addParameter("filter", words[i]);
	}
	writeAd(ad);
}


function WDGuidedNavSiteAdAds(adtype, keywords, filters, pageNo) {
	WDGuidedNavSearchAds(adtype, 1, keywords, filters, pageNo);
	//WDGuidedNavSearchAds(adtype, 2, keywords, filters, pageNo)
}

//==ENDECA Functions End ===============================================================

if( typeof(SNI.Util) == "undefined" ) {
	SNI.Util = {};
}

/**
* Defaults an input field to 'defaultText' and automatically
* removes the text when the input field is clicked.
*
* Example:
* SNI.Util.inputField('#search-box', 'Search:');
*
* Params:
*  elem: the text field to attach the default text
*  defaultText: the default text to display in the field if nothing already exists
*  preventDefault: (optional, default is 'blank') to determine if form is prevented from submitting
*                  when the default value has not been changed by the user. If set to true it will
*                  stop the form submission.
*/
SNI.Util.inputField = function(elem, defaultText, preventDefault) {
	var elem = $(elem);
	var preventDefault = preventDefault == null ? 'blank' : preventDefault;
	var hintClass = 'input-hint';

	if (elem.length > 0) {
		var input = elem.get(0);

		// make sure we're dealing w/ an input field
		if (input.tagName.toLowerCase() == 'input' && input.type == 'text') {

			// load up the default text if nothing is in the field
			if ($.trim(elem.val()) === '') {
				elem.val(defaultText);
				elem.addClass(hintClass);
			}

			// show our default text if there is nothing in the field
			elem.blur(function() {
				if ($.trim(this.value) === '') {
					this.value = defaultText;
					elem.addClass(hintClass);
				}
			});

			// hide our default text when input is clicked
			elem.focus(function() {
				if (this.value == defaultText) {
					this.value = '';
				}
				elem.removeClass(hintClass);
			});

			// prevent form from submitting when default value exists in header site search only - otherwise it submits default text
			if (preventDefault === true || preventDefault == 'blank') {
				form = $(elem.get(0).form);
				if (form) {
					form.submit(function(event) {
						if ($.trim(elem.val()) == defaultText || $.trim(elem.val()) == "") {
							if (preventDefault === true) {
								event.preventDefault();
								elem.focus();
							} else {
								elem.val('');
							}
						}
						return true;
					});
				}
			}
		}
	}
};




/**
 * popups a new browser window
 */
 
SNI.Util.popup = function(url,w,h,menu) {
	x = Math.floor((screen.width - w) / 2);
	y = Math.floor((screen.height - h) / 2);        
	now = new Date();
	features = "screenx="+x+",screeny="+y+",left="+x+",top="+y+",width="+w+",height="+h+",location=no,resizable=yes"+",directories=no,status=no,scrollbars=yes";

	if (menu != null) {
		//features += ",menubar=yes,toolbar=yes,scrollbars=yes";
		features += ",menubar=yes,toolbar=yes";
	} else {
		//features += ",menubar=no,toolbar=no,scrollbars=no"; 
		features += ",menubar=no,toolbar=no"; 
	}
	window.open(url,"newwin",features);
};


// clear input field onfocus
SNI.Util.clearinput = function() {
	var slugValue = document.getElementById("s").defaultValue;

	$(".search .input input").focus(function() {
		
		if( this.value == this.defaultValue ) {
			this.value = "";
	}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});

	$(".search-form").submit(function() {
	    if ($(".search .input input").val() == slugValue) {
		$(".search .input input").val('');
		return false;
      }
      else {
      	return true;
      }
   });
};

// wrap post images in div
SNI.Util.imgwrap = function() {
	$(".text p img").each(function() {
		$(this).wrap("<span class='center'></span>");
	});
};if (typeof(SNI.Living.Newsletter) === "undefined") { 
	SNI.Living.Newsletter = {}; 
}

SNI.Living.Newsletter = {

	init: function() {			
		var validator = $("#subscribe").validate({
   
	debug: false,

		rules: {
			hgtv_living: "required",
			email: { 
				required: true,
				email: true
			},
			email_confirm: {
				required: true,
				equalTo: "#email"
			},
			FIRST_NAME_: "required",
			LAST_NAME_: "required",
			POSTAL_CODE_: "required"
		},
	
		messages: {
			hgtv_living: "Please select at least one newsletter",
			email: "Please enter your email address",
			email_confirm: "Please confirm your email address",
			FIRST_NAME_: "Please enter your first name",
			LAST_NAME_: "Please enter your last name",
			POSTAL_CODE_: "Please enter your ZIP code"
		},
	
		errorContainer: ".form-error",
		errorLabelContainer: $(".list", ".form-error"),
		wrapper: "li",
		showErrors: function(errorMap, errorList) {
			
				if (errorList.length) {
				$('html, body').fadeIn();
				
				this.defaultShowErrors();
			}

			
		} 
	
	});
	
	// toggle for required checkall
	$("fieldset#sister-sites").find(".select-all").click(function(){
		
		var $this = $(this);
	
		var checkValue = $this.find('#all-news-toggle').text();
		
		if (checkValue === 'Select all'){
			$("#sister-sites input[type='checkbox']").each(function() {
				$("#sister-sites input[type='checkbox']").attr('checked', true);
			});
			$this.find('#all-news-toggle').text('Select none');
		} else {
			$("#sister-sites input[type='checkbox']").each(function() {
				$("#sister-sites input[type='checkbox']").attr('checked', false);
			});
			$this.find('#all-news-toggle').text('Select all');
		}
		
		return false;
	}); // end toggle for checkall


}};



SNI.Living.Newsletter.Change = {

	init: function() {			
		var validator = $("#changemail").validate({
   
	debug: false,

		rules: {
			email: { 
				required: true,
				email: true
			},
			emailnew: { 
				required: true,
				email: true
			},
			emailnew_confirm: {
				required: true,
				equalTo: "#emailnew"
			}
		},
	
		messages: {
			email: "Please enter your old email address",
			emailnew: "Please enter your new email address",
			email_confirm: "Please confirm your new email address"
		},
	
		errorContainer: ".form-error",
		errorLabelContainer: $(".list", ".form-error"),
		wrapper: "li",
		showErrors: function(errorMap, errorList) {
			if (errorList.length) {
				$('html, body').fadeIn();
				this.defaultShowErrors();
			}
		} 
	
	
	});
	
}};


SNI.Living.Newsletter.Unsubscribe = {

	init: function() {			
		var validator = $("#unsubscribe").validate({
   
	debug: false,

		rules: {
			email: { 
				required: true,
				email: true
			},
			email_confirm: {
				required: true,
				equalTo: "#email"
			}
		},
	
		messages: {
			email: "Please enter your email address",
			email_confirm: "Please confirm your email address"
		},
	
		errorContainer: ".form-error",
		errorLabelContainer: $(".list", ".form-error"),
		wrapper: "li",
		showErrors: function(errorMap, errorList) {
			if (errorList.length) {
				$('html, body').fadeIn();
				this.defaultShowErrors();
			}
		} 
	
	});
	
	// toggle for required checkall
	$("fieldset#sister-sites").find(".select-all").click(function(){
		
		var $this = $(this);
	
		var checkValue = $this.find('#all-news-toggle').text();
		
		if (checkValue === 'Select all'){
			$("#sister-sites input[type='checkbox']").each(function() {
				$("#sister-sites input[type='checkbox']").attr('checked', true);
			});
			$this.find('#all-news-toggle').text('Select none');
		} else {
			$("#sister-sites input[type='checkbox']").each(function() {
				$("#sister-sites input[type='checkbox']").attr('checked', false);
			});
			$this.find('#all-news-toggle').text('Select all');
		}
		
		return false;
	}); // end toggle for checkall

}};/* Video Player Object */

// instantiate object namespace
if( typeof(SNI.Living.Player)=='undefined' ) {
	SNI.Living.Player = {};
}



SNI.Living.Player.Configs = {
	FullSize : {
		dimensions : {
			width:'576',
			height:'638'
		},
		flashvars : {
			config:"http://web.hgtv.com/webhgtv/hg20/snap-configs/hgtv-player-fullsize.xml",
			channel:'',									// initial channel id to load
			channelurl:'',								// initial channel feed url to load
			videoid:''									// initial video id of channel to play
		},
		params : {
			menu:"false",
			scale:"noscale",
			allowFullScreen:"true",
			allowScriptAccess:"always",
			wmode:"transparent"
		}
	},

	FullSizeNoPlaylist : {
		dimensions : {
			width:'576',
			height:'460'
		},
		flashvars : {
			config:"http://web.hgtv.com/webhgtv/hg20/snap-configs/hgtv-player-fullsize-noplaylist.xml",
			channel:'',									// initial channel id to load
			channelurl:'',								// initial channel feed url to load
			videoid:''									// initial video id of channel to play
		},
		params : {
			menu:"false",
			scale:"noscale",
			allowFullScreen:"true",						// this is a flash thing and should be set to true
			allowScriptAccess:"always",					// we want to leave this at true
			wmode:"transparent"
		}
	},
	
	RightRail : {
		dimensions : {
			width:'320',
			height:'360'
		},
		flashvars : {
			config:"http://web.hgtv.com/webhgtv/hg20/snap-configs/hgtv-player-rightrail.xml",
			channel:'',									// initial channel id to load
			channelurl:'',								// initial channel feed url to load
			videoid:''									// initial video id of channel to play
		},
		params : {
			menu:"false",
			scale:"noscale",
			allowFullScreen:"true",						// this is a flash thing and should be set to true
			allowScriptAccess:"always",					// we want to leave this at true
			wmode:"transparent"
		}
	},
	
	Blog : {
		dimensions : {
			width:'576',
			height:'460'
		},
		flashvars : {
			config:"http://www.living.com/wp-content/themes/living/js/living-player-blog.xml",
			channel:'',									// initial channel id to load
			channelurl:'',								// initial channel feed url to load
			videoid:''									// initial video id of channel to play
		},
		params : {
			menu:"false",
			scale:"noscale",
			allowFullScreen:"true",						// this is a flash thing and should be set to true
			allowScriptAccess:"always",					// we want to leave this at true
			wmode:"transparent"
		}
	},
	
	Lead : {
		dimensions : {
			width:'400',
			height:'300'
		},
		flashvars : {
			config:"http://web.hgtv.com/webhgtv/hg20/snap-configs/hgtv-player-lead.xml",
			channel:'',									// initial channel id to load
			channelurl:'',								// initial channel feed url to load
			videoid:''									// initial video id of channel to play
		},
		params : {
			menu:"false",
			scale:"noscale",
			allowFullScreen:"true",						// this is a flash thing and should be set to true
			allowScriptAccess:"always",					// we want to leave this at true
			wmode:"transparent"
		}
	}
};




// video library version of player
SNI.Living.Player.FullSize = function(divId, channelId, videoId) {
	return new SNI.Player.SNAP(divId, SNI.Living.Player.Configs.FullSize, channelId, videoId);
};
SNI.Living.Player.Big = SNI.Living.Player.FullSize;							// alias
SNI.Living.Player.VideoLibrary = SNI.Living.Player.FullSize;				// alias


// single video asset version of player
SNI.Living.Player.FullSizeNoPlaylist = function(divId, channelId, videoId) {
	return new SNI.Player.SNAP(divId, SNI.Living.Player.Configs.FullSizeNoPlaylist, channelId, videoId);
};
SNI.Living.Player.VideoAsset = SNI.Living.Player.FullSizeNoPlaylist;		// alias


// right rail version of player
SNI.Living.Player.RightRail = function(divId, channelId, videoId) {
	return new SNI.Player.SNAP(divId, SNI.Living.Player.Configs.RightRail, channelId, videoId);
};


// for players dropped into pickle2 rate my apps
SNI.Living.Player.RightRailMyHGTV = function(divId, channelId, videoId) {
	buildChannelFeedUrlForPickle = function(chId) {
		return 'http://www.hgtv.com/hgtv/channel/xml/0,,' + chId + ',00.xml';
	};

	return new SNI.Player.SNAP(divId, SNI.Living.Player.Configs.RightRail, channelId, videoId, '', buildChannelFeedUrlForPickle);
};


// blog version of player (no playlist)
SNI.Living.Player.Blog = function(divId, channelId, videoId) {
	buildChannelFeedUrlForBlogs = function(chId) {
		return 'http://www.hgtv.com/hgtv/channel/xml/0,,' + chId + ',00.xml';
	};

	return new SNI.Player.SNAP(divId, SNI.Living.Player.Configs.Blog, channelId, videoId, '', buildChannelFeedUrlForBlogs);
};


// lead/dynamic-lead version of player
SNI.Living.Player.Lead = function(divId, channelId, videoId) {
	return new SNI.Player.SNAP(divId, SNI.Living.Player.Configs.Lead, channelId, videoId);
};

/* temporary functions */

$(document).ready(function() {

	//Tag Click Info
		
	$('a[rel="tag"]').click(function() { 
		var s=s_gi('scrippsliving');
		var linkText = $(this).text();
		s.linkTrackVars='prop1,eVar8,event12';
		s.linkTrackEvents='event12';
		s.prop1=linkText;
		s.eVar8=linkText;
		s.events='event12';
		s.tl(this,'o','Tag Click');
	});
	
	//Category Click Info
    $('li.cat-item a').click(function() { 
        var s=s_gi('scrippsliving');
        var linkText = $(this).text();
        s.linkTrackVars='prop11,eVar9,events';
        s.linkTrackEvents='event15';
        s.prop11=linkText;
        s.eVar9=linkText;
        s.events='event15';
        s.tl(this,'o','Category Click');
    });
	
	//RSS Clicks
	$('#nav-rss a').click(function() { 
		var s=s_gi('scrippsliving');
		s.linkTrackVars='events';
		s.linkTrackEvents='event10';
		s.events='event10';
		s.tl(this,'o','RSS Click');
	});
	
	//Newsletter Clicks
	$('#subscribe button').click(function() {
		var s=s_gi('scrippsliving');
		s.linkTrackVars='events';
		s.linkTrackEvents='event11';
		s.events='event11';
		s.tl(this,'o','Newsletter Click');
	});
	
	/*Email Clicks
	var s=s_gi('scrippsliving');
	s.linkTrackVars='events';
	s.linkTrackEvents='event13';
	s.events='event13';
	s.tl(this,'o','Email Click');
	*/

});


/*
if(typeof(SNI.Living.Omniture)=='undefined') {
	SNI.Ecologue.Omniture = {};
}

SNI.Living.Omniture.ClickTrackSpecific = function(jsel, module, propVal) {

  var $el = $(jsel);
	
	if($el.length == 0) {return;}

	$el.click( function(e) {

		var $clicked=$(e.target);
					
			var s=s_gi(s_account);	
	
			s.linkTrackVars=propVal;			
			//s.events=linkTrackEvents;

			s[propVal] = module;
		
			s.tl(this,'o',propVal);	
			e.stopPropagation();

			//alert(propVal,s);

			
	});

};

SNI.Living.Omniture.ClickTrackSpecificLinkText = function(jsel, module, propVal) {
  
  var $el = $(jsel);
	
	if($el.length == 0) {return;}
	
	$el.click( function(e) {

		var $clicked=$(e.target);
		
		if ($clicked.is("a") || $clicked.parent().is("a")) {
			var linkText = $clicked.attr('href');
			if ((linkText == "") && ($clicked.is("img"))) {
				linkText = $clicked.attr("alt");
			}
			
			var s=s_gi(s_account);	
	
			s.linkTrackVars=propVal;

			s[propVal] = linkText;
		
			s.tl(this,'o','Link Name');	
			e.stopPropagation();
		}
	});

};
*/// styled drop down list code - jford
//(function($) {
	
// If the UI scope is not available, add it
$.ui = $.ui || {};

$.fn.extend({
	dropdown: function(options, data) {
		var args = Array.prototype.slice.call(arguments, 1);
		
		return this.each(function() {
			if (typeof options == "string") {
				var dropdown = $.data(this, "ui-dropdown");
				dropdown[options].apply(dropdown, args);
			// INIT with optional options
			} else if (!$(this).is(".ui-dropdown")) {
				$.data(this, "ui-dropdown", new $.ui.dropdown(this, options));
			}
		});
	}
});

$.ui.dropdown = function(container, options) {
	this.element = $(container);
	this.options = options = $.extend({}, $.ui.dropdown.defaults, options);
	this.options.title = this.options.title || this.element.find('option.select-title').text();
	
	this.element.addClass("ui-dropdown");
	
	// build the dropdown list
	this.list = buildList(this.element, this.options);
	this.element.after(this.list);
	
	// save original css values
	this.css = {
		position: this.element.css('position'),
		left: this.element.css('left')
	};
	
	// hide the select
	this.element.hide();
	// this.element.css({ position: 'absolute', left: '-999em' });
	
	if (this.element.attr('disabled')) {
		this.disable();
	} else {
		this.enable();
	}

	// TODO: complete the keybooard implementation. The items below work but need all key events working
	// this.element.bind('focus', {dropdown: this}, this.activate);
	// this.element.blur(hideDropDowns);
	// this.element.keydown(function(event) {
	// 	event.preventDefault();
	// });
};

$.extend($.ui.dropdown, {
	defaults: {
		title: '',
		disabled: false
	}
});

$.ui.dropdown.prototype = {
	
	enable: function() {
		var element = this.element;
		var list = this.list;
		
		this.options.disabled = false;
		
		// enable the form element and visual select
		this.element.removeAttr('disabled');
		this.list.find('.disabled').removeClass('disabled');

		var handle = this.list.find('dt a');

		// show the dropdown list when clicked
		handle.mousedown(function() {
			hideDropDowns();
			list.find('dd').show();
			$(this).parent('dt').addClass('active');
			$('body').bind("mousedown", bodyClicked);
			return false;
		});

		return element;
	},
	
	disable: function() {
		this.options.disabled = true;
		
		this.element.attr('disabled', 'disabled');
		this.list.find('dt').addClass('disabled');

		var handle = this.list.find('dt a');
		handle.unbind('mousedown');

		return this.element;
	},
	
	// reset the dropdown back to its original state
	destroy: function() {
		this.list.remove();
		this.element.show();
		// this.element.css({position: this.css.position, left: this.css.left});
		this.element.removeClass("ui-dropdown");
		$.removeData(this.element, "ui-dropdown");
	},
	
	// read the list again and reset all values and hooks
	reset: function() {
		this.list.remove();
		this.options.title = this.element.find('option.select-title').text();
		this.list = buildList(this.element, this.options);
		this.element.after(this.list);
		// this.enable();
	},
	
	// reads the selected element and sets the value of the dropdown to it
	select: function() {
		select = this.element.get(0);
		option = select.selectedIndex > -1 ? select[select.selectedIndex] : false;
		if (option) {
			this.list.find('dt a').html(option.text + '<em></em>');
		}
	},
	
	activate: function(event) {
		dropdown = event && event.data ? event.data.dropdown : this;
		
		if (!dropdown.options.disabled) {
			hideDropDowns();
			dropdown.list.find('dd').show();
			dropdown.list.find('dt').addClass('active');
		}
	}
};

function buildList(element, options) {
	select = element.get(0);
	option = select.selectedIndex > -1 ? select[select.selectedIndex] : false;
	//tabindex = $(select).attr('tabindex');
	var selected = option ? option.text : '';

	// build drop down list
	var ddList = '<dl class="dd-list">';
	//ddList += tabindex ? ' tabindex="' + tabindex + '">' : '>';
	ddList += options.disabled ? '<dt class="dd-dt disabled">' : '<dt class="dd-dt">';
	ddList += '<a>' + selected + '<em></em></a></dt>';
	ddList += '<dd style="display: none;">';
	ddList += '<div class="dd-hd"></div>';
	ddList += '<div class="dd-bd">';

	if (options.title) {
		ddList += '<h3>' + options.title + '<a class="close"></a></h3>';
	}

	ddList += '</div>';
	ddList += '<div class="dd-ft"></div>';
	ddList += '</dd>';
	ddList += '</dl>';

	ddList = $(ddList);
	
	// bind event to the close icon
	ddList.find('.close').click(function() {
		hideDropDowns();
		return false;
	});

	// add select options
	var list = $('<ul class="dd-ul"></ul>');
	element.children('option:not(.select-title)').each(function(i){
		var link = $('<a href="#">' + $(this).text() + '</a>');
	
		// change the selected list item
		link.click(function() {
			ddList.find('dt a').html($(this).text() + '<em></em>');
			element.find('option:not(.select-title)')[i].selected = true;
			
			hideDropDowns();
			
			// trigger change event so other code can hook into this
			element.trigger('change');
			
			return false;
		});
		
		var item = $('<li class="dd-li"></li>').append(link);
		list.append(item);
	});
	
	ddList.find('.dd-bd').append(list);
 
	return ddList;
}

function hideDropDowns(event) {
	// don't hide if we're in FF3 or FF2 (Win) and clicking on the scrollbar
	// FF seems to think it's part of the element and registers the clicks on the scrollbar
	if ( event && $.browser.mozilla && $(event.target).hasClass('dd-ul') ) {
		return true;
	}
	
	$('.dd-list dd').hide();
	$('.dd-list .active').removeClass('active');
	$('body').unbind("mousedown", bodyClicked);
	
	return true;
}

function bodyClicked(event) {
	var element = $(event.target);
	if (element.parents().is('.dd-list')) {
		return false;
	} else {
		hideDropDowns();
	}
}

//})(jQuery);


// dropdowns that populate values depending on previous dropdown selection
//(function($) {
	
// If the UI scope is not available, add it
$.ui = $.ui || {};

$.fn.extend({
	dependent_dropdowns: function(options, data) {
		var args = Array.prototype.slice.call(arguments, 1);
		
		return this.each(function() {
			if (typeof options == "string") {
				var dependent_dropdowns = $.data(this, "ui-dependent-dropdowns");
				dependent_dropdowns[options].apply(dependent_dropdowns, args);
			// INIT with optional options
			} else if (!$(this).is(".ui-dependent-dropdowns")) {
				$.data(this, "ui-dependent-dropdowns", new $.ui.dependent_dropdowns(this, options));
			}
		});
	}
});

$.ui.dependent_dropdowns = function(container, options) {
	this.element = $(container);
	this.options = options = $.extend({}, $.ui.dependent_dropdowns.defaults, options);
	this.dropdowns = this.options.dropdowns || this.element.find('select');
	this.data = this.options.data;
	
	this.element.addClass("ui-dependent-dropdowns");
	
	// update values when select is changed
	var dd = this;
	$.each(this.dropdowns, function(i, val) {
		// make sure these are "dropdown" objects
		$(val).dropdown();
		
		$(val).bind("change", function() {
			index = $.inArray(this, dd.dropdowns);
			if (index != -1) {
				dd._updateValues(index+1);
			}
		});
	});
	
	// $(this.dropdowns).bind("change", this._updateSelect);
	
	this.enable();
};

$.ui.dependent_dropdowns.prototype = {
	
	// loads the pass values into the selects
	enable: function() {
		//for (i=0; i<this.dropdowns.length; i++) this._updateValues(i);
		this._updateValues(0);
		this.defaults();
	},
	
	disable: function() {
	},
	
	// reset the container back to its original state
	destroy: function() {
		$.each(this.dropdowns, function(key, value) {
			$(value).destroy();
		});
		this.element.removeClass("ui-dependent-dropdowns");
		$.removeData(this.element, "ui-dependent-dropdowns"); 
	},
	
	// loads default values if they were passed
	defaults: function() {
		
		if (this.data.defaults) {
			
			// values are loaded based on the time of day
			var now = new Date();
			var hours = now.getHours() < 10 ? '0' + now.getHours() : now.getHours();
			var minutes = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes();
			var time = hours.toString() + minutes.toString();
			
			var dd = this;
			$.each(this.data.defaults, function(key, values) {
			
				times = key.split('-');
			
				if (dd._checkTime(times[0], times[1], time)) {
					//console.log(values);
					index = 0;
					$.each(values, function(k, v) {
					
						// try to find the item and select it
						if (select = dd.dropdowns[index]) {
							$(select).find('option').each(function() {
								if ($(this).val() == v) {
									this.selected = true; //$(this).attr('selected', 'selected');
								
									// force the box to indicate the selected value
									$(select).dropdown('select');
									$(select).trigger('change');
								}
							});
						}
					
						index++;
					});				
				}
			});
		}
		
	},
	
	_updateValues: function(index) {
		if (index == null) {
			index = 0;
		}
		
		if (dropdown = this.dropdowns[index]) {
			values = this._findValues(this.data.values, 0, index);
			
			// use the previously selected option if it exists in the new list
			previous_value = $(dropdown).val() || false;
			
			if (this.data.titles && this.data.titles[index]) {
				options = '<option value="" class="select-title">' + this.data.titles[index] + '</option>';
			} else {
				options = '';
			}
			
			// build the new list of values
			if (values) {
				$.each(values, function(key, val) {
					options += '<option value="' + key + '"';
					if (previous_value && previous_value == key) {
						options += ' selected="selected"';
					}
					options += '>' + val.label + '</option>';
				});
			}

			// disable the dropdown if no valid options are found
			if (!values) {
				$(dropdown).dropdown('disable');
			}

			// update the dropdown and redraw it
			$(dropdown).html(options);
			$(dropdown).dropdown('reset');
			
			// enable the dropdown if there are valid options
			if (values) {
				$(dropdown).dropdown('enable');
			}
				
			this._updateValues(index+1);
		}
	},
	
	// find values to use when populating the dropdown
	_findValues: function (values, start_index, end_index) {
		if (start_index == end_index) {
			return values;
		} else {
			values = values[$(this.dropdowns[start_index]).val()];
			if (values) {
				return this._findValues(values.values, start_index+1, end_index);
			} else {
				return null;
			}
		}
	},
	
	_updateDropdown: function (dropdown) {
		//console.log('_updateDropdown', this.dropdowns);
		if (index = $.inArray(dropdown, this.dropdowns)) {
			
		//	console.log('_updateDropdown index=', index);
			
			this._updateValues(index+1);
		}
	},	
		
	// return true if time is between from_time and to_time
	_checkTime: function (from_time, to_time, time) {
		
		// if to_time is less than from time then check the correct timeframe
		if (to_time < from_time) {
			
			if (time >= from_time && time < 2400) {// check up to 2359
				return true;
			} else if (time < to_time && time >= 0) {
				return true;
			}
			
		} else if (time >= from_time && time < to_time) {
			return true;
		}
		
		return false;								
	}
};

//})(jQuery);