

//Well, this fights for your right to click - let's go for it ...


var rtc = {
		blinkTimer: 0,
		delay: 1500,
		prompts: Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService),


		LOG: function(text)
		{
		    var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
		    consoleService.logStringMessage(String(text));
		},


		getPrefs: function()
		{
			var prefstr;
			try{
				prefstr = rtcutils.prefs.getCharPref("extensions.rtc.prefs");
			}catch(e){}
			if(!prefstr || prefstr.length < rtcutils.prefs.getCharPref("extensions.rtc.prefsdefault").length){ //possibly updated addon
				rtc.resetPrefs();
				prefstr = rtcutils.prefs.getCharPref("extensions.rtc.prefs");
			}
			var p = prefstr.split(",");
			for(i = 0; i < p.length; i++){
				try{
					var el = document.getElementById(String(i));
					p[i] = el && el.disabled ? 0 : parseInt(p[i]); //reflect disabled states of elements
//					p[i] = parseInt(p[i]);
				}catch(e){alert("RTC, error loading preferences: " + e);} //rtc.resetPrefs();	break;
			}
			return p;
		},


		savePrefs: function(p)
		{
			var prefstr = p.join(",")
			rtcutils.prefs.setCharPref("extensions.rtc.prefs", prefstr);
		},


		resetPrefs: function()
		{
			rtcutils.prefs.setCharPref("extensions.rtc.prefs", rtcutils.prefs.getCharPref("extensions.rtc.prefsdefault"));
			rtc.optionsLoad(); 
			rtc.SettingsToggled(); 

		},


		optionsLoad: function()
		{
			var p = rtc.getPrefs();
			for(i = 0; i < p.length; i++)
			{
				if(el = document.getElementById(String(i))){
					if(el.nodeName == "checkbox")
						el.checked = p[i];
					else if(el.nodeName == "radiogroup")
						el.selectedIndex = p[i];
				}
			} 
			rtc.SettingsToggled(); 

		},


		optionsSave: function()
		{
			var p = rtc.getPrefs();
			for(i = 0; i < p.length; i++)
			{
				if(el = document.getElementById(String(i))){
					if(el.nodeName == "checkbox")
						p[i] = el.checked - 0;
					else if(el.nodeName == "radiogroup")
						p[i] = el.selectedIndex;
				}
			}
			rtc.savePrefs(p);
		},


		captureClick: function(event){
			rightClick = false;
			if(event.which && event.which == 3)
				rightClick = true;
			else if (event.button && event.button == 2)
				rightClick = true;
			if(!rightClick)//left click
			{
				rtc.buttonrun();
				return;
			}
			//right click...
		},


		openConfigWindow: function()
		{
			window.openDialog('chrome://rtc/content/rtcoptions.xul', '_blank', 'chrome=yes,modal=yes,resizable=no,centerscreen=yes');
		},


		populateSBContext: function()
		{
				var mPopup = document.getElementById("rtc-statusbarcontextmenu"); 
				if(!mPopup) 
					return;
				while (mPopup.hasChildNodes()) {
				  mPopup.removeChild(mPopup.firstChild);
				}
				//add items
				var mi = mPopup.appendChild(document.createElement("menuitem")); 
				mi.setAttribute("oncommand", "rtc.openConfigWindow()");
				mi.setAttribute("label", "Options");
		},


		buttonrun: function(){
			var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
			if(wm && wm.getMostRecentWindow("navigator:browser") && wm.getMostRecentWindow("navigator:browser").content)
				rtc.run(wm.getMostRecentWindow("navigator:browser").content.document, true);
		},



		parse: function(clicked, imgArr, topwin){ //frames and iframes
			if (rtc.isValidDocument(topwin.document)) 
				rtc.enable(topwin.document, clicked, imgArr);
			for (var i=0; i < topwin.frames.length; i++)
				rtc.parse(clicked, imgArr, topwin.frames[i]);
		},



		run: function(doc, clicked){
			rtcutils.prefs.setBoolPref("dom.event.contextmenu.enabled", false);
			rtcutils.prefs.setBoolPref("nglayout.events.dispatchLeftClickOnly", true);//not work currently due to Firefox bug
			if(!rtc.isValidDocument(doc))
				return;

			doc.imgs = [];


			var topwin = doc.defaultView.top; 
			rtc.parse(clicked, doc.imgs, topwin); //parse frames and execute RTC (enable, collect images, ...)

			var p = rtc.getPrefs();
			if(p[26])
			{

				doc.documentElement.innerHTML = ""; //build empty document 
				var head = doc.createElement('head');
				doc.documentElement.appendChild(head);
				var elem = doc.createElement('title')
				head.appendChild(elem);
				elem.textContent = "RightToClick Image View";
				doc.documentElement.appendChild(doc.createElement('body'));

				elem = doc.createElement('div');
				doc.body.appendChild(elem);
				elem.style.setProperty("max-width", (window.innerWidth - 10) + "px", "important"); 
				elem.style.setProperty("max-height", (window.innerHeight - 150) + "px", "important"); 
				elem.style.setProperty("overflow", "auto", "important");

				var known = "";;
				for (i = 0; i < doc.imgs.length; i++) //add collected  images
				{
					if(known.indexOf(doc.imgs[i]) != -1) //prevent duplicates
						continue;
					known += doc.imgs[i];
					var newimg = doc.createElement('img');
					newimg.src = String(doc.imgs[i]); 
					elem.appendChild(newimg); //also recreate background images as normal images
					newimg.style.setProperty("max-width", "350px", "important"); 
					newimg.style.setProperty("max-height", "350px", "important"); 
				}

				doc.defaultView.scrollbars.visible = true;
				window.scrollbars.visible = true;
				doc.defaultView.scrollbars.hidden = false;
				window.scrollbars.hidden = false;
			}
			doc.imgs = null;
		},



		getBGImageSize: function(src, doc){
			var bgiprops = new Array();
			var img = doc.createElement('img');
			img.src = src;
			img.style.setProperty("top", "-5000px", "important");
			img.style.setProperty("left", "-5000px", "important");
			doc.body.appendChild(img);
			bgiprops.width = parseInt(img.offsetWidth);
			bgiprops.height = parseInt(img.offsetHeight);
			img.parentNode.removeChild(img);
			return bgiprops;
		},


		getOffsets: function(node){
			var left = 0;
			var top = 0;
		  	if(typeof(node.offsetParent) == 'undefined')
		    	return [node.offsetLeft, node.offsetTop]; 
			var obj = node;
			if (obj.offsetParent)
			{
				do{
					left += parseInt(obj.offsetLeft);
					top += parseInt(obj.offsetTop);
					if(obj != document.body && obj != document.documentElement && obj != node){
						left -= parseInt(obj.scrollLeft);
						top -= parseInt(obj.scrollTop);
					}
				}while(obj = obj.offsetParent);
			}
			return [left, top];
		},


		isTarget: function(node, event, doc, bgiurl){ //did the user actually click the node

			var nodeleft = nodetop = 0;
			var res = rtc.getOffsets(node);

			nodeleft= res[0];
			nodetop= res[1];

			var nodewidth = parseInt(node.offsetWidth);
			var nodeheight = parseInt(node.offsetHeight);
			var width = nodewidth;
			var height = nodeheight;
			var left = nodeleft;
			var top = nodetop;

			var cs = doc.defaultView.getComputedStyle(node, null);
			var bgrepeat = 0;

			if(cs){

				try{
					var display = cs.getPropertyValue("display");
				}catch(e){}
				if(display == "none")
					return false;
				try{
					var visibility = cs.getPropertyValue("visibility");
				}catch(e){}
				if(visibility == "hidden")
					return false;
				try{
					var opacity = cs.getPropertyValue("opacity");
				}catch(e){}
				if(opacity && parseInt(opacity) < 0.5)
					return false;

				if(bgiurl){

					try{
						var repeat = cs.getPropertyValue("background-repeat");
					}catch(e){}
					if(!repeat)
						bgrepeat = 0;
					if(/repeat\-x/.test(repeat))
						bgrepeat = 1;
					else if(/repeat\-y/.test(repeat))
						bgrepeat = 2;
					else if(/no\-repeat/.test(repeat))
						bgrepeat = 3;
					else if(/repeat/.test(repeat))
						bgrepeat = 4;

					//alert(bgiurl+'  '+bgrepeat);

					var bgiprops = rtc.getBGImageSize(bgiurl, doc);
					try{
						var pos = cs.getPropertyValue("background-position");
					}catch(e){}

					if(!pos)
					{

						if(bgrepeat == 3 || bgrepeat == 2){
							width = bgiprops.width;
						}
						if(bgrepeat == 3 || bgrepeat == 1){
							height = bgiprops.height;
						}

					}else{

						pos = pos.match(/([a-z0-9%]+)\s?([a-z0-9%]+)?/i);
						if(pos)
						{

							var posx = RegExp.$1;
							var posy = RegExp.$2;
							if(bgrepeat == 3 || bgrepeat == 2)
							{
								width = bgiprops.width;
								if(!posx){
									posx = parseInt((50 * nodewidth) / 100); //pixel from left (50%)
								}
								else if(/\%/.test(posx)){ //percent
									posx = parseInt((parseInt(posx) * nodewidth) / 100); //pixel from left
								}
								else { //pixel
									posx = parseInt(posx); //pixel from left
								}
								left = nodeleft + posx;
								var diffx = (left + width) - (nodeleft + nodewidth);
								if(diffx > 0 && left - diffx > nodeleft)
									left = left - diffx;

							}
							if(bgrepeat == 3 || bgrepeat == 1)
							{
								height = bgiprops.height;
								if(!posy){
									posy = parseInt((50 * nodeheight) / 100); //pixel from top (50%)
								}
								else if(/\%/.test(posy)){ //percent
									posy = parseInt((parseInt(posy) * nodeheight) / 100); //pixel from top
								}
								else { //pixel
									posy = parseInt(posy); //pixel from top
								}
								top = nodetop + posy;
								var diffy = (top + height) - (nodetop + nodeheight);
								if(diffy > 0 && top - diffy > nodetop)
									top = top - diffy;
							}

						}//end pos
					}//end pos
				}//end bgiurl
			}//end cs

			if(isNaN(top) || isNaN(left) || isNaN(width) || isNaN(height))
				return false;

			var bottom = top + height;
			var right = left + width;

			//alert('top='+top+' bottom='+bottom+' left='+left+' right='+right+' evx='+event.pageX+' evy='+event.pageY);
			if(parseInt(event.pageX) >= left && parseInt(event.pageX) <= right && parseInt(event.pageY) >= top && parseInt(event.pageY) <= bottom)
				return true;

			return false;
		},
		




		enable: function(doc, clicked, imgArr){
				//rtc.LOG("Parsing " + doc.location.href);

		    	var elem, i;
				var win = doc.defaultView;
				var p = rtc.getPrefs();
				var removeIDs = " ";
				var errors = [];
				var head_tag = doc.getElementsByTagName('head')[0]; 



				//part 1: Disarm body eventlisteners
				try{
					if(p[24]){
						//doc.body = doc.body.cloneNode(true);	//remove all body eventlisteners (drawback: reloads iframes => listeners are registered again in iframes)
						var cs = win.getComputedStyle(head_tag, null); //hasBinding not yet implemented
						if (cs && cs.getPropertyValue('-moz-binding').indexOf('rtc.xml#head') < 0 && !rtcutils.prefs.getBoolPref("extensions.rtc.noWarningBindingErr"))
						{
							var check = {value: false};  
							rtc.prompts.alertCheck(null, "RightToClick Warning", "Another addon probably prevents the RightToClick \r\nfunction 'Disarm EventListeners' from being successful!\r\n\r\nThe addon replaced a RightToClick binding \r\nwith: '" + cs.getPropertyValue('-moz-binding') + "'", "Do not show this again", check);
							rtcutils.prefs.setBoolPref("extensions.rtc.noWarningBindingErr", check.value);
						}
						var div = doc.createElement('div');  //disarm eventlisteners, see rtc.xml
						div.id = "stopEvents";
						doc.body.appendChild(div); 
					}
				}catch(e){errors[errors.length] = "1: " + e;}


				//part 2: Disable site's event attributes (needs to be injected in HTML <head> for this) and remove onEvent-attributes
				try{
			         var script_tag = doc.createElement('script');  
			         script_tag.setAttribute('type', 'text/javascript');  
			         script_tag.setAttribute('id', 'buttonscr'); 
			         var text ="function rtcenable(){";
			         text += " var P=[" + p + "]; try{if(P[0]) document.body.onfocus = null; if(P[1]) document.body.oncopy= null; if(P[1]) document.body.onselectstart = null;if(P[2]) document.body.ondragover = null; if(P[2]) document.body.ondrag = null; if(P[2]) document.body.ondragstart = null;if(P[3]) document.body.onmouseup = null;if(P[3]) document.body.onmousedown = null;if(P[3]) document.body.onclick = null;if(P[4]) document.body.oncontextmenu = null;if(P[5]) document.body.onmouseover = null;if(P[5]) document.body.onmouseout = null;if(P[5]) document.body.onmousemove = null;if(P[6]) document.body.ondblclick = null;if(P[7]) document.body.onkeydown = null;if(P[7]) document.body.onkeyup = null;if(P[7]) document.body.onkeypress = null;if(P[0]) document.onfocus = null;if(P[1]) document.oncopy = null;if(P[1]) document.onselectstart = null;if(P[2]) document.ondragover = null;if(P[2]) document.ondrag = null;if(P[2]) document.ondragstart = null;if(P[3]) document.onmouseup = null; if(P[3]){ document.onmousedown = null;}if(P[3]) document.onclick = null;if(P[4]) document.oncontextmenu = null;if(P[5]) document.onmouseover = null;if(P[5]) document.onmouseout = null;if(P[5]) document.onmousemove = null;if(P[6]) document.ondblclick = null;if(P[7]) document.onkeydown = null;if(P[7]) document.onkeyup = null;if(P[7]) document.onkeypress = null;if(P[0]) window.onfocus = null;if(P[1]) window.oncopy = null;if(P[1]) window.onselectstart = null;if(P[2]) window.ondragover = null;if(P[2]) window.ondrag = null;if(P[2]) window.ondragstart = null;if(P[3]) window.onmouseup = null; if(P[3]){ window.onmousedown = null;}if(P[3]) window.onclick = null;if(P[4]) window.oncontextmenu = null;if(P[5]) window.onmouseover = null;if(P[5]) window.onmouseout = null;if(P[5]) window.onmousemove = null;if(P[6]) window.ondblclick = null;if(P[7]) window.onkeydown = null;if(P[7]) window.onkeyup = null;if(P[7]) window.onkeypress = null;}catch(e){}";
			         text += " var elements = document.getElementsByTagName('*'); for (i = 0; i < elements.length; i++){var el = elements[i]; "; 

			         text += " if(P[0] && el.hasAttribute('onfocus')) try{el.removeAttribute('onfocus');}catch(e){} "; 
			         text += " if(P[0] && el.hasAttribute('onblur')) try{el.removeAttribute('onblur');}catch(e){} "; 
			         text += " if(P[0]) try{el.onfocus=null;}catch(e){} "; 
			         text += " if(P[0]) try{el.onblur=null;}catch(e){} "; 
			         text += " if(P[0] && window.getComputedStyle(el, null) && window.getComputedStyle(el, null).getPropertyValue('-moz-user-focus') == 'ignore') try{el.style.setProperty('-moz-user-focus', 'normal', 'important');}catch(e){} "; 
			         text += " if(P[0] && window.getComputedStyle(el, null) && window.getComputedStyle(el, null).getPropertyValue('-moz-user-input') != 'auto') try{el.style.setProperty('-moz-user-input', 'enabled', 'important');}catch(e){} "; 

			         text += " if(P[1] && el.hasAttribute('onselectstart')) try{el.removeAttribute('onselectstart');}catch(e){} "; 
			         text += " if(P[1] && el.hasAttribute('oncopy')) try{el.removeAttribute('oncopy');}catch(e){} "; 
			         text += " if(P[1] && el.hasAttribute('onpaste')) try{el.removeAttribute('onpaste');}catch(e){} "; 
			         text += " if(P[1] && el.hasAttribute('oncut')) try{el.removeAttribute('oncut');}catch(e){} "; 
			         text += " if(P[1] && window.getComputedStyle(el, null) && window.getComputedStyle(el, null).getPropertyValue('-moz-user-select') != 'auto') try{el.style.setProperty('-moz-user-select', 'text', 'important');}catch(e){} "; 
			         text += " if(P[1] && window.getComputedStyle(el, null) && window.getComputedStyle(el, null).getPropertyValue('cursor') != 'none') try{el.style.setProperty('cursor', '', '');}catch(e){} "; 
			         text += " if(P[1]) try{el.oncopy=null;}catch(e){} ";
			         text += " if(P[1]) try{el.onpaste=null;}catch(e){} ";
			         text += " if(P[1]) try{el.oncut=null;}catch(e){} ";
			         text += " if(P[1]) try{el.onselectstart=null;}catch(e){} ";

			         text += " if(P[4] && el.hasAttribute('oncontextmenu')) try{el.removeAttribute('oncontextmenu');}catch(e){} "; 
			         text += " if(P[4]) try{el.oncontextmenu=null;}catch(e){} ";

			         text += " if(P[2] && el.hasAttribute('ondragenter')) try{el.removeAttribute('ondragover');}catch(e){} ";
			         text += " if(P[2] && el.hasAttribute('ondragleave')) try{el.removeAttribute('ondragover');}catch(e){} ";
			         text += " if(P[2] && el.hasAttribute('ondragover')) try{el.removeAttribute('ondragover');}catch(e){} ";
			         text += " if(P[2] && el.hasAttribute('ondrag')) try{el.removeAttribute('ondrag');}catch(e){} ";
			         text += " if(P[2] && el.hasAttribute('ondragstart')) try{el.removeAttribute('ondragstart');}catch(e){} "; 
			         text += " if(P[2]) try{el.ondragenter=null;}catch(e){} ";
			         text += " if(P[2]) try{el.ondragleave=null;}catch(e){} ";
			         text += " if(P[2]) try{el.ondragover=null;}catch(e){} ";
			         text += " if(P[2]) try{el.ondrag=null;}catch(e){} ";
			         text += " if(P[2]) try{el.ondragstart=null;}catch(e){} ";


			         text += " if(P[3] && el.hasAttribute('onmouseup')) try{el.removeAttribute('onmouseup');}catch(e){} "; 
			         text += " if(P[3] && el.hasAttribute('onmousedown')) try{el.removeAttribute('onmousedown');}catch(e){} "; 
			         text += " if(P[3] && el.hasAttribute('onclick')) try{el.removeAttribute('onclick');}catch(e){} "; 
			         text += " if(P[3]) try{el.onmouseup=null;}catch(e){} ";
			         text += " if(P[3]) try{el.onmousedown=null;}catch(e){} ";
			         text += " if(P[3]) try{el.onclick=null;}catch(e){} ";

			         text += " if(P[5] && el.hasAttribute('onmouseover')) try{el.removeAttribute('onmouseover');}catch(e){} "; 
			         text += " if(P[5] && el.hasAttribute('onmouseout')) try{el.removeAttribute('onmouseout');}catch(e){} "; 
			         text += " if(P[5] && el.hasAttribute('onmousemove')) try{el.removeAttribute('onmousemove');}catch(e){} "; 
			         text += " if(P[5] && el.hasAttribute('onscroll')) try{el.removeAttribute('onmousemove');}catch(e){} "; 
			         text += " if(P[5]) try{el.onmouseover=null;}catch(e){} ";
			         text += " if(P[5]) try{el.onmouseout=null;}catch(e){} ";
			         text += " if(P[5]) try{el.onmousemove=null;}catch(e){} ";
			         text += " if(P[5]) try{el.onscroll=null;}catch(e){} ";

			         text += " if(P[6] && el.hasAttribute('ondblclick')) try{el.removeAttribute('ondblclick');}catch(e){} "; 
			         text += " if(P[6]) try{el.ondblclick=null;}catch(e){} ";

			         text += " if(P[7] && el.hasAttribute('onkeydown')) try{el.removeAttribute('onkeydown');}catch(e){} "; 
			         text += " if(P[7] && el.hasAttribute('onkeyup')) try{el.removeAttribute('onkeyup');}catch(e){} "; 
			         text += " if(P[7] && el.hasAttribute('onkeypress')) try{el.removeAttribute('onkeypress');}catch(e){} "; 
			         text += " if(P[7]) try{el.onkeydown=null;}catch(e){}"; 
			         text += " if(P[7]) try{el.onkeyup=null;}catch(e){}"; 
			         text += " if(P[7]) try{el.onkeypress=null;}catch(e){}"; 

			         text += " if(P[8] && el.hasAttribute('disabled')) try{el.removeAttribute('disabled');}catch(e){} "; 
			         text += " if(P[8] && el.hasAttribute('readonly')) try{el.removeAttribute('readonly');}catch(e){} ";
			         text += " if(P[8] && window.getComputedStyle(el, null) && window.getComputedStyle(el, null).getPropertyValue('-moz-user-modify') != 'read-write') try{el.style.setProperty('-moz-user-modify', 'read-write', 'important');}catch(e){} ";  
			         text += " if(P[8]) try{el.disabled=false;}catch(e){}"; 
			         text += " if(P[8]) try{el.readonly=false;}catch(e){}"; 

			         text += " }";

					 //Disarm  document and window eventlisteners
					 if(p[24]){
				         text += " if(!document.docevents) document.docevents = []; for(var i= 0; i < document.docevents.length; i++) document.removeEventListener(document.docevents[i][0], document.docevents[i][1], document.docevents[i][2]); ";
				         text += " if(!document.winevents) document.winevents = []; for(var i= 0; i < document.winevents.length; i++) document.removeEventListener(document.winevents[i][0], document.winevents[i][1], document.winevents[i][2]); ";
					 }
				     text += " var rtcexecuted = document.createElement('div');rtcexecuted.id = 'rtc-executed';document.body.appendChild(rtcexecuted);  } document.addEventListener('load', function(){setTimeout(rtcenable," + rtc.delay + ");},true); rtcenable(); "; 
					 text += " var buttonscript = document.getElementById('buttonscr'); buttonscript.parentNode.removeChild(buttonscript); ";

			         script_tag.text = text;
			         head_tag.appendChild(script_tag);  
				}catch(e){errors[errors.length] = "2: " + e;}



				//part 3: Add override handlers
				try{
					if(p[27]){
						doc.addEventListener('click', function (event) {

							if((event.button && event.button != 2) || (event.which && event.which != 3))//left or middle click
							{  
								var node = event.target; 
								var results = [];

								while(node){
									if(p[27] == 2 && node.href && rtc.isTarget(node, event, doc, false)){
										results[results.length] = node;
										results[results.length-1].url = node.href;
									}


									if(p[27] == 1 && node.src && node.src != 'none' && rtc.isTarget(node, event, doc, false)){
										results[results.length] = node;
										results[results.length-1].url = node.src;
									}


									var cs = doc.defaultView.getComputedStyle(node, null);
									var bgiurl = cs.getPropertyValue('background-image') || cs.getPropertyValue('background');

									if(p[27] == 1 && bgiurl && bgiurl.match(/url\s?\('?"?([^'"\)]+)'?"?\)/i))
									{
										bgiurl = String(RegExp.$1);
										if(rtc.isTarget(node, event, doc, bgiurl)){
											results[results.length] = node;
											results[results.length-1].url = bgiurl;
										}
									}

									if(node == doc.documentElement)
										break;
									node = node.parentNode;
								}

								//find top image by z-index
								var zindexMax = Number.MIN_VALUE;
								var TopIndex = 0;
								for(var i = 0; i < results.length; i++){
									var zindex = 0;
									var cs = doc.defaultView.getComputedStyle(results[i], null);
									if(cs){
										zindex = parseInt(cs.getPropertyValue("z-index"));
										zindex = isNaN(zindex) ? 0 : zindex;
									}
									if(zindex > zindexMax){
										zindexMax = zindex;
										TopIndex = i;
									}
								}
								//alert(TopIndex);
								//alert('nl='+results[TopIndex].url);
								if(results[TopIndex]){
									event.preventDefault();
									event.stopPropagation();
									doc.location.href = results[TopIndex].url;
								}
							}//event

						}
						, true);
					}
				}catch(e){errors[errors.length] = "3: " + e;}





				//part 4: Disarm or disable potentially evil functions
				try{
					if(typeof win.wrappedJSObject != "undefined")
					{
						if(p[20])
							win.wrappedJSObject.setTimeout = function () 
							{
								win.wrappedJSObject.setTimeout = function() {};
								return null;
							}
						if(p[20])
							win.wrappedJSObject.setInterval = function () 
							{
								win.wrappedJSObject.setInterval = function() {};
								return null;
							}
						if(p[21])
							win.wrappedJSObject.showModalDialog = function () 
							{
							    win.wrappedJSObject.showModalDialog = function() {};
								return null;
							}
					}
				}catch(e){errors[errors.length] = "4: " + e;}



				if(p[25] && !p[26])
					rtc.setStylesDisabled(true, doc); //disable CSS styles


				//extract images
				if(p[26])
				{
					var allElements = doc.getElementsByTagName('*'); //search background images
					var url;
					for (i = 0; i < allElements.length; i++) 
					{
						if(allElements[i].tagName === "IMG") //foreground images
						{
							if(url = allElements[i].src)
								imgArr.push(url);
							continue;
						}
						if(cs = allElements[i].ownerDocument.defaultView.getComputedStyle(allElements[i], null))
						{
							url = cs.getPropertyValue('background-image') || cs.getPropertyValue('background');
							if(url && url.match(/url\s?\('?"?([^'"\)]+)'?"?\)/i))
							{
								url = String(RegExp.$1);
								imgArr.push(url);
							}
						}

					}
				}

				for (i = 0; i < errors.length; i++) 
					rtc.LOG("RightToClick exception in module " + errors[i]);
				//rtc.LOG("RTC all actions done");
				clearTimeout(rtc.blinkTimer);
				rtc.blinkIcon((clicked == true) ? 10 : 3, doc, null, errors.length);
		},



		setStylesDisabled: function(disabled, doc){
			if(gBrowser && gBrowser.markupDocumentViewer){
				gBrowser.markupDocumentViewer.authorStyleDisabled = disabled;
				doc.stylesDisabled = disabled;
			}
		},





		blinkIcon: function(num, doc, executed, errors){
			if(executed)
			{
				var img = document.getElementById('rtc-statusbarimg');
				if(num % 2 == 0){
					var png = (errors && num) ? 'error.png' : 'rtc.png';
					img.setAttribute('src', 'chrome://rtc/skin/' + png);  //even number
					if(document.getElementById('RTCButton'))
					   document.getElementById('RTCButton').setAttribute("status", (errors && num) ? 0 : 1);//also toolbar button
					if(!num)
						return; 
				}else if(!errors){
					img.setAttribute('src', 'chrome://rtc/skin/rtcd.png');
					if(document.getElementById('RTCButton'))
					   document.getElementById('RTCButton').setAttribute("status", 2);
				}
				num--;
			}else if(executed = doc.getElementById('rtc-executed')){
				executed.parentNode.removeChild(executed);
			}
			rtc.blinkTimer = setTimeout(rtc.blinkIcon, 400, num, doc, executed, errors);
		},


		nullPrompts: function (checked, win, event) {
			if (checked){ 
				event.preventDefault();
				event.stopPropagation();
			    win.wrappedJSObject.alert = function() {};
			    win.wrappedJSObject.confirm = function() {};
			    win.wrappedJSObject.prompt = function() {};
			}
		},

/*
		onContentLoaded: function (event) {
				if(!isValidDocument)
					return;
				var head_tag = doc.getElementsByTagName('head')[0];
				if(!head_tag)
					return;  
				var script_tag = doc.createElement('script');  
				script_tag.setAttribute('type', 'text/javascript');  
				script_tag.setAttribute('id', 'domscr'); 
				var text = "document.docevents = []; var oldDAEL = document.addEventListener; document.addEventListener = function (oldDAEL) {return function (evt, func, bCapture) {oldDAEL.call (this, evt, func, bCapture); document.docevents.push( [evt, func, bCapture] ); } }(oldDAEL); ";
				text += "  document.winevents = []; var oldWAEL = window.addEventListener; window.addEventListener = function (oldWAEL) {return function (evt, func, bCapture) {oldWAEL.call (this, evt, func, bCapture); document.winevents.push( [evt, func, bCapture] ); } }(oldWAEL); "; 
				text += " var domscript = document.getElementById('domscr'); domscript.parentNode.removeChild(domscript); ";
				script_tag.text = text;
				head_tag.appendChild(script_tag);  
		},
*/





		isValidDocument: function(doc){
			try{
				if ((doc instanceof HTMLDocument || doc instanceof HTMLIFrameElement) &&  !doc.location.href.toLowerCase().indexOf("http")) 
					return true;
			}catch(e){}
			return false;
		},
	

		onShow: function (event) {
			if (rtc.getPrefs()[23]) 
				setTimeout(rtc.run, 1000, event.originalTarget, false);
		},

		onDialog: function (event) { 
			rtc.wrapPrompts(event.target.document, event.target.document.defaultView, event);
		},



		onBeforeUnLoading: function (event) { 
			if(event.originalTarget.stylesDisabled)
				rtc.setStylesDisabled(false, event.originalTarget);
		},



		//part 4: Disarm prompts (add a checkbox)
		wrapPrompts: function (doc, win, event) 
		{
			if(typeof win.wrappedJSObject == "undefined")
				return;
			var p = rtc.getPrefs();
			if(!p[22] || win.RTCdone || typeof win.wrappedJSObject == "undefined")
				return;

			var domain;
			try{
				domain = doc.domain;
			}catch(e){}
			var titlemsg = domain ? ("The page at " + doc.domain + " says: ") : "Javascript Application";

			var checkmsg = "Stop dialog popups on this page";
			var check = {value: false};   

			win.wrappedJSObject.alert = function (message) 
			{
				rtc.prompts.alertCheck(win, titlemsg, String(message), checkmsg, check);
				rtc.nullPrompts(check.value, win, event);
			}
			win.wrappedJSObject.confirm = function (message) 
			{
				var val = rtc.prompts.confirmCheck(win, titlemsg, String(message), checkmsg, check);
				rtc.nullPrompts(check.value, win, event);
				return val;
			}
			win.wrappedJSObject.prompt = function (message, val) 
			{
				var input = {value: String(val)}; 
				var val = rtc.prompts.prompt(win, titlemsg, String(message), input, checkmsg, check);
				rtc.nullPrompts(check.value, win, event);
				if(val)
					return input.value;
				return null;
			}
			win.RTCdone = true;
		},




		SettingsToggled: function (event) { 


			if(document.getElementById("26").checked)
				document.getElementById("25").disabled = true;
			else
				document.getElementById("25").disabled = false;
			if(document.getElementById("24").checked)
				document.getElementById("27").disabled = true;
			else
				document.getElementById("27").disabled = false;


			if(event && event.target.id == "25")
			{
				if(document.getElementById("25").checked && !rtcutils.prefs.getBoolPref("extensions.rtc.noWarningDisableCSS")){
					check = {value: false}; 
					if(!rtc.prompts.confirmCheck(null, "RightToClick", "Disabling CSS usually makes pages look strange but might help to save images.\r\n\r\nStill disable CSS?", "Do not show this again", check))
						document.getElementById(event.target.id).checked = false;
					rtcutils.prefs.setBoolPref("extensions.rtc.noWarningDisableCSS", check.value);
				}
			}
		},



		pageInfo: function () { 
			var doc = null;
			var initialTab = "mediaTab";
			var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
			if(wm && wm.getMostRecentWindow("navigator:browser") && wm.getMostRecentWindow("navigator:browser").content)
				doc = wm.getMostRecentWindow("navigator:browser").content.document;
			var args = {doc: doc, initialTab: "securityTab"};
			window.openDialog('chrome://browser/content/pageinfo/pageInfo.xul', '_blank', 'chrome,toolbar,dialog=no,resizable', args);
		},


		LoadStyleSheet: function () { 
			var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"]
			        .getService(Components.interfaces.nsIStyleSheetService);
			var ios = Components.classes["@mozilla.org/network/io-service;1"]
			        .getService(Components.interfaces.nsIIOService);
			var rtcss = ios.newURI("chrome://rtc/content/rtc.css", null, null);
			if ( !sss.sheetRegistered(rtcss, sss.USER_SHEET) )
				sss.loadAndRegisterSheet(rtcss, sss.USER_SHEET);
		},

		Init: function () { 
			rtc.LoadStyleSheet();
			rtc.AddButtonToToolbar();
			var p = rtc.getPrefs();
			rtc.ShowIcons(p[28]);
		},

		
		ShowIcons: function (checked) { 
			var rw = Components.classes["@mozilla.org/appshell/window-mediator;1"]
				.getService(Components.interfaces.nsIWindowMediator)
				.getMostRecentWindow("navigator:browser");
			if(checked)
				rw.document.getElementById("rtcstatusbarID").setAttribute('collapsed', false);
			else
				rw.document.getElementById("rtcstatusbarID").setAttribute('collapsed', true);
		},



		AddButtonToToolbar: function () { 
			if(!rtcutils.getPref("extensions.rtc.firstrun"))
				return;
			rtcutils.setPref("extensions.rtc.firstrun", 0);
			 try {
			   var firefoxnav = document.getElementById("nav-bar");
			   var curSet = firefoxnav.currentSet;
			   if (curSet.indexOf("RTCButton") == -1)
			   {
			     var set;
			     // Place the button before the urlbar
			     if (curSet.indexOf("urlbar-container") != -1)
			       set = curSet.replace(/urlbar-container/, "RTCButton,urlbar-container");
			     else  // at the end
			       set = curSet + ",RTCButton";
			     firefoxnav.setAttribute("currentset", set);
			     firefoxnav.currentSet = set;
			     document.persist("nav-bar", "currentset");
			     // If you don't do the following call, funny things happen
			     try {
			       BrowserToolboxCustomizeDone(true);
			     }
			     catch (e) { }
			   }
			 }
			 catch(e) { }

		},




};


	//	document.addEventListener("DOMContentLoaded", rtc.onContentLoaded, true);
		document.addEventListener("pageshow", rtc.onShow, true);
		document.addEventListener("stop", rtc.onShow, true);
		document.addEventListener("beforeunload", rtc.onBeforeUnLoading, true);