//
// Created by Alexander Zalutskiy on 10.08.15.
// Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit

class LKSettingsViewController: ViewControllerWithCustomTitle, UITableViewDelegate, UITableViewDataSource {
    
    // MARK: Outlets
    
    @IBOutlet private weak var tableView: UITableView!
    var someIndex = 0
    weak var activeField: UITextField?
    var settingsChanged = false
    private var titleLabel : UILabel?
    var rightBarButtonItem: UIBarButtonItem?
    var params: [String: AnyObject] = [String: AnyObject]()
    
    private let menuIcon = UIImage(named: "menu_icon")
    private let menuButton: UIButton
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 36))
        titleLabel!.textColor = UIColor.whiteColor()
        titleLabel!.text = navigationBarTitle
        titleLabel!.textAlignment = .Center
        titleLabel!.font = NavigationBarFont
        self.navigationItem.titleView = titleLabel
    }
    
    required init?(coder aDecoder: NSCoder) {
        menuButton = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: menuIcon!.size))
        super.init(coder: aDecoder)
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        menuButton = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: menuIcon!.size))
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    func addMenuBarButton() {
        menuButton.setImage(menuIcon, forState: .Normal)
        menuButton.setImage(UIImage(named: "menu_icon_highlighted"), forState: .Highlighted)
        menuButton.addTarget(self, action: #selector(LKSettingsViewController.menuButton_TouchUpInside(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuButton)
        if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
            menuButton.enabled = !UIApplication.sharedApplication().statusBarOrientation.isLandscape
            menuButton.hidden = UIApplication.sharedApplication().statusBarOrientation.isLandscape
        }
        if UIApplication.sharedApplication().statusBarOrientation.isLandscape {
            menuButton.enabled = false
            menuButton.hidden = true
        } else {
            menuButton.enabled = true
            menuButton.hidden = false
        }
    }
    
    func menuButton_TouchUpInside(sender: UIButton) {
        if let rvc = self.navigationController!.parentViewController! as? RootVC {
            rvc.openLeftSideViewControllerAnimated(true, completion: nil)
        } else if let rvc = self.navigationController!.parentViewController! as? MainViewController {
            let vc = rvc.parentViewController! as! RootVC
            vc.openLeftSideViewControllerAnimated(true, completion: nil)
        }
    }
    
    
    // MARK: View life cycle
    override func viewDidLoad() {
        navigationBarTitle = §"menu.settings"
        PKNotification.loading(true)
        
        addMenuBarButton()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LKSettingsViewController.requestSettings),
                                                         name: AbonentInfoManager.NotificationNames.Update, object: AbonentInfoManager.sharedInstance)
        
        //    addBackButtonForDefault(.whiteColor())
        changeNavbar()
        super.viewDidLoad()
        tableView.addGestureRecognizer(tapGestureRecognizer)
        registerForKeyboardAction()
        if AbonentInfoManager.sharedInstance.abonentInfo != nil {
            requestSettings()
        } else {
            AbonentInfoManager.sharedInstance.updateUserInfo()
        }
        
        let params = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!
            ] as [String: AnyObject]
        
        Facade.sharedInstance().getMailNotificationList(params, onSuccess: { mailsList in
            for email in mailsList {
                self._fields[self._fields.count - 2].append(TextField(
                    text: email,
                    title: "",
                    placeholder: "",
                    apiField: "",
                    available: false
                    ))
            }
            self._fields[self._fields.count - 2].append(TextField(text: "", title: "", placeholder: "", apiField: ""))
            self.tableView.beginUpdates()
            var indexPaths:[NSIndexPath] = []
            //      +1 is empty cell to add new mail
            for i in 0..<mailsList.count + 1 {
                indexPaths.append(NSIndexPath(forRow: i, inSection: self.tableView.numberOfSections - 2))
            }
            self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic)
            self.tableView.endUpdates()
            }, onError: { (error) in
                
            }, onFinish: { () in
                
        })
    }
    
    // MARK: Consts
    let _headers = [
        §"settings.personaly",
        §"settings.system",
        §"setttings.notification",
        §"device_settings.label.mail_list",
        §"settings.password",
        ]
    
    @IBAction func hideKeyboardOnTap(sender: UITapGestureRecognizer) {
        view.endEditing(true)
    }
    
    func keyboardDidShow(notification: NSNotification) {
        let info = notification.userInfo!
        var kbRect = info[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue
        kbRect = view.convertRect(kbRect, fromView: nil)
        
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0,
                                         bottom:	kbRect.height, right: 0.0)
        tableView.contentInset = contentInsets
        let aRect = view.frame
        if let textField = activeField where !CGRectContainsPoint(aRect, textField.frame.origin) {
            tableView.scrollRectToVisible(textField.frame, animated: true)
        }
        tapGestureRecognizer.enabled = true
    }
    
    func keyboardWillBeHidden(notification: NSNotification) {
        let contentInsets = UIEdgeInsetsZero
        tableView.contentInset = contentInsets
        tableView.scrollIndicatorInsets = contentInsets
        tapGestureRecognizer.enabled = false
    }
    
    func fillVarsFromFields() {
        
        if let mobilePhone = params["settings.mobile_phone"] as? String, let int64MobilePhone = Int64(mobilePhone) {
            self.mobilePhone = int64MobilePhone
        }
        if let email = params["settings.email"] as? String where !email.isEmpty {
            self.email = email
        }
        if let maximumPasswordChangeAttempt = params["settings.count_password_change"] as? String, let intMaximumPasswordChangeAttempt = Int(maximumPasswordChangeAttempt) {
            self.maximumPasswordChangeAttempt = intMaximumPasswordChangeAttempt
        }
        if let maximumLoginCount = params["settings.count_lk_login_before_change_password"] as? String, let intMaximumLoginCount = Int(maximumLoginCount) {
            self.maximumLoginCount = intMaximumLoginCount
        }
        if let idleTimeout = params["settings.count_unactiv_period"] as? String, let intIdleTimeout =  Int(idleTimeout) {
            self.idleTimeout = intIdleTimeout
        }
        if let isAdv = params["settings.adv"] as? Bool {
            self.isAdv = isAdv
        }
        if let oldPassword = params["settings.old_password"] as? String, let newPassword = params["settings.new_password"] as? String, let retryPassword = params["settings.retry_password"] as? String where !oldPassword.isEmpty && !newPassword.isEmpty && newPassword == retryPassword {
            self.oldPassword = oldPassword
            self.newPassword = newPassword
        }
        
    }
    
    class TextField {
        var text: String
        let title: String
        let placeholder: String
        let apiField: String
        let available: Bool
        let listener: SettingsCellDelegate?
        var withButton : Bool = false
        
        init(text: String, title: String, placeholder: String, apiField: String, listener: SettingsCellDelegate? = nil, available: Bool = true) {
            self.text = text
            self.title = title
            self.placeholder = placeholder
            self.apiField = apiField
            self.listener = listener
            self.available = available
        }
        func setText(text: String){
            self.text = text
        }
    }
    
    class NumberField {
        var text: String
        let title: String
        let placeholder: String
        let apiField: String
        let numberValues: [Int]
        let available: Bool
        var maxLength: Int? = nil
        
        init(text: String, title: String, placeholder: String, apiField: String, numberValues: [Int], available: Bool = true, maxLength: Int? = nil) {
            self.text = text
            self.title = title
            self.placeholder = placeholder
            self.apiField = apiField
            self.numberValues = numberValues
            self.available = true
            self.maxLength = maxLength
        }
    }
    
    class SwitchField {
        var text: String
        let title: String
        let apiField: String
        let available: Bool
        
        init(text: String, title: String, apiField: String, available: Bool = true) {
            self.text = text
            self.title = title
            self.apiField = apiField
            self.available = true
        }
    }
    
    class SecureField {
        var text: String
        let title: String
        let apiField: String
        let available: Bool
        
        init(text: String, title: String, apiField: String, available: Bool = true) {
            self.text = text
            self.title = title
            self.apiField = apiField
            self.available = true
        }
    }
    
    
    private var _fields:[[AnyObject]] = [
        [
            TextField(
                text: (§"settings.your_name").uppercaseString,
                title: "settings.your_name",
                placeholder: §"settings.your_name.placeholder",
                apiField: "",
                available: false
            ),
            TextField(
                text: (§"settings.your_login").uppercaseString,
                title: "settings.your_login",
                placeholder: §"settings.your_login.placeholder",
                apiField: "",
                available: false
            ),
            TextField(
                text: (§"settings.your_guid_cash").uppercaseString,
                title: "settings.your_guid_cash",
                placeholder: §"settings.your_guid_cash.placeholder",
                apiField: "",
                available: false
            ),
            TextField(
                text: (§"settings.mobile_phone").uppercaseString,
                title: "settings.mobile_phone",
                placeholder: §"settings.mobile_phone.placeholder",
                apiField: "",
                available: true
            ),
            //            NumberField(
            //                text: (§"settings.mobile_phone").uppercaseString,
            //                title: "settings.mobile_phone",
            //                placeholder: §"settings.mobile_phone.placeholder",
            //                apiField: "mobile_phone",
            //                numberValues: [],
            //                maxLength: 10
            //            ),
            TextField(
                text: (§"settings.email").uppercaseString,
                title: "settings.email",
                placeholder: §"settings.email.placeholder",
                apiField: "email"),
            TextField(
                text: (§"settings.address").uppercaseString,
                title: "settings.address",
                placeholder: §"settings.address.placeholder",
                apiField: "",
                available: false)
        ],
        //                [
        //                    NumberField(
        //                        text: (§"settings.count_password_change").uppercaseString,
        //                        title: "settings.count_password_change",
        //                        placeholder: "7",
        //                        apiField: "in_max_pswd_change_attempt",
        //                        numberValues: [3,5,7,10]),
        //                    NumberField(
        //                        text: (§"settings.count_lk_login_before_change_password").uppercaseString,
        //                        title: "settings.count_lk_login_before_change_password",
        //                        placeholder: "60",
        //                        apiField: "in_max_logon_count",
        //                        numberValues: [10,20,30,40,50,60]),
        //                    NumberField(
        //                        text: (§"settings.count_unactiv_period").uppercaseString,
        //                        title: "settings.count_unactiv_period",
        //                        placeholder: "15",
        //                        apiField: "out_idle_timeout",
        //                        numberValues: [15,20,30,60]),
        //                    ],
        [],
        [
            SwitchField(
                text: §"settings.adv",
                title: "settings.adv",
                apiField: "in_advertisement"),
        ],
        [],
        [
            SecureField(
                text: (§"settings.old_password").uppercaseString,
                title: "settings.old_password",
                apiField: "old_password"),
            SecureField(
                text: (§"settings.new_password").uppercaseString,
                title: "settings.new_password",
                apiField: "new_password"),
            SecureField(
                text: (§"settings.retry_password").uppercaseString,
                title: "settings.retry_password",
                apiField: "retry_password"),
        ]
    ]
    
    var name: String = ""
    var login: String = ""
    var guidBalance: String = ""
    var mobilePhone: Int64 = 0
    var email: String = ""
    var address: String = ""
    var maximumPasswordChangeAttempt: Int = 0
    var maximumLoginCount: Int = 0
    var idleTimeout: Int = 0
    var isAdv: Bool = false
    var oldPassword = ""
    var newPassword = ""
    var retryPassword = ""
    var newFirstPassword = ""
    var newSecondPassword = ""
    
    private let _textCellIdentifier = "cell"
    private let _switchCellIdentifier = "switchCell"
    private let _buttonCellIdentifier = "buttonCell"
    private var settingsArr = [[AnyObject]]()
    var abonentSettings: AbonentSettings?
    var abonentInfo: AbonentInfo?
    var mailsList: [[String: String]] = []
    
    private func registerForKeyboardAction() {
        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self, selector: #selector(LKSettingsViewController.keyboardDidShow(_:)),
                                       name:UIKeyboardWillShowNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(LKSettingsViewController.keyboardWillBeHidden(_:)),
                                       name: UIKeyboardWillHideNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func requestSettings(){
        abonentInfo = AbonentInfoManager.sharedInstance.abonentInfo!
        Facade.sharedInstance().getAbonentSettings({ (error) -> Void in
            PKNotification.loading(false)
            let alert = UIAlertView(title: "Ошибка", message: error.description, delegate: nil,
                cancelButtonTitle: "OK")
            alert.show()
            }, onSuccess: { (abonentSettings) -> Void in
                self.abonentSettings = abonentSettings
                self.setSettingsToTableView(abonentSettings)
                self.tableView.reloadData()
                PKNotification.loading(false)
        })
        
    }
    
    func setSettingsToTableView(abonentSettings: AbonentSettings){
        if let toSet = abonentInfo?.name {
            name = toSet
        }
        if let toSet = abonentInfo?.login {
            self.login = toSet
        }
        self.guidBalance = "\(Facade.serverId!)-\(Facade.accountId!)"
        if let toSet = abonentSettings.mobilePhone {
            mobilePhone = toSet
        }
        if let toSet = abonentInfo?.email {
            email = toSet
        }
        if let toSet = abonentInfo?.address {
            address = toSet
        }
        if let toSet = abonentSettings.maximumPasswordChangeAttempt {
            maximumPasswordChangeAttempt = toSet
        }
        if let toSet = abonentSettings.maximumLoginCount {
            maximumLoginCount = toSet
        }
        if let toSet = abonentSettings.idleTimeout {
            idleTimeout = toSet
        }
        if let toSet = abonentSettings.isAdv {
            isAdv = toSet
        }
        
        updateSettingsArray()
    }
    
    func updateSettingsArray(){
        settingsArr = [[name, login, guidBalance, String(mobilePhone), email, address],
                       [],
                       //[String(maximumPasswordChangeAttempt), String(maximumLoginCount), String(idleTimeout)],
            [isAdv],
            [],[],[]]
    }
    
    func getPassword(new1: String, new2: String) -> String {
        if new1 == new2 {
            return new1
        }
        else {
            return ""
        }
    }
    
    func isChangedSettings() {
        var changed = false
        
        if let text = params["settings.mobile_phone"] as? String where !text.isEmpty && text != String(self.mobilePhone) {
            changed = true
        }
        if let text = params["settings.email"] as? String where !text.isEmpty && text != self.email {
            changed = true
        }
        if let text = params["settings.count_password_change"] as? String where !text.isEmpty && text != String(maximumPasswordChangeAttempt) {
            changed = true
        }
        if let text = params["settings.count_lk_login_before_change_password"] as? String where !text.isEmpty && text !=  String(maximumLoginCount) {
            changed = true
        }
        if let text = params["settings.count_unactiv_period"] as? String where !text.isEmpty && text != String(idleTimeout) {
            changed = true
        }
        if let on = params["settings.adv"] as? Bool where on != isAdv {
            changed = true
        }
        if let oldPass = params["settings.old_password"] as? String, let newPass = params["settings.new_password"] as? String, let retryPass = params["settings.retry_password"] as? String where !oldPass.isEmpty && !newPass.isEmpty && !retryPass.isEmpty {
            changed = true
        }
        
        self.settingsChanged = changed
        
        changeSaveButtonColor()
    }
    
    func changeAbonentSettings(){
        fillVarsFromFields()
        PKNotification.loading(true)
        
        let abSet = AbonentSettingsRequest(abonentSettings: self.abonentSettings!,
                                           email: email,
                                           maximumPasswordChangeAttempt: Int(maximumPasswordChangeAttempt),
                                           maximumLoginCount: Int(maximumLoginCount),
                                           idleTimeout: Int(idleTimeout),
                                           isAdv: isAdv,
                                           mobilePhone: Int64(mobilePhone),
                                           oldPassword: oldPassword,
                                           newPassword: newPassword)
        guard abSet.validateFields() else { AlertViewUtil.showAlert(abSet.validationMessage); return }
        Facade.sharedInstance().setAbonentSettings(abSet.json,
                                                   onError: { (error) -> Void in
                                                    PKNotification.loading(false)
                                                    let alert = UIAlertView(title: "Ошибка", message: error.description, delegate: nil,
                                                        cancelButtonTitle: "OK")
                                                    alert.show()
            }, onSuccess: { (success) -> Void in
                AbonentInfoManager.sharedInstance.updateUserInfo()
                self.isChangedSettings()
                PKNotification.loading(false)
                AlertViewUtil.showIncorrectAlert(LS("settings.successfully_changed"))
            }, onHalfSuccess:{ (error) -> Void in
                PKNotification.loading(false)
                let alert = UIAlertView(title: "Ошибка", message: error, delegate: nil,
                    cancelButtonTitle: "OK")
                alert.show()
        })
        
    }
    
    func changeSaveButtonColor() {
        if settingsChanged {
            rightBarButtonItem!.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal)
        } else {
            rightBarButtonItem!.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor().colorWithAlphaComponent(0.5)], forState: .Normal)
        }
        rightBarButtonItem!.enabled = settingsChanged
    }
    
    func changeNavbar() {
        configureBlueNavbar()
        //    self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default)
        //    navigationController?.navigationBar.shadowImage = nil
        //    self.navigationController?.navigationBar.barStyle = UIBarStyle.Default
        //    navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
        rightBarButtonItem = UIBarButtonItem(title: LocalizedString("settings.save"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LKSettingsViewController.changeAbonentSettings))
        rightBarButtonItem!.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal)
        rightBarButtonItem!.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor().colorWithAlphaComponent(0.5)], forState: .Highlighted)
        changeSaveButtonColor()
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
    }
}

// MARK: - UITableViewDelegate
extension LKSettingsViewController {
    //  func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    //    return indexPath
    //  }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if let cell = tableView.cellForRowAtIndexPath(indexPath) as? SettingTextFieldTableViewCell,
            let field = _fields[indexPath.section][indexPath.row] as? TextField where field.available {
            cell.textField.becomeFirstResponder()
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        var result : CGFloat = 48.0
        if let field = _fields[indexPath.section][indexPath.row] as? TextField {
            if (field.withButton) {
                return 36
            }
        }
        if let text = (_fields[indexPath.section][indexPath.row] as? TextField)?.text {
            var height: CGFloat = 58.0
            height += heightOtCellHeader(text)
            result = height
        } else if let text = (_fields[indexPath.section][indexPath.row] as? NumberField)?.text {
            var height: CGFloat = 58.0
            height += heightOtCellHeader(text)
            result = height
        } else if let text = (_fields[indexPath.section][indexPath.row] as? SecureField)?.text {
            var height: CGFloat = 58.0
            height += heightOtCellHeader(text)
            result = height
        } else if let text = (_fields[indexPath.section][indexPath.row] as? SwitchField)?.text {
            var height: CGFloat = 58.0
            height += heightOtCellHeader(text, widthWithNoContent: 107)
            result = height
        }
        
        //if (result > 88)
        
        //let text = (_fields[indexPath.section][indexPath.row] as? TextField)?.text
        //print("title: \(text) height: \(result)")
        return 74
    }
    
    private func heightOtCellHeader(text: String, widthWithNoContent: Int = 60) -> CGFloat {
        let labelWidth = Int(view.bounds.width) - widthWithNoContent
        let labelMaxSize = CGSize(width: labelWidth, height: 500)
        let attributes = [NSFontAttributeName: UIFont(name: "PTSans-Regular", size: 12)!] as [String: AnyObject]
        let rect = (text as NSString).boundingRectWithSize(labelMaxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
        
        return rect.height
    }
}


// MARK: - UITableViewDataSource
extension LKSettingsViewController {
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return _headers.count
    }
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return _headers[section]
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return _fields[section].count
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        (cell as? SettingTextFieldTableViewCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
        (cell as? SettingButtonTableViewCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifierForIndexPath(indexPath))!
        
        if (cell.isKindOfClass(SettingTextFieldTableViewCell.classForCoder())) {
            //      (cell as! SettingTextFieldTableViewCell).delegate = self
            //      (cell as! SettingTextFieldTableViewCell).textField.delegate = self
            (cell as! SettingTextFieldTableViewCell).tag = indexPath.section
            (cell as! SettingTextFieldTableViewCell).textField.tag = indexPath.row
        } else if (cell.isKindOfClass(SettingSwitchFieldTableViewCell.classForCoder())) {
            //      (cell as! SettingSwitchFieldTableViewCell).delegate = self
            //            (cell as! SettingSwitchFieldTableViewCell).switchAdv.delegate = self
            (cell as! SettingSwitchFieldTableViewCell).tag = indexPath.section
            (cell as! SettingSwitchFieldTableViewCell).switchAdv.tag = indexPath.row
        }
        setDataInCell(cell, forRowAtIndexPath: indexPath)
        
        if ( indexPath.row == 3 ) {
            if let cell = cell as? SettingTextFieldTableViewCell {
                cell.getTextField().addTarget(self, action: #selector(textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)
                cell.getTextField().keyboardType = .NumberPad
            }
            
        }
        return cell
    }
    
    // MARK: Data helper
    
    private func setDataInCell(cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if let cell = cell as? SettingTextFieldTableViewCell,
            let field = _fields[indexPath.section][indexPath.row] as? TextField {
            cell.fillCell(field.text, fieldTitle: field.title, vc: self)
            cell.setStyle(UIKeyboardType.Default)
            cell.setSecure (false)
            cell.setAvailable(field.available)
            if !settingsArr.isEmpty {
                cell.setTitle(field.text)
                cell.setPlaceholder(field.placeholder)
                if( indexPath.row == 3 ) {
                    cell.setMyTextField(getFormattedPhone(settingsArr[indexPath.section][indexPath.row] as! String))
                    cell.getTextField().keyboardType = .NumberPad
                } else {
                    cell.setMyTextField(settingsArr[indexPath.section][indexPath.row] as! String)
                }
            }
            
        } else if let cell = cell as? SettingButtonTableViewCell, let field = _fields[indexPath.section][indexPath.row] as? TextField {
            cell.fillCell(self)
            field.withButton = true
            cell.textFieldTitle = field.text
            cell.setAvailable(field.available)
            cell.successfullyUpdated = {(addedTrueRemovedFalse) in
                if addedTrueRemovedFalse {
                    self._fields[indexPath.section][self._fields[indexPath.section].count - 1] = TextField(text: cell.textField.text!, title: field.title, placeholder: "", apiField: "", available: false)
                    self._fields[indexPath.section].append(TextField(text: "", title: "", placeholder: "", apiField: ""))
                    
                } else {
                    self._fields[indexPath.section].removeAtIndex(indexPath.row)
                }
                self.tableView.reloadData()
            }
        } else if let cell = cell as? SettingTextFieldTableViewCell,
            let field = _fields[indexPath.section][indexPath.row] as? NumberField {
            cell.fillCell(field.text, fieldTitle: field.title, vc: self, maxLength: field.maxLength)
            cell.setTitle(field.text)
            cell.setPlaceholder(field.placeholder)
            cell.setStyle(UIKeyboardType.NumberPad)
            cell.setSecure (false)
            cell.setAvailable(field.available)
            if !settingsArr.isEmpty {
                cell.setMyTextField(settingsArr[indexPath.section][indexPath.row] as! String)
            }
        } else if let cell = cell as? SettingTextFieldTableViewCell,
            let field = _fields[indexPath.section][indexPath.row] as? SecureField {
            cell.fillCell(field.text, fieldTitle: field.title, vc: self)
            cell.setTitle(field.text)
            cell.setPlaceholder("")
            cell.setStyle(UIKeyboardType.Default)
            cell.setSecure(true)
            cell.setAvailable(field.available)
            if !settingsArr.isEmpty {
                cell.setMyTextField("")
            }
        } else if let cell = cell as? SettingSwitchFieldTableViewCell,
            let field = (_fields[indexPath.section][indexPath.row] as? SwitchField) {
            cell.fillCell(field.text, fieldTitle: field.title, vc: self)
            cell.setTitle(field.text)
            cell.setAvailable(field.available)
            if !settingsArr.isEmpty {
                cell.setSwitch(settingsArr[indexPath.section][indexPath.row] as! Bool)
            }
        }
        
        
    }
    
    func textFieldDidChange(textField: UITextField) {
        let phone = textField.text! as String
        textField.text = getFormattedPhone(phone)
    }
    
    private func cellIdentifierForIndexPath(indexPath: NSIndexPath) -> String {
        switch (indexPath.section, indexPath.row) {
        case (2, 0):
            return _switchCellIdentifier
        case (3, indexPath.row):
            return _buttonCellIdentifier
        default:
            return _textCellIdentifier
        }
    }
}

extension LKSettingsViewController {
    
    func textFieldDidBeginEditing(textField: UITextField) {
        textField.setBottomBorder(Color.BlueButtonColor)
        let cell: UITableViewCell?
        
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
            // Load resources for iOS 6.1 or earlier
            cell = textField.superview?.superview as? UITableViewCell
            
        } else {
            // Load resources for iOS 7 or later
            cell = textField.superview?.superview?.superview as? UITableViewCell
            // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
        }
        if let cell = cell {
            if let indexPath = tableView.indexPathForCell(cell) {
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
            }
        }
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        textField.setBottomBorder(Color.GrayTableCellSeparator)
        activeField = nil
    }
}
