
var cookie_life=120;
var is_reply=false; // is the current tweet to be sent a reply?
var in_reply_to_id=0; // if the current tweet to be sent is a reply, what is the ID of the original tweet?
var since=1; // last message id retrieved
var page=1; // set the page to 1 as the starting point
var content_update=null; // this will be the pointer to the page content refresh timer
var countdown_update=null; // this is the pointer to the countdown refresh timer
var timeline = "tweets"; //which timeline are we showing right now?
var tracked = "";// if we're viewing a tracked users timeline, which one?
var logged_in="logged_out";

$(document).ready(function(){
	
	$(".suggest").dialog({
						autoOpen: false,
						position: 'center',
						modal:true,
						resizable:false,
						draggable:false,
						height:250,
						width:505,
						title:"Suggest someone to follow."
					});
	
	login(get_cookie('tusername'),get_cookie('tpassword'));
	view(logged_in);
		
	set_top_tweeters();
	
	set_cloud();
	
	set_timeline(timeline);
	
	$("#previous_control").click(function(event){
	    event.preventDefault();
		since=1;
		page--;
		if(page>1) {
			$("#previous_control").show(); // turn off the page refresh and countdown
			clearInterval(content_update);
			clearInterval(countdown_update);
		}else{
			$("#previous_control").hide();  // turn the page refresh and countdown back on
			content_update=setInterval("retrieve(timeline,page)", refresh_interval);
			time_left=refresh_interval_seconds; 
			countdown_update = setInterval("countdown()", 1000);
			retrieve(timeline,page);
		}
		if(page<1) {
			page=1;
			$("#tweets_list").html("");// turn the page refresh and countdown on
			content_update=setInterval("retrieve(timeline,page)", refresh_interval);
			time_left=refresh_interval_seconds; 
			countdown_update = setInterval("countdown()", 1000);
			retrieve(timeline,page);
		}
	});

	$("#next_control").click(function(event){
		event.preventDefault();	
		since=1;
		page++;
		if(page>1) {
			$("#previous_control").show();// turn off the page refresh and countdown
			clearInterval(content_update);
			clearInterval(countdown_update);
		}else{
			$("#previous_control").hide();// turn the page refresh and countdown back on
			content_update=setInterval("retrieve(timeline,page)", refresh_interval);
			time_left=refresh_interval_seconds; 
			countdown_update = setInterval("countdown()", 1000);
		}
		if(page<1) page=1;
		$("#tweets_list").html("");
		retrieve(timeline,page);
	});
		
	$("#previous_control").hide();
	
});

function suggest(suggested,suggestor){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=suggest&suggested="+suggested+"&suggestor="+suggestor,
		async: false,
		cache: false,
		dataType: 'json',
		success: function(data){
			if(data.success){
				$(".suggest_open").hide();
				$(".suggest_close").show();
			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});	
}

function login(username,password){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=login&username="+username+"&password="+encodeURIComponent(password),
		async: false,
		cache: false,
		dataType: 'json',
		success: function(data){
			if(data.screen_name){
				logged_in="logged_in";
				// Tweet dialog: to show th tweet textarea by default,
				// comment out the "slideUp" and un-comment the "slideDown"
				$("#tweet_dialog").slideUp();
				// $("#tweet_dialog").slideDown();
				set_cookie('tusername',username,cookie_life);
				set_cookie('tpassword',password,cookie_life);
			}else{
				logged_in="logged_out";
				set_cookie('tusername',"",-1);
				set_cookie('tpassword',"",-1);
			}
			if(data.error==401){
				logged_in="Bad username/password combination";
			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
	view(logged_in);
}

function logout(){
	set_cookie("tusername","",-999);
	set_cookie("tpassword","",-999);
	logged_in="logged_out";
	$("#tweet_dialog").slideUp();
	view(logged_in);
}

function remember_me(){
	if($("#remember_me").attr("checked")){
		cookie_life=120;
	}else{
		cookie_life=0;
	}
}

function view(login_status){
	if(login_status=="logged_in"){
		$(".logged_in").show();
		$("#screen_name").text(get_cookie('tusername'));
		$("#login_controls").hide();
	}else{
	    $(".logged_in").hide();
		$("#login_controls").show();
	}
	
	if(get_cookie('admin-username')&&get_cookie('admin-password')&&timeline=="favorites"){
		flag = get_cookie('admin-username');
		if(flag!="logged_out"){
			$(".admin").show();
		}
	}
}

function retrieve(timeline,page){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=retrieve&timeline="+timeline+"&page="+page+"&since="+since+"&tracked="+tracked,
		async: true,
		cache: false,
		dataType: 'html',
		success: function(data){
			//alert("Success "+data);
			if(timeline=="following"){
				insert_following(data);
			}else{
				insert_tweets(data);
			}
		},
		error: function(data){
			console.error("failed 'retrieve()'");
			console.error(data);
		}
	});
	time_left=refresh_interval_seconds;
	view(logged_in);
}

function set_timeline(new_timeline){
	timeline = new_timeline;
	page = 1;
	since = 1;
	$("#tweets_list").html("");
	$("#timeline_title").text("Latest Tweets");
	if(timeline=="favorites"){
		$("#timeline_title").text("Site Favorites");
	}else if(timeline=="following"){
		$("#timeline_title").text("Who We're Following");
	}
	retrieve(new_timeline,page);
	
	clearInterval(content_update);
	clearInterval(countdown_update);
	if (new_timeline == "following") {
	// dont set the update interval, no refresh needed for this list
	}else{
		content_update = setInterval("retrieve(timeline,page)", refresh_interval);
		countdown_update = setInterval("countdown()", 1000);
	}
	return true;
}

function countdown(){
	time_left--;
	if(time_left<=0) time_left=refresh_interval_seconds;
	$("#reload_count").text(time_left);
	//$("#content_header").text(time_left);
}

/**
** insert the data retrieved from the API into the page
**/
function insert_tweets(data){
	//console.log(data);
	$("#content").html(data);
	set_hovers();
}
/**
** set the hover state for each twitter user image
** extended data should appear when hovering over the 
** tweeters avatar
**/
function set_hovers(){
	$(".tweet_li").each(function(){
		var targetId = $(this).attr("id"); 
		$("#"+targetId+"_avatar").qtip({
			content: $("#"+targetId+"_tip").html(),
		  	style:{
				border: {
					width: 2,
			     	radius: 8,
			     	color: '#e7e8e9'
			 	},
				width: 300
			},
			position: {
			  corner: {
			     target: 'center',
			     tooltip: 'leftMiddle'
			  }
			},
			show: 'mouseover',
			hide: { when: 'mouseout', fixed: true }
		});	
	});

}

function OLD_insert_tweets(data){
	data=data.reverse();
	for (var tweet in data){
		var date = new Date(data[tweet].created_at * 1000);		
		ampm="am";
		hours=date.getHours();
		if(hours>12){
			hours=hours-12;
			if(hours==12){
				ampm="am"
			}else{
				if(hours==0) hours = 12;
				ampm="pm";
			}
		}
		minutes=date.getMinutes();
		if(minutes<10){
			minutes="0"+minutes;
		}
		dayArr = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu','Fri','Sat');
		day = date.getDay();
		day = dayArr[day];
		monthArr = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
		month = date.getMonth();
		month = monthArr[month];
		mDay=date.getDate();
		year = date.getFullYear();
		timestamp = day+ " " +month+" "+mDay+", "+year;
		if(show_time==true){
			timestamp += " "+hours+":"+minutes+ampm;
		}
		message_text = create_links(data[tweet].text);
		fav_image="images/favorite_false.gif";
		if(data[tweet].site_favorited==1) fav_image="images/favorite_true.gif";
		//screen_name=data[tweet].user_screen_name;
		msg="<li class='"+data[tweet].user_screen_name+"_li tweet'>"+				
				"<span id='"+data[tweet].id+"_tip' style='display:none;'>"+	
					"<table class='tip_content'>"+
						"<tr>"+
							"<td><h3>Tweeter:</h3></td>"+
							"<td><h3>"+
								"<a href='http://twitter.com/"+data[tweet].user_screen_name+"' target='_blank' title='http://twitter.com/"+data[tweet].user_screen_name+"'>"+data[tweet].user_screen_name+"</a>"+
							"</h3></td>"+
						"</tr>";
						if(data[tweet].user_statuses_count){
							msg+="<tr><td><b>Name:</b></td><td>"+data[tweet].user_name+"</td></tr>"+
								"<tr><td><b>Following:</b></td><td>"+data[tweet].user_friends_count+"</td></tr>"+
								"<tr><td><b>Followers:</b>&nbsp&nbsp</td><td>"+data[tweet].user_followers_count+"</td></tr>"+
								"<tr><td><b>Statuses: </b></td><td>"+data[tweet].user_statuses_count+"</td></tr>"+
								"<tr><td><b>Web:</b></td><td><a href='"+data[tweet].user_url+"' target='_blank'>"+data[tweet].user_url+"</a></td></tr>";
						}else{
							msg+="<tr><td><b>Source:</b></td>"+
								"<td id='should_be_a_td'>"+html_entity_decode(data[tweet].source)+"</td></tr>";
						}
					msg+="</table>"+
				"</span>"+	
				"<table class='tweet_container'><tr>"+
					"<td id='"+data[tweet].id+"_avatar' class='avatar_content'>"+
						"<img src='"+data[tweet].user_profile_image_url+"' class='avatar sf-avatar'>"+
					"</td>"+
					"<td class='bl_cell'></td>"+
					"<td class='tweet_wrapper'>"+
						"<p class='tweet_text'>\""+message_text+"\"</p>"+
						"posted by <span class='tweet_sender'>"+data[tweet].user_screen_name+"</span>"+
						" | <span class='tweet_date'> "+timestamp+ "</span>" +
						"<span class='message_controls'>"+
							"<span class='logged_in' style='display:none'> | "+
								"<a href='#' onclick='favorite("+data[tweet].id+");return false;' title='Favorite this tweet'><img id='"+data[tweet].id+"_fav_image' src='"+fav_image+"'></a>"+
								"<a href='#' onclick='reply(\""+data[tweet].user_screen_name+"\","+data[tweet].id+");$(\"#tweet_dialog\").slideDown();return false;' title='Reply to this tweet'><img src='images/reply.gif'></a>"+
								"<a href='#' onclick='retweet(\""+data[tweet].user_screen_name+"\",\""+escape(data[tweet].text)+"\");$(\"#tweet_dialog\").slideDown();return false;' title='Retweet this tweet'><img src='images/retweet.gif'></a>"+
								"<a href='#' onclick='unfavorite(\""+data[tweet].id+"\");' title='Unfavorite this tweet' class='admin' style='display:none;'><img src='images/unfavorite.png' class='admin' style='display:none'></a>"+
							"</span>"+
						"</span>"+
					"</td>"+
				"</tr></table>"+
			"</li>";
		$("#tweets_list").prepend(msg).fadeIn("slow");
		if(get_cookie('admin-username')&&get_cookie('admin-password')&&timeline=="favorites"){
			flag = get_cookie('admin-username');
			if(flag!="logged_out"){
				$(".admin").show();
			}
		}
		// this is the last message retrieved, set the 'since' var for the next timeline request
		since = data[tweet].id;
		list_len=$("#tweets_list > li");
		if (list_len.length>15){
			// remove the oldest tweet if the list is over 15 long
			$("#tweets_list > li:last").remove();
		}
	
		$("#"+data[tweet].id+"_avatar").qtip({
			content: $("#"+data[tweet].id+"_tip").html(),
	      	style:{
				border: {
					width: 2,
		         	radius: 8,
		         	color: '#e7e8e9'
			 	},
				width: 300
			},
			position: {
		      corner: {
		         target: 'center',
		         tooltip: 'leftMiddle'
		      }
			},
			show: 'mouseover',
			hide: { when: 'mouseout', fixed: true }
		});
	}
	
		view(logged_in);
}
function insert_following(data){
	
	for (var tracked in data){
		msg="<li id='"+data[tracked].screen_name+"_li'><table class='tweet_table'><tr>"+
					"<td class='avatar_cell'>"+
						"<a href='http://twitter.com/"+data[tracked].screen_name+"' target='_blank' title='http://twitter.com/"+data[tracked].screen_name+"'>"+
							"<img src='"+data[tracked].profile_image_url+"' class='avatar'>"+
						"</a>"+
					"</td>"+
					"<td class='bl_cell'></td>"+
					"<td class='tweet_cell'>"+
						"<ul>"+
							"<li><b>Name:&nbsp</b>"+data[tracked].screen_name+"&nbsp("+data[tracked].name+")</li>"+
							"<li><b>Following:&nbsp</b>"+data[tracked].friends_count+"</li>"+
							"<li><b>Followers:&nbsp</b>"+data[tracked].followers_count+"</li>"+
							"<li><b>Statuses:&nbsp</b>"+data[tracked].statuses_count+"</li>"+
							"<li><b>Web:&nbsp</b><a href='"+data[tracked].url+"' target='_blank'>"+data[tracked].url+"</a></li>"+
						"</ul>"+
					"</td>"+
				"</tr></table></li>";
		$("#tweets_list").hide().prepend(msg).fadeIn("slow");
		// this is the last message retrieved, set the 'since' var for the next timeline request
		since = 1; //we're not following a live list of messages here, just tracked user accounts
		list_len=$("#tweets_list > li");
		if (list_len.length>15){
			// remove the oldest tweet if the list is over 15 long
			$("#tweets_list > li:last").remove();
		}
	}
}

function set_cloud(){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=tracking",
		async: false,
		dataType: 'json',
		cache: false,
		success: function(data){
			//alert("Success "+data);
			populate_cloud(data);
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
}

function populate_cloud(data){
	$(".cloud").html("");
	for(i in data){
		$(".cloud").append("<a href='#' class='cloud_item' onclick='tracked=\""+encodeURIComponent(data[i].search_term)+"\";set_timeline(\"tracked\");'> "+data[i].search_name+" </a>");
	}
}
function set_top_tweeters(){
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=top_tweeters",
		async: false,
		dataType: 'json',
		cache: false,
		success: function(data){
			//alert("Success "+data);
			populate_top_tweeters(data);
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
}

function populate_top_tweeters(data){
	$(".top_tweeters").html("");
	for(i in data){
		$tweeter_data = "<a href='#' class='top_tweeter_item' onclick='tracked=\""+data[i].user_screen_name+"\";set_timeline(\"sender\");return false;' title='"+data[i].user_screen_name+"'>";
			$tweeter_data += "<img src='"+data[i].user_profile_image_url+"' style='max-width:25px;margin:2px;'>";
		$tweeter_data += "</a>";
		$(".top_tweeters").append($tweeter_data);
	}
}

function send_tweet(text,tweet_is_reply,tweet_id){
	//alert("text: "+text+" reply: "+tweet_is_reply+" id: "+tweet_id);	
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=send_tweet&text="+encodeURIComponent(text)+"&is_reply="+tweet_is_reply+"&tweet_id="+tweet_id+"&username="+get_cookie('tusername')+"&password="+encodeURIComponent(get_cookie('tpassword')),
		async: false,
		cache: false,
		dataType: 'json',
		success: function(data){
			// success? close send dialog, otherwise notify user and keep dialog open
			if(data['user']['screen_name']){
				$("#tweet_input").text("");
				$("#tweet_input").val("");
				$("#send_success").fadeIn('slow').fadeOut(5000);
			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
	is_reply=false;
	in_reply_to_id=0;
}

function reply(reply_to_screen_name, reply_to_message_id){
	is_reply=true;
	in_reply_to_id=reply_to_message_id;
	$("#tweet_input").val();
	$("#tweet_input").val("@"+reply_to_screen_name+" ");
	$(".send_tweet").dialog('open');
	//alert(reply_to_message_id+":"+reply_to_screen_name);
}

function retweet(screen_name,message_text){
	is_reply=false;
	$("#tweet_input").val();
	$("#tweet_input").val("RT @"+screen_name+": "+unescape(message_text));
	$(".send_tweet").dialog('open');
	//alert(screen_name);
	//alert(unescape(message_text));
}
function favorite(tweet_id){
// mark the tweet as site_favorited=1
// if the user is logged in, also mark it favorited for their twitter account
	if(get_cookie('tusername')){
		username=get_cookie('tusername');
	}else{
		username=0;
	}
	if(get_cookie('tpassword')){
		password=get_cookie('tpassword');
	}else{
		password=0;
	}
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=favorite&tweet_id="+tweet_id+"&username="+username+"&password="+encodeURIComponent(password),
		async: false,
		dataType: 'json',
		success: function(data){
			// success? set tweet favorite button to "on"
			if(data['success']){
				$("#"+tweet_id+"_fav_image").attr("src","images/favorite_true.gif");
			}else{

			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
}
function unfavorite(tweet_id){
// mark the tweet as site_favorited=0
// this should only be available to logged in admins
	if(get_cookie('admin-username')){
		username=get_cookie('admin-username');
	}else{
		username=0;
	}
	if(get_cookie('admin-password')){
		password=get_cookie('admin-password');
	}else{
		password=0;
	}
	$.ajax({
		type: "get",
		url: "api.php",
		data: "request=unfavorite&tweet_id="+tweet_id+"&admin_username="+username+"&admin_password="+encodeURIComponent(password),
		async: false,
		dataType: 'json',
		success: function(data){
			// success? set tweet favorite button to "on"
			if(data['success']){
				$("#"+tweet_id+"_fav_image").attr("src","images/favorite_false.gif");
			}else{

			}
		},
		error: function(data){
			//alert("Server communication error. Sorry!  Please try again in a minute or two.");
		}
	});
}

function update_char_counter(){
	//** COUNTDOWN monitors textarea and updates "characters left" count
	var value = $("#tweet_input").val();
	
	$("#char_counter").html(140 - value.length);
	if (value.length > 130) {
		$("#char_counter").css("color", '#a7a9ac');
	} else if (value.length > 120) {
		$("#char_counter").css("color", '#5c0002');
	} else {
		$("#char_counter").css("color", '#aaaaaa');
	}

}

//
// UTILS
//
	
// CREATELINKS
function create_links(messageText){
		// create links of URLs
	var pattern = /(((ht|f)tp(s?))\:\/\/{1}[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/ig;
	urlArray = messageText.match(pattern);
	var linkVal = "";
	if(urlArray){
		$.each(urlArray, function(key, val){
			//shorten links for disply
			//if(val.length>20){
			//	linkVal =val.slice(0,16);
			//	linkVal+="...";
			//}else{
				linkVal=val;
			//}
			messageText=messageText.replace(val, "<a href=\""+val+"\" target=\"_blank\" title=\""+val+"\">"+linkVal+"</a>");
		});
	}
	//create links of @ references
	pattern = /@{1}[-a-zA-Z0-9%_\+~&\/\/=]+/ig;				
	atArray = messageText.match(pattern);
	if(atArray){
		$.each(atArray, function(key, val){
			shortVal = val.replace(/@/,"");
			messageText=messageText.replace(val, "<a href=\"http://twitter.com/"+shortVal+"\" target=\"_blank\"  title=\"http://twitter.com/"+shortVal+"\">"+val+"</a>");
		});
	}
	//create links of # references
	pattern = /#{1}[-a-zA-Z0-9%_\+~&\/\/=]+/ig;				
	hashArray = messageText.match(pattern);
	if(hashArray){
		$.each(hashArray, function(key, val){
			//shortVal = val.replace(/#/,"");
			messageText=messageText.replace(val, "<a href=\"http://search.twitter.com/search?q="+encodeURIComponent(val)+"\" target=\"_blank\" title=\"Search Twitter for "+val+"\">"+val+"</a>");
		});
	}
	return(messageText);
}


//** SET_COOKIE
	function set_cookie(c_name,value,expiredays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	}

// GET_COOKIE
	function get_cookie(c_name){
		if (document.cookie.length>0){
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
		return "";
	}

function print_r(theObj){
	if(theObj.constructor == Array || theObj.constructor == Object){
		document.write("<ul>");
		for(var p in theObj){
			if(theObj[p].constructor == Array || theObj[p].constructor == Object){
				document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
				document.write("<ul>");
				print_r(theObj[p]);
				document.write("</ul>");
			} else {
				document.write("<li>["+p+"] => "+theObj[p]+"</li>");
			}
		}
		document.write("</ul>");
	}
}

function html_entity_decode (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
 
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
 
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

