def newBrowser(remoteClient, browserType, logdir, browserWait=15):
    
    browser = None
    # Internet Explore 
    if browserType in ["ie", "ie8", "ie9"]:
        browser = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.INTERNETEXPLORER)
        #browser = webdriver.Remote("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.INTERNETEXPLORER)
        
    # HTML Util 
    elif browserType == "hu":
        # Original webdriver way
        # browser = webdriver.Remote("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.HTMLUNIT)
        browser = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.HTMLUNIT)
    
    # Google Chrome
    elif browserType == "ch":
        browser = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.CHROME)   
   
    # Firefox - Default if nothing is specified
    else:        
        browser = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.FIREFOX)
        
    browser.implicitly_wait(browserWait)
    browser.delete_all_cookies()
    browser.set_window_size(1280, 1024)
    
    return browser 
 def __init__(self, remoteClient, mcu_server, browserType, logdir, logger, browserWait=15):
     self.browserType = browser
     self.logger = logger
     self.screenshotDir = logdir
     self.browserWait = browserWait
     self.page = None
     self.element = None
     self.mcu_server = mcu_server
     
     try:
         # Internet Explore 
         if browserType in ["ie", "ie8", "ie9"]:
             self.page = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.INTERNETEXPLORER)
             self.browserType = 'ie'
             
         # HTML Util 
         elif browserType == "hu":
             self.page = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.HTMLUNIT)
             self.browserType = 'hu'
         
         # Google Chrome
         elif browserType == "ch":
             self.page = QuestWebDriver("http://{}:9515".format(remoteClient), webdriver.DesiredCapabilities.CHROME)   
             self.browserType = 'ch'
        
         # Firefox - Default if nothing is specified
         else:        
             self.page = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.FIREFOX)
                 
         self.page.implicitly_wait(browserWait)
         self.page.delete_all_cookies()
         
         # Resize the browser. I have to shrink it first then move it to the corner then enlarge it. 
         self.page.set_window_size(800, 600)
         self.page.set_window_position(0, 0)
         self.page.set_window_size(1280, 1024)
         
         self.mouse = webdriver.ActionChains(self.page)
         
         # Get the Default window name 
         self.currentWindowHandle = self.page.current_window_handle
     
     except:
         self.logger.error("\n======================================================================")
         self.logger.error("\nUnable to open connection to remote web browser on:  {}".format(remoteClient))
         self.logger.error("Check to make sure selenium is loaded on host:  {}.".format(remoteClient))
         self.logger.error("\n======================================================================\n")
class browser(object):
    #----------------------------------------------------------------------
    def __init__(self, remoteClient, mcu_server, browserType, logdir, logger, browserWait=15):
        self.browserType = browser
        self.logger = logger
        self.screenshotDir = logdir
        self.browserWait = browserWait
        self.page = None
        self.element = None
        self.mcu_server = mcu_server
        
        try:
            # Internet Explore 
            if browserType in ["ie", "ie8", "ie9"]:
                self.page = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.INTERNETEXPLORER)
                self.browserType = 'ie'
                
            # HTML Util 
            elif browserType == "hu":
                self.page = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.HTMLUNIT)
                self.browserType = 'hu'
            
            # Google Chrome
            elif browserType == "ch":
                self.page = QuestWebDriver("http://{}:9515".format(remoteClient), webdriver.DesiredCapabilities.CHROME)   
                self.browserType = 'ch'
           
            # Firefox - Default if nothing is specified
            else:        
                self.page = QuestWebDriver("http://{}:4444/wd/hub".format(remoteClient), webdriver.DesiredCapabilities.FIREFOX)
                    
            self.page.implicitly_wait(browserWait)
            self.page.delete_all_cookies()
            
            # Resize the browser. I have to shrink it first then move it to the corner then enlarge it. 
            self.page.set_window_size(800, 600)
            self.page.set_window_position(0, 0)
            self.page.set_window_size(1280, 1024)
            
            self.mouse = webdriver.ActionChains(self.page)
            
            # Get the Default window name 
            self.currentWindowHandle = self.page.current_window_handle
        
        except:
            self.logger.error("\n======================================================================")
            self.logger.error("\nUnable to open connection to remote web browser on:  {}".format(remoteClient))
            self.logger.error("Check to make sure selenium is loaded on host:  {}.".format(remoteClient))
            self.logger.error("\n======================================================================\n")
            
    #----------------------------------------------------------------------
    def _findElements(self, elementID, message, findBy="id", returnAllItems=False, ignoreErrorMessage=False, isVisible=True, browserWait=None):
        if findBy == "id":
            element = self.page.find_elements_by_id(elementID)
        elif findBy == "xpath":
            element = self.page.find_elements_by_xpath(elementID)
        elif findBy == "class":
            element = self.page.find_elements_by_class_name(elementID)
            
        return self.verifyElement(element, message, elementID, ignoreErrorMessage)
    
    #----------------------------------------------------------------------
    def _findElement(self, elementID, message, findBy="id", ignoreErrorMessage=False, isVisible=True, browserWait=None):
        if findBy == "id":
            element = self.page.find_element_by_id(elementID)
        elif findBy == "xpath":
            element = self.page.find_element_by_xpath(elementID)
        elif findBy == "class":
            element = self.page.find_element_by_class_name(elementID)
                    
        element = self.verifyElement(element, message, elementID, ignoreErrorMessage)        
        self.element = element
        
        if element != False:
            if isVisible:
                check = self.isDisplayed(element)
            else:
                check = self.shouldNotBeDisplayed(element)
            
            if check:
                return element
        
        return False
        
    #----------------------------------------------------------------------
    def findElement(self, elementID, message, findBy="id", returnAllItems=False, ignoreErrorMessage=False, isVisible=True, browserWait=None):
        '''Finds the element based on xpath, id or class and returns the found element'''
        try:
            self.logger.info("")
            if browserWait is None:
                browserWait = 15
            self.page.implicitly_wait(browserWait)
            if not ignoreErrorMessage:
                self.logger.info("Finding | {} using {}: {}".format(message, findBy, elementID))
            else:
                self.logger.info("Looking for {} using {}: {} \nWe are ignoring error messages for this element. Element may not/or should not exist at this point".format(message, findBy, elementID))

            if returnAllItems:
                return self._findElements(elementID, message, findBy, returnAllItems, ignoreErrorMessage, isVisible, browserWait)
            
            else:
                return self._findElement(elementID, message, findBy, ignoreErrorMessage, isVisible, browserWait)
        
        except selenium.common.exceptions.NoSuchElementException:
            self.logger.error("No such element! Could not find {}".format(message))
            if not ignoreErrorMessage:
                raise webdriverElementNotFound(message)
                #raise mcuTest.webdriverElementNotFound(message)
            return False
        
        except selenium.common.exceptions.ElementNotVisibleException:
            self.logger.error("Element is not visible! Could not find {}".format(message))
            if not ignoreErrorMessage:
                raise webdriverElementNotFound(message)
                #raise mcuTest.webdriverElementNotFound(message)
            return False
        
    #----------------------------------------------------------------------
    def verifyElement(self, element, elementDiscription, elementID, ignoreErrorMessage):
        if element != [] or element != None:
            self.logger.info("ELEMENT FOUND | {}".format(elementDiscription))
            return element
        
    #----------------------------------------------------------------------
    def findElementWithObject(self, client, elementID, browserWait=None):
        if browserWait is None:
            browserWait = 15
        self.page.implicitly_wait(browserWait)
            
        self.logger.info("Finding for {} using - xpath={}".format(client, elementID))
        hosts = self.page.find_elements_by_xpath(elementID)
        if hosts != []:
            for host in hosts:
                if host.text == client:
                    return host 
        return False
    
    #----------------------------------------------------------------------
    def openWebPage(self, webPage):
        # We need to wait for the server to come up. This could take a minute
        tries = 1
        result = False
        self.logger.info("Opening webpage | {}".format(webPage))
        self.page.get(webPage)
        
        while tries < 20:
            if self._pageReady(tries):
                break
            tries+=1
            if tries > 10:
                self.logger.info("Trying to open webpage again")
                self.page.get(webPage)
                
    #----------------------------------------------------------------------
    def _pageReady(self, tries):
        self.logger.info("\nAttempt {} of 20 | Checking to see if page is loaded...".format(tries))
        self.logger.info("Current Page Title | {}".format(self.page.title))
        
        if self.page.title in ["Problem loading page", "Unable to connect", "about:blank", 
                               "Internet Explorer cannot display the webpage", "", "This page can't be displayed"]:
            self.logger.warn("Page not ready yet refreshing page, please stand by...")
            time.sleep(5)
            # clear cookies and refresh. The browser was getting in a funny state, so I needed to clear cookies. 
            self.page.delete_all_cookies()
            self.page.refresh()
            return False
        return True
    
    #----------------------------------------------------------------------
    def validateWebPage(self, pageExpected):
        currentURL = self.page.current_url
        #if pageExpected not in currentURL
        newrl = currentURL.replace("?v=1", "")
        if newrl.find(pageExpected) > -1:
            return True
        else:
            if newrl == None:
                newrl = "none"
            self.logger.error('[!] Was expecting "{}", Got "{}" [!]'.format(pageExpected, newrl))
            self._takeScreenShot(self.screenshotDir, "Webpage")
            # Change this back to false. For now I am changing it so tests move on.
            return False
        return True
        
    #----------------------------------------------------------------------
    def compareText(self, element, expectedText):
        try:
            assert element.text == expectedText
        except AssertionError:
            self.logger.error('[!] Was expecting {}, Got {} [!]'.format(expectedText, element.text))
            self.screenShot()
            
    #----------------------------------------------------------------------    
    def isDisplayed(self, element):
        try:
            if not element.is_displayed():
                self.logger.error('Element should be visible')
        except AttributeError:
            self.logger.error('[!] Element should be visable [!]')
            return False
        
        return True
    
    #----------------------------------------------------------------------
    def shouldNotBeDisplayed(self, element):
        try:
            if element.is_displayed():
                self.logger.error('Element should not be visable')
        except AttributeError:
            self.logger.error('[!] Element should NOT be visable [!]')
            return False
        
        return True
        
    #----------------------------------------------------------------------
    def _takeScreenShot(self, screenDirectory="/tmp", elementDiscription="", screenType="base64"):
        # Format the Name 
        screenCaptureName = elementDiscription.replace(" ", "")
        screenCaptureName = screenCaptureName.replace(":", "")
        screenCaptureName = "{}.png".format(screenCaptureName)
        
        if screenType == "base64":
            return self._takeScreenShotAsBase64(screenCaptureName, screenDirectory, elementDiscription)
        else:
            return self._takeScreenShotAsFile(screenCaptureName, screenDirectory, elementDiscription)
            
    #----------------------------------------------------------------------
    def _takeScreenShotAsFile(self, screenDirectory, elementDiscription):
        if self.page.get_screenshot_as_file("{}/{}".format(screenDirectory, screenCaptureName)):
            #self.logger.screenShot("./{}".format(screenCaptureName))
            print "taking screenshot"
        else:
            self.logger.error('[o] Failed to take screenshot [o]')
            
    #----------------------------------------------------------------------
    def _takeScreenShotAsBase64(self, screenCaptureName, screenDirectory, elementDiscription):
        b64 = self.page.get_screenshot_as_base64()
        if b64:
            # Need to pass this up to the logger. 
            decoded = base64.decodestring(b64)
            return screenCaptureName, decoded, "image/png"
        else:
            self.logger.error('[o] Failed to take screenshot [o]')
        
    #----------------------------------------------------------------------
    def verifyClick(self, function):
        element = function
        try:
            if not element:
                return False 
            
            assert element is not None
            element.click()
            
        except AssertionError:
            self.logger.error('Failed to find element')
            return False
        
        return True
    
    #----------------------------------------------------------------------
    def closeOtherOpenWindows(self):
        # Get the list of open windows
        openWindows = self.page.window_handles
        if len(openWindows) > 1:
            for window in openWindows:
                if window != self.currentWindowHandle:
                    # Switch to that window 
                    self.page.switch_to_window(window)
                    # Close the window 
                    self.logger.info("Closing page: {}".format(self.page.title))
                    self.page.close()
        else:
            if self.page.current_window_handle != self.currentWindowHandle:
                self.logger.error("The original window does not have focus and there is only one window open")
                self.screenShot()
                
        # Set focus back to main window
        self.page.switch_to_window(self.currentWindowHandle)
        self.logger.info("Switching back parent window: {}".format(self.page.title))
        
    #----------------------------------------------------------------------
    def screenShot(self, bugNumber=None):
        """
        This will take a screen capture and set a failure in slick
        """
        if bugNumber != None:
            self.logger.error('Please see <a style="color:red;" href="https://slcbugl01.prod.quest.corp/show_bug.cgi?id={}">BUG {}</a> for details'.format(bugNumber, bugNumber))
            
        screenCaptureName, data, mimeType = self._takeScreenShot(elementDiscription=time.strftime('%Y_%m_%d %H:%M'))
        raise takeScreenCapture(screenCaptureName, data, mimeType)