; :wrap=none:collapseFolds=1:maxLineLen=80:mode=autoitscript:tabSize=8:folding=indent:
; created with jEdit4AutoIt
#include-once

#Region Copyright
#cs
	* FF.au3
	*
	* This program is free software; you can redistribute it and/or
	* modify it under the terms of the GNU General Public License
	* as published by the Free Software Foundation; either version 2
	* of the License, or any later version.
	*
	* This program is distributed in the hope that it will be useful,
	* but WITHOUT ANY WARRANTY; without even the implied warranty of
	* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	* GNU General Public License for more details.
	*
	* You should have received a copy of the GNU General Public License
	* along with this program; if not, write to the Free Software
	* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#ce
#EndRegion Copyright

#Region Many thanks to:
#cs
	- Jonathan Bennett and the AutoIt Team for AutoIt v3 the freeware
	BASIC-like scripting language
	(and thanks John George Kemeny and Thomas Eugene Kurtz for BASIC)
	- Dale Hohm, for his great IE.au3, which I've used as base for the
	functions-names and the error handling.
	- Johannes Schirmer, for some functions and suggestions for the FF.au3
	- all others for their suggestions, bug reports ...
	- the FireFox-Team for his fantastic browser

	- and Massimiliano Mirra, without his work would this UDF impossible,
	for MozLab / MozRepl
#ce
#EndRegion Many thanks to:

#Region #CURRENT# ==============================================================
	;_FFAction
	;_FFClick
	;_FFClickXY
	;_FFCmd
	;_FFConnect
	;_FFDialogWait
	;_FFDisConnect
	;_FFDisPatchKeyEvent
	;_FFFormCheckBox
	;_FFFormGetElementsLength
	;_FFFormGetLength
	;_FFFormOptionSelect
	;_FFFormRadioButton
	;_FFFormReset
	;_FFFormSubmit
	;_FFFrameEnter
	;_FFFrameGetSelected
	;_FFFrameLeave
	;_FFGetLength
	;_FFGetObjectInfo
	;_FFGetValueById
	;_FFGetValueByName
	;_FFImageClick
	;_FFImageGetBySize
	;_FFLinkClick
	;_FFLinksGetAll
	;_FFLoadWait
	;_FFObj
	;_FFObjDelete
	;_FFObjGet
	;_FFObjNew
	;_FFOpenURL
	;_FFPrefGet
	;_FFPrefReset
	;_FFPrefSet
	;_FFQuit
	;_FFReadHTML
	;_FFReadText
	;_FFSearch
	;_FFSetValueById
	;_FFSetValueByName
	;_FFStart
	;_FFTabAdd
	;_FFTabClose
	;_FFTabCloseAll
	;_FFTabDuplicate
	;_FFTabExists
	;_FFTabGetLength
	;_FFTabGetSelected
	;_FFTabSetSelected
	;_FFTableGetCell
	;_FFTableWriteToArray
	;_FFWindowClose
	;_FFWindowGetHandle
	;_FFWindowOpen
	;_FFWindowSelect
	;_FFWriteHTML
	;_FFXPath
#EndRegion #CURRENT# ==============================================================

#Region Description
; ==============================================================================
; UDF ...........: FF.au3
Global Const $_FF_AU3VERSION = "0.5.3.6b"
; Description ...: An UDF for FireFox automation.
; Requirement ...: MozRepl AddOn:
;                  http://hyperstruct.net/projects/mozlab
;                  http://wiki.github.com/bard/mozrepl/home
; Author(s) .....: Thorsten Willert, Johannes Schirmer
; Date ..........: Tue Jul 07 11:40:51 CEST 2009 @445 /Internet Time/
; FireFox Version: Firefox/3.5 (required 3.x.x)
; AutoIt Version : v3.3.0.0
; ==============================================================================
#cs
	V0.5.3.6
	- Changed: __FFIsURL: now accepts IPs and localhost addresses, too. (thanks to Elena for the suggestions)
	- Fixed: _FFLoadWait: Corrected the loading time returned from @EXTENDED

	V0.5.3.5
	- Added: _FFLoadWait: @EXTENDED returns the loading time in ms now.

	V0.5.3.4
	- Added: _FFAction: Loadwait now optional
	- Changed: _FFStart and option $bHide
	- Fixed: Error with _FFTabGetSelected and _FFTabSetSelected with datatypes on index-mode
	- Fixed: Error in _FFObj with (string)objects from _FFXpath
	- Fixed: Error in _FFWindowGetHandle
	- Fixed: Return value from _FFFrameEnter if mode="name"

	ToDo:
	Textsuche (name, id, text ...) per Substring, String, RegEx
	Events fuer die _FFForm* Funktionen
	Update der Frame Funktionen
#ce
#EndRegion Description

#Region Global Constants
	Global Const $_FF_PROC_NAME = "firefox.exe" ; Firefox process name
	Global Const $_FF_COM_DELAY_MAX = 300 ; alternative connection delay in ms
	Global Enum $_FF_ERROR_Success = 0, _ 	; No error
			$_FF_ERROR_GeneralError, _ 	; General error
			$_FF_ERROR_SocketError, _ 	; No socket
			$_FF_ERROR_InvalidDataType, _ 	; Invalid data type (IP, URL, Port ...)
			$_FF_ERROR_InvalidValue, _ 	; Invalid value in function-call
			$_FF_ERROR_SendRecv, _		; Send / Recv Error
			$_FF_ERROR_Timeout, _ 		; Connection / Send / Recv timeout
			$_FF_ERROR___UNUSED, _ 		;
			$_FF_ERROR_NoMatch, _ 		; No match for _FFAction-find/search _FFGetElement...
			$_FF_ERROR_RetValue, _		; Error echo from Repl e.g. _FFAction("fullscreen","true") <> "true"
			$_FF_ERROR_ReplException, _ 	; Exception from MozRepl / FireFox
			$_FF_ERROR_InvalidExpression ; Invalid expression in XPath query or RegEx
#EndRegion Global Constants

#Region Global Variables
	Global $_FF_GLOBAL_SOCKET = -1 ; Socket
	Global $_FF_CON_DELAY ; Connection Delay
	Global $_aFF_STATUS[2][3] ; Status-Array
	Global $_FF_COM_TRACE = True ; Trace communication to console (debugging)
	Global $_FF_ERROR_MSGBOX = True ; Shows in compiled scripts error messages in msgboxes

	Global $_aFF_ERRORS[1][5] ; Array with information about the last error
#EndRegion Global Variables

; #FUNCTION# ===================================================================
; Name ..........: _FFAction
; Description ...: Some standard actions to work with FireFox
; Beschreibung ..: Standardaktionen in FireFox
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFAction($sAction[, $vOption = ""[, $vOption2 = ""[, $bLoadWait = true]]])
; Parameter(s): .: $sAction     - one of the following actions:
;                               | about
;                               | alert
;                               | back
;                               | blank
;                               | copy
;                               | fullscreen / fs
;                               | hideall
;                               | home
;                               | maximize / max
;                               | minimize / min
;                               | presentationmode / pm
;                               | print
;                               | reload
;                               | resetconsole
;                               | restore
;                               | search / find
;                               | scrollXY
;                               | stop
;                               | zoom
;                  $vOption     - Optional: (Default = "") :
;                  $vOption2    - Optional: (Default = "") :
;                  $bLoadWait   - Optional: (Default = true) :
; Return Value ..: Success      - Return-value from MozRepl (sometimes an empty string!!!)
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 23 11:09:12 CEST 2009
; Link ..........: http://developer.mozilla.org/en/docs/XUL:tabbrowser, http://developer.mozilla.org/en/docs/XUL:Method:reloadWithFlags, https://developer.mozilla.org/En/DOM/Window.scrollBy, http://kb.mozillazine.org/About_Protocol_Links
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFAction($sAction, $vOption = "", $vOption2 = "", $bLoadWait = true)
	Local $sFuncName = "_FFAction"

	Local $sCommand, $sTemp
	Local $sActionL = StringLower($sAction)

	Select
		Case $sActionL = "back"
			$sCommand = "gBrowser.goBack()"
		Case $sActionL = "home"
			$sCommand = "gBrowser.goHome()"
		Case $sActionL = "forward"
			$sCommand = "gBrowser.goForward()"
		Case $sActionL = "copy"
			If $vOption = "" Then $vOption = "|"

			For $i = 0 To _FFGetLength("frames") -1
				_FFFrameEnter($i)
				$sTemp &= _FFCmd(".getSelection()", $_FF_CON_DELAY + 100)
				If $sTemp <> "" Then $sTemp &= $vOption
			Next

			_FFFrameLeave()
			$sTemp &= _FFCmd(".getSelection()", $_FF_CON_DELAY + 100)

			Return $sTemp
		Case $sActionL = "reload" And $vOption <> ""
			$sCommand = "gBrowser.reloadWithFlags('" & $vOption & "')"
		Case $sActionL = "reload"
			$sCommand = "gBrowser.reload()"
		Case $sActionL = "fullscreen" Or $sActionL = "fs" And $vOption
			$sCommand = "fullScreen=true"
			$bLoadWait = False
		Case $sActionL = "fullscreen" Or $sActionL = "fs" And Not $vOption
			$sCommand = "fullScreen=false"
			$bLoadWait = False
		Case $sActionL = "minimize" Or $sActionL = "min"
			$bLoadWait = False
			$sCommand = "minimize()"
		Case $sActionL = "maximize" Or $sActionL = "max"
			$bLoadWait = False
			$sCommand = "maximize()"
		Case $sActionL = "restore"
			$bLoadWait = False
			$sCommand = "restore()"
		Case $sActionL = "stop"
			$bLoadWait = False
			$sCommand = "gBrowser.stop()"
		Case $sActionL = "print"
			$bLoadWait = False
			$sCommand = "content.print()"
		Case $sActionL = "find" Or $sActionL = "search"
			_FFLoadWait()
			$sCommand = "content.find()"
		Case $sActionL = "hideall" And $vOption
			Return _FFCmd("toggleAffectedChrome(true);")
		Case $sActionL = "hideall" And Not $vOption
			Return _FFCmd("toggleAffectedChrome(false);")
		Case $sActionL = "presentationmode" Or $sActionL = "pm" And $vOption
			Return _FFCmd("toggleAffectedChrome(true)" & @CRLF & "fullScreen=true")
		Case $sActionL = "presentationmode" Or $sActionL = "pm" And Not $vOption
			Return _FFCmd("toggleAffectedChrome(false)" & @CRLF & "fullScreen=false")
		Case $sActionL = "alert" And $vOption <> ""
			$sCommand = 'alert("' & $vOption & '")'
			$bLoadWait = False
		Case $sActionL = "chrome" And $vOption <> ""
			$sCommand = 'window.content.document.location.href="' & __FFChromeSelect($vOption) & '"'
		Case $sActionL = "blank"
			$vOption = "blank"
			ContinueCase
		Case $sActionL = "about"
			$sCommand = 'window.content.document.location.href="about:' & $vOption & '"'
		Case $sActionL = "scrollxy" And IsInt($vOption) And IsInt($vOption2)
			$sCommand = "window.content.scrollBy(" & $vOption & "," & $vOption2 & ");"
			$bLoadWait = False
		Case $sActionL = "zoom" And $vOption = ""
			$vOption = 1
			ContinueCase
		Case $sActionL = "zoom" And IsNumber($vOption)
			$sCommand = "gBrowser.selectedBrowser.markupDocumentViewer.fullZoom=" & $vOption
			$bLoadWait = False
		Case $sActionL = "resetconsole"
			$sCommand = ";" & @CRLF & "repl.home()"
			$bLoadWait = False
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sAction: " & $sAction & " or " & "$vOption :" & $vOption & " or " & "$vOption2 :" & $vOption2))
			Return ""
	EndSelect

	Local $sRet = _FFCmd($sCommand)
	If Not @error Then
		If $bLoadWait Then _FFLoadWait()
		Return $sRet
	Else
		SetError(@error)
		Return ""
	EndIf

EndFunc   ;==>_FFAction

; #FUNCTION# ===================================================================
; Name ..........: _FFClick
; Description ...: Simulates a click on an element.
; Beschreibung ..: Simuliert einen Klick auf ein Element.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFClick($sElement[, $sMode = "elements"[, $iIndex = 0]])
; Parameter(s): .: $sElement    - Element to click on
;                  $sMode       - Optional: (Default = "elements") :
;                               | elements
;                               | id
;                               | name
;                               | class
;                               | tag
;                  $iIndex      - Optional: (Default = 0) : Index if $sMode = elements, name, tag
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 21:18:33 CEST 2009 @846 /Internet Time/
; Link ..........:
; Related .......: _FFClickXY, _FFImageClick, _FFLinkClick, _FFObjGet
; Example .......: Yes
; ==============================================================================
Func _FFClick($sElement, $sMode = "elements", $iIndex = 0)
	Local $sFuncName = "_FFClick"

	If Not IsInt($iIndex) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iIndex: " & $iIndex))
		Return 0
	EndIf

	Switch StringLower($sMode)
		Case "elements"
			If StringLeft($sElement, 7) = "OBJECT|" Then $sElement = StringMid($sElement, 8)
		Case "id"
			$sElement = ".getElementById('" & $sElement & "')"
		Case "name"
			$sElement = ".getElementsByName('" & $sElement & "')[" & $iIndex & "]"
		Case "class"
			$sElement = ".getElementsByClassName('" & $sElement & "')[" & $iIndex & "]"
		Case "tag"
			$sElement = ".getElementsByTagName('" & $sElement & "')[" & $iIndex & "]"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(elements|id|name|class|tag) $sMode: " & $sMode))
			Return 0
	EndSwitch

	If StringLeft($sElement, 1) = "." Then $sElement = "window.content.document" & $sElement

	Local $RetVal = _FFCmd("FFau3.simulateClick(" & $sElement & ",0,0);")
	If Not @error And $RetVal <> "_FFCmd_Err" And $RetVal = 1 Then
		Sleep(25)
		Return $RetVal
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sElement: " & $sElement))
		Return 0
	EndIf

EndFunc   ;==>_FFClick

; #FUNCTION# ===================================================================
; Name ..........: _FFClickXY
; Description ...: Clicks on the element on a X/Y coordinate
; Beschreibung ..: Klickt auf Element an einer X/Y Koordinate
; Syntax ........: _FFClickXY([$iX = 0[, $iY = 0[, $bLoadWait = True]]])
; Parameter(s): .: $iX          - Optional: (Default = 0) : X coordinate
;                  $iY          - Optional: (Default = 0) : Y coordinate
;                  $bLoadWait   - Optional: (Default = true) : LoadWait after clicking
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Modified ......: Tue Apr 07 18:25:57 CEST 2009 @726 /Internet Time/
; Link ..........: https://developer.mozilla.org/En/DOM/Document.elementFromPoint
; Related .......: _FFClick, _FFImageClick, _FFLinkClick, _FFObjGet
; Example .......: Yes
; ==============================================================================
Func _FFClickXY($iX = 0, $iY = 0, $bLoadWait = True)
	Local $sFuncName = "_FFClickXY"

	If Not IsInt($iX) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iX: " & $iX))
		Return 0
	EndIf
	If Not IsInt($iY) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iY: " & $iY))
		Return 0
	EndIf

	Local $sRetVal = _FFCmd(StringFormat("FFau3.simulateClick(content.document.elementFromPoint(%i,%i));", $iX, $iY))
	If Not @error And $sRetVal = 1 Then
		If $bLoadWait Then Return _FFLoadWait()
		Return 1
	EndIf

	Return 0
EndFunc   ;==>_FFClickXY

; #FUNCTION# ===================================================================
; Name ..........: _FFDialogWait
; Description ...: Waits for a browser-dialog-message (e.g. alert) and closes it.
; Beschreibung ..: Wartet auf ein Dialog-Fenster (z.B.: alert) und schlie?t es.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFDialogWait($sText[, $sTitle = ""[, $sClose = "close"[, $iTimeOut = 10000]]])
; Parameter(s): .: $sText       - Text in the dialog (substring)
;                  $sTitle      - Optional: (Default = "") : Window-title of the dialog (substring)
;                  $bClose      - Optional: (Default = "close") :
;                               | close = Just closes the dialog window
;                               | open = Do nothing
;                               | ok = Uses the "ok"-button
;                               | cancel = Uses the"cancel"-button
;                  $iTimeOut    - Optional: (Default = 10000) : Timeout for waiting (min. 1000ms)
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 14 12:18:08 CEST 2009
; Link ..........:
; Related .......: _FFLoadWait
; Example .......: Yes
; ==============================================================================
Func _FFDialogWait($sText, $sTitle = "", $sClose = "close", $iTimeOut = 10000)
	Local $sFuncName = "_FFDialogWait"
	If $sTitle = "" And $sText = "" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "Empty String: $sText and $sTitle"))
		Return 0
	EndIf
	If $sClose = Default Then $sClose = "close"
	If $iTimeOut < 1000 Then $iTimeOut = 1000

	Local $bFound = False, $b1 = False, $b2 = False

	Local $iTimer = TimerInit()
	While TimerDiff($iTimer) < $iTimeOut
		If _FFCmd('FFau3.obj=Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("").window;' & _
			'FFau3.obj.document.documentURI') = "chrome://global/content/commonDialog.xul" Then
			If $sTitle <> "" Then
				If StringInStr(_FFCmd("FFau3.obj.title"), $sTitle) Then $b1 = True
			EndIf
			If $sText <> "" Then
				If StringInStr(_FFCmd("FFau3.obj.document.documentElement.textContent"), $sText) Then $b2 = True
			EndIf
			Select
				Case $sTitle = "" And $sText <> "" And Not $b1 And $b2
					$bFound = True
				Case $sTitle <> "" And $sText <> "" And $b1 And $b2
					$bFound = True
				Case $sTitle <> "" And $sText = "" And $b1 And Not $b2
					$bFound = True
				Case Else
					$bFound = False
			EndSelect
			If $bFound Then
				Switch StringLower($sClose)
					Case "close" ; just close the window
						_FFCmd("FFau3.obj.close()")
					Case "ok"
						_FFCmd("FFau3.obj.document.documentElement.acceptDialog()")
					Case "cancel"
						_FFCmd("FFau3.obj.document.documentElement.cancelDialog()")
					Case "open" ; do nothing
					Case Else
						SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sClose: " & $sClose))
						Return 0
				EndSwitch
				Return 1
			EndIf
		EndIf
		Sleep(500)
	Wend

	SetError(__FFError($sFuncName, $_FF_ERROR_Timeout, Round(TimerDiff($iTimer)) & "ms > " & $iTimeOut & "ms"))
	Return 0
EndFunc

; #FUNCTION# ===================================================================
; Name ..........: _FFImageClick
; Description ...: Clicks an image-link.
; Beschreibung ..: Klickt einen Image-Link.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFImageClick($vSearch[, $sMode = "src"[, $bLoadWait = True]])
; Parameter(s): .: $vSearch     - Text to search or number (0-n) in index mode
;                  $sMode       - Optional: (Default = "src") :
;                               | src
;                               | alt
;                               | name
;                               | title
;                               | id
;                               | index
;                  $bLoadWait   - Optional: (Default = True) :
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 20:54:44 CEST 2009 @829 /Internet Time/
; Link ..........:
; Related .......: _FFClick, _FFLinkClick
; Example .......: Yes
; ==============================================================================
Func _FFImageClick($vSearch, $sMode = "src", $bLoadWait = True)
	Local $sFuncName = "_FFImageClick"

	Local $sRegEx
	Local $iIndex = -1

	$sMode = StringLower($sMode)

	Switch $sMode
		Case "index"
			If Not IsInt($vSearch) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vSearch: " & $vSearch))
				Return 0
			EndIf
			$iIndex = $vSearch
		Case "src"
			$vSearch = StringRegExpReplace($vSearch, "([\/\.\?\+\=])", "\\$1")
			ContinueCase
		Case "alt"
			ContinueCase
		Case "name"
			ContinueCase
		Case "title"
			ContinueCase
		Case "id"
			$sRegEx = $sMode
			$sRegEx = "/" & $sRegEx & "[ \t]*=[ \t]*(.*)" & $vSearch & "/"
			$iIndex = _FFCmd("FFau3.searchImageLink(" & $sRegEx & "," & __FFGetStatus() & ")", 10000)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(src|alt|name|title|id|index) $sMode: " & $sMode))
			Return 0
	EndSwitch

	If $iIndex > -1 Then
		If _FFClick(".links[" & $iIndex & "]") Then
			If $bLoadWait Then Return _FFLoadWait()
			Return 1
		EndIf
	EndIf

	SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vSearch: " & $vSearch))
	Return 0

EndFunc   ;==>_FFImageClick
Func _FFClickImage($vSearch, $sMode = "src")
	 Return _FFImageClick($vSearch, $sMode)
EndFunc

; #FUNCTION# ===================================================================
; Name ..........: _FFImagesGetBySize
; Description ...: Returns an array with the index of matching images.
; Beschreibung ..: Liefert ein Array mit den Indizes der passenden Bilder.
; Syntax ........: _FFImagesGetBySize($iHeight, $iWidth[, $sMode = "eq"])
; Parameter(s): .: $iHeight     - Heigth of the image(s)
;                  $iWidth      - Width of the image(s)
;                  $sMode       - Optional (Default = "eq") :
;                               | eq
;                               | lt
;                               | gt
; Return Value ..: Success      - array[0] > 0
;                  Failure      - array[0] = 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 20:00:03 CEST 2009 @791 /Internet Time/
; Link ..........:
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFImagesGetBySize($iHeight, $iWidth, $sMode = "eq")
	Local $sFuncName = "_FFImagesGetBySize"
	Local $aRet[1] = [0]

	If Not IsInt($iHeight) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iHeight: " & $iHeight))
		Return $aRet
	EndIf
	If Not IsInt($iWidth) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iWidth: " & $iWidth))
		Return $aRet
	EndIf
	Switch StringLower($sMode)
		Case "eq"
		Case "lt"
		Case "gt"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(eq|lt|gt) $sMode: " & $sMode))
			Return $aRet
	EndSwitch

	Local $sCommand = StringFormat("FFau3.SearchImageBySize(%s,%s,'%s',%s);", $iHeight, $iWidth, $sMode, __FFGetStatus())
	Local $iIndex = StringStripWS(_FFCmd($sCommand, 10000),3)
	$aRet = StringSplit($iIndex," ")
	If Not @error And $aRet[0] > 0 Then
		For $i = 1 To $aRet[0]
			$aRet[$i] = Int($aRet[$i])
		Next
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch))
		Return $aRet
	EndIf

	Return $aRet
EndFunc   ;==>_FFImagesGetBySize

; #FUNCTION# ===================================================================
; Name ..........: _FFLinkClick
; Description ...: Simulates a click on a link.
; Beschreibung ..: Simuliert einen Klick auf einen Link
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFLinkClick($vSearch[, $sMode = "href"[, $bLoadWait = True]])
; Parameter(s): .: $vSearch     - (Sub)String to search or number (0-n) in index mode
;                  $sMode       - Optional: (Default = "href") :
;                               | href
;                               | alt
;                               | name
;                               | title
;                               | id
;                               | index
;                  $bLoadWait   - Optional: (Default = True) :
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 20:50:44 CEST 2009 @826 /Internet Time/
; Link ..........:
; Related .......: _FFClick, _FFImageClick
; Example .......: Yes
; ==============================================================================
Func _FFLinkClick($vSearch, $sMode = "href", $bLoadWait = True)
	Local $sFuncName = "_FFLinkClick"

	Local $iIndex = -1
	$sMode = StringLower($sMode)

	Switch $sMode
		Case "index"
			If Not IsInt($vSearch) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vSearch: " & $vSearch))
				Return 0
			EndIf
			$iIndex = $vSearch
		Case "href"
			ContinueCase
		Case "text"
			ContinueCase
		Case "name"
			ContinueCase
		Case "title"
			ContinueCase
		Case "id"
			$iIndex = _FFCmd('FFau3.SearchLink("' & $sMode & '","' & $vSearch & '",' & __FFGetStatus() & ');', 5000)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|href|text|name|title|id) $sMode: " & $sMode))
			Return 0
	EndSwitch

	If $iIndex > -1 Then
		If _FFClick(".links[" & $iIndex & "]") Then
			If $bLoadWait Then Return _FFLoadWait()
			Return 1
		EndIf
	EndIf

	SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vSearch: " & $vSearch))
	Return 0

EndFunc   ;==>_FFLinkClick
Func _FFClickLink($vSearch, $sMode = "href", $bLoadWait = True)
	Return _FFLinkClick($vSearch,$sMode,$bLoadWait)
EndFunc

; #FUNCTION# ===================================================================
; Name ..........: _FFFrameGetSelected
; Description ...: Returns the index or label of the currently entered frame
; Beschreibung ..: Gibt das Label oder Index des aktuellen Frames zur?ck
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFrameGetSelected([$sMode = "index"])
; Parameter(s): .: $sMode       - Optional: (Default = "index") :
;                               | index = returns the index of the frame
;                               | name = the name of the frame
; Return Value ..: Success      - Index or name of the currently entered frame
;                  Failure      - -1 if no frame is selected
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 23:26:41 CET 2009 @976 /Internet Time/
; Link ..........:
; Related .......: _FFFrameLeave, _FFFrameEnter
; Example .......: Yes
; ==============================================================================
Func _FFFrameGetSelected($sMode = "index")
	Local $sFuncName = "_FFFrameGetSelected"

	Local $iIndex = __FFGetStatus()

	Switch StringLower($sMode)
		Case "index"
			Return $iIndex
		Case "name"
			Local $RetVal = _FFCmd('content.frames[' & $iIndex & '].name')
			If $RetVal = "" Then Return -1
			Return $RetVal
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name) $sMode: " & $sMode))
			Return -1
	EndSwitch

	Return -1
EndFunc   ;==>_FFFrameGetSelected

; #FUNCTION# ===================================================================
; Name ..........: _FFFrameLeave
; Description ...: Leaves the currently entered frame
; Beschreibung ..: Verl??t den aktuellen Frame
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFrameLeave()
; Parameter(s): .:
; Return Value ..: Success      - 1
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 23:26:09 CET 2009 @976 /Internet Time/
; Link ..........:
; Related .......: _FFFrameEnter, _FFFrameGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFFrameLeave()
	;Local $sFuncName = "_FFFrameLeave"
	Return __FFSetStatus(-1)
EndFunc   ;==>_FFFrameLeave

; #FUNCTION# ===================================================================
; Name ..........: _FFFrameEnter
; Description ...: Selects a frame, which all subsequent commands apply on.
; Beschreibung ..: W?hlt einen Frame aus, auf den alle nachfolgenden Befehle wirken.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFrameEnter($vFrame[, $sMode = "index"])
; Parameter(s): .: $vFrame      - Frame name or id or number in index mode
;                  $sMode       - Optional: (Default = "index") :
;                               | name
;                               | id
;                               | index
; Return Value ..: Success      - Index of the entered frame
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert & Johannes Schirmer
; Date ..........: Thu Apr 30 09:20:44 CEST 2009
; Link ..........:
; Related .......: _FFFrameLeave, _FFFrameGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFFrameEnter($vFrame, $sMode = "index")
	Local $sFuncName = "_FFFrameEnter"

	Local $iLength = _FFGetLength("frames")
	If $iLength = 0 Then
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "No frames found."))
		Return ""
	EndIf

	Local $sArg, $i

	Switch $sMode
		Case "index"
			$sArg = "content.frames[" & $vFrame & "]"
		Case "name" Or "id"
			$sArg = 'content.frames["' & $vFrame & '"]'
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name) $sMode: " & $sMode))
			Return ""
	EndSwitch

	If _FFFrameGetSelected() > -1 Then _FFFrameLeave()

	If $sMode = "index" Then
		_FFCmd($sArg & ".document.location.href")
		If Not @error Then
			__FFSetStatus($vFrame)
			Return $vFrame
		EndIf
	Else
		If StringInStr("parent top", $vFrame) Then
			__FFSetStatus(-1)
			Return -1
		EndIf
		For $i = 0 To $iLength - 1
			If _FFCmd("content.frames[" & $i & "].name", 3000) = $vFrame Then
				__FFSetStatus($i)
				Return $i
			EndIf
		Next
	EndIf

	SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vFrame: " & $vFrame))
	Return -1
EndFunc   ;==>_FFFrameEnter

; #FUNCTION# ===================================================================
; Name ..........: _FFGetLength
; Description ...: Returns the length of the elements in $sMode
; Beschreibung ..: Gibt die Anzahl der angegebenen Elemente zur?ck.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFGetLength([$sMode = "links"])
; Parameter(s): .: $sMode       - Optional: (Default = "links") :
;                               | links
;                               | images
;                               | forms
;                               | frames
;                               | anchors
;                               | tables
;                               | styleSheets
;                               | tabs
;                               | history
;                               | applets
;                               | embeds
;                               | plugins
;                               | tag
; Return Value ..: Success      - Length of the elements
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 23:24:13 CET 2009 @975 /Internet Time/
; Link ..........:
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFGetLength($sMode = "links")
	Local $sFuncName = "_FFGetLength"

	$sMode = StringLower($sMode)

	Switch $sMode
		Case "links"
			ContinueCase
		Case "images"
			ContinueCase
		Case "forms"
			ContinueCase
		Case "anchors"
			ContinueCase
		Case "applets"
			ContinueCase
		Case "embeds"
			Return _FFCmd("." & $sMode & ".length")
		Case "tabs"
			Return _FFCmd("gBrowser.tabContainer.childNodes.length")
		Case "frames"
			Return _FFCmd("content.frames.length")
		Case "tables"
			Return _FFCmd(".getElementsByTagName('table').length")
		Case "history"
			Return _FFCmd("content.history.length")
		Case "stylesheets"
			Return _FFCmd(".styleSheets.length")
		Case "plugins"
			Return _FFCmd("navigator.plugins.length")
		Case Else
			Local $RetVal = _FFCmd(".getElementsByTagName('" & $sMode & "').length;")
			If Not @error And $RetVal <> "_FFCmd_Err" Then
				Return $RetVal
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sMode: " & $sMode))
				Return 0
			EndIf
	EndSwitch

	Return 0

EndFunc   ;==>_FFGetLength

; #FUNCTION# ===================================================================
; Name ..........: _FFLinksGetAll
; Description ...: Returns an array with informations about all existing links.
; Beschreibung ..: Gibt ein Array mit Informationen ?ber alle vorhandenen Links zur?ck.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFLinksGetAll()
; Parameter(s): .:
; Return Value ..: Success      - 2 dim array with the link informations:
;                               | array[n][0] = href
;                               | array[n][1] = hash
;                               | array[n][2] = search
;                               | array[n][3] = name
;                               | array[n][4] = id
;                               | array[n][5] = text
;                               | array[n][6] = innerHTML
;                               | array[n][7] = target
;                               | array[n][8] = protocol
;                               | array[n][9] = port
;                  Failure      - array[0][0] = 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 16 09:34:25 CEST 2009
; Link ..........:
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFLinksGetAll()
	Local $sFuncName = "_FFLinksGetAll"

	Local $aInfo, $sInfo, $aRet[1][9], $aTmp
	Local $sDelimiter

	If _FFGetLength() > 0 Then
		$sDelimiter = "FF" & Random(1000, 9999, 1)
		$sInfo = _FFCmd('FFau3.GetLinks(' & _FFFrameGetSelected() & ',"' & $sDelimiter & '");')
		$aInfo = StringSplit($sInfo, @CRLF)
		If @error Then
			SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch))
			Return $aRet[0][0] = 0
		EndIf
		ReDim $aRet[$aInfo[0] - 1][9]
		For $i = 1 To $aInfo[0] - 1
			$aTmp = StringSplit($aInfo[$i], $sDelimiter, 1)
			If @error Then
				SetError(__FFError($sFuncName, $_FF_ERROR_RetValue, "StringSplit: " & $aInfo[$i]))
				ExitLoop
			EndIf
			If UBound($aTmp) <> 11 Then
				$sDelimiter = "FF" & Random(1000, 9999, 1)
				$sInfo = _FFCmd("FFau3.GetLinkInfo(" & $i & " ,'top','" & $sDelimiter & "')")
				$aTmp = StringSplit($sInfo, $sDelimiter, 1)
			EndIf
			For $j = 1 To $aTmp[0] - 1
				$aRet[$i - 1][$j - 1] = $aTmp[$j]
			Next
		Next
		Return $aRet
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch))
		$aRet[0][0] = 0
	EndIf

	SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError))
	Return $aRet[0][0] = 0
EndFunc   ;==>_FFLinksGetAll

; #FUNCTION# ===================================================================
; Name ..........: _FFConnect
; Description ...: Connects to FireFox / MozRepl
; Beschreibung ..: Stellt eine Verbindung mit Firefox / MozRepl her.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFConnect([$IP = "127.0.0.1"[, $iPort = 4242[, $iTimeOut = 60000]]])
; Parameter(s): .: $IP          - Optional: (Default = "127.0.0.1") :
;                  $iPort       - Optional: (Default = 4242) :
;                  $iTimeOut    - Optional: (Default = 60000) :
; Return Value ..: Success      - 1 / $_FF_GLOBAL_SOCKET > -1
;                  @EXTENDED    - 1 = Non Browser-window
;                               | 2 = Browser-window
;                  Failure      - 0 / $_FF_GLOBAL_SOCKET = -1
;                  @ERROR       -
;                  @EXTENDED    - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Apr 13 18:37:59 CEST 2009
; Link ..........: http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx
; Related .......: _FFDisConnect, _FFIsConnected, _FFStart
; Example .......: Yes
; ==============================================================================
Func _FFConnect($IP = "127.0.0.1", $iPort = 4242, $iTimeOut = 60000)
	Local $sFuncName = "_FFConnect"
	Local $Extended = 2

	If $IP = Default Then $IP = "127.0.0.1"
	If $iPort = Default Then $iPort = 4242
	If $iTimeOut = Default Then $iTimeOut = 60000

	If Not __FFIsIP($IP) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, $IP))
		Return 0
	EndIf
	If Not __FFIsPort($iPort) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, $iPort))
		Return 0
	EndIf

	Local $iTCPErr
	Local $bTrace = $_FF_COM_TRACE
	;$_FF_COM_TRACE = false

	ConsoleWrite("_FFConnect: OS:" & @TAB & @OSVersion & " " & @OSTYPE & " " & @OSBuild & " " & @OSServicePack & @CRLF)
	ConsoleWrite("_FFConnect: AutoIt:" & @TAB & @AutoItVersion & @CRLF)
	ConsoleWrite("_FFConnect: FF.au3:" & @TAB & $_FF_AU3VERSION & @CRLF)
	ConsoleWrite("_FFConnect: IP:" & @TAB & $IP & @CRLF)
	ConsoleWrite("_FFConnect: Port:" & @TAB & $iPort & @CRLF)

	TCPStartup()
	If Not @error Then
		; delay for connection over network
		$_FF_CON_DELAY = Ping($IP)
		If @error Then
			SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError, "Ping Error: " & @error))
			$_FF_CON_DELAY = $_FF_COM_DELAY_MAX
		EndIf
		$_FF_CON_DELAY += Round($_FF_CON_DELAY * 0.5)
		ConsoleWrite("_FFConnect: Delay: " & @TAB & $_FF_CON_DELAY & "ms" & @CRLF)

		; trying to connect
		Local $iTimeOutTimer = TimerInit()
		While 1
			$_FF_GLOBAL_SOCKET = TCPConnect($IP, $iPort)
			$iTCPErr = @error
			Sleep(500)
			If __FFIsSocket($_FF_GLOBAL_SOCKET) Then ExitLoop
			If (TimerDiff($iTimeOutTimer) > $iTimeOut) Then ; Profil laden
				SetError(__FFError($sFuncName, $_FF_ERROR_Timeout, "TCPConnect Error: " & $iTCPErr ))
				$_FF_GLOBAL_SOCKET = -1
				ExitLoop
			EndIf
		WEnd
		If $_FF_GLOBAL_SOCKET <> -1 Then
			ConsoleWrite("_FFConnect: Socket: " & @TAB & $_FF_GLOBAL_SOCKET & @CRLF)
			If __FFWaitForRepl(10000) Then
				__FFAddStatus()
				_FFCmd(".browserDOMWindow")
				If @error Then
					SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError, "Warning: Connected to a non browser-window" ))
					$Extended = 1
				EndIf
				ConsoleWrite("_FFConnect: Browser:" & @TAB & _FFCmd("navigator.userAgent") & @CRLF)
				__FFSendJavaScripts()
				$_FF_COM_TRACE = $bTrace
				Return SetError(0, $Extended, 1)
			EndIf
		Else
			TCPShutdown()
			$_FF_COM_TRACE = $bTrace
			Return SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError, "Timeout: Can not connect to FireFox/MozRepl on: " & $IP & ":" & $iPort ), 0, 0)
		EndIf
	Else
		$_FF_COM_TRACE = $bTrace
		Return SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError, "TCPStartup Error: " & @error), 0, 0)
	EndIf

	$_FF_COM_TRACE = $bTrace
	Return SetError($_FF_ERROR_GeneralError, $Extended, 0)
EndFunc   ;==>_FFConnect

; #FUNCTION# ===================================================================
; Name ..........: _FFDisConnect
; Description ...: Disconnects from FireFox
; Beschreibung ..: Trennt die Verbindung mit FireFox / MozRepl
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFDisConnect()
; Parameter(s): .:
; Return Value ..: Success      - 1 / $_FF_GLOBAL_SOCKET = -1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Wed Apr 15 09:54:09 CEST 2009
; Link ..........: http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx
; Related .......: _FFConnect, _FFIsConnected, _FFStart
; Example .......: Yes
; ==============================================================================
Func _FFDisConnect()
	Local $sFuncName = "_FFDisConnect"

	If __FFIsSocket($_FF_GLOBAL_SOCKET) Then
		__FFSend("repl.quit()")
		TCPCloseSocket($_FF_GLOBAL_SOCKET)
		If @error Then
			SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError, "TCP Error: " & @error))
			Return 0
		EndIf
		TCPShutdown()
		If Not @error Then
			If $_FF_COM_TRACE Then ConsoleWrite("_FFDisConnect: disconnected" & @CRLF)
			__FFRemoveStatus()
			$_FF_GLOBAL_SOCKET = -1
			Return 1
		Else
			SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError, "TCP Error: " & @error))
			Return 0
		EndIf
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_SocketError, $_FF_GLOBAL_SOCKET))
		Return 0
	EndIf

EndFunc   ;==>_FFDisConnect

; #FUNCTION# ===================================================================
; Name ..........: _FFIsConnected
; Description ...: Connection status to FireFox / MozRepl
; Beschreibung ..: Liefert den Status der Verbindung mit FireFox / MozRepl
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFIsConnected()
; Parameter(s): .:
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 07 11:11:05 CEST 2009 @424 /Internet Time/
; Link ..........:
; Related .......: _FFConnect, _FFDisConnect, _FFStart
; Example .......: Yes
; ==============================================================================
Func _FFIsConnected()
	Local $sFuncName = "_FFIsConnected"

	If __FFIsSocket($_FF_GLOBAL_SOCKET) Then
		If _FFCmd("FFau3 != null?1:0") = 1 Then Return 1
	EndIf

	SetError(__FFError($sFuncName, $_FF_ERROR_SocketError, $_FF_GLOBAL_SOCKET))
	Return 0
EndFunc ;==> _FFIsConnected

; #FUNCTION# ===================================================================
; Name ..........: _FFFormCheckBox
; Description ...: Checks or unchecks a CheckBox in a form.
; Beschreibung ..: W?hlt eine Checkbox an oder ab.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFormCheckBox($vBox[, $bChecked = True[, $iBoxNameIndex = 0[, $sBoxMode = "index"[, $vForm = 0[, $sFormMode = "index"[, $bCheckBox = True]]]]]])
; Parameter(s): .: $vBox        - Index name, id or value of the CheckBox
;                  $bChecked    - Optional: (Default = True) :
;                               | True
;                               | False
;                  $iBoxNameIndex - Optional: (Default = 0) : Index if $sBoxMode = "name"
;                  $sBoxMode    - Optional: (Default = "index") :
;                               | index
;                               | name
;                               | id
;                               | value
;                  $vForm       - Optional: (Default = 0) : Index, name or id of the Form
;                  $sFormMode   - Optional: (Default = "index") :
;                               | index
;                               | name
;                               | id
;                  $bCheckBox   - Optional: (Default = True) : Internal use if the function should work for RadioButtons
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Wed Mar 25 09:25:43 CET 2009 @392 /Internet Time/
; Link ..........:
; Related .......: _FFFormOptionSelect, _FFFormRadioButton, _FFFormReset, _FFFormSubmit
; Example .......: Yes
; ==============================================================================
Func _FFFormCheckBox($vBox, $bChecked = True, $iBoxNameIndex = 0, $sBoxMode = "index", $vForm = 0, $sFormMode = "index" , $bCheckBox = True)
	Local $sFuncName = "_FFFormCheckBox"

	; Default parameters
	;If $bChecked = Default Then $bChecked = true
	If $iBoxNameIndex = Default Then $iBoxNameIndex = 0
	If $sBoxMode = Default Then $sBoxMode = "index"
	If $vForm = Default Then $vForm = 0
	If $sFormMode = Default Then $sFormMode = "index"

	Local $sType
	If $bCheckBox Then
		$sType = "checkbox"
	Else
		$sType = "radio"
	EndIf

	$sBoxMode = StringLower($sBoxMode)
	$sFormMode = StringLower($sFormMode)

	If Not IsBool($bChecked) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(bool) $bChecked: " & $bChecked))
		Return 0
	EndIf

	Local $sCommand = "checked=" & __FFB2S($bChecked)
	Local $sForm, $sCheckBox

	Switch $sFormMode
		Case "index"
			If Not IsInt($vForm) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vForm: " & $vForm))
				Return 0
			EndIf
			$sForm = $vForm + 1
		Case "name"
			ContinueCase
		Case "id"
			$sForm = StringFormat("@%s='%s'", $sFormMode, $vForm)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name|id) $sFormMode: " & $sFormMode))
			Return 0
	EndSwitch

	Switch $sBoxMode
		Case "index"
			If Not IsInt($vBox) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vBox: " & $vBox))
				Return 0
			EndIf
			$sCheckBox = "position()=" & $vBox + 1
		Case "name"
			If Not IsInt($iBoxNameIndex) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iBoxNameIndex: " & $iBoxNameIndex))
				Return 0
			EndIf
			$sCheckBox = StringFormat("@name='%s' and position()=%i", $vBox, $iBoxNameIndex + 1)
		Case "id"
			ContinueCase
		Case "value"
			$sCheckBox = StringFormat("@%s='%s'", $sBoxMode, $vBox)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name|id|value) $sBoxMode: " & $sBoxMode))
			Return 0
	EndSwitch

	_FFXPath(StringFormat("//form[%s]//input[@type='%s' and %s]", $sForm, $sType, $sCheckBox), $sCommand, 9)
	If Not @error Then
		Return 1
	Else
		SetError(@error)
		Return 0
	EndIf

EndFunc   ;==>_FFFormCheckBox

; #FUNCTION# ===================================================================
; Name ..........: _FFFormGetLength
; Description ...: Length of the forms
; Beschreibung ..: Gibt die Anzahl der Formulare zur?ck.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFormGetLength()
; Parameter(s): .:
; Return Value ..: Success      - >0
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 23:15:23 CET 2009 @969 /Internet Time/
; Link ..........:
; Related .......: _FFGetLength
; Example .......: Yes
; ==============================================================================
Func _FFFormGetLength()
	;Local $sFuncName = "_FFFormGetLength"
	Return _FFGetLength("forms")
EndFunc   ;==>_FFFormGetLength

; #FUNCTION# ===================================================================
; Name ..........: _FFFormGetElementsLength
; Description ...: Length of the form elements
; Beschreibung ..: Gibt die Anzahl der Elemente eines Formulars zur?ck.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFormGetElementsLength([$vForm = 0[, $sMode = "index"[, $sCount = "DOM"]]])
; Parameter(s): .: $vForm       - Optional: (Default = 0) : Index (0-n), name or id
;                  $sMode       - Optional: (Default = "index") :
;                               | index
;                               | name
;                               | id
;                  $sCount      - Optional: (Default = "DOM") :
;                               | DOM = <input type='image'> are not counted
; Return Value ..: Success      - >0
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Fri Apr 10 12:06:30 CEST 2009
; Link ..........:
; Related .......: _FFFormGetLength, _FFGetLength
; Example .......: Yes
; ==============================================================================
Func _FFFormGetElementsLength($vForm = 0, $sMode = "index", $sCount = "DOM")
	Local $sFuncName = "_FFFormGetElementsLength"
	Local $sForm, $sInput

	If $vForm = Default Then $vForm = 0
	If $sMode = Default Then $sMode = "index"
	$sCount = StringLower($sCount)

	Switch StringLower($sMode)
		Case "index"
			If IsInt($vForm) Then
				$sForm = $vForm +1
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vForm: " & $vForm))
				Return 0
			EndIf
		Case "name"
			$sForm = "@name='" & $vForm & "'"
		Case "id"
			$sForm = "@id='" & $vForm & "'"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name|id) $vForm: " & $vForm))
			Return 0
	EndSwitch

	If $sCount = "dom" Then
		$sInput = "input[@type!='image']"
	Else
		$sInput = "input"
	EndIf

	Local $bTrace = $_FF_COM_TRACE
	$_FF_COM_TRACE = False

	Local $c = _FFXPath(StringFormat("//form[%s]//%s", $sForm, $sInput), "", 10)
	If Not @error Then
		$c += _FFXPath(StringFormat("//form[%s]//textarea", $sForm), "", 10)
		$c += _FFXPath(StringFormat("//form[%s]//select", $sForm), "", 10)
		$c += _FFXPath(StringFormat("//form[%s]//fieldset", $sForm), "", 10)
		$_FF_COM_TRACE = $bTrace
		Return $c
	Else
		$_FF_COM_TRACE = $bTrace
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vForm: " & $vForm))
		Return 0
	EndIf
EndFunc   ;==>_FFFormGetElementsLength

; #FUNCTION# ===================================================================
; Name ..........: _FFFormOptionSelect
; Description ...: Selects an element of an OptionSelect.
; Beschreibung ..: W?hlt ein Element eines OptionSelect aus.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFormOptionSelect([$vElement = 0[, $sElementMode = "index"[, $vOption = 0[, $sOptionMode = "index"[, $vForm = 0[, $sFormMode = "index"]]]]]])
; Parameter(s): .: $vElement    - Optional: (Default = 0) : index (0-n), name, id
;                  $sElementMode - Optional: (Default = "index") :
;                               | index
;                               | name
;                               | id
;                  $vOption     - Optional: (Default = 0) : index (0-n), name, id, text, value
;                  $sOptionMode - Optional: (Default = "index") :
;                               | index
;                               | name
;                               | id
;                               | text
;                               | value
;                  $vForm       - Optional: (Default = 0) : index (0-n), name, id
;                  $sFormMode   - Optional: (Default = "index") :
;                               | index
;                               | name
;                               | id
; Return Value ..: Success      - 1
;                  Failure      - 0 and sets
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Wed Mar 25 09:27:49 CET 2009 @394 /Internet Time/
; Link ..........:
; Related .......: _FFFormCheckBox, _FFFormRadioButton, _FFFormReset, _FFFormSubmit
; Example .......: Yes
; ==============================================================================
Func _FFFormOptionSelect($vElement = 0, $sElementMode = "index", $vOption = 0, $sOptionMode = "index", $vForm = 0, $sFormMode = "index")
	Local $sFuncName = "_FFFormOptionSelect"

	; Default parameters
	If $vElement = Default Then $vElement = 0
	If $sElementMode = Default Then $sElementMode = "index"
	If $vOption = Default Then $vOption = 0
	If $sOptionMode = Default Then $sOptionMode = "index"
	If $vForm = Default Then $vForm = 0
	If $sFormMode = Default Then $sFormMode = "index"

	Local $sForm, $sElement, $sOption
	$sElementMode = StringLower($sElementMode)
	$sOptionMode = StringLower($sOptionMode)
	$sFormMode = StringLower($sFormMode)

	Switch $sFormMode
		Case "index"
			If Not IsInt($vForm) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vForm: " & $vForm))
				Return 0
			EndIf
			$sForm = $vForm + 1
		Case "name"
			ContinueCase
		Case "id"
			$sForm = StringFormat("@%s='%s'", $sFormMode, $vForm)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name|id) $sFormMode: " & $sFormMode))
			Return 0
	EndSwitch

	Switch $sElementMode
		Case "index"
			If Not IsInt($vElement) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vElement: " & $vElement))
				Return 0
			EndIf
			$sElement = "position()=" & $vElement + 1
		Case "name"
			ContinueCase
		Case "id"
			$sElement = StringFormat("@%s='%s'", $sElementMode, $vElement)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name|id) $sElementMode: " & $sElementMode))
			Return 0
	EndSwitch

	Switch $sOptionMode
		Case "index"
			If Not IsInt($vOption) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vOption: " & $vOption))
				Return 0
			EndIf
			$sOption = "position()=" & $vOption + 1
		Case "text"
			$sOption = StringFormat("contains(.,'%s')", $vOption)
		Case "name"
			ContinueCase
		Case "value"
			ContinueCase
		Case "id"
			$sOption = StringFormat("@%s='%s'", $sOptionMode, $vOption)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|text|name|id|value) $sOptionMode: " & $sOptionMode))
			Return 0
	EndSwitch

	Local $sCommand = StringFormat("//form[%s]//select[%s]//option[%s]", $sForm, $sElement, $sOption)
	_FFXPath($sCommand, "selected=true", 9)
	If Not @error Then
		Return 1
	Else
		SetError(@error)
		Return 0
	EndIf

EndFunc   ;==>_FFFormOptionSelect

; #FUNCTION# ===================================================================
; Name ..........: _FFFormRadioButton
; Description ...: Selects a RadioButton in a form
; Beschreibung ..: W?hlt ein RadioButton aus.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFormRadioButton($vRadioButton[, $iRadioButtonIndex = 0[, $sRadioButtonMode = "index"[, $vForm = 0[, $sFormMode = "index"]]]])
; Parameter(s): .: $vRadioButton - name, id or value
;                  $iRadioButtonIndex - Optional: (Default = 0) : RadioButton index (0-n)
;                  $sRadioButtonMode - Optional: (Default = "index") : RadioButton
;                               | index
;                               | name
;                               | id
;                               | value
;                  $vForm       - Optional: (Default = 0) : Form index or name
;                  $sFormMode   - Optional: (Default = "index") :
;                               | index
;                               | name
; Return Value ..: Success      - RadioButton state 1 or 0
;                  Failure      - -1
; Author(s) .....: Thorsten Willert
; Date ..........: Wed Mar 25 09:22:11 CET 2009 @390 /Internet Time/
; Link ..........:
; Related .......: _FFFormCheckBox, _FFFormOptionSelect, _FFFormReset, _FFFormSubmit
; Example .......: Yes
; ==============================================================================
Func _FFFormRadioButton($vRadioButton, $iRadioButtonIndex = 0, $sRadioButtonMode = "index", $vForm = 0, $sFormMode = "index")
	;Local $sFuncName = "_FFFormRadioButton"
	Local $RetVal = _FFFormCheckBox($vRadioButton, True, $iRadioButtonIndex, $sRadioButtonMode, $vForm, $sFormMode , False)
	SetError(@error)
	Return  $RetVal
EndFunc   ;==>_FFFormRadioButton

; #FUNCTION# ===================================================================
; Name ..........: _FFFormReset
; Description ...: Resets a form
; Beschreibung ..: Setzt ein Formular zur?ck.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFormReset([$vForm = 0[, $sMode = "index"]])
; Parameter(s): .: $vForm       - Optional: (Default = 0) : Index (0-n), name, id
;                  $sMode       - Optional: (Default = "index") :
;                               | Index
;                               | name
;                               | id
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 07 18:08:06 CEST 2009 @713 /Internet Time/
; Link ..........:
; Related .......: _FFFormCheckBox, _FFFormOptionSelect, _FFFormSubmit, _FFFormRadioButton
; Example .......: Yes
; ==============================================================================
Func _FFFormReset($vForm = 0, $sMode = "index")
	Local $sFuncName = "_FFFormReset"

	Local $sCommand

	Switch StringLower($sMode)
		Case "index"
			If Not IsInt($vForm) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vForm: " & $vForm))
				Return 0
			EndIf
			$sCommand = 'forms[' & $vForm & ']'
		Case "id"
			$sCommand = 'getElementById("' & $vForm & '")'
		Case "name"
			$sCommand = 'getElementsByName("' & $vForm & '")[0]'
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|id|name) $sMode: " & $sMode))
			Return 0
	EndSwitch

	$sCommand = StringFormat('window.content.document.%s.reset();', $sCommand)

	Local $sRetVal = _FFCmd($sCommand)
	If Not @error And $sRetVal <> "_FFCmd_Err" Then Return 1

	SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vForm: " & $vForm))
	Return 0

EndFunc   ;==>_FFFormReset

; #FUNCTION# ===================================================================
; Name ..........: _FFFormSubmit
; Description ...: Submits a form
; Beschreibung ..: Sendet ein Formular ab.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFFormSubmit([$vForm = 0[, $sMode = "index"[, $sSubmitMode = "submit"[, $bLoadWait = True]]]])
; Parameter(s): .: $vForm       - Optional: (Default = 0) : Index-number, name or id
;                  $sSubmitMode - Optional: (Default = "auto") :
;                               | auto
;                               | click
;                               | submit
;                               | keydown
;                               | keypress
;                  $bLoadWait   - Optional: (Default = true) :
;                               | True
;                               | False
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 07 17:56:46 CEST 2009 @706 /Internet Time/
; Link ..........:
; Related .......: _FFFormCheckBox, _FFFormOptionSelect, _FFFormReset, _FFFormRadioButton
; Example .......: Yes
; ==============================================================================
Func _FFFormSubmit($vForm = 0, $sMode = "index", $sSubmitMode = "submit", $bLoadWait = True)
	Local $sFuncName = "_FFFormSubmit"

	Local $sRetVal
	Local $iSubmit = -1, $iPassword = -1
	Local $bTrace
	$sMode = StringLower($sMode)

	If $sMode = "index" Then
		If IsInt($vForm) Then
			$vForm = 'forms[' & $vForm & ']'
		Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vForm: " & $vForm))
			Return 0
		EndIf
	ElseIf $sMode = "id" Then
		$vForm = "getElementById('" & $vForm & "')"
	ElseIf $sMode = "name" Then
		$vForm = "getElementsByName('" & $vForm & "')[0]"
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|id|name) $sMode: " & $sMode))
		Return 0
	EndIf

	Local $iLength = _FFCmd(StringFormat('.%s.elements.length;', $vForm))
	If $iLength = "_FFCmd_Err" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "No Elements found in form: " & $vForm))
		Return 0
	EndIf

	$bTrace = $_FF_COM_TRACE
	$_FF_COM_TRACE = False
	If $iLength > 0 And ($sSubmitMode = "enter" Or $sSubmitMode = "click" Or $sSubmitMode = "auto") Then
		For $i = 0 To $iLength - 1
			$sRetVal = _FFCmd(StringFormat('.%s.elements[%i].type;', $vForm, $i))
			If @error Then Return 0

			If $sRetVal = "submit" Then $iSubmit = $i
			If $sRetVal = "password" Then $iPassword = $i
			If $iSubmit > -1 And $iPassword > -1 Then ExitLoop
		Next
	EndIf
	$_FF_COM_TRACE = $bTrace

	Switch StringLower($sSubmitMode)
		Case "auto"
			ContinueCase
		Case "click"
			; clicks on the submit element
			$sRetVal = _FFCmd(StringFormat('.%s.elements[%i].click();', $vForm, $iSubmit), 3000)
			If Not @error And $sRetVal <> "_FFCmd_Err" Then
				If $bLoadWait Then
					If Not _FFLoadWait() And $sSubmitMode = "auto" Then ContinueCase
				EndIf
				Return 1
			Else
				If $sSubmitMode = "auto" Then ContinueCase
			EndIf
		Case "submit"
			; use form.submit()
			$sRetVal = _FFCmd(StringFormat('.%s.submit();', $vForm))
			If Not @error And $sRetVal <> "_FFCmd_Err" Then
				If $bLoadWait Then
					If Not _FFLoadWait() And $sSubmitMode = "auto" Then ContinueCase
				EndIf
				Return 1
			Else
				If $sSubmitMode = "auto" Then ContinueCase
			EndIf
		Case "keydown"
			; fire "enter" with keydown on the password element
			_FFDispatchKeyEvent(StringFormat(".%s.elements[%i]", $vForm, $iPassword), 13)
			If Not @error Then
				If $bLoadWait Then
					If Not _FFLoadWait() And $sSubmitMode = "auto" Then ContinueCase
				EndIf
				Return 1
			Else
				If $sSubmitMode = "auto" Then ContinueCase
			EndIf
		Case "keypress"
			; fire "enter" with keypress on the password element
			_FFDispatchKeyEvent(StringFormat('.%s.elements[%i]', $vForm, $iPassword), 13, "keypress")
			If Not @error Then
				If $bLoadWait Then
					If Not _FFLoadWait() Then Return 0
				EndIf
				Return 1
			EndIf
		Case Else
			Return 0
	EndSwitch

	Return 0

EndFunc   ;==>_FFFormSubmit

; #FUNCTION# ===================================================================
; Name ..........: _FFGetValueById
; Description ...: Gets an value of an element by ID
; Beschreibung ..: Liefert ein Value anhand der Element-Id
; AutoIt Version : V3.3.0.0
; Syntax ........:  _FFGetValueById($sID[, $iFilter = 0])
; Parameter(s): .: $sID         - ID of the element
;                  $iFilter     - Optional: (Default = 0) : you can add them:
;                               | 0 = No filter
;                               | 1 = Remove all non ASCII
;                               | 2 = Remove all double withespaces
;                               | 4 = Remove all double linefeeds
;                               | 8 = Remove all HTML-tags
;                               | 16 = simple html-tag / entities convertor
; Return Value ..: Success      - Value
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 15:16:22 CEST 2009 @594 /Internet Time/
; Link ..........:
; Related .......: _FFGetValueByName, _FFSetValueById, _FFSetValueByName, _FFXPath
; Example .......: Yes
; ==============================================================================
Func _FFGetValueById($sID, $iFilter = 0)
	Local $sFuncName = "_FFGetValueById"

	If $sID = "" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "Empty String: $sID"))
		Return ""
	EndIf
	If Not IsInt($iFilter) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iFilter: " & $iFilter))
		Return ""
	EndIf

	Local $sRndErr = "_FFGetValueById_Error"
	Local $sElement = "content.document.getElementById('" & $sID & "')"
	Local $sRetVal = _FFCmd(StringFormat("(%s != null ? %s.value : '%s');", $sElement, $sElement, $sRndErr), 3000)

	If $sRetVal <> $sRndErr Then
		If $iFilter > 0 Then __FFFilterString($sRetVal, $iFilter)
		Return $sRetVal
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sID: " & $sID))
		Return ""
	EndIf

EndFunc   ;==>_FFGetValueById

; #FUNCTION# ===================================================================
; Name ..........: _FFGetValueByName
; Description ...: Gets a value of an element by name.
; Beschreibung ..: Liefert ein Value anhand des Element-Namens
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFGetValueByName($sName[, $iIndex = 0[, $iFilter = 0]])
; Parameter(s): .: $sName       - Name of the element
;                  $iIndex      - Optional: (Default = 0) : Index of the element (0-n)
;                  $iFilter     - Optional: (Default = 0) : you can add them:
;                               | 0 = No filter
;                               | 1 = Remove all non ASCII
;                               | 2 = Remove all double withespaces
;                               | 4 = Remove all double linefeeds
;                               | 8 = Remove all HTML-tags
;                               | 16 = simple html-tag / entities convertor
; Return Value ..: Success      - Value
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 15:14:25 CEST 2009 @593 /Internet Time/
; Link ..........:
; Related .......: _FFGetValueById, _FFSetValueById, _FFSetValueByName, _FFXPath
; Example .......: Yes
; ==============================================================================
Func _FFGetValueByName($sName, $iIndex = 0, $iFilter = 0)
	Local $sFuncName =  "_FFGetValueByName"

	If $sName = "" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "Empty String: $sName"))
		Return ""
	EndIf
	If Not IsNumber($iIndex) Or $iIndex < 0 Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(int) >= 0 $iIndex: " & $iIndex))
		Return ""
	EndIf
	If Not IsInt($iFilter) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iFilter: " & $iFilter))
		Return ""
	EndIf

	Local $sRndErr = "_FFGetValueByName_Error"
	Local $sElement = "content.document.getElementsByName('" & $sName & "')[" & $iIndex & "]"
	Local $sRetVal = _FFCmd(StringFormat("(%s != null ? %s.value : '%s');", $sElement, $sElement, $sRndErr), 3000)

	If $sRetVal <> $sRndErr Then
		If $iFilter > 0 Then __FFFilterString($sRetVal, $iFilter)
		Return $sRetVal
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, $sName))
		Return ""
	EndIf

EndFunc   ;==>_FFGetValueByName

; #FUNCTION# ===================================================================
; Name ..........: _FFDispatchKeyEvent
; Description ...: Simulates a key-event on an element.
; Beschreibung ..: Simuliert ein Tastatur-Ereignis an einem Element.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFDisPatchKeyEvent($sObject, $iKeyCode[, $sEventType = "keydown"])
; Parameter(s): .: $sElement    - Element where the keyevent is fired
;                  $iKeyCode    - ASCII-KeyCode (decimal)
;                  $sEventType  - Optional: (Default = "keydown") :
;                               | keydown
;                               | keypress
;                               | keyup
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 15:21:38 CEST 2009 @598 /Internet Time/
; Link ..........:
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFDispatchKeyEvent($sElement, $iKeyCode, $sEventType = "keydown")
	Local $sFuncName = "_FFDispatchKeyEvent"

	If $iKeyCode < 0 Or $iKeyCode > 255 Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(int) $iKeyCode: 0-255" & $iKeyCode))
		Return 0
	EndIf
	$sEventType = StringLower($sEventType)

	Switch $sEventType
		Case "keydown"
		Case "keypress"
		Case "keyup"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(keydown|keypress|keyup) $sEventType: " & $sEventType))
			Return 0
	EndSwitch

	If StringLeft($sElement, 1) = "." Then $sElement = "content.frames[" & __FFGetStatus() & "].document" & $sElement

	Local $RetVal = _FFCmd("FFau3.simulateKey(" & $sElement & "," & $iKeyCode & ", '" & $sEventType & "');")
	If Not @error And $RetVal <> "_FFCmd_Err" Then
		Return $RetVal
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sElement: " & $sElement))
		Return 0
	EndIf

	Return 0
EndFunc   ;==>_FFDispatchKeyEvent

; #FUNCTION# ===================================================================
; Name ..........: _FFLoadWait
; Description ...: Wait while the page is loading.
; Beschreibung ..: Wartet bis die Seite geladen ist.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFLoadWait([$iDelay = 0[, $iTimeOut = 20000]])
; Parameter(s): .: $iDelay      - Optional: (Default = 0) : Delay before and after waiting in ms
;                  $iTimeOut    - Optional: (Default = 20000) : Timeout while waiting in ms
; Return Value ..: Success      - 1
;                  @EXTENDED    - loading time in ms
;                  Failure      - 0
;                  @ERROR       -
;                  @EXTENDED    - loading time in ms
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Jul 07 10:06:11 CEST 2009
; Link ..........: https://developer.mozilla.org/en/nsIWebProgress
; Related .......: _FFDialogWait
; Example .......: Yes
; ==============================================================================
Func _FFLoadWait($iDelay = 0, $iTimeOut = 20000)
	Local $sFuncName = "_FFLoadWait"

	Local $iLoadingTime = 0

	Local $bTrace = $_FF_COM_TRACE
	$_FF_COM_TRACE = False
	If Not $_FF_COM_TRACE Then ConsoleWrite("_FFLoadWait: ")
	If $iDelay = Default Then $iDelay = 0
	Sleep($iDelay + $_FF_CON_DELAY)

	Local $TimeOutTimer = TimerInit()

	While TimerDiff($TimeOutTimer) < $iTimeOut
		If Not $_FF_COM_TRACE Then ConsoleWrite(".")
		If Not _FFCmd("window.getBrowser().webProgress.isLoadingDocument") And _
				_FFCmd("window.getBrowser().webProgress.busyFlags") = 0 Then
			$iLoadingTime =  Round(TimerDiff($TimeOutTimer))
			ConsoleWrite(" loaded in " & $iLoadingTime & "ms" & @CRLF)
			Sleep($iDelay + $_FF_CON_DELAY + 25)
			$_FF_COM_TRACE = $bTrace
			Return SetError(0, $iLoadingTime - $_FF_CON_DELAY - 25 - $iDelay, 1)
		EndIf
		Sleep(250)
	WEnd
	$_FF_COM_TRACE = $bTrace
	ConsoleWrite(@CRLF & @CRLF)

	Return SetError(__FFError($sFuncName, $_FF_ERROR_Timeout, "Can not check site status."), $iLoadingTime,0)

EndFunc   ;==>_FFLoadWait

; #FUNCTION# ===================================================================
; Name ..........: _FFGetObjectInfo
; Description ...: Returns a 2-dimensional array with every information of an object.
; Beschreibung ..: Liefert ein 2-dimensionales Array mit allen Informationen ?ber ein Objekt.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFGetObjectInfo([$sObject = "window"])
; Parameter(s): .: $sObject     - Optional: (Default = "window") :
; Return Value ..: Success      - Array with object information
;                  Failure      -
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 23:05:55 CET 2009 @962 /Internet Time/
; Link ..........:
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFGetObjectInfo($sObject = "window")
	Local $sFuncName = "_FFGetObjectInfo"

	Local $aRet[1][2], $aTmp
	If StringLeft($sObject, 1) = "." Then $sObject = "window.content.document" & $sObject

	Local $aInfo = StringSplit(_FFCmd("repl.inspect(" & $sObject & ");"), @CRLF, 2)
	If Not @error And IsArray($aInfo) And $aInfo <> "_FFCmd_Err" Then
		ReDim $aRet[UBound($aInfo)][2]
		For $i = 0 To UBound($aInfo) - 1
			$aTmp = StringRegExp($aInfo[$i], "<object>.(.*?)=(.*?)$", 3)
			If Not @error And IsArray($aTmp) Then
				$aRet[$i][0] = $aTmp[0]
				$aRet[$i][1] = $aTmp[1]
			EndIf
		Next
		Return $aRet
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, $sObject))
		Return $aRet[0][0] = 0
	EndIf
EndFunc   ;==>_FFGetObjectInfo

; #FUNCTION# ===================================================================
; Name ..........: _FFOpenURL
; Description ...: Opens a new URL
; Beschreibung ..: ?ffnet eine URL.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFOpenURL($sURL[, $bWait = True])
; Parameter(s): .: $sURL        - URL or chrome (shortcut)
;                  $bLoadWait   - Optional: (Default = True) :
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 23:05:21 CET 2009 @962 /Internet Time/
; Link ..........:
; Related .......: _FFTabAdd
; Example .......: Yes
; ==============================================================================
Func _FFOpenURL($sURL, $bLoadWait = True)
	Local $sFuncName = "_FFOpenURL"

	If Not __FFCheckURL($sURL) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(URL) $sURL: " & $sURL))
		Return 0
	EndIf

	If StringLeft($sURL, 7) = "chrome:" Then $sURL = __FFChromeSelect(StringMid($sURL, 8))

	ConsoleWrite("_FFOpenURL: " & $sURL & @CRLF)

	Local $sRetVal = _FFCmd(StringFormat('.location.href="%s";', $sURL))
	If Not @error And $sRetVal = $sURL Then
		If $bLoadWait Then Return _FFLoadWait()
		Return 1
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, $sURL))
		Return 0
	EndIf

EndFunc   ;==>_FFOpenURL

; #FUNCTION# ===================================================================
; Name ..........: _FFPrefReset
; Description ...: Resets a config entry
; Beschreibung ..: Setzt einen Eintrag in der Config zur?ck
; Syntax ........: _FFPrefReset($sName)
; Parameter(s): .: $sName       - Name of the config entry
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Modified ......: Wed Mar 25 18:06:53 CET 2009 @754 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/nsIPrefBranch, http://kb.mozillazine.org/About:config_entries
; Related .......: _FFPrefSet, _FFPrefGet
; Example .......: Yes
; ==============================================================================
Func _FFPrefReset($sName)
	Local $sFuncName = "_FFPrefReset"

	Local $iType = _FFCmd('FFau3.obj=Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);FFau3.obj.getPrefType("' & $sName & '");')
	If @error Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sName: " & $sName))
		Return 0
	EndIf

	If $iType <> 0 Then
		If Not _FFCmd('FFau3.obj.prefHasUserValue("' & $sName & '");') Then Return 1

		_FFCmd('FFau3.obj.clearUserPref("' & $sName & '");')
		If Not @error Then Return 1
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sName: " & $sName))
	EndIf

	Return 0
EndFunc   ;==>_FFPrefReset

; #FUNCTION# ===================================================================
; Name ..........: _FFPrefGet
; Description ...: Gets a config entry
; Beschreibung ..: Lie?t einen Wert aus der Config aus
; Syntax ........: _FFPrefGet($sName)
; Parameter(s): .: $sName       - Name of the config entry
; Return Value ..: Success      - Value of the entry
;                  Failure      - 0 and sets @error
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Modified ......: Wed Mar 25 18:06:59 CET 2009 @754 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/nsIPrefBranch, http://kb.mozillazine.org/About:config_entries
; Related .......: _FFPrefSet, _FFPrefReset
; Example .......: Yes
; ==============================================================================
Func _FFPrefGet($sName)
	Local $sFuncName = "_FFPrefGet"

	Local $sCommand
	Local $iType = _FFCmd('FFau3.obj=Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch); FFau3.obj.getPrefType("' & $sName & '");')
	If @error Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, $sName))
		Return 0
	EndIf

	Switch $iType
		Case 0
			SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sName: " & $sName))
			Return 0
		Case 32 ; PREF_STRING
			$sCommand = "getCharPref"
		Case 64 ; PREF_INT
			$sCommand = "getIntPref"
		Case 128 ; PREF_BOOL
			$sCommand = "getBoolPref"
	EndSwitch

	$sCommand = StringFormat('FFau3.obj.%s("%s");', $sCommand, $sName)

	Return _FFCmd($sCommand)
EndFunc   ;==>_FFPrefGet

; #FUNCTION# ===================================================================
; Name ..........: _FFPrefSet
; Description ...: Sets a config entry
; Beschreibung ..: Setzt einen Wert in der Config.
; Syntax ........: _FFPrefSet($sName, $vValue)
; Parameter(s): .: $sName       - Name of the config entry
;                  $vValue      - Value of the config entry
; Return Value ..: Success      - 1 and sets @EXTENDED
;                  Failure      - 0
;                  @ERROR       -
;                  @EXTENDED    - Old value
; Author(s) .....: Thorsten Willert
; Modified ......: Wed Mar 25 18:07:07 CET 2009 @754 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/nsIPrefBranch, http://kb.mozillazine.org/About:config_entries
; Related .......: _FFPrefGet, _FFPrefReset
; Example .......: Yes
; ==============================================================================
Func _FFPrefSet($sName, $vValue)
	Local $sFuncName = "_FFPrefSet"

	Local $sCommand
	Local $iType = _FFCmd('FFau3.obj=Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);FFau3.obj.getPrefType("' & $sName & '");')
	If @error Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, $sName))
		Return 0
	EndIf
	Local $vOldValue = _FFPrefGet($sName)

	Switch $iType
		Case 0
			SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sName: " & $sName))
			Return 0
		Case 32 ; PREF_STRING
			If Not IsString($vValue) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(string) $vValue: " & $vValue))
				Return 0
			EndIf
			$sCommand = StringFormat('FFau3.obj.%s("%s","%s");', "setCharPref", $sName, $vValue)
		Case 64 ; PREF_INT
			If Not IsInt($vValue) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vValue: " & $vValue))
				Return 0
			EndIf
			$sCommand = StringFormat('FFau3.obj.%s("%s",%s);', "setIntPref", $sName, $vValue)
		Case 128 ; PREF_BOOL
			If Not IsBool($vValue) Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(bool) $vValue: " & $vValue))
				Return 0
			EndIf
			$sCommand = StringFormat('FFau3.obj.%s("%s",%s);', "setBoolPref", $sName, __FFB2S($vValue))
	EndSwitch

	_FFCmd($sCommand)
	If Not @error Then
		Local $vRetVal = _FFPrefGet($sName)
		If Not @error And $vRetVal = $vValue Then
			SetExtended($vOldValue)
			Return 1
		Else
			SetError(__FFError($sFuncName, $_FF_ERROR_RetValue, "$vValue <> " & $vRetVal))
			Return 0
		EndIf
	EndIf

	Return 0
EndFunc   ;==>_FFPrefSet

; #FUNCTION# ===================================================================
; Name ..........: _FFQuit
; Description ...: Quits FireFox
; Beschreibung ..: Schlie?t FireFox
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFQuit()
; Parameter(s): .:
; Return Value ..: Success      - 1 / $_FF_GLOBAL_SOCKET = -1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Sat Mar 14 14:44:55 CET 2009 @614 /Internet Time/
; Link ..........:
; Related .......: _FFDisConnect
; Example .......: Yes
; ==============================================================================
Func _FFQuit()
	Local $sFuncName = "_FFQuit"

	If $_FF_GLOBAL_SOCKET = -1 Then Return
	If Not __FFIsSocket($_FF_GLOBAL_SOCKET) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_SocketError))
		Return 0
	EndIf

	TCPSend($_FF_GLOBAL_SOCKET, "close()" & @CRLF)
	If Not @error Then
		__FFRemoveStatus()
		$_FF_GLOBAL_SOCKET = -1
		If $_FF_COM_TRACE Then ConsoleWrite('__FFQuit: Closing FireFox ...' & @CRLF)
		Return 1
	Else
		Return 0
	EndIf

EndFunc   ;==>_FFQuit

; #FUNCTION# ===================================================================
; Name ..........: _FFReadHTML
; Description ...: Returns the HTML-source code of a page.
; Beschreibung ..: Liefert den HTMl-Quellcode einer Seite.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFReadHTML([$sMode = "body"[, $iFilter = 0]])
; Parameter(s): .: $sMode       - Optional: (Default = "body") :
;                               | body = innerHTML from <body>
;                               | html = innerHTML from <html>
;                  $iFilter     - Optional: (Default = 0) : you can add them:
;                               | 0 = No filter
;                               | 1 = Remove all non ASCII
;                               | 2 = Remove all double withespaces
;                               | 4 = Remove all double linefeeds
;                               | 8 = Remove all HTML-tags
;                               | 16 = simple html-tag / entities convertor
; Return Value ..: Success      - String with the HTML-source code
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:55:56 CET 2009 @955 /Internet Time/
; Link ..........:
; Related .......: _FFReadText, _FFXPath
; Example .......: Yes
; ==============================================================================
Func _FFReadHTML($sMode = "body", $iFilter = 0)
	Local $sFuncName = "_FFReadHTML"

	Local $sCommand

	Switch StringLower($sMode)
		Case "body"
			$sCommand = ".body"
		Case "html"
			$sCommand = ".documentElement"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(body|html) $sMode: " & $sMode))
			Return 0
	EndSwitch

	Local $sRetVal = _FFCmd($sCommand & ".innerHTML;", 10000)
	If Not @error And $sRetVal <> "_FFCmd_Err" Then
		If $iFilter > 0 Then $sRetVal = __FFFilterString($sRetVal, $iFilter)
		Return $sRetVal
	Else
		SetError(1)
		Return ""
	EndIf
EndFunc   ;==>_FFReadHTML

; #FUNCTION# ===================================================================
; Name ..........: _FFReadText
; Description ...: Returns the text of a page.
; Beschreibung ..: Liefert den Text einer Seite.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFReadText([$iFilter = 0])
; Parameter(s): .: $iFilter     - Optional: (Default = 0) : you can add them:
;                               | 0 = No filter
;                               | 1 = Remove all non ASCII
;                               | 2 = Remove all double withespaces
;                               | 4 = Remove all double linefeeds
;                               | 8 = Remove all HTML-tags
;                               | 16 = simple html-tag / entities convertor
; Return Value ..: Success      - String
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:55:05 CET 2009 @954 /Internet Time/
; Link ..........:
; Related .......: _FFReadHTML, _FFXPath
; Example .......: Yes
; ==============================================================================
Func _FFReadText($iFilter = 0)
	;Local $sFuncName = "_FFReadText"

	Local $sRetVal = _FFCmd(".documentElement.textContent;", 10000)
	If Not @error And $sRetVal <> "_FFCmd_Err" Then
		If $iFilter > 0 Then $sRetVal = __FFFilterString($sRetVal, $iFilter)
		Return $sRetVal
	Else
		SetError(1)
		Return ""
	EndIf
EndFunc   ;==>_FFReadText

; #FUNCTION# ===================================================================
; Name ..........: _FFSearch
; Description ...: Searches a string
; Beschreibung ..: Sucht einen Text.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFSearch($sSearchString[, $bCaseSensitive = false[, $bBackwards = false[, $bWrapAround = true[, $bWholeWord = false[, $bSearchInFrames = true]]]]])
; Parameter(s): .: $sSearchString - String to search
;                  $bCaseSensitive - Optional: (Default = false) :
;                  $bBackwards  - Optional: (Default = false) :
;                  $bWrapAround - Optional: (Default = true) :
;                  $bWholeWord  - Optional: (Default = false) :
;                  $bSearchInFrames - Optional: (Default = true) :
; Return Value ..: Success      - 1
;                  Failure      - 0 and sets
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:54:33 CET 2009 @954 /Internet Time/
; Link ..........:
; Related .......: _FFAction("search")
; Example .......: Yes
; ==============================================================================
Func _FFSearch($sSearchString, $bCaseSensitive = False, $bBackwards = False, $bWrapAround = True, $bWholeWord = False, $bSearchInFrames = True)
	Local $sFuncName = "_FFSearch"

	If $sSearchString = "" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "Empty String $sSearchString"))
		Return ""
	EndIf

	If $bCaseSensitive = Default Then $bCaseSensitive = False
	If $bBackwards = Default Then $bBackwards = False
	If $bWrapAround = Default Then $bWrapAround = True
	If $bWholeWord = Default Then $bWholeWord = False
	If $bSearchInFrames = Default Then $bSearchInFrames = True

	Local $sCommand = 'content.find("' & $sSearchString & '", ' & _
			__FFB2S($bCaseSensitive) & ', ' & _
			__FFB2S($bBackwards) & ', ' & _
			__FFB2S($bWrapAround) & ', ' & _
			__FFB2S($bWholeWord) & ', ' & _
			__FFB2S($bSearchInFrames) & ', false);'

	Local $RetVal = _FFCmd($sCommand)
	If Not @error And $RetVal <> "_FFCmd_Err" Then
		Return 1
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sSearchString: " & $sSearchString))
		Return 0
	EndIf
EndFunc   ;==>_FFSearch

; #FUNCTION# ===================================================================
; Name ..........: _FFCmd
; Description ...: Send and receive data from Firefox.
; Beschreibung ..: Sendet und empf?ngt Daten von FireFox.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFCmd($sArg[, $iTimeOut = 30000[, $bTry = True]])
; Parameter(s): .: $sArg        - Any JavaScript
;                  $iTimeOut    - Optional: (Default = 30000) :
; Return Value ..: Success      - String
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Wed Apr 15 10:25:14 CEST 2009
; Link ..........:
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFCmd($sArg, $iTimeOut = 30000, $bTry = True)
	Local $sFuncName = "_FFCmd"
	Local $sRet

	If StringLeft($sArg, 1) = "." Then $sArg = "window.content.document" & $sArg

	If $bTry And Not StringInStr(StringLower($sArg),"try") Then $sArg = "try{" & $sArg & "}catch(e){'_FFCmd_Err';};"

	Local $sArgWrapped = StringReplace($sArg,"window.content.document", "window.content.wrappedJSObject.document")

	Local $iFrameSelected = _FFFrameGetSelected()
	;Msgbox(64,"",$iFrameSelected)
	If $iFrameSelected > -1 Or $iFrameSelected <> '"top"' Then
		$sArg = StringReplace($sArg, "window.content.document", "window.content.frames[" & $iFrameSelected & "].document")
		$sArgWrapped = StringReplace($sArgWrapped, "window.content.wrappedJSObject.document", "window.content.wrappedJSObject.frames[" & $iFrameSelected & "].document")
	EndIf


	If StringInStr($sArg,"evaluate") Or Not StringRegExp($sArg,"\.[a-zA-z]+\(.*?\)(\[.+\])?\.", 0) Then
		If __FFSend($sArg) Then
			$sRet = __FFRecv($iTimeOut)
			If Not @error And String($sRet) <> "_FFCmd_Err" Then
				Return $sRet
			ElseIf StringInStr($sArgWrapped,"wrappedJSObject") Then
				__FFSend($sArgWrapped)
				$sRet = __FFRecv($iTimeOut)
				If Not @error And String($sRet) <> "_FFCmd_Err" Then Return $sRet
			EndIf
		EndIf
	Else
		__FFSend($sArgWrapped)
		$sRet = __FFRecv($iTimeOut)
		If Not @error And String($sRet) <> "_FFCmd_Err" Then Return $sRet
	EndIf

	SetError(__FFError($sFuncName, $_FF_ERROR_RetValue, $sRet))
	Return ""
EndFunc   ;==>_FFCmd

; #FUNCTION# ===================================================================
; Name ..........: _FFSetValueById
; Description ...: Sets a value of an element by ID
; Beschreibung ..: Setzt einen Wert (value) anhand der Element-Id
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFSetValueById($sID[, $sValue = ""])
; Parameter(s): .: $sID         - ID of the element
;                  $sValue      - Optional: (Default = "") : Value to set
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 22:48:10 CEST 2009 @908 /Internet Time/
; Link ..........:
; Related .......: _FFSetValueByName, _FFGetValueById, _FFGetValueByName, _FFXPath
; Example .......: Yes
; ==============================================================================
Func _FFSetValueById($sID, $sValue = "")
	Local $sFuncName = "_FFSetValueById"

	If $sID = "" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "Empty String $sID"))
		Return 0
	EndIf

	__FFValue2JavaScript($sValue)

	Local $sRetVal = _FFCmd(StringFormat(".getElementById('%s').value='%s';", $sID, $sValue), 3000)
	If $sRetVal <> "_FFCmd_Err" Then
		Return 1
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sID: " & $sID))
		Return 0
	EndIf

EndFunc   ;==>_FFSetValueById

; #FUNCTION# ===================================================================
; Name ..........: _FFSetValueByName
; Description ...: Sets a value of an element by Name
; Beschreibung ..: Setzt einen Wert (value) anhand des Element-Namens.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFSetValueByName($sName[, $sValue = ""[, $iIndex = 0]])
; Parameter(s): .: $sName       - Name of the element
;                  $sValue      - Optional: (Default = "") : Value to set
;                  $iIndex      - Optional: (Default = 0) : Index of the element (0-n)
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 09 22:58:50 CEST 2009 @915 /Internet Time/
; Link ..........:
; Related .......: _FFSetValueById, _FFGetValueById, _FFGetValueByName, _FFXPath
; Example .......: Yes
; ==============================================================================
Func _FFSetValueByName($sName, $sValue = "", $iIndex = 0)
	Local $sFuncName = "_FFSetValueByName"

	If $sName = "" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "Empty String $sName: " & $sName))
		Return 0
	EndIf
	If Not IsNumber($iIndex) Or $iIndex < 0 Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(int) $iIndex: " & $iIndex))
		Return 0
	EndIf

	__FFValue2JavaScript($sValue)

	Local $sRetVal = _FFCmd(StringFormat(".getElementsByName('%s')[%s].value='%s';", $sName, $iIndex, $sValue), 3000)
	If $sRetVal <> "_FFCmd_Err" Then
		Return 1
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sName: " & $sName))
		Return 0
	EndIf

EndFunc   ;==>_FFSetValueByName

; #FUNCTION# ===================================================================
; Name ..........: _FFStart
; Description ...: Starts FireFox
; Beschreibung ..: Startet FireFox
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFStart([$sURL = "about:blank"[, $sProfile = "default"[, $iMode = 1[, $bHide = False[, $IP = "127.0.0.1"[, $iPort = 4242]]]]]])
; Parameter(s): .: $sURL        - Optional: (Default = "about:blank") : Start URL
;                  $sProfile    - Optional: (Default = "default") : User profile
;                  $iMode       - Optional: (Default = 1) : Start mode:
;                               | 0 = Connect to existing process
;                               | 1 = Start new process
;                               | 2 = Connect to an existing process, on failure start a new process
;                               | +8 = Starting FF with parameter -no-remote
;                  $bHide       - Optional: (Default = False) : Start in hidden mode
;                  $IP          - Optional: (Default = "127.0.0.1") : IP of MozRepl
;                  $iPort       - Optional: (Default = 4242) : Port number of MozRepl
; Return Value ..: Success      - 1
;                  @EXTENDED    - PID
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 30 22:10:07 CEST 2009
; Link ..........:
; Related .......: _FFQuit, _FFConnect, _FFDisConnect, _FFIsConnected
; Example .......: Yes
; ==============================================================================
Func _FFStart($sURL = "about:blank", $sProfile = "default", $iMode = 1, $bHide = False, $IP = "127.0.0.1", $iPort = 4242)
	Local $sFuncName = "_FFStart"

	; Default parameters
	If $sURL = Default Then $sURL = "about:blank"
	If $IP = Default Then $IP = "127.0.0.1"
	If $iPort = Default Then $iPort = 4242

	If Not __FFCheckURL($sURL) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(URL) $sURL: " & $sURL))
		Return 0
	EndIf
	If Not __FFIsIP($IP) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(IP) $IP: " & $IP))
		Return 0
	EndIf
	If Not __FFIsPort($iPort) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(PORT) $iPort: " & $iPort))
		Return 0
	EndIf

	; Default parameters
	If $sProfile = Default Then $sProfile = "default"
	If $iMode = Default Then $iMode = 1
	If $bHide = Default Then $bHide = False

	Local $PID = -1, $bNoRemote = False

	If $iMode >= 8 Then
		$iMode -= 8
		$bNoRemote = True
	EndIf

	Switch $iMode
		Case 2
			ContinueCase
		Case 0
			If ProcessExists($_FF_PROC_NAME) Then _FFConnect($IP, $iPort)
			If $_FF_GLOBAL_SOCKET > -1 Then
				_FFOpenURL($sURL)
			ElseIf $iMode = 2 Then
				ContinueCase
			EndIf
		Case 1
			__FFStartProcess($sURL, True, $sProfile, $bNoRemote, $bHide, $iPort)
			$PID = @EXTENDED
			If ProcessExists($_FF_PROC_NAME) Then _FFConnect($IP, $iPort)
			If $_FF_GLOBAL_SOCKET > -1 Then _FFLoadWait()
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$iMode: " & $iMode))
			Return 0
	EndSwitch

	If $bHide Then
		Local $hWin = _FFWindowGetHandle()
		WinSetState($hWin, "", @SW_HIDE)
	EndIf

	SetExtended($PID)
	Return 1
EndFunc   ;==>_FFStart

; #FUNCTION# ===================================================================
; Name ..........: _FFTabAdd
; Description ...: Opens a new tab.
; Beschreibung ..: ?ffnet einen neuen Tab
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabAdd([$sURL = "about:blank"[, $bSelect = True[, $bLoadWait = True]]])
; Parameter(s): .: $sURL        - Optional: (Default = "about:blank") :
;                  $bSelect     - Optional: (Default = true) : Select new tab
;                  $bLoadWait   - Optional: (Default = true) : Wait while the page is loading
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:44:43 CET 2009 @947 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......: _FFTabDuplicate, _FFTabClose, _FFTabCloseAll, _FFTabExists, _FFTabGetLength, _FFTabSetSelected, _FFTabGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabAdd($sURL = "about:blank", $bSelect = True, $bLoadWait = True)
	Local $sFuncName = "_FFOpenURL"

	If $sURL = Default Then $sURL = "about:blank"
	If Not __FFCheckURL($sURL) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(URL) $sURL: " & $sURL))
		Return 0
	EndIf

	If $bSelect Then
		_FFCmd("gBrowser.selectedTab = gBrowser.addTab('" & $sURL & "')", 3000)
		If Not @error Then
			If $bLoadWait Then Return _FFLoadWait()
			Return 1
		EndIf
	Else
		_FFCmd("gBrowser.loadOneTab('" & $sURL & "',null,null,null,true)", 3000)
		If Not @error Then
			If $bLoadWait Then Return _FFLoadWait()
			Return 1
		EndIf
	EndIf

	Return 0

EndFunc   ;==>_FFTabAdd

; #FUNCTION# ===================================================================
; Name ..........: _FFTabClose
; Description ...: Closes one or all existing tabs.
; Beschreibung ..: Schlie?t einen oder alle vorhandenen Tabs.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabClose([$vTab = -1[, $sMode = "index"]])
; Parameter(s): .: $vTab        - Optional: (Default = -1 = current tab) :
;                               | index (0-n)
;                               | label
;                               | prev
;                               | next
;                               | first
;                               | last
;                               | all (except current)
;                  $sMode       - Optional: (Default = "index") :
;                               | index
;                               | label
;                               | key or keyword
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:44:10 CET 2009 @947 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......: _FFTabAdd, _FFTabDuplicate, _FFTabCloseAll, _FFTabExists, _FFTabGetLength, _FFTabSetSelected, _FFTabGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabClose($vTab = -1, $sMode = "index")
	Local $sFuncName = "_FFTabClose"

	Local $sCommand, $iIndex
	;Local $bWarn
	Local $iLength = _FFGetLength("tabs")

	Switch StringLower($sMode)
		Case "index"
			If $vTab = -1 Then
				$sCommand = "gBrowser.removeCurrentTab();"
			ElseIf $vTab > -1 And $vTab < $iLength Then
				$sCommand = "gBrowser.removeTab(gBrowser.mTabs[" & $vTab & "]);"
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(int) $vTab: " & $vTab))
				Return 0
			EndIf
		Case "label"
			$iIndex = _FFTabExists($vTab)
			If $iIndex >= 0 Then
				$sCommand = "gBrowser.removeTab(gBrowser.mTabs[" & $iIndex & "]);"
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vTab: " & $vTab))
				Return 0
			EndIf
		Case "key" Or "keyword"
			Switch StringLower($vTab)
				Case "prev"
					$sCommand = "gBrowser.removeTab(gBrowser.mTabs[gBrowser.tabContainer.selectedIndex-1]);"
				Case "next"
					$sCommand = "gBrowser.removeTab(gBrowser.mTabs[gBrowser.tabContainer.selectedIndex+1]);"
				Case "first"
					$sCommand = "gBrowser.removeTab(gBrowser.mTabs[0]);"
				Case "last"
					$sCommand = "gBrowser.removeTab(gBrowser.mTabs[gBrowser.tabContainer.childNodes.length-1]);"
				Case "all"
					; browser.tabs.warnOnClose
					$sCommand = "gBrowser.removeAllTabsBut(gBrowser.selectedTab);"
				Case Else
					SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(prev|next|first|last|all) $vTab: " & $vTab))
					Return 0
			EndSwitch
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|label|key|keyword) $sMode: " & $sMode))
			Return 0
	EndSwitch

	If _FFCmd($sCommand & "gBrowser.tabContainer.childNodes.length", 3000) < $iLength - 1 Then
		Sleep(100)
		Return 1
	EndIf

	Return 0
EndFunc   ;==>_FFTabClose

; #FUNCTION# ===================================================================
; Name ..........: _FFTabCloseAll
; Description ...: Closes all Tabs except the selected
; Beschreibung ..: Schlie?t alle Tabs, au?er dem Aktiven.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabCloseAll()
; Parameter(s): .:
; Return Value ..: Success      - 1
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:43:12 CET 2009 @946 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......:_FFTabAdd, _FFTabDuplicate, _FFTabClose, _FFTabExists, _FFTabGetLength, _FFTabSetSelected, _FFTabGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabCloseAll()
	;Local $sFuncName = "_FFTabCloseAll"
	Return _FFTabClose("all", "key")
EndFunc   ;==>_FFTabCloseAll

; #FUNCTION# ===================================================================
; Name ..........: _FFTabDuplicate
; Description ...: Duplicates a tab
; Beschreibung ..: Dupliziert einen Tab
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabDuplicate([$vTab = -1[, $sMode = "index"[, $bSelect = False]]])
; Parameter(s): .: $vTab        - Optional: (Default = -1) : Tab to duplicate, -1 = current tab
;                  $sMode       - Optional: (Default = "index") :
;                               | index
;                               | label
;                  $bToFront    - Optional: (Default = false) : Bring duplicated tab to front
; Return Value ..: Success      - Lenght of tabs >= 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:42:05 CET 2009 @945 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......: _FFTabAdd, _FFTabClose, _FFTabCloseAll, _FFTabExists, _FFTabGetLength, _FFTabSetSelected, _FFTabGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabDuplicate($vTab = -1, $sMode = "index", $bSelect = False)
	Local $sFuncName = "_FFTabDuplicate"

	If $sMode = "index" And Not IsInt($vTab) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vTab: " & $vTab))
		Return 0
	EndIf

	If $vTab = Default Then $vTab = -1
	If $sMode = Default Then $sMode = "index"

	Local $iRet, $iIndex
	Local $sCommand

	Switch StringLower($sMode)
		Case "index"
			If $vTab = -1 Then
				$sCommand = "gBrowser.duplicateTab(gBrowser.mCurrentTab);"
			ElseIf $vTab >= 0 And $vTab < _FFGetLength("tabs") Then
				$sCommand = "gBrowser.duplicateTab(gBrowser.mTabs[" & $vTab & "]);"
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$vTab: " & $vTab))
				Return 0
			EndIf
		Case "label"
			$iIndex = _FFTabExists($vTab)
			If $iIndex >= 0 Then
				$sCommand = "gBrowser.duplicateTab(gBrowser.mTabs[" & $iIndex & "]);"
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vTab: " & $vTab))
				Return 0
			EndIf
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|label) $sMode: " & $sMode))
			Return 0
	EndSwitch

	$iRet = _FFCmd($sCommand & "gBrowser.tabContainer.childNodes.length;", 3000)

	If $bSelect Then _FFTabSetSelected("last")

	Return $iRet

EndFunc   ;==>_FFTabDuplicate

; #FUNCTION# ===================================================================
; Name ..........: _FFTabExists
; Description ...: Checks if a tab exists
; Beschreibung ..: Pr?ft ob ein Tab existiert.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabExists($sLabel)
; Parameter(s): .: $sLabel      - Label of the tab (substring or RegEx)
; Return Value ..: Success      - Tab index 0-n
;                  Failure      - -1
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 30 20:33:33 CEST 2009 @814 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......: _FFTabAdd, _FFTabDuplicate, _FFTabClose, _FFTabCloseAll, _FFTabGetLength, _FFTabSetSelected, _FFTabGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabExists($sLabel)
	Local $sFuncName = "_FFTabExists"

	_FFLoadWait()
	Local $RetVal = Int(_FFCmd("FFau3.SearchTab('" & $sLabel & "')", 3000))
	Switch @error
		Case $_FF_ERROR_Success
			If $RetVal > -1 Then
				Return $RetVal
			ElseIf $RetVal = -3 Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidExpression, "$sLabel: " & $sLabel))
				Return -1
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sLabel: " & $sLabel))
				Return -1
			EndIf
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError))
			Return -1
	EndSwitch
EndFunc   ;==>_FFTabExists

; #FUNCTION# ===================================================================
; Name ..........: _FFTabGetLength
; Description ...: Length of the tabs
; Beschreibung ..: Liefert die Anzahl aller vorhandener Tabs.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabGetLength()
; Parameter(s): .:
; Return Value ..: Success      - Tab index 0-n
;                  Failure      - -1
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:39:15 CET 2009 @943 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......: _FFTabAdd, _FFTabDuplicate, _FFTabClose, _FFTabCloseAll, _FFTabExists, _FFTabSetSelected, _FFTabGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabGetLength()
	;Local $sFuncName = "_FFTabGetLength"
	Return _FFGetLength("tabs")
EndFunc   ;==>_FFTabGetLength

; #FUNCTION# ===================================================================
; Name ..........: _FFTabSetSelected
; Description ...: Select a tab
; Beschreibung ..: W?hlt ein Tab aus.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabSetSelected([$vTab = 0[, $sMode = "index"]])
; Parameter(s): .: $vTab        - Optional: (Default = 0) :
;                               | index (0-n)
;                               | label = Substring or RegEx
;                               | prev
;                               | next
;                               | first
;                               | last
;                  $sMode       - Optional: (Default = "index") :
;                               | index
;                               | label
;                               | otherwise the keywords in $vTab are used
; Return Value ..: Success      -
;                  Failure      - -1
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 23 09:03:25 CEST 2009
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......: _FFTabAdd, _FFTabDuplicate, _FFTabClose, _FFTabCloseAll, _FFTabExists, _FFTabGetLength, _FFTabGetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabSetSelected($vTab = 0, $sMode = "index")
	Local $sFuncName = "_FFTabSetSelected"

	Local $sCommand = "gBrowser.tabContainer"

	If $sMode = "index" Then
		$sCommand &= ".selectedIndex = " & $vTab
	ElseIf $sMode = "label" Then
		Local $iIndex = _FFTabExists($vTab)
		If $iIndex > -1 Then
			$sCommand &= ".selectedIndex = " & $iIndex
		Else
			Return -1
		EndIf
	Else
		Switch StringLower($vTab)
			Case "prev"
				$sCommand &= ".advanceSelectedTab( -1, true )"
			Case "next"
				$sCommand &= ".advanceSelectedTab( 1, true )"
			Case "first"
				$sCommand &= ".selectedIndex = 0"
			Case "last"
				$sCommand &= ".selectedIndex = gBrowser.tabContainer.childNodes.length -1"
			Case Else
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|label|prev|next|first|last) $sMode: " & $sMode))
				Return -1
		EndSwitch
	EndIf

	Local $RetVal = _FFCmd($sCommand, 3000)
	Sleep(50)
	Return $RetVal

EndFunc   ;==>_FFTabSetSelected

; #FUNCTION# ===================================================================
; Name ..........: _FFTabGetSelected
; Description ...: Returns the name or the index of the selected tab.
; Beschreibung ..: Gibt den Namen (label) oder den Index des aktuellen Tabs zur?ck.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTabGetSelected([$sMode = "index"])
; Parameter(s): .: $sMode       - Optional: (Default = "index") :
;                               | index
;                               | label
; Return Value ..: Success      - Tab index 0-n or label
;                  Failure      - -1
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 23 08:52:13 CEST 2009 @327 /Internet Time/
; Link ..........: https://developer.mozilla.org/en/XUL/tabs
; Related .......: _FFTabAdd, _FFTabDuplicate, _FFTabClose, _FFTabCloseAll, _FFTabExists, _FFTabGetLength, _FFTabSetSelected
; Example .......: Yes
; ==============================================================================
Func _FFTabGetSelected($sMode = "index")
	Local $sFuncName = "_FFTabGetSelected"

	_FFLoadWait()
	Switch StringLower($sMode)
		Case "index"
			Return Int(_FFCmd("gBrowser.tabContainer.selectedIndex", 3000))
		Case "label"
			Return _FFCmd("gBrowser.mTabs[gBrowser.tabContainer.selectedIndex].label", 3000)
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|label) $sMode: " & $sMode))
			Return -1
	EndSwitch

EndFunc   ;==>_FFTabGetSelected

; #FUNCTION# ===================================================================
; Name ..........: _FFTableWriteToArray
; Description ...: Writes a HTML-table to an array
; Beschreibung ..: Kopiert eine HTML-Tabelle in ein Array.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTableWriteToArray($vTable[, $sMode = "index"[, $sReturnMode = "text"[, $bTransponse = False]]])
; Parameter(s): .: $vTable      - Table selection by $sMode
;                  $sMode       - Optional: (Default = "index") :
;                               | index (0-n)
;                               | name
;                               | id
;                  $sReturnMode - Optional: (Default = "text") :
;                               | text
;                               | html
;                  $bTransponse - Optional: (Default = False) : Switch Rows and Columns
; Return Value ..: Success      - Array containing contents of the table
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Johannes Schirmer, Thorsten Willert
; Date ..........: Mon Mar 23 22:36:35 CET 2009 @942 /Internet Time/
; Link ..........:
; Related .......: _FFTableGetCell
; Example .......: Yes
; ==============================================================================
Func _FFTableWriteToArray($vTable, $sMode = "index", $sReturnMode = "text", $bTransponse = False)
	Local $sFuncName = "_FFTableWriteToArray"

	Local $sArg

	If IsInt($vTable) And $sMode = "index" And $vTable < _FFGetLength("tables") Then
		$sArg = "content.document.getElementsByTagName('tbody')[" & $vTable & "]"
	ElseIf $sMode = "name" Or $sMode = "id" Then
		$sArg = "content.document." & $vTable
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sMode: " & $sMode))
		Return 0
	EndIf
	If $sReturnMode = "text" Then
		$sReturnMode = ".textContent"
	ElseIf $sReturnMode = "html" Then
		$sReturnMode = ".innerHTML"
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sReturnMode: " & $sReturnMode))
		Return 0
	EndIf
	If Not IsBool($bTransponse) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$bTransponse: " & $bTransponse))
		Return 0
	EndIf

	_FFCmd($sArg, 3000)
	If @error Then
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$vTable: " & $vTable & ", $sMode: " & $sMode))
		Return 0
	EndIf

	Local $i_cols = 0, $trs, $tds, $i_col, $col, $row
	$trs = _FFCmd($sArg & ".getElementsByTagName('tr').length", 3000)
	For $i = 0 To $trs - 1
		$tds = _FFCmd($sArg & ".getElementsByTagName('tr')[" & $i & "].getElementsByTagName('td').length", 3000)
		$i_col = 0
		For $i2 = 0 To $tds - 1
			$i_col = $i_col + _FFCmd($sArg & ".getElementsByTagName('tr')[" & $i & "].getElementsByTagName('td')[" & $i2 & "].colSpan", 3000)
		Next
		If $i_col > $i_cols Then $i_cols = $i_col
	Next
	Local $a_TableCells[$i_cols][$trs]
	$row = 0
	For $i = 0 To $trs - 1
		$tds = _FFCmd($sArg & ".getElementsByTagName('tr')[" & $i & "].getElementsByTagName('td').length", 3000)
		$col = 0
		For $i2 = 0 To $tds - 1
			$a_TableCells[$col][$row] = _FFCmd($sArg & ".getElementsByTagName('tr')[" & $i & "].getElementsByTagName('td')[" & $i2 & "]" & $sReturnMode, 3000)
			$col = $col + _FFCmd($sArg & ".getElementsByTagName('tr')[" & $i & "].getElementsByTagName('td')[" & $i2 & "].colSpan", 3000)
		Next
		$row = $row + 1
	Next

	If $bTransponse Then
		Local $i_d1 = UBound($a_TableCells, 1), $i_d2 = UBound($a_TableCells, 2), $aTmp[$i_d2][$i_d1]
		For $i = 0 To $i_d2 - 1
			For $j = 0 To $i_d1 - 1
				$aTmp[$i][$j] = $a_TableCells[$j][$i]
			Next
		Next
		$a_TableCells = $aTmp
	EndIf
	Return $a_TableCells
EndFunc   ;==>_FFTableWriteToArray

; #FUNCTION# ===================================================================
; Name ..........: _FFTableGetCell
; Description ...: Returns the content of a table cell.
; Beschreibung ..: Liefert den Inhalt einer Tabellenzelle.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFTableGetCell($vTable, $iColumn, $iRow[, $sMode = "index"[, $sReturnMode = "text"[, $iFilter = 1]]])
; Parameter(s): .: $vTable      - index (0-n), name or id
;                  $iColumn     - Column (0-n)
;                  $iRow        - Row (0-n)
;                  $sMode       - Optional: (Default = "index") :
;                               | index (0-n)
;                               | name
;                               | id
;                  $sReturnMode - Optional: (Default = "text") :
;                               | text
;                               | html
;                  $iFilter     - Optional: (Default = 1) : you can add them:
;                               | 0 = No filter
;                               | 1 = Remove all non ASCII
;                               | 2 = Remove all double withespaces
;                               | 4 = Remove all double linefeeds
;                               | 8 = Remove all HTML-tags
;                               | 16 = simple html-tag / entities convertor
; Return Value ..: Success      - Text or HTML
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Sat Apr 11 22:56:21 CEST 2009
; Link ..........:
; Related .......: _FFTableWriteToArray
; Example .......: Yes
; ==============================================================================
Func _FFTableGetCell($vTable, $iColumn, $iRow, $sMode = "index", $sReturnMode = "text", $iFilter = 1)
	Local $sFuncName = "_FFTableGetCell"

	If $sMode = Default Then $sMode = "index"
	If $sReturnMode = Default Then $sReturnMode = "text"

	If Not IsInt($vTable) And $sMode = "index" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vTable: " & $vTable))
		Return ""
	EndIf
	If Not IsInt($iColumn) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iColumn: " & $iColumn))
		Return ""
	EndIf
	If Not IsInt($iRow) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iRow: " & $iRow))
		Return ""
	EndIf
	Switch StringLower($sReturnMode)
		Case "text"
			$sReturnMode = "textContent"
		Case "html"
			$sReturnMode = "innerHTML"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(text|html) $sReturnMode: " & $sReturnMode))
			Return ""
	EndSwitch

	Local $sObject = "content.document"

	Switch StringLower($sMode)
		Case "index"
			$sObject &= ".getElementsByTagName('tbody')[" & $vTable & "]"
		Case "name"
			ContinueCase
		Case "id"
			$sObject &= ".getElementsByTagName('tbody')['" & $vTable & "']"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(index|name|id) $sMode: " & $sMode))
			Return ""
	EndSwitch

	$sObject &= StringFormat(".getElementsByTagName('tr')[%i].getElementsByTagName('td')[%i]", $iRow, $iColumn)

	Local $sRetVal = _FFCmd($sObject & "." & $sReturnMode & ";")
	If Not @error And $sRetVal <> "_FFCmd_Err" Then
		If $iFilter > 0 Then __FFFilterString($sRetVal, $iFilter)
		Return $sRetVal
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "Table/Column/Row: " & $vTable & "/" & $iColumn & "/" & $iRow))
		Return ""
	EndIf

EndFunc   ;==>_FFTableGetCell

; #FUNCTION# ===================================================================
; Name ..........: _FFWindowClose
; Description ...: Closes a browser window
; Beschreibung ..: Schlie?t ein Browser Fenster.
; Syntax ........: _FFWindowClose([$sSearch = ""[, $sSearchMode = "title"]])
; Parameter(s): .: $sSearch     - Optional: (Default = "") : "" = current window, Substring to search
;                  $sSearchMode - Optional: (Default = "title") :
;                               | "title" window title
;                               | "label" tab label
;                               | "href" current url
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:33:01 CET 2009 @939 /Internet Time/
; Link ..........: https://developer.mozilla.org/En/DOM/Window, https://developer.mozilla.org/En/NsIWindowMediator
; Related .......: _FFWindowSelect, _FFWindowOpen
; Example .......: Yes
; ==============================================================================
Func _FFWindowClose($sSearch = "", $sSearchMode = "title")
	Local $sFuncName = "_FFWindowClose"

	If $sSearch = "" Then
		_FFCmd("window.close();")
		Return @error
	EndIf

	Switch StringLower($sSearchMode)
		Case "title" ; window title
			ContinueCase
		Case "label" ; tab label
			ContinueCase
		Case "href" ; current href
			Local $sRetVal = _FFCmd(StringFormat("FFau3.CloseWin('%s','%s')", $sSearch, $sSearchMode))
			If Not @error And $sRetVal = 1 Then
				Return 1
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sSearch: " & $sSearch))
			EndIf
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(title|label|href) $sSearchMode: " & $sSearchMode))
	EndSwitch

	Return 0
EndFunc   ;==>_FFWindowClose

; #FUNCTION# ===================================================================
; Name ..........: _FFWindowGetHandle
; Description ...: Returns the window-handle (hwnd) from the current browser-window.
; Beschreibung ..: Liefert das Window-handle (hwnd) des aktuellen Browser Fenster.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFWindowGetHandle()
; Parameter(s): .:
; Return Value ..: Success      - Window handle
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 28 17:29:49 CEST 2009
; Link ..........:
; Related .......: _FFWindowClose, _FFWindowSelect, _FFWindowOpen
; Example .......: Yes
; ==============================================================================
Func _FFWindowGetHandle()
	Local $sFuncName = "_FFWindowGetHandle"
	; in the future to handle with XPCOM???
	Local $bErr = False
	Local $hWindow = ""

	BlockInput(1)
	Local $sTitle = _FFCmd(".title")
	If Not @error Then
		Local $sTitleRnd = "FFAU3" & Random(1000000000,9999999999,1)
		_FFCmd(".title='" & $sTitleRnd & "'")
		Local $iMatchMode = AutoItSetOption("WinTitleMatchMode", 1)
		$hWindow = WinGetHandle($sTitleRnd)
		If @error Then $bErr = True
		AutoItSetOption("WinTitleMatchMode", $iMatchMode)
		_FFCmd(".title='" & $sTitle & "'")
		ConsoleWrite("_FFWindowGetHandle: " & $hWindow & @crlf)
	EndIf
	BlockInput(0)

	If $bErr Then SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError))
	Return $hWindow
EndFunc

; #FUNCTION# ===================================================================
; Name ..........: _FFWindowSelect
; Description ...: Selects the active window for all other functions
; Beschreibung ..: W?hlt das aktive Browser Fenster f?r alle nachfolgenden Befehle.
; Syntax ........: _FFWindowSelect([$sSearch = ""[, $sSearchMode = "title"[, $bActivate = True]]])
; Parameter(s): .: $sSearch     - Optional: (Default = "") : "" = most recent window, Substring to search
;                  $sSearchMode - Optional: (Default = "title") :
;                               | "title" window title
;                               | "label" tab label
;                               | "href" current url
;                  $bActivate   - Optional: (Default = True) :
; Return Value ..: Success      - 1
;                  @EXTENDED    - Window handle
;                  Failure      - 0
;                  @ERROR       -
;                  @EXTENDED    - ""
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:32:05 CET 2009 @938 /Internet Time/
; Link ..........: https://developer.mozilla.org/En/DOM/Window, https://developer.mozilla.org/En/NsIWindowMediator
; Related .......: _FFWindowOpen, _FFWindowClose, _FFWindowGetHandle
; Example .......: Yes
; ==============================================================================
Func _FFWindowSelect($sSearch = "", $sSearchMode = "title", $bActivate = True)
	Local $sFuncName = "_FFWindowSelect"

	Local $hWin = ""

	If $sSearch = "" Then
		Local $sCommand = 'Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser")'
		_FFCmd("repl.enter(" & $sCommand & ")")
		If Not @error Then
			$hWin = _FFWindowGetHandle()
			If Not @error And $bActivate Then WinActivate($hWin)
			SetExtended($hWin)
			Return 1
		EndIf
		SetExtended($hWin)
		Return 0
	EndIf

	Switch StringLower($sSearchMode)
		Case "title" ; window title
			ContinueCase
		Case "label" ; tab label
			ContinueCase
		Case "href" ; current href
			Local $sRetVal = _FFCmd(StringFormat("FFau3.SelectWin('%s','%s','navigator:browser');", $sSearch, $sSearchMode))
			If Not @error And $sRetVal = 1 Then
				$hWin = _FFWindowGetHandle()
				If Not @error And $bActivate Then WinActivate($hWin)
				SetExtended($hWin)
				Return 1
			Else
				SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sSearch: " & $sSearch), $hWin)
			EndIf
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(title|label|href) $sSearchMode: " & $sSearchMode), $hWin)
	EndSwitch

	SetExtended($hWin)
	Return 0
EndFunc   ;==>_FFWindowSelect

; #FUNCTION# ===================================================================
; Name ..........: _FFWindowOpen
; Description ...: Opens a new browser window
; Beschreibung ..: ?ffnet ein neues Browser Fenster.
; Syntax ........: _FFWindowOpen([$sURL = "about:blank"[, $bActivate = True]])
; Parameter(s): .: $sURL        - Optional: (Default = "about:blank") :
;                  $bActivate   - Optional: (Default = True) :
; Return Value ..: Success      - 1 and sets
;                  @EXTENDED    - Window handle
;                  Failure      - 0 and sets
;                  @ERROR       -
;                  @EXTENDED    - ""
; Author(s) .....: Thorsten Willert
; Date ..........: Fri Apr 03 13:44:38 CEST 2009 @530 /Internet Time/
; Link ..........: https://developer.mozilla.org/En/DOM/Window, https://developer.mozilla.org/En/NsIWindowMediator
; Related .......: _FFWindowSelect, _FFWindowClose, _FFWindowGetHandle
; Example .......: Yes
; ==============================================================================
Func _FFWindowOpen($sURL = "about:blank", $bActivate = True)
	Local $sFuncName = "_FFWindowOpen"

	If Not __FFCheckURL($sURL) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(URL) $sURL: " & $sURL))
		Return 0
	EndIf

	Local $bTrace = $_FF_COM_TRACE
	$_FF_COM_TRACE = False

	ConsoleWrite("_FFWindowOpen: " & $sURL & @CRLF)

	_FFCmd("window.open('" & $sURL & "');")
	If Not @error Then
		If _FFWindowSelect() Then
			Local $hWin = @extended
			If Not @error And $bActivate Then WinActivate($hWin)
			__FFSendJavaScripts()
			$_FF_COM_TRACE = $bTrace
			SetExtended($hWin)
			Return 1
		EndIf
	EndIf

	$_FF_COM_TRACE = $bTrace
	SetExtended("")
	Return 0
EndFunc   ;==>_FFWindowOpen

; #FUNCTION# ===================================================================
; Name ..........: _FFWriteHTML
; Description ...: Replaces the html of body element
; Beschreibung ..: Ersetzt das HTML des Body Elements.
; Syntax ........: _FFWriteHTML([$sHTML = ""[, $sMode = "body"]])
; Parameter(s): .: $sHTML       - Optional: (Default = "") :
;                  $sMode       - Optional: (Default = "body") :
;                               | body
;                               | html
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:30:01 CET 2009 @937 /Internet Time/
; Link ..........:
; Related .......:
; Example .......: Yes
; ==============================================================================
Func _FFWriteHTML($sHTML = "", $sMode = "body")
	Local $sFuncName = "_FFWriteHTML"

	Local $sCommand

	Switch StringLower($sMode)
		Case "body"
			$sCommand = "body"
		Case "html"
			$sCommand = "documentElement"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(body|html) $sMode: " & $sMode))
			Return 0
	EndSwitch

	$sCommand = StringFormat("content.document.%s.innerHTML='" & $sHTML & "';", $sCommand)

	Local $sRetVal = _FFCmd($sCommand)
	If Not @error And $sRetVal <> "_FFCmd_Err" Then Return 1

	Return 0
EndFunc   ;==>_FFWriteHTML

; #FUNCTION# ===================================================================
; Name ..........: _FFXPath
; Description ...: Returns and sets values due to a XPath-query.
; Beschreibung ..: Abfrage und setzen von Werten anhand einer XPath-Abfrage.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFXPath($sQuery[, $sAttribute = "textContent"[, $iReturnType = 2[, $iFilter = 0]]])
; Parameter(s): .: $sQuery      - XPath query
;                  $sAttribute  - Optional: (Default = "textContent") : attribute OR searchstring for SEARCH
;                  $iReturnType - Optional: (Default = 0) :
;                               | 0 = ANY_TYPE
;                               | 1 = NUMBER_TYPE (Returns numberValue)
;                               | 2 = STRING_TYPE (Return stringValue)
;                               | 3 = BOOLEAN_TYPE (Returns booleanValue)
;                               | 4 = UNORDERED_NODE_ITERATOR_TYPE - not implemented
;                               | 5 = ORDERED_NODE_ITERATOR_TYPE - not implemented
;                               | 6 = UNORDERED_NODE_SNAPSHOT_TYPE (Returns arrray)
;                               | 7 = ORDERED_NODE_SNAPSHOT_TYPE (Returns arrray)
;                               | 8 = ANY_UNORDERED_NODE_TYPE (Returns singleNodeValue) (Object in FFau3.xpath)
;                               | 9 = FIRST_ORDERED_NODE_TYPE (Returns singleNodeValue) (Object in FFau3.xpath)
;                               | 10 = COUNT (Returns the number of matches)
;                               | 11 = CONTAINS (stringValue contains substring in $sAttribute) (Returns booleanValue)
;                               | 12 = STARTS-WITH (stringValue start-with string in $sAttribute) (Returns booleanValue)
;                               | 13 = SUBSTRING-AFTER (stringValue substring-after in $sAttribute)
;                               | 14 = SUBSTRING-BEFORE (stringValue substring-bevore in $sAttribute)
;                  $iFilter     - Optional: (Default = 0) :
;                               | 0 = No filter
;                               | 1 = Remove all non ASCII
;                               | 2 = Remove all double withespaces
;                               | 4 = Remove all double linefeeds
;                               | 8 = Remove all HTML-tags
;                               | 16 = simple html-tag / entities convertor
; Return Value ..: Success      - Value $iReturnType 0-5 and 8-10
;                               | Value $iReturnType 8-9 + object FFau3.xpath
;                               | Array $iReturnType 6-7 or if an attribute is set the number of the matches.
;                  Failure      - 0 and sets
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Sat Apr 11 13:07:19 CEST 2009
; Link ..........: http://www.w3.org/TR/xpath, https://developer.mozilla.org/en/XPath, https://developer.mozilla.org/En/XPathResult, https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript
; Related .......: _FFGetValueById, _FFSetValueById, _FFSetValueByName, _FFGetValueById
; Example .......: Yes
; ==============================================================================
Func _FFXPath($sQuery, $sAttribute = "textContent", $iReturnType = 2, $iFilter = 0)
	Local $sFuncName = "_FFXPath"

	If $sQuery = "" Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "Empty String $sQuery"))
		Return 0
	EndIf
	If Not IsInt($iFilter) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $iFilter: " & $iFilter))
		Return 0
	EndIf
	If $iReturnType < 10 And Not StringInStr($sAttribute, "=") And StringRegExp($sAttribute, "[\W]+") Then
		SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sAttribute: " & $sAttribute))
		Return 0
	EndIf

	If $sAttribute = Default Then $sAttribute = "textContent"
	If $iReturnType = Default Then $iReturnType = 0
	$sQuery = StringReplace($sQuery, '"', "'")

	Local $sResult, $sValue

	Switch StringLower($sAttribute)
		Case "textcontent"
			$sAttribute = "textContent"
		Case "innerhtml"
			$sAttribute = "innerHTML"
	EndSwitch

	Switch $iReturnType
		Case 0
			$sResult = "ANY_TYPE"
		Case 1
			$sResult = "NUMBER_TYPE"
			$sValue = ".numberValue"
		Case 2
			$sResult = "STRING_TYPE"
			$sValue = ".stringValue"
		Case 3
			$sResult = "BOOLEAN_TYPE"
			$sValue = ".booleanValue"
			#cs  - not implemented yet
				Case 4
				$sResult = "UNORDERED_NODE_ITERATOR_TYPE"
				Case 5
				$sResult = "ORDERED_NODE_ITERATOR_TYPE"
			#ce
		Case 6
			$sResult = "UNORDERED_NODE_SNAPSHOT_TYPE"
			If $sAttribute <> "" And StringLeft($sAttribute, 1) <> "." Then $sValue &= "." & $sAttribute
		Case 7
			$sResult = "ORDERED_NODE_SNAPSHOT_TYPE"
			If $sAttribute <> "" And StringLeft($sAttribute, 1) <> "." Then $sValue &= "." & $sAttribute
		Case 8
			$sResult = "ANY_UNORDERED_NODE_TYPE"
			$sValue = ".singleNodeValue"
			If $sAttribute <> "" And StringLeft($sAttribute, 1) <> "." Then $sValue &= "." & $sAttribute
		Case 9
			$sResult = "FIRST_ORDERED_NODE_TYPE"
			$sValue = ".singleNodeValue"
			If $sAttribute <> "" And StringLeft($sAttribute, 1) <> "." Then $sValue &= "." & $sAttribute
		; no datatypes
		Case 10
			$sQuery = "count(" & $sQuery & ")"
			$sResult = "NUMBER_TYPE"
			$sValue = ".numberValue"
		Case 11
			$sQuery = "contains(" & $sQuery & ",'" & $sAttribute & "')"
			$sResult = "BOOLEAN_TYPE"
			$sValue = ".booleanValue"
		Case 12
			$sQuery = "starts-with(" & $sQuery & ",'" & $sAttribute & "')"
			$sResult = "BOOLEAN_TYPE"
			$sValue = ".booleanValue"
		Case 13
			$sQuery = "substring-after(" & $sQuery & ",'" & $sAttribute & "')"
			$sResult = "STRING_TYPE"
			$sValue = ".stringValue"
		Case 14
			$sQuery = "substring-before(" & $sQuery & ",'" & $sAttribute & "')"
			$sResult = "STRING_TYPE"
			$sValue = ".stringValue"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(int) $iReturnType: 0-9 10-14: " & $iReturnType))
			Return 0
	EndSwitch

	Local $sErrVal = "_FFXPath_Error: "
	Local $sCommand

	If $iReturnType < 6 Or $iReturnType >= 8 Then

		$sCommand = 'try{FFau3.xpath=window.content.document.evaluate("' & $sQuery & '",window.content.document,null,XPathResult.' & $sResult & ',null)'
		$sCommand &= $sValue & ";}catch(e){'" & $sErrVal & "'+e;};"
	ElseIf $iReturnType = 6 Or $iReturnType = 7 Then

		Local $sDelimiter = "FF" & Random(100, 999, 1)
		$sCommand = 'try{with(FFau3){'
		$sCommand &= 'this.obj=window.content.document.evaluate("' & $sQuery & '",window.content.document,null,XPathResult.' & $sResult & ',null);'
		$sCommand &= 'this.tmp=this.obj.snapshotLength;'
		If Not StringInStr($sAttribute, "=") Then
			$sCommand &= 'for(var i=0;i<this.obj.snapshotLength;i++){this.tmp+="' & $sDelimiter & '"+this.obj.snapshotItem(i)' & $sValue & ';};'
		Else
			$sCommand &= 'for(var i=0;i<this.obj.snapshotLength;i++){this.obj.snapshotItem(i)' & $sValue & ';};'
		EndIf
		$sCommand &= "this.tmp;}}catch(e){'" & $sErrVal & "' +e;};"
	EndIf

	Local $sRetVal = _FFCmd("FFau3.xpath=null;" & $sCommand)
	If Not StringInStr($sRetVal, $sErrVal) Then
		If $iFilter > 0 Then __FFFilterString($sRetVal, $iFilter)

		If $iReturnType = 6 Or $iReturnType = 7 Then
			Return StringSplit($sRetVal, $sDelimiter, 3)
		Else
			If $iReturnType < 10 And $sAttribute = "" Then Return "OBJECT|FFau3.xpath"
			Return StringStripWS($sRetVal, 3)
		EndIf
	Else
		If StringInStr($sRetVal, "TypeError") And StringInStr($sRetVal, "is null") Then
			SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "singleNodeValue is null $sQuery: " & $sQuery & " - " & $sAttribute))
		ElseIf StringInStr($sRetVal, "NS_ERROR_DOM_INVALID_EXPRESSION_ERR") Then
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidExpression, "NS_ERROR_DOM_INVALID_EXPRESSION_ERR $sQuery: " & $sQuery))
		Else
			SetError(__FFError($sFuncName, $_FF_ERROR_RetValue, $sRetVal))
		EndIf
		Return 0
	EndIf
EndFunc   ;==>_FFXPath

; #FUNCTION# ===================================================================
; Name ..........: _FFObjGet
; Description ...: Returns an object (string to use with the other _FFObj* functions)
; Beschreibung ..: Liefert ein Object zurueck. (String zur Verwendung mit den anderen _FFObj* Funktionen)
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFObjGet($sElement[, $sMode = "id"[, $iIndex = 0]])
; Parameter(s): .: $sElement    -
;                  $sMode       - Optional: (Default = "id") :
;                               | ID
;                               | Name + index
;                               | Class + index
;                               | Tag-name + index
;                  $iIndex      - Optional: (Default = 0) :
; Return Value ..: Success      - String (object to use in the _FFObj* functions)
;                  Failure      - Epmty string
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 07 15:12:43 CEST 2009
; Link ..........:
; Related .......: _FFObj, _FFObjNew, _FFObjDelete, _FFClick
; Example .......: Yes
; ==============================================================================
Func _FFObjGet($sElement, $sMode = "id", $iIndex = 0)
	Local $sFuncName = "_FFObjGet"

	Local $sRet

	Switch StringLower($sMode)
		Case "id"
			$sRet = "window.content.document.getElementById('" & $sElement & "')"
		Case "name"
			$sRet = "window.content.document.getElementsByName('" & $sElement & "')[" & $iIndex & "]"
		Case "class"
			$sRet = "window.content.document.getElementsByClassName('" & $sElement & "')[" & $iIndex & "]"
		Case "tag"
			$sRet = "window.content.document.getElementsByTagName('" & $sElement & "')[" & $iIndex & "]"
		Case Else
			SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "(id|name|class|tag) $sMode: " & $sMode))
			Return ""
	EndSwitch

	Local $RetVal = _FFCmd($sRet & "?1:0;")
	If Not @error And $RetVal = 1 Then
		Return "OBJECT|" & $sRet
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sElement not found: " & $sElement))
		Return ""
	EndIf
EndFunc   ;==>_FFObjGet

; #FUNCTION# ===================================================================
; Name ..........: _FFObj
; Description ...: Returns or sets an value of an attribute.
; Beschreibung ..: Liefert oder setzt den Wert eines Attributes.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFObj($sObject[, $sAttrib = ""[, $vValue = ""]])
; Parameter(s): .: $sObject     - Object or element in FireFox
;                  $sAttrib     - Optional: (Default = "") :
;                  $vValue      - Optional: (Default = "") :
; Return Value ..: Success      -
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Fri Apr 24 17:16:13 CEST 2009
; Link ..........:
; Related .......: _FFObjGet, _FFObjNew, _FFObjDelete
; Example .......: Yes
; ==============================================================================
Func _FFObj($sObject, $sAttrib = "", $vValue = "")
	Local $sFuncName = "_FFObj"

	If StringLeft($sObject, 1) = "." Then $sObject = "window.content.document" & $sObject
	If StringLeft($sObject, 7) = "OBJECT|" Then $sObject = StringMid($sObject, 8)
	If Not (StringInStr($sObject, "window.content") Or StringInStr($sObject, "FFau3.")) Then $sObject = "FFau3." & $sObject

	If $sAttrib <> "" Then
		If Not StringInStr($sAttrib,"(") Then
			If Not _FFCmd($sObject & ".hasAttribute('" & $sAttrib & "')") Then
				SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, "$sAttrib not found: " & $sAttrib))
				Return ""
			EndIf
		EndIf
		$sObject &= "." & $sAttrib

		If IsInt($vValue) Then
			$sObject &= "=" & $vValue
		ElseIf IsBool($vValue) Then
			$sObject &= "=" & __FFB2S($vValue)
		ElseIf $vValue <> "" Then
			$sObject &= "='" & $vValue & "'"
		EndIf
	EndIf

	Local $RetVal = _FFCmd($sObject)
	If Not @error And $RetVal <> "_FFCmd_Err" Then
		Return $RetVal
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sObject not found: " & $sObject))
		Return ""
	EndIf
EndFunc   ;==>_FFObj

; #FUNCTION# ===================================================================
; Name ..........: _FFObjNew
; Description ...: Creates a new object in FireFox.
; Beschreibung ..: Erzeugt ein neues Object in FireFox.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFObjNew($sNewObject, $sObject)
; Parameter(s): .: $sNewObject  -
;                  $sObject     -
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 07 15:14:59 CEST 2009
; Link ..........:
; Related .......: _FFObjGet, _FFObj, _FFObjDelete
; Example .......: Yes
; ==============================================================================
Func _FFObjNew($sNewObject, $sObject)
	If StringRegExp($sNewObject, "[\W]+") Then Return 0
	Local $RetVal = _FFCmd("try{FFau3." & $sNewObject & "=" & $sObject & "}catch(e){};FFau3." & $sNewObject & "?1:0;",3000,False)
	Return SetError(Number($RetVal),@extended, $RetVal)
EndFunc   ;==>_FFObjNew

; #FUNCTION# ===================================================================
; Name ..........: _FFObjDelete
; Description ...: Deletes an object in FireFox.
; Beschreibung ..: Loescht ein Objekt in FireFox.
; AutoIt Version : V3.3.0.0
; Syntax ........: _FFObjDelete($sObject)
; Parameter(s): .: $sObject     -
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Wed Apr 08 14:21:26 CEST 2009 @556 /Internet Time/
; Link ..........:
; Related .......: _FFObjGet, _FFObjNew, _FFObj
; Example .......: Yes
; ==============================================================================
Func _FFObjDelete($sObject)
	Local $sFFau3 = "simulateClick simulateKey searchImageLink getlinkinfo getlinks searchimagebysize searchlink searchtab closewin selectwin"
	If StringInStr($sFFau3,StringLower($sObject)) Then Return 0
	Return _FFCmd("delete FFau3." & $sObject & ";!FFau3." & $sObject & "?1:0;")
EndFunc   ;==>_FFObjDelete

;===============================================================================
;
; Internal Functions with names starting with two underscores will not be documented
; as user functions
;
; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFRecv
; Description ...:
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFRecv([$iTimeOut = 10000])
; Parameter(s): .: $iTimeOut    - Optional: (Default = 10000) : TimeOut for __FFWaitForRepl
; Return Value ..: Success      - Return value from MozRepl
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:27:52 CET 2009 @936 /Internet Time/
; ==============================================================================
Func __FFRecv($iTimeOut = 30000)
	Local $sRet = __FFWaitForRepl($iTimeOut)
	Local $iErr = @error
	$sRet = StringStripWS($sRet, 3)

	; Removing leading and trailing "
	If StringLeft($sRet, 1) = '"' Then $sRet = StringTrimLeft($sRet, 1)
	If StringRight($sRet, 1) = '"' Then $sRet = StringTrimRight($sRet, 1)

	; String to bool
	If $sRet = "true" Then
		$sRet = 1
	ElseIf $sRet = "false" Then
		$sRet = 0
	EndIf

	If $_FF_COM_TRACE Then ConsoleWrite("__FFRecv: " & $sRet & @CRLF)

	SetError($iErr)
	Return $sRet
EndFunc   ;==>__FFRecv

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFSend
; Description ...:
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFSend($sCommand)
; Parameter(s): .: $sCommand    - String to send
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:26:09 CET 2009 @934 /Internet Time/
; ==============================================================================
Func __FFSend($sCommand)
	Local $sFuncName = "__FFSend"

	If Not __FFIsSocket($_FF_GLOBAL_SOCKET) Then
		SetError(__FFError($sFuncName, $_FF_ERROR_SocketError))
		Return 0
	EndIf

	TCPSend($_FF_GLOBAL_SOCKET, $sCommand & @CRLF)
	If Not @error Then
		If $_FF_COM_TRACE Then ConsoleWrite("__FFSend: " & $sCommand & @CRLF)
		Return 1
	Else
		SetError(__FFError($sFuncName, $_FF_ERROR_SendRecv, "TCPSend: " & $sCommand))
		Return 0
	EndIf
EndFunc   ;==>__FFSend

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFChromeSelect
; Description ...: Some shortcuts for chrome
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFChromeSelect($sOpt)
; Parameter(s): .: $sOpt        - Shortcut
; Return Value ..: Success      - crome: + ....xul
;                  Failure      - crome: + $sOpt
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Sat Feb 14 12:33:16 CET 2009 @523 /Internet Time/
; ==============================================================================
Func __FFChromeSelect($sOpt)
	Local $sXUL

	Switch StringLower($sOpt)
		Case "bookmarks"
			$sXUL = "//browser/content/bookmarks/bookmarksPanel.xul"
		Case "history"
			$sXUL = "//browser/content/history/history-panel.xul"
		Case "extensions"
			$sXUL = "//mozapps/content/extensions/extensions.xul?type=extensions"
		Case "advanced-scripts"
			$sXUL = "//browser/content/preferences/advanced-scripts.xul"
		Case "changeaction"
			$sXUL = "//browser/content/preferences/changeaction.xul"
		Case "prefs"
			$sXUL = "//browser/content/preferences/preferences.xul"
		Case "colors"
			$sXUL = "//browser/content/preferences/colors.xul"
		Case "connection"
			$sXUL = "//browser/content/preferences/connection.xul"
		Case "cookies"
			$sXUL = "//browser/content/preferences/cookies.xul"
		Case "downloads"
			$sXUL = "//mozapps/content/downloads/downloads.xul"
		Case "downloadactions"
			$sXUL = "//browser/content/preferences/downloadactions.xul"
		Case "fonts"
			$sXUL = "//browser/content/preferences/fonts.xul"
		Case "languages"
			$sXUL = "//browser/content/preferences/languages.xul"
		Case "permissions"
			$sXUL = "//browser/content/preferences/permissions.xul"
		Case "sanitize"
			$sXUL = "//browser/content/preferences/sanitize.xul"
		Case "fireftp"
			$sXUL = "//fireftp/content/fireftp.xul"
		Case Else
			$sXUL = $sOpt
	EndSwitch

	Return "chrome:" & $sXUL
EndFunc   ;==>__FFChromeSelect

; #FUNCTION# ===================================================================
; Name ..........: __FFFilterString
; Description ...: Filter for strings
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFFilterString(ByRef $sString[, $iMode = 1])
; Parameter(s): .: $sString     - String to filter
;                  $iMode       - Optional: (Default = 0) : removes nothing
;                               - 0 = no filter
;                               - 1 = removes non ascii characters
;                               - 2 = removes all double whitespaces
;                               - 4 = removes all double linefeeds
;                               - 8 = removes all html-tags
;                               - 16 = simple html-tag / entities convertor
; Return Value ..: Success      - Filterd String
;                  Failure      - Input String
; Author(s) .....: Thorsten Willert
; Date ..........: Wed Apr 08 20:58:17 CEST 2009 @832 /Internet Time/
; ==============================================================================
Func __FFFilterString(ByRef $sString, $iMode = 0)
	;16 simple HTML tag converter
	If $iMode >= 16 And $iMode < 32 Then
		Local $sRepl[2][6] = [["<br>", "&nbsp;", "&gt;", "&lt;", "&amp;" ,"&quot;"], _
					[@crlf, " "    , ">"   , "<"   , "&"      , '"']]
		$sString = StringRegExpReplace($sString, "<p.*>", @crlf & @crlf)
		For $i = 0 To UBound($sRepl,2) -1
			$sString = StringReplace($sString,$sRepl[0][$i],$sRepl[1][$i])
		Next
		$iMode -= 16
	EndIf
	;8 Tag filter
	If $iMode >= 8 And $iMode < 16 Then
		$sString = StringRegExpReplace($sString, "<[^>]*>", "")
		$iMode -= 8
	EndIf
	; 4 remove all double cr, lf
	If $iMode >= 4 And $iMode < 8 Then
		$sString = StringRegExpReplace($sString, "([ \t]*[\n\r]+[ \t]*)", @CRLF)
		$sString = StringRegExpReplace($sString, "[\n\r]+", @CRLF)
		$iMode -= 4
	EndIf
	; 2 remove all double withespaces
	If $iMode = 2 Or $iMode = 3 Then
		$sString = StringRegExpReplace($sString, "[[:blank:]]+", " ")
		$sString = StringRegExpReplace($sString, "\n[[:blank:]]+", @CRLF)
		$sString = StringRegExpReplace($sString, "[[:blank:]]+\n", "")
		$iMode -= 2
	EndIf
	; 1 remove all non ASCII
	If $iMode = 1 Then
		$sString = StringRegExpReplace($sString, "[^\x00-\x7F]", " ")
	EndIf

	Return $sString
EndFunc   ;==>__FFFilterString

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFError
; Description ...: Writes Error to the console and show message-boxes if the script is compiled
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFError($sFuncName, Const ByRef $i_FF_ERROR[, $sMessage = ""])
; Parameter(s): .: $i_FF_ERROR  - Error Const
;                  $sMessage    - Optional: (Default = "") : Additional Information
; Return Value ..: Success      - Error Const from $i_FF_ERROR
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 12:18:48 CET 2009 @513 /Internet Time/
; ==============================================================================
Func __FFError($sWhere, Const ByRef $i_FF_ERROR, $sMessage = "")
	Local $sOut
	Sleep(200)

	Switch $i_FF_ERROR
		Case $_FF_ERROR_Success
			Return $_FF_ERROR_Success
		Case $_FF_ERROR_GeneralError
			$sOut = "General Error"
		Case $_FF_ERROR_SocketError
			$sOut = "Socket Error"
		Case $_FF_ERROR_InvalidDataType
			$sOut = "Invalid data type"
		Case $_FF_ERROR_InvalidValue
			$sOut = "Invalid value"
		Case $_FF_ERROR_Timeout
			$sOut = "Timeout"
		Case $_FF_ERROR_NoMatch
			$sOut = "No match"
		Case $_FF_ERROR_RetValue
			$sOut = "Error return value"
		Case $_FF_ERROR_SendRecv
			$sOut = "Error TCPSend / TCPRecv"
		Case $_FF_ERROR_ReplException
			$sOut = "MozRepl Exception"
		Case $_FF_ERROR_SendRecv
			$sOut = "Error TCPSend / TCPRecv"
		Case $_FF_ERROR_InvalidExpression
			$sOut = "Invalid Expression"
	EndSwitch
	If $sMessage = "" Then
		ConsoleWriteError($sWhere & " ==> " & $sOut & @CRLF)
		If @Compiled And $_FF_ERROR_MSGBOX And $i_FF_ERROR < 6 Then MsgBox(16, "FF.au3 Error:", $sWhere & " ==> " & $sOut & @CRLF)
	Else
		ConsoleWriteError($sWhere & " ==> " & $sOut & ": " & $sMessage & @CRLF)
		If @Compiled And $_FF_ERROR_MSGBOX And $i_FF_ERROR < 6 Then MsgBox(16, "FF.au3 Error:", $sWhere & " ==> " & $sOut & ": " & $sMessage & @CRLF)
	EndIf

	$_aFF_ERRORS[0][0] = @HOUR & ":" & @MIN & ":" & @SEC ; time
	$_aFF_ERRORS[0][1] = $sWhere ; function
	$_aFF_ERRORS[0][2] = $i_FF_ERROR ; error int
	$_aFF_ERRORS[0][3] = $sOut ; error string
	$_aFF_ERRORS[0][4] = $sMessage ; message

	Return $i_FF_ERROR
EndFunc   ;==>__FFError

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFAddStatus
; Description ...: Adds a new status to the status-array
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFAddStatus()
; Parameter(s): .:
; Return Value ..: Success      - 1
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:25:17 CET 2009 @934 /Internet Time/
; ==============================================================================
Func __FFAddStatus()

	For $i = 1 To UBound($_aFF_STATUS) - 1
		If $_aFF_STATUS[$i][0] = -1 Then
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][0] = $_FF_GLOBAL_SOCKET
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][1] = -1
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][2] = -1
			$_aFF_STATUS[0][0] += 1
		Else
			ReDim $_aFF_STATUS[UBound($_aFF_STATUS) + 1][3]
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][0] = $_FF_GLOBAL_SOCKET
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][1] = -1
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][2] = -1
			$_aFF_STATUS[0][0] += 1
		EndIf

	Next

	Return 1
EndFunc   ;==>__FFAddStatus

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFRemoveStatus
; Description ...: Removes a status from the status-array
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFRemoveStatus()
; Parameter(s): .:
; Return Value ..: Success      - 1
;                  Failure      -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:24:38 CET 2009 @933 /Internet Time/
; ==============================================================================
Func __FFRemoveStatus()
	Local $i

	For $i = 1 To UBound($_aFF_STATUS) - 1
		If $_aFF_STATUS[$i][0] = $_FF_GLOBAL_SOCKET Then
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][0] = -1
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][1] = -1
			$_aFF_STATUS[UBound($_aFF_STATUS) - 1][2] = -1
		EndIf
	Next

	Return 1
EndFunc   ;==>__FFRemoveStatus

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFGetStatus
; Description ...:
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFGetStatus([$sType = "frame"])
; Parameter(s): .: $sType       - Optional: (Default = "frame") :
; Return Value ..: Success      - index of frame or tab
;                  Failure      - -1
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:24:06 CET 2009 @933 /Internet Time/
; ==============================================================================
Func __FFGetStatus($sType = "frame")
	Local $i, $iIndex

	; Status Array:
	; $_aFF_Status[0][0] = [ [ Anzahl ] ]
	; $_aFF_Status[1][3] = [ [ Socket, TabLabel, FrameIndex ] ]
	$sType = StringLower($sType)

	Switch $sType
		Case "frame"
			$iIndex = 2
		Case "tab"
			$iIndex = 1
		Case Else
			Return ""
	EndSwitch

	For $i = 1 To UBound($_aFF_STATUS) - 1
		If $_aFF_STATUS[$i][0] = $_FF_GLOBAL_SOCKET Then
			; no-frame-sites
			If $_aFF_STATUS[$i][$iIndex] = -1 And $sType = "frame" Then
				Return '"top"'
				; frame-sites
			Else
				Return $_aFF_STATUS[$i][$iIndex]
			EndIf
		EndIf
	Next

	Return -1

EndFunc   ;==>__FFGetStatus

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFSetStatus
; Description ...:
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFSetStatus($vValue[, $sType = "frame"])
; Parameter(s): .: $vValue      -
;                  $sType       - Optional: (Default = "frame") :
; Return Value ..: Success      - index of frame or tab
;                  Failure      - -1
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:23:00 CET 2009 @932 /Internet Time/
; ==============================================================================
Func __FFSetStatus($vValue, $sType = "frame")
	Local $i, $iIndex

	; Status Array:
	; $_aFF_Status[0][0] = [ [ Anzahl ] ]
	; $_aFF_Status[1][3] = [ [ Socket, TabLabel, FrameIndex ] ]

	Switch StringLower($sType)
		Case "frame"
			$iIndex = 2
		Case "tab"
			$iIndex = 1
		Case Else
			Return ""
	EndSwitch

	For $i = 1 To UBound($_aFF_STATUS) - 1
		If $_aFF_STATUS[$i][0] = $_FF_GLOBAL_SOCKET Then $_aFF_STATUS[$i][$iIndex] = $vValue
	Next

	Return 1

EndFunc   ;==>__FFSetStatus

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFIsIP
; Description ...: IP4 check
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFIsIP(ByRef $IP[, $bSubstring = False])
; Parameter(s): .: $IP          - IP4 Address
; Return Value ..: Success      - 1
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Sun Feb 15 00:21:41 CET 2009
; ==============================================================================
Func __FFIsIP(ByRef $IP, $bSubstring = False)
	If $bSubstring Then
		Return StringRegExp(StringStripWS($IP,3), "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])")
	Else
		Return StringRegExp(StringStripWS($IP,3), "^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$")
	EndIf
EndFunc   ;==>__FFIsIP

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFIsPort
; Description ...: Port check
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFIsPort(ByRef $iPort)
; Parameter(s): .: $iPort       - Port number 1024-65535
; Return Value ..: Success      - 1
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: 28. August 2007
; ==============================================================================
Func __FFIsPort(ByRef $iPort)
	Return (IsInt($iPort) And $iPort >= 1024 And $iPort <= 65535)
EndFunc   ;==>__FFIsPort

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFIsSocket
; Description ...: Socket check
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFIsSocket(ByRef $Socket)
; Parameter(s): .: $Socket      -
; Return Value ..: Success      - 1
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Apr 07 11:08:05 CEST 2009 @422 /Internet Time/
; ==============================================================================
Func __FFIsSocket(ByRef $Socket)
	Return ($Socket > 0 And IsInt($Socket))
EndFunc   ;==>__FFIsSocket

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFIsURL
; Description ...: URL check
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFIsURL(ByRef $URL)
; Parameter(s): .: $URL         - http/https/ftp/about/chrome/file
; Return Value ..: Success      - 1
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Tue Jul 07 11:32:45 CEST 2009
; Link ..........: http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx
; ==============================================================================
Func __FFIsURL(ByRef $URL)
	Return (StringRegExp($URL, '^^((ht|f)tp(s?)\:\/\/|~/|/)([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?') Or _
			StringRegExp($URL,'^^((ht|f)tp(s?)\:\/\/|~/|/)(\d{1,3}\.){3}\d{1,3}(:[\d]{1,5})?(/.*)?$') Or _
			StringLeft($URL, 6) = "about:" Or _
			StringLeft($URL, 7) = "chrome:" Or _
			StringLeft($URL, 10)= "localhost:" Or _
			StringLeft($URL, 8) = "file:///")
EndFunc   ;==>__FFIsURL

Func __FFCheckURL(ByRef $URL)
	If Not __FFIsURL($URL) Then
		If Not StringRegExp($URL, '^((ht|f)tp(s?)\:\/\/|~/|/)') Then $URL = "http://" & $URL
	EndIf

	Return __FFIsURL($URL)
EndFunc

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFB2S
; Description ...: Bool to string
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFB2S($bBool)
; Parameter(s): .: $bBool       - true / false
; Return Value ..: Success      - String "true" or "false"
;                  Failure      - ""
; Author(s) .....: Thorsten Willert
; Date ..........: Sun Feb 15 00:26:46 CET 2009
; ==============================================================================
Func __FFB2S($bBool)
	If $bBool Then
		Return "true"
	Else
		Return "false"
	EndIf
EndFunc   ;==>__FFB2S

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFValue2JavaScript
; Description ...:
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFValue2JavaScript(ByRef $sValue)
; Parameter(s): .: $sValue      -
; Return Value ..: Success      -
;                  Failure      -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Apr 13 15:42:21 CEST 2009
; ==============================================================================
Func __FFValue2JavaScript(ByRef $sValue)
	If $sValue = "" Then Return ""
	Local $sTmp = "", $C

	$sValue = StringRegExpReplace($sValue, "([\\""])", "\\$1")
	$sValue = StringReplace($sValue, @CRLF, "\n")
	$sValue = StringReplace($sValue, @CR, "\r")
	$sValue = StringReplace($sValue, @TAB, "\t")

	If StringRegExp($sValue, "[^\x00-\x7F]",0) Then
		For $i = 0 To StringLen($sValue)
			$C = StringMid($sValue,$i,1)
			If StringRegExp($C, "[^\x00-\x7F]",0) Then $C = StringFormat("\\u%0000s",Hex(AscW($C),4))
			$sTmp &= $C
		Next
		$sValue = $sTmp
	EndIf

	Return $sValue

EndFunc   ;==>__FFValue2JavaScript

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFSendJavaScripts
; Description ...: JavaScript functions
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFSendJavaScripts([$bRefresh = False])
; Parameter(s): .: $bRefresh    - Optional: (Default = false) : Send again to FF
; Return Value ..: Success      - 1
;                  Failure      - 0
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 30 20:36:06 CEST 2009 @816 /Internet Time/
; Link ..........: http://developer.mozilla.org/en/docs/DOM:event.initMouseEvent
; ==============================================================================
Func __FFSendJavaScripts($bRefresh = False, $bTrace = False)

	Local $bTrc = $_FF_COM_TRACE
	$_FF_COM_TRACE = $bTrace

	If _FFCmd("repl.search(/FFau3/i)", 3000) = "FFau3" And Not $bRefresh Then
		$_FF_COM_TRACE = $bTrace
		Return 1
	EndIf
	If $bRefresh Then _FFCmd('try{delete FFau3;}catch(e){e};')

	ConsoleWrite("_FFSendJavaScripts: Sending functions to FireFox .")

	Local $sJavaScript = 'FFau3 = new Object(); FFau3.tmp="";FFau3.obj;'
	; simulateClick(): JavaScript to simulate mouse-clicks on an object
	$sJavaScript &= 'FFau3.simulateClick = function simulateClick(oObject,X,Y)'
	$sJavaScript &= '{'
	$sJavaScript &= 'try {'
	$sJavaScript &= 'var evt = document.createEvent("MouseEvents");'
	$sJavaScript &= 'evt.initMouseEvent("click", true, true, window,'
	$sJavaScript &= '0, 0, 0, X, Y,'
	$sJavaScript &= 'false, false, false, false,'
	$sJavaScript &= '0, null);'
	$sJavaScript &= 'oObject.dispatchEvent(evt);'
	$sJavaScript &= 'return 1;'
	$sJavaScript &= '} catch(e) {return 0;}'
	$sJavaScript &= '};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; simulateKey(): JavaScript to simulate a keypress
	$sJavaScript = 'FFau3.simulateKey = function simulateKey(oObject,KeyCode,sEventType)'
	$sJavaScript &= '{'
	$sJavaScript &= 'try {'
	$sJavaScript &= 'var evt = document.createEvent("KeyboardEvent");'
	$sJavaScript &= 'evt.initKeyEvent(sEventType, true, true, null,'
	$sJavaScript &= 'false, false, false, false,'
	$sJavaScript &= 'KeyCode, 0);'
	$sJavaScript &= 'oObject.dispatchEvent(evt);'
	$sJavaScript &= 'return 1;'
	$sJavaScript &= '}catch(e){return 0;}'
	$sJavaScript &= '};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; searchImageLink(): JavaScript to search an image in the innerHTML of all links
	$sJavaScript = 'FFau3.searchImageLink = function searchImageLink(RegEx,iFrame)'
	$sJavaScript &= '{'
	$sJavaScript &= 'try {'
	$sJavaScript &= 'var html;var i;'
	$sJavaScript &= 'for (var i=0;i<content.frames[iFrame].document.links.length;i++)'
	$sJavaScript &= '{'
	$sJavaScript &= 'html=content.frames[iFrame].document.links[i].innerHTML;'
	$sJavaScript &= 'if (RegEx.test(html) && html.toLowerCase().indexOf("<img") != -1) return i;'
	$sJavaScript &= '} return -1;'
	$sJavaScript &= '}catch(e){return -3;}'
	$sJavaScript &= '};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; GetLinkInfo(): JavaScript to get all informations about a link
	$sJavaScript = 'FFau3.GetLinkInfo = function GetLinkInfo(i,iFrame,sLimiter)'
	$sJavaScript &= '{ var info=""; with(content.frames[iFrame].document) {'
	$sJavaScript &= 'try {'
	$sJavaScript &= 'info = links[i].href + sLimiter;'
	$sJavaScript &= 'info += links[i].hash + sLimiter;'
	$sJavaScript &= 'info += links[i].search + sLimiter;'
	$sJavaScript &= 'info += links[i].name + sLimiter;'
	$sJavaScript &= 'info += links[i].id + sLimiter;'
	$sJavaScript &= 'info += links[i].text + sLimiter;'
	$sJavaScript &= 'info += links[i].innerHTML + sLimiter;'
	$sJavaScript &= 'info += (links[i].hasAttribute("target") ? links[i].target + sLimiter : sLimiter);'
	$sJavaScript &= 'info += links[i].protocol + sLimiter;'
	$sJavaScript &= 'info += links[i].port;'
	$sJavaScript &= 'return info.replace(/[\s]+/g," ");'
	$sJavaScript &= '}catch(e){return -3;}'
	$sJavaScript &= '}};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; GetLinks(): JavaScript to get an information of all links
	$sJavaScript = 'FFau3.GetLinks = function GetLinks(iFrame,sLimiter)'
	$sJavaScript &= '{ var res=""; with(content.frames[iFrame].document) {'
	$sJavaScript &= 'try {'
	$sJavaScript &= 'for (var i=0;i<links.length;i++){res += this.GetLinkInfo(i, iFrame,sLimiter) + "\n";}'
	$sJavaScript &= 'return res; } catch(e) {return -3;}'
	$sJavaScript &= '}};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; SearchImageBySize(): JavaScript
	$sJavaScript = 'FFau3.SearchImageBySize = function SearchImageBySize(iH, iW, sMode, iFrame)'
	$sJavaScript &= '{'
	$sJavaScript &= 'var sRet = ""; with(content.frames[iFrame].document) {'
	$sJavaScript &= 'for (var i=0;i<images.length;i++)'
	$sJavaScript &= '{'
	$sJavaScript &= 'var iWidth=images[i].width;'
	$sJavaScript &= 'var iHeight=images[i].height;'
	$sJavaScript &= 'switch (sMode) {'
	$sJavaScript &= 'case "eq": if (iWidth == iW && iHeight == iH) sRet += " " + i; break;'
	$sJavaScript &= 'case "lt": if (iWidth < iW && iHeight < iH) sRet += " " + i; break;'
	$sJavaScript &= 'case "gt": if (iWidth > iW && iHeight > iH) sRet += " " + i; break;'
	$sJavaScript &= 'default: return -1}'
	$sJavaScript &= '} return sRet; }'
	$sJavaScript &= '};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; SearchLink(): JavaScript to search a link
	$sJavaScript = 'FFau3.SearchLink = function SearchLink(sMode,sSearch,iFrame)'
	$sJavaScript &= '{try{'
	$sJavaScript &= 'with(content.frames[iFrame].document) {'
	$sJavaScript &= 'var info="";'
	$sJavaScript &= 'for (var i=0;i<links.length;i++)'
	$sJavaScript &= '{'
	$sJavaScript &= 'switch (sMode) {'
	$sJavaScript &= 'case "href": info=links[i].href; break;'
	$sJavaScript &= 'case "text": info=links[i].text; break;'
	$sJavaScript &= 'case "id": info=links[i].id; break;'
	$sJavaScript &= 'case "name": info=links[i].name; break;'
	$sJavaScript &= 'case "title": info=links[i].title; break;'
	$sJavaScript &= 'default: return -1;}'
	$sJavaScript &= 'if (info.indexOf(sSearch) != -1) return i;'
	$sJavaScript &= '}'
	$sJavaScript &= 'return -2;}}catch(e){return -3;}'
	$sJavaScript &= '};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; SearchTab(); JavaScript to search a tab by label
	$sJavaScript = 'FFau3.SearchTab = function SearchTab(RegEx)'
	$sJavaScript &= '{try{'
	$sJavaScript &= 'for (var i=0;i<gBrowser.mTabs.length;i++){'
	$sJavaScript &= 'if (RegExp(RegEx).test(gBrowser.mTabs[i].label)) return i;};'
	$sJavaScript &= 'return -1;}catch(e){return -3;}};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; CloseWin()
	$sJavaScript = 'FFau3.CloseWin = function CloseWin(sSearch,sMode){'
	$sJavaScript &= 'var win;var enum = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getEnumerator("navigator:browser");'
	$sJavaScript &= 'while(enum.hasMoreElements() ){'
	$sJavaScript &= 'win=enum.getNext();'
	$sJavaScript &= 'switch(sMode){'
	$sJavaScript &= 'case "title": if (win.title.indexOf(sSearch) != -1){win.close();return 1;};break;'
	$sJavaScript &= 'case "label": if (FFau3.SearchTab(sSearch)>-1){win.close();return 1;};break;'
	$sJavaScript &= 'case "href": if (win.content.document.location.href.indexOf(sSearch) != -1){win.close();return 1;}break;'
	$sJavaScript &= 'default: return -1;'
	$sJavaScript &= '}}return -1;};'

	_FFCmd($sJavaScript)
	ConsoleWrite(".")

	; SelectWin()
	$sJavaScript = 'FFau3.SelectWin = function SelectWin(sSearch,sMode,sType){'
	$sJavaScript &= 'var win;var enum = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getEnumerator(sType);'
	$sJavaScript &= 'while(enum.hasMoreElements() ){'
	$sJavaScript &= 'win=enum.getNext();'
	$sJavaScript &= 'switch(sMode){'
	$sJavaScript &= 'case "title": if (win.title.indexOf(sSearch) != -1){repl.enter(win);return 1;};break;'
	$sJavaScript &= 'case "label": if (FFau3.SearchTab(sSearch)>-1){repl.enter(win);return 1;};break;'
	$sJavaScript &= 'case "href": if (win.content.document.location.href.indexOf(sSearch) != -1){repl.enter(win);return 1;};break;'
	$sJavaScript &= 'default: return -1};'
	$sJavaScript &= '}return -1;};'

	_FFCmd($sJavaScript)
	ConsoleWrite(". done" & @CRLF)

	$_FF_COM_TRACE = $bTrc
	;
	Return 1

EndFunc   ;==>__FFSendJavaScripts

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFWaitForRepl
; Description ...:
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFWaitForRepl($iTimeOut)
; Parameter(s): .: $iTimeOut
; Return Value ..: Success      - Return value from MozRepl
;                  Failure      - ""
;                  @ERROR       -
; Author(s) .....: Thorsten Willert
; Date ..........: Mon Mar 23 22:19:52 CET 2009 @930 /Internet Time/
; ==============================================================================
Func __FFWaitForRepl($iTimeOut)
	Local $sFuncName = "__FFWaitForRepl"

	Local $recv, $sRet = "", $TimeOutTimer = TimerInit()
	If $iTimeOut < 200 Then $iTimeOut = 200

	While TimerDiff($TimeOutTimer) < $iTimeOut

		; connection delay
		Sleep($_FF_CON_DELAY)

		$recv = TCPRecv($_FF_GLOBAL_SOCKET, 4096)
		;ConsoleWrite($recv & @CRLF)
		; TCP error
		If @error Then
			SetError(__FFError($sFuncName, $_FF_ERROR_SendRecv, "TCPRecv :" & @error))
			Return ""
		EndIf
		$sRet &= $recv

		; error from MozRepl
		If StringRegExp($recv, "!!!(.*?)(TypeError|Exception|ReferenceError):?") Then
			$recv = StringLeft($recv, StringInStr($recv, "location") - 1)
			SetError(__FFError($sFuncName, $_FF_ERROR_ReplException, StringStripWS($recv, 3)))
			Return ""
		ElseIf StringInStr($recv, "....>") Then
			__FFSend(";") ; MozRepl-Reset
			Sleep(100)
			SetError(__FFError($sFuncName, $_FF_ERROR_RetValue, "MozRepl ....>"))
			Return ""
		ElseIf StringInStr($recv, "beginning of the line to force evaluation") Then
			Sleep(500) ; first connection delay
		EndIf

		; multiple connections to MozRepl (e.g repl2?> ...)
		If StringRegExp($recv, "repl[\d]?>") Then Return StringRegExpReplace($sRet, "repl[\d]?>", "")
	WEnd

	; Timeout
	SetError(__FFError($sFuncName, $_FF_ERROR_Timeout, Round(TimerDiff($TimeOutTimer)) & "ms > " & $iTimeOut & "ms $iTimeOut"))
	Return ""

EndFunc   ;==>__FFWaitForRepl

; #INTERNAL_USE_ONLY# ==========================================================
; Name ..........: __FFStartProcess
; Description ...: Starts the firefox.exe
; AutoIt Version : V3.3.0.0
; Syntax ........: __FFStartProcess([$sURL = "about:blank"[, $bNewWin = False[, $sProfile = "default"[, $bNoRemote = False[, $bHide = False[, $iPort = 4242[, $iTimeOut = 30000]]]]]]])
; Parameter(s): .: $sProfile    - Optional: (Default = "default") :
;                  $bNewWin     - Optional: (Default = false) :
;                  $bNoRemote   - Optional: (Default = false) :
;                  $bHide       - Optional: (Default = False) :
;                  $iPort       - Optional: (Default = 4242) :
;                  $iTimeOut    - Optional: (Default = 30000) : min. 2000ms
; Return Value ..: Success      - 1
;                  Failure      - 0
;                  @ERROR       -
;                  @EXTENDED    - PID from the firefox.exe
; Author(s) .....: Thorsten Willert
; Date ..........: Thu Apr 30 22:09:55 CEST 2009
; ==============================================================================
Func __FFStartProcess($sURL = "about:blank", $bNewWin = False, $sProfile = "default", $bNoRemote = False, $bHide = False, $iPort = 4242, $iTimeOut = 30000)
	Local $sFuncName = "__FFStartProcess"

	Local $PID = -1
	Local $sNoRemote = "", $sNewWin
	Local $sProcName = $_FF_PROC_NAME

	If $sProfile = "default" Then
		$sProfile = ''
	Else
		$sProfile = ' -P "' & $sProfile & '"'
	EndIf
	If $bNoRemote Then $sNoRemote = "-no-remote"
	If $bNewWin Then $sNewWin = "-new-window"
	$sURL = '"' & $sURL & '"'
	If $iTimeOut < 2000 Then $iTimeOut = 2000

	Local $sHKLM = "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox"
	Local $sFFExe = RegRead($sHKLM & "\" & RegRead($sHKLM, "CurrentVersion") & "\Main", "PathToExe")
	If @error Then
		SetError(__FFError($sFuncName, $_FF_ERROR_GeneralError, "Browser not found in: " & $sFFExe))
		Return 0
	EndIf

	If $bHide Then BlockInput(1)
	Local $sCommand = StringFormat('"%s" %s %s %s -repl %i %s', $sFFExe, $sNewWin, $sURL, $sNoRemote, $iPort, $sProfile)
	$PID = Run($sCommand)

	Local $iTimeOutTimer = TimerInit()
	While 1
		Sleep(2000)
		If ProcessExists($sProcName) Then ExitLoop
		If (TimerDiff($iTimeOutTimer) > $iTimeOut) Then
			SetError(__FFError($sFuncName, $_FF_ERROR_Timeout, "Browser process not exists: " & $sProcName))
			BlockInput(0)
			Return 0
		EndIf
	WEnd

	If $bHide Then
		Local $WINTITLE_MATCH_MODE = AutoItSetOption("WinTitleMatchMode", 4)
		WinWaitActive("[CLASS:MozillaUIWindowClass]")
		Sleep(500)
		WinSetState("[CLASS:MozillaUIWindowClass]", "", @SW_MINIMIZE)
		BlockInput(0)
		AutoItSetOption("WinTitleMatchMode", $WINTITLE_MATCH_MODE)
	Else
		Sleep(1000)
	EndIf

	If $_FF_COM_TRACE Then ConsoleWrite('__FFStartProcess: "' & $sCommand & @CRLF)

	SetExtended($PID)
	Return 1
EndFunc   ;==>__FFStartProcess