var url_count     = 10;
var base_domain   = 'similpedia';
var powered_by    = 'http://www.' + base_domain + '.com';

var base_url      = 'http://www.' + base_domain + '.com/crss_jsw';
var extra_args    = '';

//global hash where the data sent by the server will be placed - create it iff it doesn't exist
crss_data     = (typeof crss_data == "undefined") ? new Array() : crss_data; 

// find/set this script's id - iff this script is loaded before incr the global counter 
    script_cnt = (typeof script_cnt == "undefined") ? 1 : script_cnt + 1;
var  script_id = script_cnt;

// key into crss_data to access the data sent by the server 
var crss_data_key = 'crss.' + url_count + '.' + script_id;
// id of the span where the link list will be placed
var crss_span     = crss_data_key + '.span';
// class name for the UL element (entire list)
var crss_ul_class = base_domain + '-items';
// class name for each LI element (each list emelent)
var crss_li_class = base_domain + '-item';

getCRSSData();

/*
 * Retrieves data from the server in the form of dynamically genrated  javascript content
 * which contains a variable declaration with the data. The variable is called 
 * 'crss_data'. This method creates:(1) a script tag in the current location  
 * poining to the data-javascript, (2) a <span> tag that will be 
 * populated with the results, and finally calls another function that will
 * display the data by insterting the formated data in the <span>.
 *
 * Author: Ledion Bitincka 07/13/07
 */
function getCRSSData()
{
   var target = encodeURIComponent(window.location);
   var url    = base_url +'?q=' + target + '&count=' + url_count + '&data_key=' + crss_data_key + extra_args;

   document.write('<span id='+crss_span+'></span>'); 


   // include the data - make sure this script uses DEFER so that the browser continues rendering   
   document.write('<script type="text/javascript" src="' + url + '" defer="defer"></script>');
  
   // check every 20  ms iff the data has arrived
   var sleep = 20;   
   displayCRSSData(0, sleep, 1000, crss_data_key, crss_span); 
}

/*
 * Periodically checks for the data's arrival and displays it. If the data 
 * has not arrived yet this function schedules itself for execution after 
 * a period of time (incrementing the counter) - thus yielding to the browser to fetch the data and do other 
 * things such as rendering etc...
 *
 * @param cnt     - counter ALWAYS set to 0 when calling this func (this is used internally)
 * @param sleep   - time in ms to "sleep" if the data is not here yet
 * @param max_cnt - the maximum number of times to reschedule (max_cnt*sleep = max time to wait) or 
 *                  set to a negative number to reschedule infinitely (might NOT be a good idea)
 * @param data_key - name of the key (into crss_data) to wait for
 * @param span_name - name of the span element where to place the data
 *
 *
 * Author: Ledion Bitincka 07/13/07
 */
function displayCRSSData(cnt, sleep, max_cnt, data_key, span_name)
{
   if(cnt < max_cnt || max_cnt < 0) 
   {
      // wait for the data to get here (check again later, in 10ms) 
      if (typeof crss_data[data_key] == "undefined"){
	var callback ='displayCRSSData(' + (cnt+1) + ',' + sleep  + ','+ max_cnt + 
		      ',"' + data_key + '", "' + span_name +'")';

//	if(cnt > 0)
//		alert(callback);
	setTimeout(callback, sleep);

      }else{
	setInnerHTML(span_name, formatCRSSData(crss_data[data_key]));
      }
   }else{
	;// timed out 
   }
}
/* 
 * Parses the given data and formats it into an html list (ul) of hyperlink items.
 * The list (ul) and the hyperlinks (a) belong to the following CSS classes:
 * UL - crss_list  (can be overriden by setting crss_ul_class to something different)
 * A  - crss_link  (can be overriden by setting crss_a_class to something different)
 * This can be used by the webmasters to decorate the results to their liking by using CSS.
 * 
 * Author: Ledion Bitincka 07/13/07
 */
function formatCRSSData(data)
{
   var result = '<UL class="' +  crss_ul_class + '">';
   var cnt    = 0;
   var pairs  = data.split('\n');
   for(var i=0; i<pairs.length && cnt < url_count; i++)
   {
        if(pairs[i] && pairs[i].length > 0)
        {
            var url_title = pairs[i].split('\t');
	    if(url_title && url_title.length > 1)
	    {
            	result += ('\n<LI class="' + crss_li_class +'">' + 
		           '\n<A href="' + url_title[0] + '">' + url_title[1] + 
                           '</A>\n</LI>');
		cnt++;
	    }
        }
   }
   result += '<li class="' + crss_li_class + '" style="text-align: left; font-size: 90%; list-style-image: none; list-style-type:none;">' +
   '<A href="' +  powered_by +'">Powered by <b>Similpedia</b></A></li>';
   result += ('</UL>');

   return result;
}

/*
 * Simple utility function for setting the inner html  of an element
 * Author: Ledion Bitincka 07/13/07
 */
function setInnerHTML(id, html)
{
        var loc = document.getElementById(id);
	if(loc){
           loc.innerHTML = html;
        }
}

