var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 28;

//knocknok config vars
var _kn_window_height = 638;
var _kn_window_width = 540;

//set the version numbers...
//this will allow us to make updates then change these numbers to keep people's
//browsers from caching the old versions of the swf and HTML
knWidgetSwfVersion = 13;
knHTMLVer = 3;

//variable used to hold the chat "host"
var _chat_host = document.location.host;


//Base64 encode / decoding functions from: http://www.webtoolkit.info/javascript-base64.html
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=Base64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}
return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}}
output=Base64._utf8_decode(output);return output;},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}
else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;}}


//KNJSON functions from: http://www.KNJSON.org/KNJSON2.js
if(!this.KNJSON){KNJSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toKNJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){return escapeable.test(string)?'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toKNJSON==='function'){value=value.toKNJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
return{stringify:function(value,replacer,space){var i;gap='';indent='';if(space){if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}}
if(!replacer){rep=function(key,value){if(!Object.hasOwnProperty.call(this,key)){return undefined;}
return value;};}else if(typeof replacer==='function'||(typeof replacer==='object'&&typeof replacer.length==='number')){rep=replacer;}else{throw new Error('KNJSON.stringify');}
return str('',{'':value});},parse:function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('KNJSON.parse');},quote:quote};}();}



function KNJSONscriptRequest(fullUrl, container) {
    this.fullUrl = fullUrl; 
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'JscriptId' + KNJSONscriptRequest.scriptCounter++;
    this.container = container ? document.getElementById(container) : this.headLoc;
}
KNJSONscriptRequest.scriptCounter = 1;
KNJSONscriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
	if( this.fullUrl.indexOf('?') < 0 )
    	this.fullUrl = this.fullUrl + '?someval=1'
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
KNJSONscriptRequest.prototype.removeScriptTag = function () {
    this.container.removeChild(this.scriptObj);  
}
KNJSONscriptRequest.prototype.addScriptTag = function () {
    this.container.appendChild(this.scriptObj);
}

var chatWindows = { };
function launch_knocknok( launchId )
{
    var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
    var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
    var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

	var launch = __KnocknokLaunchObjs[launchId];
	
	//unable to find launch info
	if( !launch ) return;

	var kn = __KnocknokInstances[launch.knInstanceId];
	
	var width = _kn_window_width;
	var height = _kn_window_height;
	
	if( kn.config.windowWidth ) {
		width = kn.config.windowWidth;
	}
	
	if( kn.config.windowHeight ) {
		height = kn.config.windowHeight;
	}
	
    if( !chatWindows[launch.room] || chatWindows[launch.room].closed ) {
        var url = 'http://static.knocknok.com/knocknokWidget.html?account='+kn.id+'&roomName='+escape(launch.room)+'&chatTitle='+escape(launch.title)+'&chatHost='+escape(_chat_host)+'&knHTMLVer='+knHTMLVer+'&width='+width;
        if( kn.config.widgetVersion == "2" ) {
            var urlVars = '';
            if( launch.parameters.room )  urlVars += '&roomName=' + launch.room;
            if( launch.parameters.title ) urlVars += '&chatTitle=' + launch.title;
            if( launch.parameters.otherRooms ) urlVars += '&otherRooms=' + launch.parameters.otherRooms;
            height = 700;

            url = 'http://static.knocknok.com/v2/knWidget.html?account='+kn.id+'&chatTitle='+escape(launch.title)+'&chatLink='+escape(launch.link)+'&chatHost='+escape(_chat_host) + '&knHTMLVer=' + knHTMLVer + urlVars;
            chatWindows[launch.room] = window.open(url,'knwin' + launch.room,'width='+width+',height='+height+',resizable=yes,scrollbars=yes');
            return;
        } else if( kn.config.widgetVersion == "widgetHtml" ) {
            var config = KNJSON.stringify(launch.parameters);
            config = Base64.encode(config);
            
            height = 700;
            width = 630;

            if( launch.parameters.windowHeight )
                height = launch.parameters.windowHeight;

            if( launch.parameters.windowWidth )
                width = launch.parameters.windowHeight;
            
            if( isIE ) width += 10;

            url = 'http://static.knocknok.com/accounts/'+kn.id+'/widget/index.html?account='+kn.id+'&config='+escape(config)+'&chatHost='+escape(_chat_host) + '&chatTitle='+escape(launch.title);
            chatWindows[launch.room] = window.open(url,'knwin' + launch.room,'width='+width+',height='+height+',resizable=no,scrollbars=no');
            return;
        } else if( kn.config.widgetVersion == "custom" ) {
            var config = KNJSON.stringify(launch.parameters);
            config = Base64.encode(config);
            
            height = 700;
            width = 630;

            if( launch.parameters.windowHeight )
                height = launch.parameters.windowHeight;

            if( launch.parameters.windowWidth )
                width = launch.parameters.windowHeight;
            
            if( isIE ) width += 10;

            knurl = Base64.encode('http://static.knocknok.com/accounts/'+kn.id+'/widget/index.html?account='+kn.id+'&config='+escape(config)+'&chatHost='+escape(_chat_host) + '&chatTitle='+escape(launch.title));
            url = kn.config.widgetUrl + '?kn=' + knurl;            
            chatWindows[launch.room] = window.open(url,'knwin' + launch.room,'width='+width+',height='+height+',resizable=no,scrollbars=no');
            return;
        }
        
	    chatWindows[launch.room] = window.open(url,'knwin' + launch.room,'width='+width+',height='+height+',resizable=yes,scrollbars=yes');
	}
	else {
	    chatWindows[launch.room].focus();
	}
	
	if( launch.redirect && launch.link ) {
		document.location = launch.link;
	}
}

var __KnocknokInstances = {};
var __knInstanceId = 0;
var __knLaunchId = 0;
var __KnocknokLaunchObjs = {};
var __roomInstanceMap = {};
var __roomUpdatePollingEnabled = false;
var Knocknok = function( account ) {
	var parts = account.split('-');
	this.id = parts[1];

	this._roomMemberListeners = new Array();

	this.addRoomMemberListener = function( func ) {
		this._roomMemberListeners.push( func );
		__roomUpdatePollingEnabled = true;
		
		//start the polling
		_pollForRoomUpdates();
	}

	this.generateLaunchId = function( roomOrOptions, title, link ) {
		__knLaunchId++;
        var room = '';
		var launch = {};
		launch.id = __knLaunchId;
        launch.knInstanceId = this.instanceId;
        launch.memberName = '';
        if( !roomOrOptions ) roomOrOptions = {};
        
		//check to see if an options object was passed instead of a room parameter
		if( roomOrOptions != null && typeof(roomOrOptions) == 'object' )
		{
			var options = roomOrOptions;
			launch.parameters = options;
			launch.room = options.room;
			launch.title = options.title ? options.title : document.title;
			launch.link = options.link ? options.link : document.location.href;
			launch.memberName = options.memberName ? options.memberName : '';
			launch.redirect = options.redirect;
			room = options.room;
			title = launch.title;
			link = launch.link;
		}
        else {
            launch.parameters = {};
            launch.parameters.room = launch.room = roomOrOptions;
            launch.parameters.title = launch.title = title ? title : document.title;
            launch.link = link ? link : window.location;
            launch.redirect = false;
       }

        if( !room ) room = '__lobby__';
        
        //prepend the account ID onto the room name
        launch.room = room = this.id + room;

		__KnocknokLaunchObjs[launch.id] = launch;
		
		if( !__roomInstanceMap[room] )
			__roomInstanceMap[room] = new Array();
		__roomInstanceMap[room].push( this.instanceId );

		_pollForRoomUpdates();
		
		return launch.id;
	}

	this.insert = function( room, title, link ) {
    	//prepend the account ID onto the room name
	    room = this.id + room;
		var launchId = this.generateLaunchId( room, title, link );
		var iconDiv = '<div id="knicon'+launchId+'" style="z-index: 100"></div>';
		document.write( iconDiv );
		
		this.insert_icon( launchId );

		return launchId;
	};

	this._queuedIconInserts = new Array();
	this._globalIconLoaded = false;
	this.insert_icon = function(launchId) {
		if( !this.config ) {
			this._queuedIconInserts.push( launchId );
			return;
		}
		
		var containerId = 'knicon' + launchId;
		var launch = __KnocknokLaunchObjs[launchId];
		var room = launch.room;
		
		if( this.config.icon && this.config.icon.indexOf('http') >= 0 )
		{
			if( this.config.icon.indexOf('.swf') > 0 )
			{
				var src = this.config.icon.replace('.swf', '');

				AC_FL_RunContent(
					"src", src,
					"width", this.config.iconWidth,
					"height", this.config.iconHeight,
					"align", "middle",
					"id", containerId,
					"quality", "high",
					"bgcolor", "#ffffff",
					"name", containerId,
					"flashvars",'roomName='+room+'&launchId='+launchId,
					"allowScriptAccess","always",
					"type", "application/x-shockwave-flash",
					"pluginspage", "http://www.adobe.com/go/getflashplayer",
					"container_id", containerId,
					"wmode", "transparent"
				);
			}
			else
			{
				document.getElementById(containerId).innerHTML = '<img src="'+this.config.icon+'" onclick="launch_knocknok(\''+launchId+'\')" style="cursor: pointer; cursor: hand;" />';
			}
		}
	};
	
	this.config = false;
	this._config_loaded = function( conf ) {
		this.config = conf;
		
		//set the default icon, if one is not specified
		if( !this.config.icon )
		{
			this.config.iconWidth = 125;
			this.config.iconHeight = 25;
			this.config.icon = 'http://static.knocknok.com/knicons/chatnow/icon.swf';
		}
		
		//when the configuration is loaded we need to process any queued icon inserts
		for( var i = 0; i < this._queuedIconInserts.length; i++ ) {
			var qi = this._queuedIconInserts[i];
			this.insert_icon( qi );
		}
	};
	
	__knInstanceId++;
	this.instanceId = __knInstanceId;

	//index it by both the account id and the instance id
	__KnocknokInstances[this.id] = this;
	__KnocknokInstances[this.instanceId] = this;

	_kn_load_config( this.id );
};

var _config_requests = {};
function _kn_load_config( id ) {
	var req = new KNJSONscriptRequest( 'http://static.knocknok.com/accounts/' + id + '/config_kn_config_loaded?salt=' + Math.random() );
	req.buildScriptTag();
	req.addScriptTag();
	_config_requests[id] = req;
}

function _kn_config_loaded( res ) {
	if( res && res.id ) {
		__KnocknokInstances[res.id]._config_loaded( res );
		_config_requests[res.id].removeScriptTag();
	}
}

var __room_update_poll_request = null;
function _pollForRoomUpdates() {
    if( !__roomUpdatePollingEnabled ) return false;
    
    var roomList = new Array();
	for( var room in __roomInstanceMap )
	{
		var hasListeners = false;
		var instances = __roomInstanceMap[room];
		for( var i = 0; i < instances.length && !hasListeners; i++ ) {
			var kn = __KnocknokInstances[instances[i]];

			if( kn._roomMemberListeners.length > 0 )
				hasListeners = true;
		}
		
		if( hasListeners )
		    roomList.push( room );
	}
	
	if( roomList.length > 0 ) {
       	__roomUpdatePollingEnabled = false;
        var req = new KNJSONscriptRequest( 'http://ws.knocknok.com/room_members/?rooms=' + roomList.join(',') + '&callback=_kn_room_poll_result' );
        req.buildScriptTag();
        req.addScriptTag();
        __room_update_poll_request = req;
	}
	
	window.setTimeout( '_pollForRoomUpdates()', 8000 );
}


function _kn_room_poll_result( res ) {
	if( __room_update_poll_request ) {
	    try {
            __room_update_poll_request.removeScriptTag();
        } catch( e ) { }
	}

    __roomUpdatePollingEnabled = true;
    
    for( var room in res ) {
        var instances = __roomInstanceMap[room];
        var num = Number(res[room]);
        if( instances ) {
            for( var i = 0; i < instances.length; i++ ) {
                var kn = __KnocknokInstances[instances[i]];
        
                for( var f = 0; f < kn._roomMemberListeners.length; f++ ) {
                    try
                    {
                        var func = kn._roomMemberListeners[f];
                        func( room, num );
                    } catch( e ) {
                        //console.log( e );
                    }
                }
            }
        }
	}
}

function _kn_openNewWin( url, name, options ) {
    pop = window.open( url, name, options );
    return pop;
}
