var userID;
var userInfo;
var friendInfo;

var foo = "this is a test";

var fb_connect		= null;
var streamObject 	= null;
var streamObject	= null;

if ( window.addEventListener )
	{
		window.addEventListener ( "load", startLoadingFbBootstrap, false );
	}
	
if ( window.attachEvent )
	{
		window.attachEvent ( "onload", startLoadingFbBootstrap );
	}

function startLoadingFbBootstrap (  ) {
	FB.Bootstrap.requireFeatures ( ["Connect"], initAppliaction );
}

function initAppliaction (  ) {
	init (  );
}

function init (  ) {
    fb_connect = new FB_connect (  );
    // a7aac39b28b6a1c85ae5f1776f1b3191
    fb_connect.setAPIKey ( "2552749db37de04c174d8505ff93876a" );
    
    var tmpCountryCode = document.getElementById ( "countryCode" );
    if ( tmpCountryCode != null )
    	{
    		fb_connect.setCountryCode ( tmpCountryCode.value );
    	}
    
    setTimeout ( "fb_connect.logIn (  )", 1000 );
    
    // fb_connect.logIn (  );
    
    // alert ( "init" );
}

function flashObject (  ) {
    var self = this;
    
    this.flashMovie = null;
}

flashObject.prototype = {
    getFlashMovie : function (  ) {
       
       /*
       if ( navigator.appName.indexOf ( "Microsoft" ) != -1 )
			{
				this.flashMovie = window["flashContent"];
				return this.flashMovie;
			} 
			else
			{
				if ( document["flashContent"].length != undefined )
					{
						this.flashMovie = document["flashContent"][1];
						return this.flashMovie;
					}
					
				this.flashMovie = document["flashContent"];
				return this.flashMovie;
			}
		*/
		
        this.flashMovie = ( navigator.appName.indexOf ("Microsoft") != -1 ) ? window["flashContent"] : document["flashContent"];
        
        return this.flashMovie;
    }
}



function StreamObject (  ) {
	var self		= this;
	
	this.title			= "";
	this.subTitle		= "Your comment";
	this.description	= "";
	this.url			= "";
	
	this.linkArray		= [{ "text": "What's your feeldgoodie?", "href": "http://campaign.sloggi.com/is/index.php?pageID=223&countryCode=" + fb_connect.getCountryCode (  )}];
}

// "name" : "name", 
// "href" : "href", 
// "caption" : "caption",
// "description" : "description",
// "properties" : [{'type': 'image'}]

StreamObject.prototype = {
	getInfo : function ( _value ) {
		return this[_value];
	},
	publishStream : function ( _name, _id, _flashVal1, _flashVal2, faceBookPagePost_0, faceBookPagePost_1, faceBookPagePost_2, faceBookPageID ) {
		FB.Connect.streamPublish ( '', { 
			"name" : _name + " " + faceBookPagePost_0, 
			"href" : "http://www.facebook.com/profile.php?ref=profile&id=" + _id, 
			"caption" : _flashVal1,
			"description" : _flashVal2,
			// "properties" : [{"text" : "campaign.sloggi.com", "href" : document.location.toString (  )}],
			// "properties" : [{"text" : "campaign.sloggi.com", "href" : "http://campaign.sloggi.com/sloggi-invisiblesense/index.php?pageID=" + faceBookPageID + "&countryCode=" + fb_connect.getCountryCode (  )}],
			// "properties":[{"category":[{"text":"humor", "href':'http://bit.ly/KYbaN"}], "ratings":"5 stars"}],
			"media" : [{'type': 'image', "src" : "http://campaign.sloggi.com/is/img/sloggi_fb_post_goodie.jpg", "href" : "http://campaign.sloggi.com/is/index.php?pageID=" + faceBookPageID + "&countryCode=" + fb_connect.getCountryCode (  )}]
		}, [{ "text": faceBookPagePost_2, "href": "http://campaign.sloggi.com/is/index.php?pageID=" + faceBookPageID + "&countryCode=" + fb_connect.getCountryCode (  )}], null,
		faceBookPagePost_1, this.stream_callback, true, null );
	},
	stream_callback : function ( post_id, exception ) {
		var self = this;
		
		if (post_id) {
			// post_to_my_server(post_id);
			// write to DB and other stuff after post
			// alert ( fb_connect );
			
			
			var queryParams = { 
				"fb_id" 	: fb_connect.userID,
				"result_1" 	: fb_connect.result_1,
				"result_2" 	: fb_connect.result_2,
				"firstname"	: "", // fb_connect.getUserName (  ), NOT ALLOWED
				"lastname"	: "", // fb_connect.getUserLastName (  ), NOT ALLOWED
				"email"		: fb_connect.getProxiedMail (  ),
				"countryID"	: fb_connect.getCountryCode (  )
			};
			/*
			var ajax = new Ajax (  );
			
			ajax.responseType 	= Ajax.FBML;
			ajax.ondone 		= this.onRequestComplete;
			ajax.onerror 		= this.onAjaxError;
	
			ajax.requireLogin = true;
	
			ajax.post ( 'http://campaign.sloggi.com/sloggi-invisiblesense/scripts/class_php/GatewayHandler.php?mode=fbpost&action=post', queryParams );
			*/
			
			streamObject.ajaxFunction ( "http://campaign.sloggi.com/is/scripts/class_php/GatewayHandler.php?mode=fbpost&action=post", queryParams );
		}
	},
	ajaxFunction : function ( _url, _params ) {
		 var self = this;
		 
		 var url 	= _url;
		 var params = _params;
		 var paramstring = "";
		 
		 for ( var i in params )
		 	{
		 		paramstring += "&" + i + "=" + params[i];
		 	}
		 
		 var xmlHttp;
		 
          try {
            // Firefox, Opera 8.0+, Safari
          	xmlHttp=new XMLHttpRequest();
          }
          catch ( e ) {
            // Internet Explorer
          	try {
            	xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            } catch ( e ) {
            	try {
                	xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                } catch ( e ) {
                	alert("Your browser does not support AJAX!");
                	return false;
                }
              }
            }
            xmlHttp.onreadystatechange = function (  ) {
            	if  ( xmlHttp.readyState == 4 ) {
            		self.onRequestComplete (  );
            	}
            }
            
    	xmlHttp.open("POST",url + paramstring,true);
        xmlHttp.send(null);
	},
	onRequestComplete : function ( data ) {
		// alert ( "saved" );
		// TO DO call flash to hide test
		
		fb_connect.result_1 = null;
		fb_connect.result_2 = null;
	},
	onAjaxError : function (  ) {
		// alert ( "error" );
		fb_connect.result_1 = null;
		fb_connect.result_2 = null;
	}
}

function FB_connect (  ) {
    var self = this;
    
    this.key    		= null;
    this.secret 		= null;
    this.countryCode 	= null;
    
    this.userID 	= null;
    this.userData 	= null;
    
    var flash 		= flash = new flashObject (  )
    this.flashMovie	= flash.getFlashMovie (  );
    
    this.result_1		= null;
	this.result_2		= null;
    
    this.inviteURL		= null;
    
    this.dialog			= null;
    
    this.getInviteUrl = "http://campaign.sloggi.com/is/fb_invite.php";
}

FB_connect.prototype = {
    setAPIKey : function ( _key ) {
        this.key = _key;
    },
    setAPISecret : function ( _secret ) {
        this.secret = _secret;
    },
    getAPIKey : function (  ) {
        return this.key;
    },
    logIn : function (  ) {
    	var self = this;
    	// alert ( "logIn" );
    	// FB.Facebook.init ( self.key, "http://campaign.sloggi.com/is/scripts/js/fb/xd_receiver.htm" );
    	FB.Facebook.init ( self.key, "xd_receiver.htm");
    	// alert ( FB.Connect.get_status (  ) );
    	FB.Connect.get_status (  ).waitUntilReady ( function ( status ) {
			switch ( status ) {
				case FB.ConnectState.connected:
					self.userID = FB.Facebook.apiClient.get_session (  ).uid;
					self.getProfileData (  );
					
					// alert ( status );
					/*
					var fb_connect_button = document.getElementById ( "fb_connect_button" );
					fb_connect_button.innerHTML = "";
					
					var fb_connect_post_button = document.getElementById ( "fb_connect_post_button" );
					fb_connect_post_button.innerHTML = "Post";
					
					var fb_connect_invite_button = document.getElementById ( "fb_connect_invite_button" );
					fb_connect_invite_button.innerHTML = "Invite Friends";
					
					var fb_connect_logout_button = document.getElementById ( "fb_connect_logout_button" );
					fb_connect_logout_button.innerHTML = "Log out";
					*/
				break;
				case FB.ConnectState.appNotAuthorized:
				case FB.ConnectState.userNotLoggedIn:
					
					// alert ( status );
					/*
					var fb_connect_button = document.getElementById ( "fb_connect_button" );
					fb_connect_button.innerHTML = "Facebook connect";
					
					var fb_connect_post_button = document.getElementById ( "fb_connect_post_button" );
					fb_connect_post_button.innerHTML = "";
					
					var fb_connect_invite_button = document.getElementById ( "fb_connect_invite_button" );
					fb_connect_invite_button.innerHTML = "";
					
					var fb_connect_logout_button = document.getElementById ( "fb_connect_logout_button" );
					fb_connect_logout_button.innerHTML = "";
					*/
					
					self.sendUserDataToFlash ( "login" );
				break;
			}
		});
    },
    logOut : function (  ) {
        /*
            var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["container"]:document["container"];
        	flash.returnLogoutStatus(true); 	
        	statusMsg("Finished logout");	
    	*/
        FB.Connect.logout ( this.sendLogoutStatus );
    },
    checkFBConnect : function (  ) {
        var self = this;
        
        // FB.Connect.ifUserConnected ( this.testIsLogged ( "yes" ), this.testIsLoggedOff ( "no" ) );
        
        // FB.Facebook.init ( self.key, "http://campaign.sloggi.com/sloggi-invisiblesense/scripts/js/fb/xd_receiver.htm");
        
        FB.Connect.requireSession ( fb_connect.sendLoginStatus, function() { fb_connect.onCancel(); } );
       	// FB.Connect.forceSessionRefresh ( null );
       	
        if ( !self.userID ) {
			FB.Facebook.get_sessionState (  ).waitUntilReady ( function (  ) {
				fb_connect.userID = FB.Facebook.apiClient.get_session (  ).uid;
				
				fb_connect.getProfileData (  );
				
				if ( !fb_connect.userID ) {
					return false;
				} else {
					return true;
				}
			});
		}
		else {
			fb_connect.getProfileData (  );
		}
    },
    onCancel : function (  ) {
    	// alert ( fb_connect.flashMovie.fb_logIn );
    	fb_connect.flashMovie.fb_enableSite (  );
    	
    	trackItem ( "Cancel Facebook connect" );
    	
    	return false;
    },
    testIsLogged : function ( _type ) {
    	alert ( _type );
    },
    testIsLoggedOff : function ( _type ) {
    	alert ( _type );
    },
    getProfileData : function (  ) {
    	var self 		= this;
    	var userInfo 	= null;
    	// alert ( self.userID );
    	FB.Facebook.apiClient.users_getInfo ( self.userID, "first_name, last_name, name, pic_square, is_app_user, proxied_email", function ( result, ex ) {
			
			if ( result != null )
				{
					userInfo = result.slice (  );
			
					self.userData = userInfo;
					self.sendUserDataToFlash ( "" );	
				}
				else
				{
					// FB.Connect.requireSession ( this.sendLoginStatus );
       				// FB.Connect.forceSessionRefresh ( fb_connect.checkFBConnect (  ) );
       				FB.Connect.forceSessionRefresh ( null );
					// FB.Connect.logout ( fb_connect.checkFBConnect );
				}
		});
    },
    getFriends : function ( faceBookPageInvite_0, faceBookPageInvite_1, faceBookPageInvite_2, faceBookPageInvite_3, faceBookPageID ) {
    	
		var finalURL = "?countryCode=" + this.getCountryCode (  ) + "&pageID=" + faceBookPageID + "&text0=" + escape ( htmlentities ( faceBookPageInvite_0 ) ) + "&text1=" + escape ( htmlentities ( faceBookPageInvite_1 ) ) + "&text2=" + escape ( htmlentities ( faceBookPageInvite_2 ) ) + "&text3=" + escape ( htmlentities ( faceBookPageInvite_3 ) );
		// var finalURL = this.getInviteUrl + "?countryCode=" + this.getCountryCode (  ) + "&pageID=" + faceBookPageID + "&text0=" + escape ( htmlentities ( faceBookPageInvite_0 ) ) + "&text1=" + escape ( htmlentities ( faceBookPageInvite_1 ) ) + "&text2=" + escape ( htmlentities ( faceBookPageInvite_2 ) ) + "&text3=" + escape ( htmlentities ( faceBookPageInvite_3 ) );
		switch ( this.getCountryCode (  ) )
			{
				case "ru":
				case "pl":
				case "hu":
				case "si":
				case "hr":
				case "ro":
				case "bg":
				case "cz":
				case "demo":
					var finalURL = "?countryCode=" + this.getCountryCode (  ) + "&pageID=" + faceBookPageID + "&text0=" + faceBookPageInvite_0  + "&text1=" + faceBookPageInvite_1 + "&text2=" + faceBookPageInvite_2 + "&text3=" + ( htmlentities ( faceBookPageInvite_3 ) );
					// var finalURL = this.getInviteUrl + "?countryCode=" + this.getCountryCode (  ) + "&pageID=" + faceBookPageID + "&text0=" + faceBookPageInvite_0  + "&text1=" + faceBookPageInvite_1 + "&text2=" + faceBookPageInvite_2 + "&text3=" + ( htmlentities ( faceBookPageInvite_3 ) );
					
				break;
			}
		
// ---------------------------------------------------------------------- deactivated for preview

		$.facebox.settings.boxTitle = faceBookPageInvite_0;
		jQuery.facebox({ajax: 'fb_test_content1.php' + finalURL});

// ---------------------------------------------------------------------- deactivated for preview
		
		// Facebook canceled that iFrame function!!!
		
		/*
		var fbmlIframe 	= "<fb:iframe src='" + finalURL + "' smartsize='false' frameborder='false' style='border: 0; width: 100%; height: 500px;' scrolling='yes' />";
		
		this.dialog = new FB.UI.FBMLPopupDialog ( faceBookPageInvite_0, fbmlIframe );
		
		this.dialog.setContentWidth(750);
		this.dialog.setContentHeight(500);
		this.dialog.set_placement(FB.UI.PopupPlacement.center);
		this.dialog.show();
		
		window.value = this.dialog;
		*/
    },
    closeOverlay : function (  ) {
    	// fb_connect.dialog.close (  );
    	fb_connect.dialog.close (  );
    },
    fb_getInviteFBML : function (  ) {
    	var uid = FB.Facebook.apiClient.get_session().uid;
    	var fbml = "";
    	
    	fbml = 
	    '<fb:fbml>\n' +
	        '<fb:request-form\n'+
	                            //Redirect back to this page
	                            ' action="'+ document.location +'"\n'+
	                            ' method="POST"\n'+
	                            ' invite="true"\n'+
	                            ' type="Sloggi invisible sense"\n' +
	                            ' content="Find out here and increase your mood - with our feelgoodie of the day. Made to make you happy.'+ 
	                            //Callback the server with the appropriate Webwars Account URL
	                            ' <fb:req-choice url=\'' + document.location + '\' label=\'Get your feelgoodie of the day\' />"\n'+
	                      '>\n'+
	                       ' <fb:multi-friend-selector\n'+
	                            ' rows="2"\n'+
	                            ' cols="4"\n'+
	                            ' bypass="Cancel"\n'+
	                            ' showborder="false"\n'+
	                            ' actiontext="Invite friends"/>\n'+
	                ' </fb:request-form>'+
	        ' </fb:fbml>';
	    return fbml;
    },
    sendUserDataToFlash : function ( _messageType ) {
    	switch ( _messageType )
    		{
    			case "logout":
    				// alert ( this.flashMovie );
    				this.flashMovie.fb_logOut (  );
    			break;
    			case "login":
    				// alert ( "Login needed..." );
    				if ( this.flashMovie != null )
    					{
    						if ( this.flashMovie.fb_logIn != null )
    							{
    								this.flashMovie.fb_logIn (  );	
    							}
    					}
    			break;
    			default:
    				// alert ( "flashMovie : " + this.flashMovie + " - FB UserData object to Flash: " + this.userData );
    				// alert ( this.flashMovie );
    				if ( this.flashMovie != null )
    					{
    						if ( this.flashMovie.fb_setUserData != null )
    							{
    								this.flashMovie.fb_setUserData ( this.userData );		
    							}
    					}
    			break;
    		}
    },
    postMsg : function ( _flashVal1, _flashVal2, faceBookPagePost_0, faceBookPagePost_1, faceBookPagePost_2, faceBookPageID ) {
    	this.result_1 = _flashVal1;
    	this.result_2 = _flashVal2;
    	
    	// alert ( FB.Connect.forceSessionRefresh ( null ) );
    	/*
    	if (  )
    		{
    			// this.sendUserDataToFlash ( "logout" );
    		}
    	*/
    	
    	streamObject = new StreamObject (  );
    	streamObject.publishStream ( this.getUserName (  ), this.userID, _flashVal1, _flashVal2, faceBookPagePost_0, faceBookPagePost_1, faceBookPagePost_2, faceBookPageID );
    },
    handleMessage : function ( perms ) {
    	
    },
    sendLogoutStatus : function (  ) {
    	var flash 		= flash = new flashObject (  )
    	var flashMovie	= flash.getFlashMovie (  );
    	flashMovie.fb_logOut (  );
    },
    sendLoginStatus : function (  ) {
    	var flash 		= flash = new flashObject (  )
    	var flashMovie	= flash.getFlashMovie (  );
    	
    	var sess = FB.Facebook.apiClient.get_session (  );
        
    	if ( sess == null )
    		{
    			// alert ( sess );
    		}
    		else
    		{
    			fb_connect.userID = FB.Facebook.apiClient.get_session (  ).uid;
    			fb_connect.getProfileData (  );
    		}
    	
    	// flashMovie.fb_setUserData (  );
    	// FB_connect.logIn (  );
    },
    getUserID : function (  ) {
        return this.userID;
    },
    getUserName : function (  ) {
        return this.userData[0].first_name;
    },
    getUserLastName : function (  ) {
        return this.userData[0].last_name;
    },
    getProxiedMail : function (  ) {
    	return this.userData[0].proxied_email;
    },
    setCountryCode : function ( _countryCode ) {
    	this.countryCode = _countryCode;
    },
    getCountryCode : function (  ) {
    	return this.countryCode;
    }
}

// flash calls
function checkFB (  ) {
	// fb_connect.logIn (  );
	setTimeout ( "fb_connect.logIn (  )", 1000 );
}

function checkLogin (  ) {
	// fb_connect.checkFBConnect (  );
	setTimeout ( "fb_connect.checkFBConnect (  )", 1000 );
}

function post ( _flashVal1, _flashVal2, faceBookPagePost_0, faceBookPagePost_1, faceBookPagePost_2, faceBookPageID ) {
	fb_connect.postMsg ( 
		( _flashVal1 == null ) ? "_flashVal1" : _flashVal1, 
		( _flashVal2 == null ) ? "_flashVal2" : _flashVal2, 
		( faceBookPagePost_0 == null ) ? "faceBookPagePost_0" : faceBookPagePost_0,
		( faceBookPagePost_1 == null ) ? "faceBookPagePost_0" : faceBookPagePost_1,
		( faceBookPagePost_2 == null ) ? "faceBookPagePost_0" : faceBookPagePost_2,
		( faceBookPageID == null ) ? "_pageID" : faceBookPageID
	);
}

function getFriends ( faceBookPageInvite_0, faceBookPageInvite_1, faceBookPageInvite_2, faceBookPageInvite_3, faceBookPageID ) {
	fb_connect.getFriends ( 
		faceBookPageInvite_0,
		faceBookPageInvite_1,
		faceBookPageInvite_2,
		faceBookPageInvite_3,
		faceBookPageID
	);
}

function logout (  ) {
	fb_connect.logOut (  );
}

// ---------------------

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   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;';
        entities['ё'] = '&#1077;';
    }
 
    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;
}

function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/htmlentities
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    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: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    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;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}