var ajaxInstances = 0;
var ajaxArray = [];

function closePopup(divid){
	document.getElementById(divid).style.visibility="hidden";
	grayOut(false);
}

function TableDeleteRows(id){
    var obj = document.getElementById(id);
    if(!obj && !obj.rows)
      return;
    
      toDeleteHeader = false;
    var limit = !!toDeleteHeader ? 0 : 1;
    var rows = obj.rows; 
    if(limit > rows.length)
      return;
    for(; rows.length > limit; ) {
      obj.deleteRow(limit);
  	}		
}


function showPopup(divid){

	var scrolledX, scrolledY; 

	if( self.pageYoffset ) { 
		scrolledX = self.pageXoffset; 
		scrolledY = self.pageYoffset; 
	} else if( document.documentElement && document.documentElement.scrollTop ) { 
		scrolledX = document.documentElement.scrollLeft; 
		scrolledY = document.documentElement.scrollTop; 
	} else if( document.body ) { 
		scrolledX = document.body.scrollLeft; 
		scrolledY = document.body.scrollTop; 
	}


	var centerX, centerY; 
	if( self.innerHeight ) { 
		centerX = self.innerWidth; 
		centerY = self.innerHeight; 
	} else if( document.documentElement && document.documentElement.clientHeight ) { 
		centerX = document.documentElement.clientWidth; 
		centerY = document.documentElement.clientHeight; 
	} else if( document.body ) { 
		centerX = document.body.clientWidth; 
		centerY = document.body.clientHeight; 
	}


	
	var o=document.getElementById(divid); 
	var r=o.style; 

	
	var leftoffset = (scrolledX + (centerX ) / 2)-(o.offsetWidth/2); 
	var topoffset = (scrolledY + (centerY ) / 2)-(o.offsetHeight/2); 

	r.position='absolute'; 
	r.top = topoffset + 'px'; 
	r.left = leftoffset + 'px'; 
	r.display = "block"; 

	grayOut(true);

	document.getElementById(divid).style.visibility="visible";

	
}

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 || 70;
  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 ClearOptions(id)
{
	var selectObj = document.getElementById(id);
	if(selectObj == null){
		return;
	}
	var selectParentNode = selectObj.parentNode;
	var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
	selectParentNode.replaceChild(newSelectObj, selectObj);
	return newSelectObj;
}

function getHTTPObject() {
	var xhr = false;//set to false, so if it fails, do nothing
	if(window.XMLHttpRequest) {//detect to see if browser allows this method
		ajaxArray[ajaxInstances] = new XMLHttpRequest();//set var the new request

	} else if(window.ActiveXObject) {//detect to see if browser allows this method
		try {
			ajaxArray[ajaxInstances] = new ActiveXObject("Msxml2.XMLHTTP");//try this method first
		} catch(e) {//if it fails move onto the next
			try {
				ajaxArray[ajaxInstances] = new ActiveXObject("Microsoft.XMLHTTP");//try this method next
			} catch(e) {//if that also fails return false.
				ajaxArray[ajaxInstances] = false;
			}
		}
	}
	return ajaxArray[ajaxInstances++];//return the value of xhr
}

function CleanPrice(price){
	return parseFloat(price.replace("$","").replace(",",""));
}

function FormatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function findPosX(obj){
    var curleft = 0;
    if(obj.offsetParent)
        while(1){
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}
 
/* Find the Y position of the textbox */
 
function findPosY(obj){
    var curtop = 0;
    if(obj.offsetParent)
        while(1){
            curtop += obj.offsetTop;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}

function ajaxPost(http,url,params,callback){
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	if(callback != null){
		http.onreadystatechange = callback;
	}
	http.send(params);
}

function evalJSON(http){
	try{
		s = eval('(' + http.responseText + ')');
		return s;
	}catch(e){
		alert("There was an error. A log has been sent. Error details: "+http.responseText);
		ErrorHttpObject = getHTTPObject();

		if (ErrorHttpObject != null) {
			ajaxPost(ErrorHttpObject,"ajaxhandler.php","action=logError&dertails="+escape(http.responseText),null);
		
		}

		
		return null;
	}
}

function HideLoadingIcon(d){
   d.style.visibility = "hidden";
}

function ShowLoadingIcon(d,widthOffset,heightOffset){
        var waitDiv=document.createElement("DIV");
        waitDiv.style.position="absolute";
    waitDiv.innerHTML ="<img src='/assets/shared/images/loading.gif'>";

			var x = findPosX( d ) + widthOffset;
		    var y = findPosY( d ) + heightOffset;
		    waitDiv.style.left = x + 'px';
		    waitDiv.style.top = ( y ) + 'px';
document.body.appendChild(waitDiv);
return waitDiv;

}
