// trap escape key and use it to close the popup
function $(x){return document.getElementById(x);}

var boxVisible=false;
var popupWindow;
var pleaseWait="<table id=\"popup_txt\" width=100% height=100%><tr height=10><td>&nbsp;</td></tr><tr ><td align='center'><img border=0 src='http://assets.feedblitz.com/js/tinybox2/images/preload.gif'></td></tr><tr height=10><td>&nbsp;</td></tr></table>";
var pleaseWaitInner="<table id=\"popup_txt_wait\" width=100% height=100%><tr height=10><td>&nbsp;</td></tr><tr ><td align='center'><img border=0 src='http://assets.feedblitz.com/js/tinybox2/images/preload.gif'></td></tr><tr height=10><td>&nbsp;</td></tr></table>";

var reloadNeeded=false;
var noreload=false;

function checkReload()
{
	if(reloadNeeded && !noreload)
	{
		reloadNeeded=false;
		setTimeout("window.location.reload();",100);		
	}
	noreload=false;
}

function hideTinyBox()
{
	try
	{
		TINY.box.hide();
		var e=$('popup_txt');
		if(e==null || e==undefined) e=parent.document.getElementById('popup_txt');
		if(e!=null && e!=undefined) e.id='';
	} catch(e){}
}

function TrackEscapeKey(eventRef)
{
	if ( !eventRef )
		eventRef = event; 

	var keyStroke = (eventRef.keyCode) ? eventRef.keyCode : ((eventRef.charCode) ? eventRef.charCode : eventRef.which);

	if ( keyStroke==27 && boxVisible && popupWindow!=null && popupWindow!=undefined)
	{
		popupWindow.close();
	}
	
	hideTinyBox();
	
	return true;
}

function EscNOP(eventRef)
{
	return true;
}

window.document.onkeydown = TrackEscapeKey;

// find all forms inside the lightbox
function ChangeFormTarget(elem)
{
	v=$(elem);
	if(v==null || v==undefined) 
	{
		v=parent.document.getElementById(elem);
	}
	if(v==null || v==undefined) 
	{
	// do nothing
	} else {
		var children = v.getElementsByTagName('*');
		var formfound=0;
		for(i=0;i<children.length;i++)
		{
			if(children[i].nodeName=='FORM')
			{
				children[i].target=window.name;
				TakeOverDirectForm(children[i]);
			}
		}
		// if(!formfound) alert("Takeover form failed\r\n\r\n",v.innerHTML);
	}
}

function FindFormInside(elem)
{
	v=$(elem);
	if(v==null || v==undefined) 
	{
		v=parent.document.getElementById(elem);
	}
	if(v==null || v==undefined) 
	{
	// do nothing
	} else {
		var children = v.getElementsByTagName('*');
		var formfound=0;
		for(i=0;i<children.length;i++)
		{
			if(children[i].nodeName=='FORM')
			{
				TakeOverForm(children[i]);
				formfound=1;
			}
		}
		// if(!formfound) alert("Takeover form failed\r\n\r\n",v.innerHTML);
	}
}

// remove standard non-printing characters from a string
function RemoveWhiteSpace(v)
{
	var s=v;

	s=s.replace(/ /g,"");
	s=s.replace(/\r/g,"");
	s=s.replace(/\f/g,"");
	s=s.replace(/\n/g,"");
	s=s.replace(/\t/g,"");

	return s;
}

// Update string of variables to post with the given name / value pair
function AddToPostString(PostString, name, value)
{
	if(name!='')
	{
		if(PostString!='')
		{
			PostString+='&';
		}
		PostString+=name+'=';
		value=escape(value);
		PostString+=value;
	}

	return PostString;
}

// iterate through the selected form, getting all variables and creating the data to POST
function CheckFormValues(MyForm){
    var elLength = MyForm.elements.length;
    var PostString='';

    for (i=0; i<elLength; i++)
    {
		var postname='';
		var postval='';

        var type = MyForm.elements[i].type;
		var value = MyForm.elements[i].value;
		var name = MyForm.elements[i].name;
        if ((type=="checkbox" || type=="radio") && MyForm.elements[i].checked){
			postname=name;
			postval=value;
        } else if (type=="checkbox" || type=="radio")  {
            // do nothing
        } else if (type=="select-multiple")  {
			for(j=0;j<MyForm.elements[i].options.length;j++)
			{
				if(MyForm.elements[i].options[j].selected)
				{
					PostString=AddToPostString(PostString,name,MyForm.elements[i].options[j].value);
				}
			}
        } else {
			postname=name;
			postval=value;
        }

		PostString=AddToPostString(PostString,postname,postval);
    }

    return PostString;
}

function cx(txt)
{
TINY.box.psh(txt,1,0,0);
}

// Processes the data from the Ajax POST to the FeedBlitz server
// if blank, reloads the page
// otherwise reloads the dialog box
function AndTheResultsAre(txt)
{
	okfunc=undefined;
	var s=txt;
	s=RemoveWhiteSpace(s);
	if(s=='')
	{	
		reloadNeeded=false;
		noreload=false;

		if(popupWindow!=undefined)
		{
			popupWindow.close();
		}

		hideTinyBox();		

		if(parent.UpdateNavPaneFromServer!=undefined)
		{
			parent.UpdateNavPaneFromServer();
		}

		setTimeout("window.location.reload();",100);		
		//window.location.reload();
	} else {
	
		reloadNeeded=true;
		cx(txt);
	}
}

function AjaxDirectSubmitForm(MyForm)
{
	var v=false;
	var PostString='';

	if(s!='' && s!=undefined)
	{
		if(s.match('ajax=')==null)
		{
			if(s.match('\\?')==null)
			{
				s=s+'?ajax=3';
			} else {
				s=s+'&ajax=3';
			}
		}
		hideTinyBox();
		setTimeout("MyForm.oldsubmit()",100);
	}

	return v;
}

function AjaxSubmitForm(MyForm)
{
	var v=true;
	var PostString='';
	var s=MyForm.action;

	PostString=CheckFormValues(MyForm);
	
	if(s!='' && s!=undefined)
	{
		if(s.match('ajax=')==null)
		{
			if(s.match('\\?')==null)
			{
				s=s+'?ajax=3';
			} else {
				s=s+'&ajax=3';
			}
		}
		// alert('submitting form to '+s+' with values '+PostString);
		okfunc=AndTheResultsAre;
		window.document.onkeydown = EscNOP;
		TINY.box.psh(pleaseWaitInner,1,-1,-1);
		makePOSTRequest(s,PostString);
	} else {
		alert('NOT submitting');
		v=false;
	}

	return v;
}

function ajaxdirectsubmit()
{
	var v=true;
	if(this.oldsubmit)
	{
		v=oldsubmit();
	}
	if(v)
	{
		AjaxDirectSubmitForm(this);
	}
	return v;
}

function ajaxsubmit()
{
	var v=true;
	if(this.oldsubmit)
	{
		v=oldsubmit();
	}
	if(v)
	{
		AjaxSubmitForm(this);
	}
	return v;
}

function TakeOverForm(MyForm)
{
	var theForm=MyForm;

	if(theForm.onsubmit && theForm.onsubmit!=ajaxsubmit)
	{
		theForm.oldsubmit=theForm.onsubmit;
		theForm.onsubmit=ajaxsubmit;
		theForm.submit=ajaxsubmit;
	} else {
		theForm.onsubmit=ajaxsubmit;
		theForm.submit=ajaxsubmit;
	}
}

function TakeOverDirectForm(MyForm)
{
	var theForm=MyForm;

	if(theForm.onsubmit && theForm.onsubmit!=ajaxdirectsubmit)
	{
		theForm.oldsubmit=theForm.onsubmit;
		theForm.onsubmit=ajaxdirectsubmit;
		theForm.submit=ajaxdirectsubmit;
	} else {
		theForm.onsubmit=ajaxdirectsubmit;
		theForm.submit=ajaxdirectsubmit;
	}
}

var okfunc;
var failfunc;

function customcb(foo)
{
popupWindow.close();
hideTinyBox();
}

function alertContents() {
    var http_request=this;
	if (http_request.readyState == 4) {
		if (http_request.status == 200) 
		{      
			result = http_request.responseText;
			if(okfunc)
			{
				okfunc(result,http_request.fbzurl);
			} else {
				populateModal(results);
			}
			FindFormInside('popup_txt');
		} else {
			if(failfunc)
			{
				failfunc(http_request.status,http_request.fbzurl);
			} else {
				try{
				$('txt').innerHTML = "<span style='color:red'>. . . unable to load ["+http_request.status+": "+http_request.responseText+"] . . .</span>";
				$('popup_txt').innerHTML = "<span style='color:red'>. . . unable to load ["+http_request.status+": "+http_request.responseText+"] . . .</span>";
				} catch(e){};
			}
		}
	}
}

var divArray=new Array();
var sDivID="";

function UpdatePageWithResults(txt,url)
{
	var divToUpdate;
	if(url==undefined)
	{
		divToUpdate=sDivID;
	} else {
		divToUpdate=divArray[url];
	}
//	okfunc=undefined;
//	failfunc=undefined;
	$(divToUpdate).innerHTML=txt;
	sDivID="";
}

function UpdatePageWithError(txt,url)
{
	var divToUpdate;
	if(url==undefined)
	{
		divToUpdate=sDivID;
	} else {
		divToUpdate=divArray[url];
	}
//	okfunc=undefined;
//	failfunc=undefined;
	$(divToUpdate).innerHTML="<p><font color='red'><b>We're sorry, there was an error fulfulling your request (Details: "+txt+"). Please try again.</b></font></p>";
	sDivID="";
}

// places specified content in the specified div id
function JSDivFromURL(sUrl,sDiv)
{
	sDivID=sDiv;
	divArray[sUrl]=sDiv;
	okfunc=UpdatePageWithResults;
	failfunc=UpdatePageWithError;
	document.getElementById(sDiv).innerHTML = pleaseWait;
	var poststr='';
	makePOSTRequest(sUrl, poststr);
}

function populateModal(results)
{
}

function JSModalFromUrl(s,title,force,norel,directsubmit)
{
	if(force==1 || (parent.dhxLayout!=undefined && parent.dhxLayout!=null))
	{
		if(title==null || title==undefined) title='Edit Settings';
		if(norel==true) noreload=true; else noreload=false;

		reloadNeeded=false;
		if(directsubmit==true)
		{
			try{TINY.box.show({url:s,animate:1,boxid:'popup_txt',openjs:function(){ChangeFormTarget('popup_txt')},closejs:function(){checkReload()}});} catch(e){};
		} else {
			try{TINY.box.show({url:s,animate:1,boxid:'popup_txt',openjs:function(){FindFormInside('popup_txt')},closejs:function(){checkReload()}});} catch(e){};
		}
		boxVisible=true;
	}
}


function JSModal(s)
{
$('plaintxt').innerHTML = s;
sm('box',500,250);
}

