// JavaScript Document

//set <ENTER> key code
var ENTER = 13;

$(function(){
	$('.warning').fadeIn('slow');
	
	$('.Warning').hide();
	$('.Warning').fadeIn('slow');
	
	AddTextAreaDefault('#SubscribeEmailAddress', "Type Email Address");
	AddTextAreaDefault('#BlogSearch', "Enter Search Terms");
	AddTextAreaDefault('#SidebarSearch', "Search Contacts");
	
	$('.Tab').bind('click', function(){
		ShowTab($(this).attr('TabBoxName'), $(this).attr('TabCount'));
	});
	$('.TabDiv').children('.Tab:first').each(function(){
		ShowTab($(this).attr('TabBoxName'), $(this).attr('TabCount'));
	});
	/*
	$('[type=button], [type=submit]').bind('mouseover', function(){
		$(this).addClass('HoverButton');
	})
	
	$('[type=button], [type=submit]').bind('mouseout', function(){
		$(this).removeClass('HoverButton');
	})
	*/
	$('.AutoComplete').each(function(){
		SetUpAutoComplete(this)
	});
});

function jqAlert(msg, title, buttons, width, closeafter, closefunction) {
	var id = 'jqalertbox_'+Math.floor(Math.random()*100000000);
	if(title == null)
		title = '';
	
	if(buttons == null) {
		buttons = {
			Ok: function() { }
		};
	}
	
	if(closefunction == null)
		closefunction = function(){}
	
	//Add $('#'+id).dialog('close');  to the BEGINNING of every button function.
	for(var b in buttons) {
		buttons[b] = function(old) {
			return function() {
				if(closeafter) {
					old();
					$('#'+id).dialog('close');
				}
				else {
					$('#'+id).dialog('close');
					old();
				}
			}
		}(buttons[b]);
	}
	
	if(width == null)
		width = 300;
	
	if(msg.indexOf('<') == -1)
		msg = '<p>'+msg+'</p>';
	
	$('body').append('<div class="dialog" style="left=-10000px; top=-10000px; width:'+width+'px;" id="'+id+'" title="'+title+'">'+msg+'<!--[if lte IE 6.5]><iframe src="/ajax/blank.php"></iframe><![endif]--></div>');
	var h = $("#"+id).get(0).offsetHeight;
	
	$('#'+id).dialog({
		buttons:buttons,
		modal:true,
		width:width+50,
		height:h+150,
		beforeclose: closefunction
	}).bind('dialogclose', function() {
		$('#'+id).dialog('destroy');
		$('#'+id).remove();
	});
	
	return $('#'+id);
}

String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

/////////////////////////////////
// Start Dialog Box Stuff
/////////////////////////////////

function CreateAjaxDialog(UniqueId, Title, Width, Height){
	if(Height < 0)
		Height = 'auto';
	$('#'+UniqueId).dialog({
		autoOpen:false,
		modal:true,
		title:Title,
		height:Height,
		width:Width
	});
}
	
function AlertBox(Text){
	var CloseText = '<br /><br /><div align="center"><input type="button" class="button" onclick="$(\'#AlertBox\').dialog(\'close\');" value="OK" /></div>';
	$('#AlertBox').get(0).innerHTML = Text+CloseText;
	$('#AlertBox').dialog('open');
}

function CreateHTMLDialog(UniqueId, Title, Width){
	$('#'+UniqueId).dialog({
		autoOpen:false,
		modal:true,
		title:Title,
		height:'auto',
		width:Width	
	});
}

/////////////////////////////////
// End Dialog Box Stuff
/////////////////////////////////



//////////////////////////////////////////////
// got this code from http://blog.josh420.com/archives/2007/11/determine-if-any-other-outside-element-was-clicked-with-javascript.aspx
// It is used to detect clicks outside of an element (to close that element)
///////////////////////////////////////////////

function clickedOutsideElement(elemId, evt) {
var theElem = '';
if(window.event)
theElem = getEventTarget(window.event);
else theElem = getEventTarget(evt);

while(theElem != null) {
if(theElem.id == elemId)
return false;

theElem = theElem.offsetParent;
}

return true;
}

function getEventTarget(evt) {
var targ = (evt.target) ? evt.target : evt.srcElement;

if(targ != null) {
if(targ.nodeType == 3)
targ = targ.parentNode;
}

return targ;
}
/*
document.onclick = function(evt) {
if(clickedOutsideElement('AlertBox', evt))
	$('.AlertBox').slideUp('fast');

}
*/
//////////////////////////////////////////////
// End Code Snippet
///////////////////////////////////////////////


/*
Call this function on a form field to add text that will appear until they first
click on the field
*/
function AddTextAreaDefault(Selector, DefaultText){
	$(Selector).each(function(){
		if($(this).val() == '' || $(this).val() == DefaultText){
			$(this).css('color', '#999999');
			$(this).val(DefaultText);
			$(this).css('color', '#999999');
			$(this).bind('focus', function(){
				if($(this).css('color') == '#999999' || DefaultText == $(this).val()){
					$(this).val('');
					$(this).css('color', '#333333');
				}
			});
			$(this).bind('blur', function(){
				if($(this).val() == ''){
					$(this).val(DefaultText);
					$(this).css('color', '#999999');
				}
			});
		}
	});
}

function ValidateFormField(FieldId, SpanId, Type){
	$('#ShowErrors_'+FieldId).hide();
	$(SpanId).html('<img src="/i/loading_small.gif" />');
	$(SpanId).show();

	$.post('/include/ajax/validate.php', {Data:$('#'+FieldId).val(), Type:Type}, function(data){
		$(SpanId).html(data);
	});
}

function ShowTab(UniqueName, Count){
	$('.TabContent').hide();
	$('.Tab').removeClass('TabSelected');
	$('#Tab_'+UniqueName+'_'+Count).show();
	$('#TabButton_'+UniqueName+'_'+Count).addClass('TabSelected');
	//TabContent(hide);
}

//////////////////////////////////////
///// AUTOCOMPLETE
//////////////////////////////////////
var AutoCompleteHighlighted = '';
var UseAutoCompleteHotkeys = false;
function SetUpAutoComplete(Element){
	var Type = $(Element).attr('AutoCompleteType');
	
	if(Type == 'Company'){
		$(Element).bind('keyup', function(e){
			if(e.keyCode == 40 || e.keyCode == 38){
				return;
			}
			
			RemoveAutoComplete(false)
			var Text = $(Element).val();
			if(Text != ''){
				var Break = false;
				var Count = 0;
				for(i=0; i<CompanyAutoComplete.length && !Break; ++i){
					if(CompanyAutoComplete[i].substr(0, Text.length).toLowerCase() == Text.toLowerCase() && CompanyAutoComplete[i].length > Text.length){
						if(Count == 0)
							$(Element).after("<span class='AutoCompleteBR'><br /></span><div class='CompanyAutoComplete' style='position:absolute;  background-color:#eeeeee; border:1px solid #999999; width:"+($(Element).width()+2)+"px;'></div>");
		
						$('.CompanyAutoComplete').append("<div class='AutoCompleteOption' Count='"+Count+"' id='AutoComplete_"+Count+"' style='padding:3px; cursor:pointer;'>"+CompanyAutoComplete[i]+"</div>");
						Count++;
						if(Count > 4)
							Break = true;
					}
				}
				if(Count > 0){
					UseAutoCompleteHotkeys = true;
					
					//Select the first item
					HighlightAutoComplete(0);
					
					$('.AutoCompleteOption').bind('click', function(){
						SelectAutoComplete($(this).html(), Element);
					})
				}			
			}
		});
		
		$(Element).bind('blur', function(){
			RemoveAutoComplete()
		});
		
		$(Element).bind('keydown', 'down', function(){
			if(UseAutoCompleteHotkeys){
				CurrentCount = AutoCompleteHighlighted;
				if($('#AutoComplete_'+(CurrentCount+1)).length){
					HighlightAutoComplete(CurrentCount+1);
				}
				return false;
			}
		});
		
		$(Element).bind('keydown', 'up', function(){
			if(UseAutoCompleteHotkeys){
				CurrentCount = AutoCompleteHighlighted;
				if($('#AutoComplete_'+(CurrentCount-1)).length){
					HighlightAutoComplete(CurrentCount-1);
				}
				return false;
			}
		});
		
		$(Element).bind('keydown', 'return', function(){
			if(UseAutoCompleteHotkeys){
				SelectAutoComplete($('#AutoComplete_'+AutoCompleteHighlighted).html(), Element);
				return false;
			}
		});
		
		$(Element).bind('keydown', 'tab', function(){
			if(UseAutoCompleteHotkeys){
				SelectAutoComplete($('#AutoComplete_'+AutoCompleteHighlighted).html(), Element);
				return false;
			}
		});
		
		}
}

function RemoveAutoComplete(Wait){
	UseAutoCompleteHotkeys = false;
	if(Wait == null){
		setTimeout("RemoveAutoComplete(true)", 200);
	}
	else{
		$('.CompanyAutoComplete').remove();
		$('.AutoCompleteBR').remove();
	}
}

function SelectAutoComplete(Text, Target){
	$(Target).val(Text);
	RemoveAutoComplete(false);
	$(Target).change();
}

function HighlightAutoComplete(Count){
	//alert(Count);
	AutoCompleteHighlighted = Count;
	$('.AutoCompleteHighlighted').removeClass('AutoCompleteHighlighted');
	$("#AutoComplete_"+Count).addClass('AutoCompleteHighlighted');
}

///////////////////////////////////////
/////////  End Autocomplete
////////////////////////////////////////

function ClickOffElement(Element, ButtonElement){
	 $('body').click(function() {
		$(Element).hide();
	 });
	
	 $(Element).click(function(event){
	     event.stopPropagation();
	 });
	
	if(ButtonElement != null){
		$(ButtonElement).click(function(event){
			//if(!$(Element).is(':visible'))
				event.stopPropagation();
		});
	}
}

function ShowLoadingScreen(Text){
	if(Text == null)
		Text = 'Saving';
	$('body').append("<div class='LoadingScreen' style='background-color:#ffffff; position:absolute;z-index:9999; top:0px; left:0px; filter:alpha(opacity=30);-moz-opacity:0.3;-khtml-opacity: 0.3;opacity: 0.3;'></div>"+
		"<div align='center' class='SavingNotice' style='position:absolute;z-index:99999'><div align='center' style='width:300px;background-color:white;border:3px solid #999999;padding:20px;'><h1>"+Text+"</h1><img src='/i/loading_big.gif' /></div></div>");
	$('.LoadingScreen').height($('body').height());
	$('.LoadingScreen').width($('body').width());
	
	$('.SavingNotice').css('top', ($(window).height()-$('.SavingNotice').height())/2 + $(window).scrollTop());
	$('.SavingNotice').css('left', ($(window).width()-$('.SavingNotice').width())/2);
}

function HideLoadingScreen(){
	$('.LoadingScreen').remove();
	$('.SavingNotice').remove();
}
