var urltag = urltag || {};
(function(){
   var settings = {origin:'urltag.net',
		   app_id : 1};

   var qsEncode = function(obj){
     if (typeof(obj)=='object'){
       var ret ='';
       for (var k in obj){
	 if (obj[k].constructor==Array ){
	   for (var i in obj[k]){
	     ret += encodeURIComponent(k) +'=' +encodeURIComponent(qsEncode(obj[k][i]))+'&';
	   }
	 } else {
	   ret += encodeURIComponent(k) +'=' +encodeURIComponent(qsEncode(obj[k]))+'&';
	 }

       }
       return ret;
     } else {
       return obj;
     }
   };

   var getJsonXd = function(url, params, callback) {
     urltag._jsonXdCallback = callback;
     var d = new Date();
     params['_' ] =  d.getTime();
     var _call_js = document.createElement('script'); _call_js.type = 'text/javascript'; _call_js.async = true;
     _call_js.src = ('https:' == document.location.protocol ? 'https://' : 'http://') +
       settings.origin + url + '?' + qsEncode(params);
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(_call_js, s);
   };


   var tag = function(orig_urls,
		       callback,
		       data,
		       type){
     //Returns tagged link
     // orig_urls - the URLs to tag (array)
     // callback - the callback function that receives the result (array of tagged URLs)
     // data - (optional) data  to associate with the tagged URL (JS object)
     // type - (optional) type of tagging: anchor/shorten
     if (!data)
       data = {};
     if (!type)
       type='anchor';
     getJsonXd('/l/' + settings.app_id + '/fn/tag.js',
	       {'orig_urls' : orig_urls,
		'data' : data,
		'type' : type},
	       function(response) { callback(response.urls); }
	      );
   };

   urltag.tag = tag;

 })();

