var headMessageTimer = null;

// Onload When Document Ready
$j(document).ready(function() {
  	$j('a[rel=external]').attr('target', '_blank');
  	//$j(document).pngFix();
  	$j('.pngfix').pngfix();
	$j('.equalize').equalHeights('true');
	// Placed to try and fix footer on IE6
	// $j(document).stickyfooter();	
	if(!$j.browser.msie || $j.browser.version > 6.99) {
		$j('#barHider').css('cursor','pointer').click(function(e) {
			$j('div#header-nav-spacer').slideUp();
			$j('div#persistenttoolbar').slideUp();
			$j.cookie('hideToolbar','yes',{path:'/'});
		});
	
		$j('#barHandle').css('cursor','pointer').click(function(e) {
			$j('div#persistenttoolbar').slideDown();
			$j('div#header-nav-spacer').slideDown();
			$j.cookie('hideToolbar',null,{path:'/'});
		});
	};
	
	$j('a.gfConfirm').not('.ajaxify').click(function(a) {
		if(!gfConfirm('Are you sure you want to ' + $j(this).attr('title').toLowerCase() + '?')) {
			a.preventDefault();
			a.stopPropagation();
			return false;
		} else return true;
	});
	
	$j('a.ajaxify').not('.gfConfirm').click(function(a) { 
		ajaxify(this);
		return false;
	});
	
	$j('a.ajaxify').filter('.gfConfirm').click(function(a) { 
		if(!gfConfirm('Are you sure you want to ' + $j(this).attr('title').toLowerCase() + '?')) {
			a.preventDefault();
			a.stopPropagation();
			return false;
		} else {
			ajaxify(this);
		}
		return false;
	});
	
	if(typeof parent.showNotification != 'undefined') {
		$j('a.hsExit').click(function(a){
			parent.document.location.href = $j(this).attr('href');
			//parent.hs.close();
			return false;
		});
	}
	
	hs.graphicsDir = '/images/graphics/';
	hs.outlineType = 'rounded-white';
	hs.outlineWhileAnimating = true;
	bindHighslide();
	
	// Setup Search Autocomplete
	if($j('input#searchKeyword').length > 0) {
		$j('input#searchKeyword').autocomplete('/search/ajaxResults.cfm', {
			width: 300,
			selectFirst: false,
			matchContains: true,
			minChars: 2
		});
	
		$j('input#searchKeyword').result(function(event, data, formatted) {
			document.location.href='/search/searchClick.cfm?resID=' + data[1];
			$j('input#searchKeyword').val('');
		});
	}
	
	$j('span#advancedOptionsToggle').css('cursor','pointer').click(function(e) {
		$j('#advancedshow,#advancedhide').toggle();
		$j('#advancedoptions').toggle();
	});
	$j('div#quickMoveBanner').click(toggleQuickMove);
	
	if($j('#dreamlist').length > 0) {
		var dreamHomeRequest = null;
		$j("#dreamlist").sortable({
			handle : '.handle',
			axis: 'y', 
			items: 'li', 
			update : function () {
				if(dreamHomeRequest != null) dreamHomeRequest.abort();
				formData = $j('#dreamlist').sortable('serialize');
				formData = appendVar(formData, 'isAjaxy', '1');
				if($j(document.location).attr('href').toLowerCase().indexOf('inhighslide=1') != -1) formData = appendVar(formData, 'inHighslide', '1');
				dreamHomeRequest = $j.ajax({
				  type: "GET",
				  url: '/profile/updateDreamHomeSort.cfm',
				  data: formData,
					cache: false,
					dataType: "script",
					success: dreamHomeRequest = null
				});
	    }
	  });
		$j('.dreamHomeNote').hide();
		$j('.dreamNoteHandler').click(function(c){
			$j(this).parent('div:first').siblings('div.dreamHomeNote').toggle();
			return false;
		});
		$j('.dreamNoteHandler').show();
	}
	
	//alert($j(':input[name="vilID"]').not(':checkbox').length);
	$j(':input[name="vilID"]').not(':checkbox').change(setupQuickMove);
  
	// Setup Form Validation
	$j('form.ajaxify').not('.validate').bind('submit', function() {ajaxSubmit(this);return false;} );
	if($j('form#headerLogin').length > 0) $j('form#headerLogin').validate({submitHandler: ajaxSubmit});
	if($j('form#emailToFriend').length > 0) $j('form#emailToFriend').validate({
		highlight: function( element, errorClass ) {
			$j( element ).addClass( errorClass ).parent('p').addClass('invalid');
		},
		unhighlight: function( element, errorClass ) {
			$j( element ).removeClass( errorClass ).parent('p').removeClass('invalid');
		},
		submitHandler: ajaxSubmit
	});
	if($j('form#savedSearchUpdate').length > 0) $j('form#savedSearchUpdate').validate({submitHandler: ajaxSubmit});
	if($j('form#vendorReg').length > 0) $j('form#vendorReg').validate();
	if($j('form#feedbackForm').length > 0) {
		$j('form#feedbackForm').validate({
			submitHandler: ajaxSubmit,
			rules: {
				feeRating: "required",
				feeName: "required",
				feePhone: "required",
				feeComments: "required",
				feeEmail: { required: true, email: true }
			}
		});
		$j('input#feePhone').setMask('(999) 999-9999');
		
	}
	if($j('form#forgotPassword').length > 0) $j('form#forgotPassword').validate({submitHandler: ajaxSubmit});
	if($j('form#profileUpdate').length > 0) $j('form#profileUpdate').validate({
		submitHandler: ajaxSubmit,
		rules: {confirmPassword: { equalTo: "#proUpMemPassword" }}
	});
	if($j('form#myLWRSignup').length > 0) $j('form#myLWRSignup').validate({
		submitHandler: ajaxSubmit,
		rules: {confirmPassword: { equalTo: "#myLWRSignupMemPassword" }}
	});
	
	$j("div#header-message").hover(function(){clearTimeout(headMessageTimer);}, function(){setTimeout('$j("div#header-message").hide(\'fast\')', 1000);})
});

function addBookmark(title,url) {
  if (window.sidebar) {
    window.sidebar.addPanel(title, url,'');
  } else if( document.all ) {
    window.external.AddFavorite( url, title);
  } else if( window.opera && window.print ) {
    return true;
  }
}

function bindHighslide() {
	if(window.location.href.toLowerCase().indexOf('inhighslide=1') == -1) {
		$j('a.hsLink').click(function(hs) { 
			launchHighslide(this);
			return false;
		});
	}
}

function rebindHighslide() {
	if(window.location.href.toLowerCase().indexOf('inhighslide=1') == -1) {
		$j('a.hsLink').unbind('click');
		bindHighslide();
	}
}

function launchHighslide(obj){
	var attribs = new Object();
	attribs.objectType = 'iframe';
	attribs.width = 815;
	attribs.height = 640;
	//attribs.contentId = new Date().getTime().toString();
	attribs.align = 'center';
	attribs.objectLoadTime = 'after';
	attribs.preserveContent = false;
	attribs.allowWidthReduction = 1;
	attribs.cacheAjax = false;
	
	if($j(obj).attr("hsType")) attribs.objectType = $j(obj).attr("hsType");
	if($j(obj).attr("hsWidth")) attribs.width = $j(obj).attr("hsWidth");
	if($j(obj).attr("hsHeight")) attribs.height = $j(obj).attr("hsHeight");
	if($j(obj).attr("hsTargetX")){
		attribs.targetX = $j(obj).attr("hsTargetX");
		attribs.align = 'auto';
	}
	if($j(obj).attr("title")) {
		attribs.captionText = $j(obj).attr("title");
		attribs.captionOverlay = new Object();
		attribs.captionOverlay.position = 'top center';
	}
	$j(obj).attr('href', appendVar(obj.href, 'inHighslide', '1'));
	
	hs.htmlExpand(obj, attribs);
	return false;
}

function toggleQuickMove(event){
	if (event.target.type != 'checkbox') {
		if ($j('input#homIsQuickMove:checked').length == 0){
			$j('input#homIsQuickMove').attr('checked','checked');
			$j('input#homIsQuickMove').change();
		} else {
			$j('input#homIsQuickMove').removeAttr('checked');
			$j('input#homIsQuickMove').change();
		}
	} else return true;
	return false;
}

function setupQuickMove(){
	if ($j(':input[name="vilID"]').not(':checkbox').val() == 'Show All'){
		$j(':checkbox[name="vilIsGated"]').parent().show();
	} else {
		$j(':checkbox[name="vilIsGated"]').removeAttr('checked');
		$j(':checkbox[name="vilIsGated"]').parent().hide();
	}
}

function showNotification(message, type, time) {
	positionNotification();
	clearTimeout(headMessageTimer);
	type = (typeof type == "undefined") ? 'success' : type;
	time = (typeof time == "undefined") ? 3000 : time;
	$j('div#header-message').html(message).removeClass('success').removeClass('fail').addClass(type).show('fast');
	headMessageTimer = setTimeout('$j("div#header-message").hide(\'fast\')', time);
}

function positionNotification(){
	var top = 0;
	if($j('#persistenttoolbar').css('display') != 'none'){
		top = top + ($j('#persistenttoolbar').outerHeight() - 3);
	}
	if($j('div#header-login-form').css('display') != 'none'){
		top = top + $j('div#header-login-form').outerHeight();
	}
	$j('div#header-message').css('top', top);
}

function showFieldError(form, input, message) {
	var theInput = $j(form + ' ' + input);
	var theLabel = '';
	if(theInput.length != 0) {
		theLabel = theInput.next('label.error[generated="true"][for="'+ $j(form + ' ' + input).attr("id") + '"]');
		if(theLabel.length != 0) {
			theLabel.text(message);
			theLabel.show();
		} else {
			theInput.after('<label class="error" generated="true" for="'+ $j(form + ' ' + input).attr("id") + '">' + message + '</label>');
		}
	}
}

function ajaxSubmit(theForm, formAction) {
	var formData = $j(theForm).serialize();
	formAction = (typeof formAction == "undefined") ? theForm.action : formAction;
	formMethod = 'GET';
	if($j(theForm).attr("method")) formMethod = $j(theForm).attr("method");
	formData = appendVar(formData, 'isAjaxy', '1');
	formData = appendVar(formData, 'ajaxFormID', $j(theForm).attr('id'));
	if($j(document.location).attr('href').toLowerCase().indexOf('inhighslide=1') != -1) formData = appendVar(formData, 'inHighslide', '1');
	
	ajaxRequest = $j.ajax({
	  type: formMethod,
	  url: formAction,
	  data: formData,
		cache: false,
		dataType: "script"
	});
	
	return false;
}

function appendVar(href, name, value) {
	if(href.toLowerCase().indexOf(siteRootURL.toLowerCase()) != -1 && href.toLowerCase().indexOf(name.toLowerCase()) == -1) {
		if(href.indexOf('?') == -1){
			if(href.toLowerCase().indexOf('.cfm') == -1 && href.toLowerCase().indexOf('/images/') == -1){
				href = href + 'index.cfm?' + name + '=' + value;
			} else {
				href = href + '?' + name + '=' + value;
			}
		} else {
			href = href + '&' + name + '=' + value;
		}
	} else if (href.toLowerCase().indexOf('http://') == -1 && href.toLowerCase().indexOf(name.toLowerCase()) == -1) {
		href = href + '&' + name + '=' + value;
	}
	return href;
}

function ajaxify(obj){
	ajaxRequest = $j.ajax({
	  type: "GET",
	  url: appendVar(obj.href, 'isAjaxy', '1'),
		cache: false,
		dataType: "script"
	});
	return false;
}

function showHeaderLogin() {
	var top = 0;
	if($j('#persistenttoolbar').css('display') != 'none'){
		top = $j('#persistenttoolbar').height() - 3;
	}
	$j('div#header-login-form').css('top', top).show('fast', positionNotification);
}

function hideHeaderLogin() {
	$j('div#header-login-form').hide('fast', positionNotification);
}

function gfConfirm(prompt) {
	return confirm(prompt);
}