// $Id: $
/**
* @author:        Avi Mehta
* @description:   A library of general functions used in the Form Builder
*                 Module.
* @license:       GPL
*/


asyncapi = function() {};
asyncapi.effects = function(el ) {};

/*dylapi.load(args)
    'type' Required    can be 'node' 'block' or 'data'  //The data part is not fully researched into as indicated later.
    'callback' Optional    function to be called when data arrives to the client after request. If nothing is specified, use default function
    'div' Optional    the div which should be updated when data is receive by client.
    'refresh'   Optional    State whether cached item should be used or a new request should be sent.
   
//For node
    'nid' Required    the node_id as drupal recognizes a node.
//For block
    'module' Required    the module that created the block.
    'block_id' Required    The identification for block as used by drupal.
//For generic data : The security aspect has not been explored
    'funcName' Required    The function that should be called for data.
   
//For next page in pagination (refresh is not of any use in this case)
    'page_no' Required    The page to be loaded next.
*/
asyncapi.cache = {};
asyncapi.processing = [];
asyncapi.currentPage = 0;

asyncapi.load = function(args) {

  if(!(args['type'] != null && (args['type'] == 'node' || args['type'] == 'block' || args['type'] == 'data' || args['type'] == 'page'))) 
  {
    alert('Error in arguments, request type should be "node" or "block" or "data".');
    return false;
  }
  var type = args['type'];
  var showButton = '+';
  if (args['showbuttontext'] != null) {
    showButton = args['showbuttontext'];
  }
  var hideButton = 'x';
  if (args['hidebuttontext'] != null) {
    hideButton = args['hidebuttontext'];
  }
  var endPage = 'End of page';
  if (args['endPagetext'] != null) {
    endPage = args['endPagetext'];
  }


  if(args['type'] == 'node')
  {
    if(args['nid'] == null)
    {
      alert('Error in arguments, nid should be specified for "node" type ');
      return false;
    }
    else
    {
      var nid = args['nid'];
			if(asyncapi.processing[nid] == true)
			{
				return false;
			}
			if(args['toggle'] != false && asyncapi.cache[nid])
			{
				//Code to hide or show the node that is already loaded.
				if($('asyncapi_content_'+nid).style.display == 'block')
				{
          //Height gets removed when some restructuring takes place on page so set it to 0 if not defined
          if(!$('asyncapi_content_'+nid).height)
            $('asyncapi_content_'+nid).height = '0px';
					//Hide the node but save the height.
					var height = Math.max($('asyncapi_content_'+nid).offsetHeight,parseInt(($('asyncapi_content_'+nid).height).substring(0,$('asyncapi_content_'+nid).height.length-2)));
 					asyncapi.effects.slideUp($('asyncapi_content_'+nid),nid, 1, 20, 0,height, asyncapi_postSlideUp);	
 					$('asyncapi_button_'+nid).innerHTML = showButton;			
				}
				else
				{
					//Show it
					$('asyncapi_content_'+nid).style.display = 'block';

          //Height gets removed when some restructuring takes place on page so set it to 0 if not defined
          if(!$('asyncapi_content_'+nid).height)
          {
            //Here I am setting the height as offset height as height is not defined.
            $('asyncapi_content_'+nid).style.maxHeight = '';
            $('asyncapi_content_'+nid).height = $('asyncapi_content_'+nid).offsetHeight+'px';
            $('asyncapi_content_'+nid).style.maxHeight = '0px';
          }
					var height = Math.max( $('asyncapi_content_'+nid).offsetHeight, parseInt(($('asyncapi_content_'+nid).height).substring(0,$('asyncapi_content_'+nid).height.length-2)));
					asyncapi.effects.slideDown($('asyncapi_content_'+nid),nid, 1, 20,height, asyncapi_postSlideDown);	
 					$('asyncapi_button_'+nid).innerHTML = hideButton;
					if($('asyncapi_title_'+nid))
					{
					  $('asyncapi_title_'+nid).style.display = 'none';
					}
				}
				return true;
			}
      $('asyncapi_content_'+nid).style.display = 'block';
      if(args['refresh'] == false)
      {
        if(asyncapi.cache[nid])
        {
          return true;
        }
      }
      if(args['callback'])
      {
        var fn = args['callback'];
				asyncapi.processing[nid] = true;
        HTTPGet('?q=asyncapi/node/'+nid+'/'+ args['teaser'] +'&rand='+Math.random()+'&pageurl='+escape(document.URL),function(data,xmlhttp,callback) {
        eval('var x = ' + data); 	asyncapi.cache[x['nid']] = x;	$('asyncapi_button_'+x['nid']).innerHTML = hideButton; callback(data); },fn);
        return true;
      }
      else
      {
				asyncapi.processing[nid] = true;
        var response = HTTPGet('?q=asyncapi/node/'+nid+'/'+ args['teaser'] +'&rand='+Math.random());
        asyncapi.cache[nid] = response;
        asyncapi.showLoadedNode(response);
				$('asyncapi_button_'+nid).innerHTML = hideButton;
        return true;
      }
    }
  }
  else if (args['type'] == 'page')
  {
    if(asyncapi.currentPage == -1)
    {
      return true;
    }
    if(args['callback'])
    {
      var fn = args['callback'];
      HTTPGet('?q=asyncPage/page&page='+(++asyncapi.currentPage)+'&rand='+Math.random(),function(data,xmlhttp,callback) {
      callback(data); },fn);
      return true;
    }
    else
    {
      var response = HTTPGet('?q=asyncPage/page&page='+(++asyncapi.currentPage)+'&rand='+Math.random());
      asyncapi.showPage(response,endPage);
	  
      return true;
    }
  }
	
};

function asyncapi_postSlideUp(nid)
{
	if($('asyncapi_title_'+nid))
	{
		$('asyncapi_title_'+nid).style.display = 'block';
	}
}
function asyncapi_postSlideDown(nid)
{
	//voteUpDownAutoAttach();
}

function asyncapi_postPageSlideDown(page)
{
}
asyncapi.showLoadedNode = function(data)
{
  eval('var node = ' + data);
  $('asyncapi_content_'+node['nid']).style.visibility = 'hidden';
  $('asyncapi_title_'+node['nid']).style.display = 'none';
  $('asyncapi_content_'+node['nid']).innerHTML = node['node_view'];
  var height = $('asyncapi_content_'+node['nid']).offsetHeight;
  var temp = new asyncapi.effects.slideDown($('asyncapi_content_'+node['nid']),node['nid'], 10, 20, height, asyncapi_postSlideDown);
	
  //alert('loaded ' +node['nid'] )
}

asyncapi.showPage = function(data,lastPageText)
{
  eval('page = ' + data);

  //$('asyncapi_page_'+asyncapi.currentPage).style.visibility = 'hidden';
  $('asyncapi_pager_content').innerHTML += page['content'];
  var height = $('asyncapi_pager_content').offsetHeight;
  //var temp = new asyncapi.effects.slideDown($('asyncapi_page_'+asyncapi.currentPage), 1, 20, height);
  var temp = new asyncapi.effects.slideDown($('asyncapi_page_'+asyncapi.currentPage),0, 5, 40, height, asyncapi_postPageSlideDown);
  if(page['last']) {
	  asyncapi.currentPage = -1;
	  $('asyncapi_pager_more_content').innerHTML = lastPageText;
  }   
}

asyncapi.effects.slideDown = function(el,nid,timeInterval, heightStep , maxH, callback)
{
  var z = this;
  z.nextStep = function()
  {
    if(z.counter < z.nTimes)
    {
      z.currHeight += z.h ;
      z.div.height = z.currHeight + 'px';
      z.div.style.maxHeight =  z.currHeight + 'px';
			z.counter++;
    }
    else
    {
      clearInterval(z.timer);
			asyncapi.processing[z.nid] = false;
			if(z.c != null && typeof(z.c) != "undefined")
				z.c(z.nid);
    }

  }
  if(el)
  {
    z.div = el;
		z.nid = nid;
    z.t = timeInterval;
    z.h = heightStep;
    z.max = maxH;
    z.div.style.overflow = 'hidden';
    z.div.style.visibility = 'visible';
    z.div.height = 0;
    z.div.style.maxHeight = '0px';
    z.timer = setInterval(z.nextStep, z.t);
    z.div.style.display = 'block';
		z.c = callback;
		z.nTimes = (maxH - 0)/heightStep;
		z.counter = 0;
		z.currHeight = 0;
  }
}

asyncapi.effects.slideUp = function(el,nid,timeInterval, heightStep , minH, initialHeight, callback)
{
  var y = this;
  y.nextStep = function()
  {
    if(y.counter < y.nTimes)
    {
      y.currHeight -= y.h ;
      y.div.height = Math.max(y.currHeight,0) + 'px';
      y.div.style.maxHeight =  Math.max(y.currHeight,0) + 'px';
			y.counter++;
    }
    else
    {
      clearInterval(y.timer);
			y.div.style.display ="none";
			y.div.style.visibility  = "hidden";
			y.div.height = y.iH + "px";
			asyncapi.processing[y.nid] = false;
			if(y.c != null && typeof(y.c) != "undefined")
				y.c(y.nid);
    }
  }
  if(el)
  {
    y.div = el;
		y.nid = nid;
    y.t = timeInterval;
    y.h = heightStep;
    y.min = minH;
    y.div.style.overflow = 'hidden';
    y.div.style.visibility = 'visible';
    y.timer = setInterval(y.nextStep, y.t);
    y.div.style.display = 'block';
		y.iH = initialHeight;
		y.nTimes = (initialHeight - minH)/heightStep;
		y.counter = 0;
		y.currHeight = initialHeight;
		y.c = callback;
  }
}
