var connections = 0;
var callUsesWYSIWYG = 0;

function jsDebug(msg){
	if(0){
		document.getElementById("jsDebug").style.display = "block";
		document.getElementById("jsDebug").innerHTML = document.getElementById("jsDebug").innerHTML + "<li>" + msg;
	}
}

function getAHAH(l_args, divID){
   return getAHAHm(l_args, divID, 1); 
}
function getAHAH2(l_args, divID){
	return getAHAHm(l_args, divID, 0); 
}
function getAHAH3(l_args, divID){
	return getAHAHm(l_args, divID, 2); 
}
function getAHAH4(l_args, divID){
	return getAHAHm(l_args, divID, 4); 
}
function getAHAH5(l_args, divID){
	return getAHAHm(l_args, divID, 99); 
}
function getAHAHForm(obj, divID) {
   //var l_args = Form.serialize(obj);
   var l_args = $(obj).serialize();
	return getAHAHm(l_args, divID, 109); 
}

function getAHAHm(l_args, divID, showLoading)
{
jsDebug("Doing AHAH - loading results to " + divID);
jsDebug(l_args);

	if(showLoading != 2 && showLoading != 99)
		$('#'+divID).html("");

	if(showLoading == 1)
		$('#'+divID).html("<center><img src='/community/images/wait2.gif'></center>");	

	if(showLoading == 4)
		$('#'+divID).html("<img onclick='hideModal();' align='absmiddle' src='/community/images/closebutton.gif'> Cancel Request<hr><center><P><img src='images/wait2.gif'><BR>Loading Content, Please Wait...</center>");	
	
	//TODO:  Process AHAH request here....
	var url = "/community/includes/ahah.php";
	connections++;
	if(connections > 0 && showLoading != 99)
	{
		$('#statDivID').show();
	}

	// We are submitting a form via AHAH
	if(showLoading == 109)
	{
		$.ajax({
			type:		"POST",
			url:		url,
			data:		l_args,
			dataType:	"html",
			success: function(msg) 
			{
				$('#'+divID).html(msg);
				connections--;
				if(connections <= 0)
				{
					$('#statDivID').hide();
				}
			},			
			
			error: function(msg) 
			{
				$('#'+divID).html("Error loading content.  If errors persist, please contact <a href='mailto:support@pathtags.com'>support@pathtags.com</a>");
				connections--;
				if(connections <= 0)
				{
					$('#statDivID').hide();
				}
			}
		});
	}
	// It's not a form, just some action
	else
	{
		$.ajax({
			type:		"POST",
			url:		url,
			data:		'args=' + l_args,
			dataType:	"html",
			success: function(msg) 
			{
				if(divID != "AJAXDIVRESP")
					$("#"+divID).html(msg);
				else if(msg != "")
				{
					//myDiv = makeDiv(msg);
					//document.body.appendChild(myDiv);
					$.jGrowl(msg, {life: 10000});
				}
				
				connections--;
				if(connections <= 0)
				{
					$('#statDivID').hide();
				}
			},			
			
			error: function(msg) 
			{
				$('#'+divID).html("Error loading content.  If errors persist, please contact <a href='mailto:support@pathtags.com'>support@pathtags.com</a>");
				connections--;
				if(connections <= 0)
				{
					$('#statDivID').hide();
				}
			}
		});
		
	
	}

	return false;
}


function getAJAX(obj)
{
	return getAJAX_m(obj, 0, 0);
}
function getAJAXcond(obj)
{
	return getAJAX_m(obj, 1, 0);
}
function getAJAXsticky(obj)
{
	return getAJAX_m(obj, 0, 1);
}

function getAJAX_m(obj, conditional, stickyvar) 
{
	var l_args = $(obj).serialize();
	//TODO:  Do AJAX call here...
	var url = "/community/includes/ajax.php";
	connections++;
	if(connections > 0 && conditional == 0)
	{
		$('#statDivID').show();
	}

	$.ajax({
		type:		"POST",
		url:		url,
		data:		l_args,
		dataType:	"html",
		success: function(msg) 
		{
			if(msg != "false" || conditional == 0)
			{
				if(stickyvar == 1)
					$.jGrowl(msg,{life: 10000, sticky: true});
				else
					$.jGrowl(msg,{life: 10000});
			}
			connections--;
			if(connections <= 0)
			{
				$('#statDivID').hide();
			}
			return false;
		},			
		
		error: function(msg) 
		{
			makeDiv("Error loading content.  If errors persist, please contact <a href='mailto:support@pathtags.com'>support@pathtags.com</a>");
			connections--;
			if(connections <= 0)
			{
				$('#statDivID').hide();
			}
			return false;
		}
	});
	return false;
}

var modalWidth = 800;
var originalModalWidth = 800;
function loadModalSized(ahahLoad, theWidth)
{
	var tempModalWidth = modalWidth;
	modalWidth = theWidth;
	loadModal(ahahLoad);
	modalWidth = tempModalWidth;
}

function loadModal(ahahLoad)
{
	$('select').hide();

	grayOut(true);
	viewport.getAll();
	modalSize = modalWidth;
	$("#modalDiv").html("<div id='modalcontent' style='background-color: #ffffff;border: 10px solid #1E62A1;position: relative;padding: 5px;'><center><h2>Loading Content, Please Wait</h2><P><img src='images/loading.gif'></center></div>");		
	$("#modalDiv").css("top",(viewport.scrollY + 20) + "px");
	$("#modalDiv").css("left",((viewport.width/2) - (modalSize/2)) + "px");
	$("#modalDiv").css("display","block");
	getAHAH4(ahahLoad, "modalcontent");
	modalWidth = originalModalWidth;
}	

function hideModal()
{
	$('select').show();
	grayOut(false);
	$("#modalDiv").hide();
}
	
var viewport = {
  getWinWidth: function () {
    this.width = 0;
    if (window.innerWidth) this.width = window.innerWidth - 18;
    else if (document.documentElement && document.documentElement.clientWidth) 
  		this.width = document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth) 
  		this.width = document.body.clientWidth;
  },
  
  getWinHeight: function () {
    this.height = 0;
    if (window.innerHeight) this.height = window.innerHeight - 18;
  	else if (document.documentElement && document.documentElement.clientHeight) 
  		this.height = document.documentElement.clientHeight;
  	else if (document.body && document.body.clientHeight) 
  		this.height = document.body.clientHeight;
  },
  
  getScrollX: function () {
    this.scrollX = 0;
  	if (typeof window.pageXOffset == "number") this.scrollX = window.pageXOffset;
  	else if (document.documentElement && document.documentElement.scrollLeft)
  		this.scrollX = document.documentElement.scrollLeft;
  	else if (document.body && document.body.scrollLeft) 
  		this.scrollX = document.body.scrollLeft; 
  	else if (window.scrollX) this.scrollX = window.scrollX;
  },
  
  getScrollY: function () {
    this.scrollY = 0;    
    if (typeof window.pageYOffset == "number") this.scrollY = window.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop)
  		this.scrollY = document.documentElement.scrollTop;
  	else if (document.body && document.body.scrollTop) 
  		this.scrollY = document.body.scrollTop; 
  	else if (window.scrollY) this.scrollY = window.scrollY;
  },
  
  getAll: function () {
    this.getWinWidth(); this.getWinHeight();
    this.getScrollX();  this.getScrollY();
  } 
}

// Vars for auto dive generation
var xPtStat = 0;
var yPtStat = 500;
var xPt = 50;
var yPt = 0;
var divCount = "0";

function makeDiv(text)
{
	var eDiv=document.createElement("DIV");
	eDiv.style.width="90%";
	eDiv.style.height="50px";
	eDiv.style.position="fixed";
	eDiv.style.zIndex="100";        

	eDiv.style.borderBottom ="2px solid orange";
	eDiv.style.borderTop ="2px solid orange";
	eDiv.style.borderLeft ="2px solid orange";
	eDiv.style.borderRight ="2px solid orange";
	eDiv.style.backgroundColor ="#E1E1E1";
	eDiv.style.overflow = "auto";
	eDiv.style.margin = "0px auto";

	eDiv.style.bottom = yPt.toString() + "px"
	
	xPt += 5;
	yPt += 3;
	
	eDiv.style.fontfamily = "Trebuchet MS, Arial, sans-serif";
	eDiv.style.fontSize = "12px";
	eDiv.style.lineheight = "1.5em";
	eDiv.style.cursor = "pointer";
	var divID = 'dyndiv'+divCount;
	eDiv.setAttribute('id', divID);
	eDiv.innerHTML = "";
	eDiv.innerHTML += '<div style="float: right;margin: 5px;"><img src="/community/images/closebutton.gif" onclick="xPt -= 5;yPt -= 3;$(\'#'+ divID +'\').hide();alert(\''+divID+'\');"></div>';
	eDiv.innerHTML += '<div style="padding: 5px; position: relative">' + text + "</div>" ;
	
	eDiv.setAttribute('id', divID);
		
	divCount++;
	return eDiv;
}	

function hide(theDiv){
	theDiv.style.visibility = "hidden";	
}
function submitKeyword(keyword){ 
	document.keywordsuggest.keyword.value = keyword;
}
		


function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 85;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}	

function addDiv(text)
{
	myDiv = makeDiv(text);
	document.body.appendChild(myDiv);
}

var tradeLabelId = 0;
function setTradeLabel(tradeid)
{
	tradeLabelId = tradeid;
}

var isNav4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) == 4)
var isNav4Min = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) >= 4)
var isIE4Min = (navigator.appName.indexOf("Microsoft") != -1 && parseInt(navigator.appVersion) >= 4)
function processTradeLabel() 
{
	var theString = "";
	//alert(navigator.appVersion);
    if (isNav4Min) {
		theString = document.getSelection().toString();
    } else if (isIE4Min) {
        if (document.selection) {
			theString = document.selection.createRange().text;
            event.cancelBubble = true
			document.selection.empty();
        }
    }
	else
	{
		alert("Browser not currently supported for fast labels.  To request browser support contact support@pathtags.com");
	}
	if(theString.length > 4)
	{
		divID = 'dyndiv'+divCount;
		divCount++;
		
		makeDivNow(
			"<h1>Create A Mailing Label For Trade " + tradeLabelId + "</h1>" +
			"<B>Remember:</B>  The system will automatically combine tags going to a single partner for you and the final labels will indicate which tags of yours to send.  You do not need to include that information in the label.  You may need to edit for format (your partner's address is all on one line, etc.)  " +
			"<P><B>Review/Edit the Label:</B><BR>" +
			"<form onsubmit=\"grayOut(false);document.getElementById('"+divID+"').style.display='none';return getAJAX(this);\">" + 
			'						<input type="hidden" name="action" value="addLabel">' +
			'						<input type="hidden" name="tradeid" value="' + tradeLabelId + '">' +
			"<textarea name=\"labeltext\" cols=30 rows=5>" + theString + "</textarea><BR><input type=submit value=Save></form>"
			, divID
			);
	}
}
if (isNav4) 
{
    document.captureEvents(Event.MOUSEUP)
}

     
function makeDivNow(text, newDivID)
{
	grayOut(true);
	var eDiv=document.createElement("DIV");
	
	var divID = "";
	if(newDivID == null)
	{
		divID = 'dyndiv'+divCount;
		divCount++;
	}
	else
	{
		divID = newDivID;
	}	

	eDiv.setAttribute('id', divID);
	
	eDiv.style.border ="2px solid orange";
	eDiv.style.backgroundColor ="white";

	eDiv.style.width="300px";
	eDiv.style.minHeight="100px";
	eDiv.style.position="fixed";
	eDiv.style.zIndex="100";        
	eDiv.style.padding = "5px";

	eDiv.style.top = 10 + "px"
	eDiv.style.left = 10 + "px"
	eDiv.style.overflow = "auto";

	eDiv.innerHTML = "<div style='position: relative;'>" + text + 
		'<div style="position: absolute; top: 0px; right: 0px; z-index: 150;">' +
			'<img onclick="grayOut(false);document.getElementById(\''+ divID +'\').style.display=\'none\';" src="/community/images/closebutton.gif" align="absmiddle">'+
		'</div></div>';
		
	document.body.appendChild(eDiv);
}					  
				  
				  
function setClassNameForID(theID,className)
{
	var myElement = document.getElementById(theID);

	if (navigator.appName == "Microsoft Internet Explorer") {
	myElement.className = className;
	}
	else {
	myElement.setAttribute("class", className);
	}	
}				  

// For auto complete
function lookup(inputString,action) {
	if(action == null)
	{
		action = "nothing";
	}
 	var url = "/community/includes/ahah.php";
		if(inputString.length < 4) {
			// Hide the suggestion box.
			$('#suggestions').hide();
		} else {
			$.post(url, {queryString: ""+inputString+"", action: ""+action+""}, function(data){
				if(data.length >0) {
					$('#suggestions').show();
					$('#autoSuggestionsList').html(data);
				}
			});
		}
	} // lookup

function fill(thisValue) {
	$('#inputString').val(thisValue);
	setTimeout("$('#suggestions').hide();", 200);
}
