var apphit_checker  = null;
var update_menu_drawed = 0;
var apphit_channel	= null;
var apphit_downloading = 0;
var apphit_update_data = null;
var apphit_strbundle = null;

function apphit_checker_OnLoad()
{
	netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
	apphit_checker = null;
	try
	{
		apphit_checker = Components.classes["@apphit.com/SoftwareChecker;1"].createInstance(Components.interfaces.ISoftwareUpdateChecker);
	} catch( e ) { }	
	if (null == apphit_checker)
		dump("checker no instance!!!");
		
	apphit_strbundle = document.getElementById("autoupdater-strings");
}

function apphit_checker_OnUnload()
{

}

window.addEventListener("load", apphit_checker_OnLoad, false);
window.addEventListener("unload", apphit_checker_OnUnload, false);

function apphit_checker_impl()
{
	if( update_menu_drawed == 1 )
	{
		return;
	}

	if( apphit_downloading != 0 )
	{
		return;
	}

	if( document.getElementById("software_update_checker_loading") == null )
	{
		var tempItem = document.createElement("menuitem");
		tempItem.setAttribute("id", "software_update_checker_loading");
		tempItem.setAttribute("label", apphit_strbundle.getString("menu_label_checking"));
		tempItem.setAttribute("class", "menuitem-iconic");
		tempItem.setAttribute("image", "chrome://browser/skin/Throbber.gif");
		document.getElementById("software_update_checker_popup").appendChild(tempItem);	
	}
	
	if( apphit_update_data != null )
	{
		apphit_checker_on_get_file( apphit_update_data );
		return;
	}

	apphit_downloading = 1;
	apphit_checker_get_file_from_url( apphit_strbundle.getString("autoupdater_url") );
}

function apphit_checker_insert_menu(parent, soft)
{
	var tempItem = null;
	tempItem = document.createElement("menuitem");
	tempItem.setAttribute("label", soft.title + " " + soft.version);
	tempItem.setAttribute("oncommand", "apphit_checker_gotoURL(\"" + soft.url + "\")");
	tempItem.setAttribute("class", "menuitem-iconic");
	tempItem.setAttribute("image", apphit_strbundle.getString("autoupdater_image_url") + soft.id + "/icon_16x16.png");
	parent.appendChild(tempItem);	
}

function apphit_checker_gotoURL(URL)
{
    const browser = getBrowser();  
    browser.selectedTab = browser.addTab(URL);  
    window.content.focus();
}

function apphit_checker_openAll(opentype)
{
	if (null != apphit_checker )	
	{
		var s = apphit_checker.CheckUpdateSoftwares( "", 0 );
		if( s == null || s == "" )
		{
				return;
		}

		var obj = eval( s );

		if( opentype == 0 && obj.recommend )
		{
			for( var i = 0; i < obj.recommend.length; ++i )
			{
				apphit_checker_gotoURL( obj.recommend[i].url );
			}
		}

		if( opentype == 0 && obj.stable )
		{
			for( var i = 0; i < obj.stable.length; ++i )
			{
				apphit_checker_gotoURL( obj.stable[i].url );
			}
		}

		if( opentype == 1 && obj.beta )
		{
			for( var i = 0; i < obj.beta.length; ++i )
			{
				apphit_checker_gotoURL( obj.beta[i].url );
			}
		}
	}
}

function apphit_checker_start_check(event)
{
	apphit_checker_impl();
}

function apphit_checker_on_get_file(data)
{
	apphit_downloading = 0;
	if( null == data )
	{
		setTimeout( apphit_checker_impl, 10 );
		return;
	}

	apphit_update_data = data;	
	if (null != apphit_checker )	
	{
		var s = apphit_checker.CheckUpdateSoftwares( apphit_update_data, apphit_update_data.length );
		if( s == null || s == "" )
		{
				setTimeout( apphit_checker_impl, 10 );
		}
		else
		{
			update_menu_drawed = 1;
			var menuId = document.getElementById("software_update_checker_popup");
			for( var i = menuId.childNodes.length - 1; i >= 0; --i )
			{
				menuId.removeChild( menuId.childNodes[i] );
			}

			var obj 			= eval( s );
         var tempItem 	= null;

			// 显示推荐项目
			if( obj.recommend )
			{
				{
					var tempItem = null;
					tempItem = document.createElement("menuitem");
					tempItem.setAttribute("label", apphit_strbundle.getString("menu_label_recommend" ));
					tempItem.setAttribute("style", "color:black; font-weight:bold;");
					tempItem.setAttribute("disabled", "true");
					menuId.appendChild(tempItem);	

		     		tempItem = document.createElement("menuseparator");
		      	menuId.appendChild(tempItem);
				}
				
				for( var i = 0; i < obj.recommend.length; ++i )
				{
					apphit_checker_insert_menu( menuId, obj.recommend[i] );
				}

				tempItem = document.createElement("menuseparator");
      		menuId.appendChild(tempItem);
			}

			if( !obj.stable || !obj.beta )
			{
				// 没有需要更新的软件
            tempItem = document.createElement("menuitem");
            tempItem.setAttribute("label", apphit_strbundle.getString("autoupdater_no_update") );
            menuId.appendChild(tempItem);
            
            return;
			}

			if( obj.stable )
			{
				{
					var tempItem = null;
					tempItem = document.createElement("menuitem");
					tempItem.setAttribute("label", apphit_strbundle.getString("menu_label_stable" ));
					tempItem.setAttribute("style", "color:black; font-weight:bold;");
					tempItem.setAttribute("disabled", "true");
					menuId.appendChild(tempItem);	

		     		tempItem = document.createElement("menuseparator");
		      	menuId.appendChild(tempItem);
				}

				for( var i = 0; i < obj.stable.length; ++i )
				{
					apphit_checker_insert_menu( menuId, obj.stable[i] );
				}
			}

     		tempItem = document.createElement("menuseparator");
      	menuId.appendChild(tempItem);

			var betaItem = document.createElement("menu");
         betaItem.setAttribute("label", apphit_strbundle.getString("menu_label_beta") );
			betaItem.setAttribute("style", "color:black;");
			menuId.appendChild(betaItem);

			if( obj.beta )
			{
	      	var popItem = document.createElement("menupopup");
	      	betaItem.appendChild(popItem);
				for( var i = 0; i < obj.beta.length; ++i )
				{
					apphit_checker_insert_menu( popItem, obj.beta[i] );
				}

	         tempItem = document.createElement("menuseparator");
	         popItem.appendChild(tempItem);
	         tempItem = document.createElement("menuitem");
	         tempItem.setAttribute("label", apphit_strbundle.getString("menu_label_openall" ) );
				tempItem.setAttribute("oncommand", "apphit_checker_openAll(1)");
	         popItem.appendChild(tempItem);
			}
			else
			{
				betaItem.disabled = true;
			}

         tempItem = document.createElement("menuseparator");
         menuId.appendChild(tempItem);
         tempItem = document.createElement("menuitem");
	      tempItem.setAttribute("label", apphit_strbundle.getString("menu_label_openall" ) );
			tempItem.setAttribute("oncommand", "apphit_checker_openAll(0)");
         menuId.appendChild(tempItem);
		}
	}
}

ApphitStreamListener.prototype = 
{
	mData: "",
	// nsIStreamListener
	onStartRequest: function (aRequest, aContext) 
	{
		this.mData = "";
	},

	onDataAvailable: function (aRequest, aContext, aStream, aSourceOffset, aLength) 
	{
		try
		{
			var stream = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
			stream.setInputStream( aStream );
			
			this.mData += stream.readBytes( aLength );
		} catch( x ) { 
			// do nothing
		}
	},

	onStopRequest: function (aRequest, aContext, aStatus) 
	{
		if (Components.isSuccessCode(aStatus)) 
		{
			// request was successfull
			this.mCallbackFunc(this.mData);
		} else {
			// request failed
			this.mCallbackFunc(null);
		}

		apphit_channel = null;
	},

		// nsIChannelEventSink
	onChannelRedirect: function (aOldChannel, aNewChannel, aFlags) 
	{
		// if redirecting, store the new channel
		apphit_channel = aNewChannel;
	},

	// nsIInterfaceRequestor
	getInterface: function (aIID) 
	{
		try 
		{
			return this.QueryInterface(aIID);
		} catch (e) {
			throw Components.results.NS_NOINTERFACE;
		}
	},

	// nsIProgressEventSink (not implementing will cause annoying exceptions)
	onProgress : function (aRequest, aContext, aProgress, aProgressMax) { },
	onStatus : function (aRequest, aContext, aStatus, aStatusArg) { },

	// nsIHttpEventSink (not implementing will cause annoying exceptions)
	onRedirect : function (aOldChannel, aNewChannel) { },

	// we are faking an XPCOM interface, so we need to implement QI
	QueryInterface : function(aIID) 
	{
		if (aIID.equals(Components.interfaces.nsISupports) ||
		  aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
		  aIID.equals(Components.interfaces.nsIChannelEventSink) || 
		  aIID.equals(Components.interfaces.nsIProgressEventSink) ||
		  aIID.equals(Components.interfaces.nsIHttpEventSink) ||
		  aIID.equals(Components.interfaces.nsIStreamListener))
			return this;

		throw Components.results.NS_NOINTERFACE;
	}
};

function ApphitStreamListener(aCallbackFunc) 
{
	this.mCallbackFunc = aCallbackFunc;
}

function apphit_checker_get_file_from_url(url) 
{ 
	var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); 
	
	// create an nsIURI
	var uri = ioService.newURI(url, null, null);
	var apphit_channel = ioService.newChannelFromURI(uri); 
	
	// get an listener
	var listener = new ApphitStreamListener(apphit_checker_on_get_file);
	
	apphit_channel.notificationCallbacks = listener;
	apphit_channel.asyncOpen( listener, null );
}
