local _,ns = ...
local outterFrame = CreateFrame("Frame", nil, UIParent)
local L = ns.L
local toggleAutoScrapOff = nil

local function autoscrapButtonSetOn()
    AutoScrap_CharSettings.autoscrapOn = true
    ns.limpiarCacheAS()
    ns.scrapIventory()
end

local function savePosition(frame)
    AutoScrap_CharSettings.OutterFrame.startPoint, _ , AutoScrap_CharSettings.OutterFrame.relativePoint, AutoScrap_CharSettings.OutterFrame.xOfs, AutoScrap_CharSettings.OutterFrame.yOfs = frame:GetPoint()
end
local function setOFPosition()
    outterFrame:ClearAllPoints()
    outterFrame:SetPoint(AutoScrap_CharSettings.OutterFrame.startPoint,UIParent,AutoScrap_CharSettings.OutterFrame.relativePoint,AutoScrap_CharSettings.OutterFrame.xOfs,AutoScrap_CharSettings.OutterFrame.yOfs)
    --print(AutoScrap_CharSettings.OutterFrame.startPoint,nil,AutoScrap_CharSettings.OutterFrame.relativePoint,AutoScrap_CharSettings.OutterFrame.xOfs,AutoScrap_CharSettings.OutterFrame.yOfs)
end
ns.setOFPosition=setOFPosition

local outterW, outterH =  212, 331
outterFrame:SetPoint("TOPRIGHT",-35, -230) -- ,, offset izq y abajo
outterFrame:SetSize(outterW, outterH) -- tamaño del marco más grande
outterFrame:SetClampedToScreen(true)
outterFrame:SetMovable(true);
outterFrame:SetResizable(false);
outterFrame:EnableMouse(true);
outterFrame:SetToplevel(true);
outterFrame:SetFrameStrata("HIGH");
outterFrame:SetScript("OnMouseDown",function (self,button) if button=="LeftButton" then outterFrame:StartMoving() end end); --StartSizing()
outterFrame:SetScript("OnMouseUp",function (self,button) if button=="LeftButton" then outterFrame:StopMovingOrSizing() savePosition(self) end end);
outterFrame:SetToplevel(true)

local backW, backH = 412-220, 317-10
local f = ns.Utils.crearFrameConTextura (outterFrame,220,412,10,317,0.7)
f:SetPoint("CENTER", outterFrame, "CENTER")
ns.f = f
ns.outterFrame = outterFrame
ns.frameOutterFrame = outterFrame
ns.AttachFrameTabs (outterFrame)

function ns.setMainWindowNewSize(w,h)
    outterFrame:SetSize(w,h)
    f:SetSize(w*backW/outterW,h*backH/outterH)
end

function ns.getOutterSize()
    return outterW, outterH
end

local z = ns.Utils.crearFrameConTextura(f,3,215,0,331,1)
z:SetPoint("CENTER", f, "CENTER")
ns.FrameSetup(z,"MainWindow")

z.statsPanelFrame = ns.Utils.crearFrameConTextura(outterFrame,370,512,166,209,1,"mailpanel")
z.statsPanelFrame:SetPoint("TOP", outterFrame, "BOTTOM",0,8)
--[[ local statsPanelFrameButton = ns.Utils.crearBoton(z.statsPanelFrame,88,22,L["Stats Panel"],function ()
    ns.combatToggle()
end)
statsPanelFrameButton:SetPoint("CENTER",13,3) ]]
local statsPanelFrameButton = CreateFrame("Button", nil, z.statsPanelFrame, "UIPanelButtonTemplate")
statsPanelFrameButton:SetPoint("CENTER",13,4)
statsPanelFrameButton:SetSize(88, 22)
statsPanelFrameButton:SetText(L["Stats Panel"])
statsPanelFrameButton:SetScript("OnClick", function(self, button)
	ns.combatToggle()
end)

local ocultarFrames = nil
z.c = CreateFrame("Button", nil, z)
z.c:SetNormalTexture(130832) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Up"
z.c:SetPushedTexture(130830) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Down"
z.c:SetHighlightTexture(130831) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight"
z.c:SetSize(32, 32)
z.c:SetPoint("TOPRIGHT", z, "TOPRIGHT", 0, -3)
z.c:SetScript("OnClick", function() ocultarFrames() end)


--CreateFrame( "GameTooltip", "AutoScrapTooltip", nil, "GameTooltipTemplate" ); -- nombre de tooltip no puede ser nil
--[[ AutoScrapTooltip:AddFontStrings(
AutoScrapTooltip:CreateFontString( "$parentTextLeft1", nil, "GameTooltipText" ),
AutoScrapTooltip:CreateFontString( "$parentTextRight1", nil, "GameTooltipText" ) ); ]]

--esta función está repetida en los frames, porque se cargan después que la ventana y ya no me apetecía cambiar el esquema, para el próximo addon.
local function setTooltip(parentFrame,...)
    local text1,text2,text3,text4=...
    parentFrame:HookScript("OnEnter", function(self)
        GameTooltip:SetOwner( parentFrame, "ANCHOR_NONE" );
        GameTooltip:SetPoint("TOPLEFT", z, "BOTTOMLEFT", -2, -4)
        if text1 then
        --print(HIGHLIGHT_FONT_COLOR_CODE..text1..FONT_COLOR_CODE_CLOSE)
            GameTooltip:AddLine(NORMAL_FONT_COLOR_CODE..text1..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        if text2 then
            GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..text2..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        if text3 then
            GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..text3..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        if text4 then
            GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..text4..FONT_COLOR_CODE_CLOSE,1,0,0,true)
        end
        --AutoScrapTooltip:AddDoubleLine("prob", "lala")
        GameTooltip:Show()
    end)
    parentFrame:HookScript("OnLeave", function(self)
        GameTooltip:Hide()
    end)
end


local autoScrapOn = ns.Utils.crearFrameConTextura(z, 0,136,388,439, 1)
local autoScrapOff = ns.Utils.crearFrameConTextura(z, 0,136,439,490, 1)
local autoScrapOnToOff = ns.Utils.crearFrameConTextura(z, 0,136,337,388, 1)
local autoScrapOffToOn = ns.Utils.crearFrameConTextura(z, 136,272,337,388, 1)

autoScrapOn:SetPoint("TOP",z,"TOP",0,-38)
autoScrapOff:SetPoint("TOP",z,"TOP",0,-38)
autoScrapOnToOff:SetPoint("TOP",z,"TOP",0,-38)
autoScrapOffToOn:SetPoint("TOP",z,"TOP",0,-38)

autoScrapOff:Hide()
autoScrapOnToOff:Hide()
autoScrapOffToOn:Hide()



z.slider1 = CreateFrame("SLIDER", nil, z, "OptionsSliderTemplate");
z.slider1:SetPoint("TOP", z, "TOP", 0, -105);
z.slider1:SetMinMaxValues(50, 5000);
z.slider1.Low:SetText("50")
z.slider1.High:SetText("5000")
z.slider1:SetValue(AutoScrap_CharSettings.cantidad);
z.title = z:CreateFontString (nil, "OVERLAY", "GameFontHighlight")
-- otra forma: locas success = f.title:SetFont("Fonts\\FRIZQT__.ttf", 11, "OUTLINE") // THICKOUTLINE, MONOCHROME
z.title:SetPoint("TOP", z, "TOP", 0, -92)
z.title:SetText(AutoScrap_CharSettings.cantidad .. "g") -- no hace falta en realidad, se pondrá sólo llegar los datos
--z.slider1:SetUserPlaced(true) --salva la posición al cerrar del usuario
z.slider1:SetValueStep(50);
z.slider1:SetObeyStepOnDrag(true); --fuerza moverse en steps la barrita

function ns.AddOnValueChangedLater()
    z.slider1:SetScript("OnValueChanged", function (self, value)
        AutoScrap_CharSettings.cantidad = value
        --print("valor cambiado")
        ns.updateUI()
        toggleAutoScrapOff()
        --print(value)
    end)
    z.slider1:SetScript("OnMouseWheel", function (self, delta) 
        --print(delta , self:GetValue() , self:GetValueStep())
        AutoScrap_CharSettings.cantidad = AutoScrap_CharSettings.cantidad + ( delta * self:GetValueStep() )
        ns.updateUI()
        toggleAutoScrapOff()
    end) 
end


z.checkDbmarket = CreateFrame("CheckButton", nil, z, "UICheckButtonTemplate");
--z.checkDbmarket:SetPoint("TOPLEFT", z, "TOPLEFT", 38, -140) --antes de quitar el botón de limpiar
z.checkDbmarket:SetPoint("TOPLEFT", z, "TOPLEFT", 38, -131)
z.checkDbmarket.text:SetText(L["DBmarket"]);

z.checkDbregion = CreateFrame("CheckButton", nil, z, "UICheckButtonTemplate");
z.checkDbregion:SetPoint("TOPLEFT", z.checkDbmarket, "TOPLEFT", 0, -22);
z.checkDbregion.text:SetText(L["DBregionmarketavg"]);

z.anillos = CreateFrame("CheckButton", nil, z, "UICheckButtonTemplate");
--z.anillos:SetPoint("TOPLEFT", z.checkDbregion, "TOPLEFT", 32, -32); --antes de quitar el botón de limpiar
z.anillos:SetPoint("TOPLEFT", z.checkDbregion, "TOPLEFT", 32, -35)
z.anillos.text:SetText((L["Rings, Trinkets, Necks"]));

local dialogSETopened = false
local dialogSet
local dialogContext = {}

local SetDialogContext

z.bSetRings = CreateFrame("Button", nil, z, "UIPanelButtonTemplate")
z.bSetRings:SetPoint("TOPRIGHT",z.anillos,"TOPLEFT",-2,-5)
z.bSetRings:SetSize(30, 18)
z.bSetRings:SetText("Set")
z.bSetRings:SetScript("OnClick", function(self, button)
	if(button == "LeftButton") then
        if not dialogSETopened then
            SetDialogContext("Rings")
            dialogSet:Show()
            dialogSETopened = true
        else
            dialogSet:Hide()
            dialogSETopened = false
        end
    end
end)


z.grises = CreateFrame("CheckButton", nil, z, "UICheckButtonTemplate");
z.grises:SetPoint("TOPLEFT", z.anillos, "TOPLEFT", 0, -22);
z.grises.text:SetText(L["Grays"]);

z.bSetGrays = CreateFrame("Button", nil, z, "UIPanelButtonTemplate")
z.bSetGrays:SetPoint("TOPRIGHT",z.grises,"TOPLEFT",-2,-5)
z.bSetGrays:SetSize(30, 18)
z.bSetGrays:SetText("Set")
z.bSetGrays:SetScript("OnClick", function(self, button)
	if(button == "LeftButton") then
        if not dialogSETopened then
            SetDialogContext("Grays")
            dialogSet:Show()
            dialogSETopened = true
        else
            dialogSet:Hide()
            dialogSETopened = false
        end
    end
end)

z.blancos = CreateFrame("CheckButton", nil, z, "UICheckButtonTemplate");
z.blancos:SetPoint("TOPLEFT", z.grises, "TOPLEFT", 0, -22);
z.blancos.text:SetText(L["Whites"]);

z.bSetWhites = CreateFrame("Button", nil, z, "UIPanelButtonTemplate")
z.bSetWhites:SetPoint("TOPRIGHT",z.blancos,"TOPLEFT",-2,-5)
z.bSetWhites:SetSize(30, 18)
z.bSetWhites:SetText("Set")
z.bSetWhites:SetScript("OnClick", function(self, button)
	if(button == "LeftButton") then
        if not dialogSETopened then
            SetDialogContext("Whites")
            dialogSet:Show()
            dialogSETopened = true
        else
            dialogSet:Hide()
            dialogSETopened = false
        end
    end
end)

local played=nil
local handle=nil

z.blizzardScrap = CreateFrame("CheckButton", nil, z, "UICheckButtonTemplate");
--z.blizzardScrap:SetPoint("TOPLEFT", z.checkDbregion, "TOPLEFT", 32, -32); --antes de quitar el botón de limpiar
z.blizzardScrap:SetPoint("TOPLEFT", z.bSetWhites, "TOPLEFT", 0, -25)
z.blizzardScrap.text:SetText((L["Sell default junk"]));
z.blizzardScrap:SetChecked(true)
z.blizzardScrap:SetScript("OnClick", function(self, button)
    if button == "LeftButton" then
        AutoScrap_CharSettings.blizzardDefaultJunk = self:GetChecked()
        toggleAutoScrapOff()
    end
end)

--[[ z.bclear = CreateFrame("Button", nil, z, "UIPanelButtonTemplate")
z.bclear:SetPoint("TOP",z,"TOP",0,-273)
z.bclear:SetSize(100, 20)
z.bclear:SetText(L["Clear Scrap"])
z.bclear:SetScript("OnClick", function(self, button)
	if(button == "LeftButton") then
        ns.limpiarMonedas()
        toggleAutoScrapOff()
        PlaySound(148283)
    end
end) ]]
local dialog = nil

z.bSet = CreateFrame("Button", nil, z, "UIPanelButtonTemplate")
z.bSet:SetPoint("TOPRIGHT",z,"TOPRIGHT",-28,-129)
z.bSet:SetSize(30, 18)
z.bSet:SetText("Set")
z.bSet:SetScript("OnClick", function(self, button)
	if(button == "LeftButton") then
        dialog:Show()
    end
end)

--cuadro de diálogo del botón set para poner el valor del slider. acaba en : -- fin del ..
dialog = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
dialog:SetPoint("CENTER")
dialog:SetSize(150, 40)
dialog:SetFrameStrata("DIALOG")
dialog:SetClipsChildren(true)
dialog:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
    edgeFile = "Interface\\PVPFrame\\UI-Character-PVP-Highlight",
    edgeSize = 16,
    insets = { left = 4, right = 4, top = 4, bottom = 4 },
})
dialog:SetBackdropBorderColor(225/255, 143/256, 60/255  , 0.7)
--:SetVertexColor(r, g, b [, a])

local function comprobarNumeros(value)
    local err = tonumber(value)
    if(err and err%1==0 and err>0)then
        AutoScrap_CharSettings.sliderMax=err
        ns.updateUI()
    end
end

local eb = CreateFrame("EditBox", nil, dialog)
eb:SetSize(100, 40)
eb:SetMaxLetters(7)
eb:SetPoint("LEFT", dialog, "LEFT", 10, 0)
eb:SetMultiLine(false)
eb:SetAutoFocus(true) -- probar false
eb:SetFontObject("ChatFontNormal")
eb:SetText("5000")
eb:HighlightText(0)
eb:SetScript("OnEscapePressed",function() dialog:Hide() end)
eb:SetScript("OnEnterPressed",function() dialog:Hide() comprobarNumeros(eb:GetText()) end)

local dialogButton = CreateFrame("Button", nil, dialog, "UIPanelButtonTemplate")
--dialogButton:SetNormalTexture(130832) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Up"
--dialogButton:SetPushedTexture(130830) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Down"
--dialogButton:SetHighlightTexture(130831) --"Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight"
dialogButton:SetSize(30, 22)
dialogButton:SetText("Set")
dialogButton:SetPoint("RIGHT", dialog, "RIGHT", -8, 0)
dialogButton:SetScript("OnClick", function() dialog:Hide() comprobarNumeros(eb:GetText()) end)

dialog:Hide()

--fin del cuadro del botón set para poner el valor del slider.

z.checkDbmarket:SetScript("OnClick", function (self)
    if self:GetChecked() then
        if z.checkDbregion:GetChecked() then
            AutoScrap_CharSettings.usar2Mercados = true
            AutoScrap_CharSettings.TSM_mercado = "dbmarket"
            toggleAutoScrapOff()
        else
            AutoScrap_CharSettings.usar2Mercados = false
            AutoScrap_CharSettings.TSM_mercado = "dbmarket"
            toggleAutoScrapOff()
        end
    else
        if z.checkDbregion:GetChecked() then
            AutoScrap_CharSettings.usar2Mercados = false
            AutoScrap_CharSettings.TSM_mercado = "dbregionmarketavg"
            toggleAutoScrapOff()
        else
            AutoScrap_CharSettings.usar2Mercados = false
            AutoScrap_CharSettings.TSM_mercado = "dbmarket"
            self:SetChecked(true)
            PlaySound(1213)
        end
    end
    --print(AutoScrap_CharSettings.TSM_mercado, AutoScrap_CharSettings.usar2Mercados)
    --ns.refreshDataBankFrame()
    ns.refreshDataGuildBankFrame()
    ns.limpiarCacheAS()
    ns.updateFarmIconsWithInventoryNumbers()
    ns.recalcFarmItemsOnParty()
    toggleAutoScrapOff()
end)
z.checkDbregion:SetScript("OnClick", function (self)
    if self:GetChecked() then
        if z.checkDbmarket:GetChecked() then
            AutoScrap_CharSettings.usar2Mercados = true
            AutoScrap_CharSettings.TSM_mercado = "dbregionmarketavg"
            toggleAutoScrapOff()
        else
            AutoScrap_CharSettings.usar2Mercados = false
            AutoScrap_CharSettings.TSM_mercado = "dbregionmarketavg"
            toggleAutoScrapOff()
        end
    else
        if z.checkDbmarket:GetChecked() then
            AutoScrap_CharSettings.usar2Mercados = false
            AutoScrap_CharSettings.TSM_mercado = "dbmarket"
            toggleAutoScrapOff()
        else
            AutoScrap_CharSettings.usar2Mercados = false
            AutoScrap_CharSettings.TSM_mercado = "dbregionmarketavg"
            self:SetChecked(true)
            PlaySound(1213)
        end
    end
    --print(AutoScrap_CharSettings.TSM_mercado, AutoScrap_CharSettings.usar2Mercados)
    --ns.refreshDataBankFrame()
    ns.refreshDataGuildBankFrame()
    ns.limpiarCacheAS()
    ns.updateFarmIconsWithInventoryNumbers()
    ns.recalcFarmItemsOnParty()
    toggleAutoScrapOff()
end)

z.anillos:SetScript("OnClick", function (self)
    AutoScrap_CharSettings.venderAnillos = self:GetChecked()
    --ns.scrapIventory()
    toggleAutoScrapOff()
end)
z.grises:SetScript("OnClick", function (self)
    AutoScrap_CharSettings.venderGrises = self:GetChecked()
    --ns.scrapIventory()
    toggleAutoScrapOff()
end)
z.blancos:SetScript("OnClick", function (self)
    AutoScrap_CharSettings.venderBlancos = self:GetChecked()
    --ns.scrapIventory()
    toggleAutoScrapOff()
end)

autoScrapOn:SetScript("OnEnter", function(self,motion)
    if motion then 
        --print("You entered")
        autoScrapOn:Hide()
        autoScrapOnToOff:Show()
    end
end)

autoScrapOnToOff:SetScript("OnLeave", function(self,motion)
    if motion then 
        --print("You leaved") 
        autoScrapOnToOff:Hide()
        autoScrapOn:Show()
    end
end)

autoScrapOnToOff:SetScript("OnMouseUp", function (self, button)
    if button == "LeftButton" then
        --print("You clicked me with "..button)
        autoScrapOnToOff:Hide()
        autoScrapOffToOn:Show()
        AutoScrap_CharSettings.autoscrapOn = false
        ns.limpiarCacheAS()
        ns.limpiarASjunkTable()
        if handle then
            StopSound(handle)
        end
    end
end)

autoScrapOffToOn:SetScript("OnLeave", function(self,motion)
    if motion then 
        --print("You leaved") 
        autoScrapOff:Show() 
        autoScrapOffToOn:Hide()
    end
end)

autoScrapOff:SetScript("OnEnter", function(self,motion)
    if motion then 
        --print("You entered") 
        autoScrapOff:Hide() 
        autoScrapOffToOn:Show()
    end
end)

autoScrapOffToOn:SetScript("OnMouseUp", function (self, button)
    if button == "LeftButton" then
        --print("You clicked me with "..button)
        autoScrapOffToOn:Hide()
        autoScrapOnToOff:Show()
        autoscrapButtonSetOn()
        played,handle = PlaySound(416)
    end
end)

toggleAutoScrapOff = function (fromButton)
    if ns.PLAYER_LOGIN then --No lo hace cuando llega ADDON_LOADED hasta que entra al mundo para evitar que empiece siempre en off.
        if fromButton then --ahora mismo esto no ocurre, porque es nil en todos
            autoScrapOnToOff:Hide()
            autoScrapOffToOn:Hide()
            autoScrapOff:Show()
            autoScrapOn:Hide()
            AutoScrap_CharSettings.autoscrapOn = false
            ns.limpiarCacheAS()
            ns.limpiarASjunkTable()
            if handle then
                StopSound(handle)
            end
        else
            if AutoScrap_CharSettings.autoscrapOn then
                ns.limpiarCacheAS()
                ns.limpiarASjunkTable()
                autoscrapButtonSetOn()
            end
        end
    end
end
ns.toggleAutoScrapOff = toggleAutoScrapOff
ns.autoscrapButtonSetOn = autoscrapButtonSetOn


dialogSet = function ()
    dialogSETopened = true
end

--cuadro del botón set poner el valor de anillos trinkets collares grises y blancos. Acaba en : -- fin del ..

dialogContext.type = "Rings"
dialogContext.title = "title"
dialogContext.gold = 999999
dialogContext.iLevel = 380
dialogContext.rate = 0.2


dialogSet = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
dialogSet:SetPoint("CENTER",0,170)
dialogSet:SetSize(300, 200)
dialogSet:SetFrameStrata("DIALOG")
--dialogSet:SetClipsChildren(true)
dialogSet:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
    edgeFile = "Interface\\PVPFrame\\UI-Character-PVP-Highlight",
    edgeSize = 16,
    insets = { left = 4, right = 4, top = 4, bottom = 4 },
})
dialogSet:SetBackdropBorderColor(225/255, 143/256, 60/255  , 0.7)
-- no tiene dialogSet:SetScript("OnEscapePressed",function() dialogSet:Hide()dialogSETopened = false end)

local title = CreateFrame("Frame", nil, dialogSet, "BackdropTemplate")
title:SetSize(180, 32)
title:SetPoint("TOP",dialogSet,"TOP",0,15) --7
title:SetFrameStrata("DIALOG")
title:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-dark",
    edgeFile = "Interface\\PVPFrame\\UI-Character-PVP-Highlight",
    edgeSize = 16,
    insets = { left = 4, right = 4, top = 4, bottom = 4 },
})
title:SetBackdropBorderColor(225/255, 143/256, 60/255  , 0.7)

local titleText = title:CreateFontString (nil, "OVERLAY", "GameFontHighlight")
titleText:SetPoint("CENTER",title,"CENTER")
titleText:SetText("Probando 123")

local descText = title:CreateFontString (nil, "OVERLAY", "GameFontNormal")
descText:SetPoint("TOPLEFT",dialogSet,"TOPLEFT",20,-25)
descText:SetJustifyH("LEFT")
descText:SetText("Sell Accesories from 0g to "..dialogContext.gold.."g\nDon't sell if iLevel is bigger than "..dialogContext.iLevel.."\nDon't sell if rate is bigger than "..dialogContext.rate)

dialogSet.gold={}

dialogSet.gold.t = title:CreateFontString (nil, "OVERLAY", "GameFontNormal")
dialogSet.gold.t:SetPoint("TOPLEFT",descText,"BOTTOMLEFT",10,-25)
dialogSet.gold.t:SetJustifyH("LEFT")
dialogSet.gold.t:SetText("Gold: ")

dialogSet.gold.backFrame = CreateFrame("Frame", nil, dialogSet)
dialogSet.gold.backFrame:SetPoint("LEFT", dialogSet.gold.t, "RIGHT", 5, 0)
dialogSet.gold.backFrame:SetSize(70, 18)
dialogSet.gold.backFrame.tex = dialogSet.gold.backFrame:CreateTexture()
dialogSet.gold.backFrame.tex:SetAllPoints(dialogSet.gold.backFrame)
dialogSet.gold.backFrame.tex:SetColorTexture(255/255, 20/255, 147/255 , 0.2); --rgb

dialogSet.gold.e = CreateFrame("EditBox", nil, dialogSet)
dialogSet.gold.e:SetSize(70, 18)
dialogSet.gold.e:SetMaxLetters(7)
dialogSet.gold.e:SetPoint("LEFT", dialogSet.gold.t, "RIGHT", 5, 0)
dialogSet.gold.e:SetMultiLine(false)
dialogSet.gold.e:SetAutoFocus(true) -- probar false
dialogSet.gold.e:SetFontObject("ChatFontNormal")
dialogSet.gold.e:SetText(dialogContext.gold)
dialogSet.gold.e:HighlightText(0)
dialogSet.gold.e:SetScript("OnEscapePressed",function() dialogSet:Hide() dialogSETopened = false end)
--dialogSet.gold.e:SetScript("OnEnterPressed",function() dialogSet:Hide() comprobarNumeros(eb:GetText()) end)


dialogSet.iLevel={}

dialogSet.iLevel.t = title:CreateFontString (nil, "OVERLAY", "GameFontNormal")
dialogSet.iLevel.t:SetPoint("TOPLEFT",dialogSet.gold.t,"BOTTOMLEFT",0,-10)
dialogSet.iLevel.t:SetJustifyH("LEFT")
dialogSet.iLevel.t:SetText("iLevel: ")

dialogSet.iLevel.backFrame = CreateFrame("Frame", nil, dialogSet)
dialogSet.iLevel.backFrame:SetPoint("LEFT", dialogSet.iLevel.t, "RIGHT", 5, 0)
dialogSet.iLevel.backFrame:SetSize(70, 18)
dialogSet.iLevel.backFrame.tex = dialogSet.iLevel.backFrame:CreateTexture()
dialogSet.iLevel.backFrame.tex:SetAllPoints(dialogSet.iLevel.backFrame)
dialogSet.iLevel.backFrame.tex:SetColorTexture(255/255, 20/255, 147/255 , 0.2); --rgb

dialogSet.iLevel.e = CreateFrame("EditBox", nil, dialogSet)
dialogSet.iLevel.e:SetSize(70, 18)
dialogSet.iLevel.e:SetMaxLetters(7)
dialogSet.iLevel.e:SetPoint("LEFT", dialogSet.iLevel.t, "RIGHT", 5, 0)
dialogSet.iLevel.e:SetMultiLine(false)
dialogSet.iLevel.e:SetAutoFocus(false) -- probar false
dialogSet.iLevel.e:SetFontObject("ChatFontNormal")
dialogSet.iLevel.e:SetText(dialogContext.iLevel)
--dialogSet.iLevel.e:HighlightText(0)
dialogSet.iLevel.e:SetScript("OnEscapePressed",function() dialogSet:Hide() dialogSETopened = false end)
--dialogSet.iLevel.e:SetScript("OnEnterPressed",function() dialogSet:Hide() comprobarNumeros(eb:GetText()) end)

dialogSet.rate={}

dialogSet.rate.t = title:CreateFontString (nil, "OVERLAY", "GameFontNormal")
dialogSet.rate.t:SetPoint("TOPLEFT",dialogSet.iLevel.t,"BOTTOMLEFT",0,-10)
dialogSet.rate.t:SetJustifyH("LEFT")
dialogSet.rate.t:SetText("Sell Rate: ")

dialogSet.rate.backFrame = CreateFrame("Frame", nil, dialogSet)
dialogSet.rate.backFrame:SetPoint("LEFT", dialogSet.rate.t, "RIGHT", 5, 0)
dialogSet.rate.backFrame:SetSize(70, 18)
dialogSet.rate.backFrame.tex = dialogSet.rate.backFrame:CreateTexture()
dialogSet.rate.backFrame.tex:SetAllPoints(dialogSet.rate.backFrame)
dialogSet.rate.backFrame.tex:SetColorTexture(255/255, 20/255, 147/255 , 0.2); --rgb

dialogSet.rate.e = CreateFrame("EditBox", nil, dialogSet)
dialogSet.rate.e:SetSize(70, 18)
dialogSet.rate.e:SetMaxLetters(7)
dialogSet.rate.e:SetPoint("LEFT", dialogSet.rate.t, "RIGHT", 5, 0)
dialogSet.rate.e:SetMultiLine(false)
dialogSet.rate.e:SetAutoFocus(false) -- probar false
dialogSet.rate.e:SetFontObject("ChatFontNormal")
dialogSet.rate.e:SetText(dialogContext.rate)
--dialogSet.rate.e:HighlightText(0)
dialogSet.rate.e:SetScript("OnEscapePressed",function() dialogSet:Hide() dialogSETopened = false end)
--dialogSet.rate.e:SetScript("OnEnterPressed",function() dialogSet:Hide() comprobarNumeros(eb:GetText()) end)

local function comprobarNumerosGold(value)
    local err = tonumber(value)
    if(err and err%1==0 and err>=1 and err<=99999999)then
        if dialogContext.type == "Rings"then
            AutoScrap_CharSettings.ringsGold=err
        elseif dialogContext.type == "Grays"then
            AutoScrap_CharSettings.graysGold=err
        elseif dialogContext.type == "Whites"then
            AutoScrap_CharSettings.whitesGold=err
        end
        ns.updateUI()
    end
end
local function comprobarNumerosIlevel(value)
    local err = tonumber(value)
    if(err and err%1==0 and err>=1 and err<=999)then
        if dialogContext.type == "Rings"then
            AutoScrap_CharSettings.ringsiLevel=err
        elseif dialogContext.type == "Grays"then
            AutoScrap_CharSettings.graysiLevel=err
        elseif dialogContext.type == "Whites"then
            AutoScrap_CharSettings.whitesiLevel=err
        end
        ns.updateUI()
    end
end
local function comprobarNumerosRate(value)
    value=value:gsub("%,", ".")
    local err = tonumber(value)
    if(err and err>=0.01 and err<=1)then
        err = math.floor(err * 100+ 0.5) / 100
        if dialogContext.type == "Rings"then
            AutoScrap_CharSettings.ringsRate=err
        elseif dialogContext.type == "Grays"then
            AutoScrap_CharSettings.graysRate=err
        elseif dialogContext.type == "Whites"then
            AutoScrap_CharSettings.whitesRate=err
        end
        ns.updateUI()
    end
end

local dialogSetButton = CreateFrame("Button", nil, dialogSet, "UIPanelButtonTemplate")
dialogSetButton:SetSize(80, 22)
dialogSetButton:SetText(L["Save"])
dialogSetButton:SetPoint("BOTTOM", dialogSet, "BOTTOM", -90, 22)
dialogSetButton:SetScript("OnClick", function() dialogSETopened = false comprobarNumerosGold(dialogSet.gold.e:GetText()) comprobarNumerosIlevel(dialogSet.iLevel.e:GetText()) comprobarNumerosRate(dialogSet.rate.e:GetText()) ns.limpiarCacheAS() toggleAutoScrapOff() dialogSet:Hide() end) -- aquí comprobar los datos.

local dialogExitButton = CreateFrame("Button", nil, dialogSet, "UIPanelButtonTemplate")
dialogExitButton:SetSize(170, 22)
dialogExitButton:SetText(L["Exit without saving"])
dialogExitButton:SetPoint("LEFT", dialogSetButton, "RIGHT", 8, 0)
dialogExitButton:SetScript("OnClick", function() dialogSETopened = false dialogSet:Hide() end) -- aquí comprobar los datos.

dialogSet:Hide()

SetDialogContext = function (type)
    if type == "Rings" then
        dialogContext.title = L["Rings, Trinkets, Necks"]
        dialogContext.gold = AutoScrap_CharSettings.ringsGold
        dialogContext.iLevel = AutoScrap_CharSettings.ringsiLevel
        dialogContext.rate = AutoScrap_CharSettings.ringsRate
        descText:SetText(L["Sell "]..L["Rings, Trinkets, Necks"]..L[" from 0g to "]..dialogContext.gold..L["g\nDon't sell if iLevel is bigger than "]..dialogContext.iLevel..L["\nDon't sell if rate is bigger than "]..dialogContext.rate)
    elseif type == "Grays" then
        dialogContext.title = L["Grays"]
        dialogContext.gold = AutoScrap_CharSettings.graysGold
        dialogContext.iLevel = AutoScrap_CharSettings.graysiLevel
        dialogContext.rate = AutoScrap_CharSettings.graysRate
        descText:SetText(L["Sell "]..L["Grays"]..L[" from 0g to "]..dialogContext.gold..L["g\nDon't sell if iLevel is bigger than "]..dialogContext.iLevel..L["\nDon't sell if rate is bigger than "]..dialogContext.rate)
    elseif type == "Whites" then
        dialogContext.title = L["Whites"]
        dialogContext.gold = AutoScrap_CharSettings.whitesGold
        dialogContext.iLevel = AutoScrap_CharSettings.whitesiLevel
        dialogContext.rate = AutoScrap_CharSettings.whitesRate
        descText:SetText(L["Sell "]..L["Whites"]..L[" from 0g to "]..dialogContext.gold..L["g\nDon't sell if iLevel is bigger than "]..dialogContext.iLevel..L["\nDon't sell if rate is bigger than "]..dialogContext.rate)
    end
    dialogSet.gold.e:SetText(dialogContext.gold)
    dialogSet.iLevel.e:SetText(dialogContext.iLevel)
    dialogSet.rate.e:SetText(dialogContext.rate)
    titleText:SetText(dialogContext.title)
    dialogContext.type=type
end

--fin del cuadro del botón set poner el valor de anillos trinkets collares grises y blancos

local function updateUI()
    --set button:
    if not ns.fatalError then
        if AutoScrap_CharSettings.autoscrapOn then
            autoScrapOff:Hide()
            autoScrapOn:Show()
        else
            autoScrapOn:Hide()
            autoScrapOff:Show()
        end

        --checks
        z.blizzardScrap:SetChecked(AutoScrap_CharSettings.blizzardDefaultJunk)
        
        if AutoScrap_CharSettings.usar2Mercados then
            z.checkDbmarket:SetChecked(true)
            z.checkDbregion:SetChecked(true)
        elseif AutoScrap_CharSettings.TSM_mercado == "dbregionmarketavg" then
            z.checkDbmarket:SetChecked(false)
            z.checkDbregion:SetChecked(true)
        else
            z.checkDbmarket:SetChecked(true)
            z.checkDbregion:SetChecked(false)
        end
        z.anillos:SetChecked(AutoScrap_CharSettings.venderAnillos)
        z.grises:SetChecked(AutoScrap_CharSettings.venderGrises)
        z.blancos:SetChecked(AutoScrap_CharSettings.venderBlancos)

        --print("cantidad entrada -> ",AutoScrap_CharSettings.cantidad)
        --slider range
        if AutoScrap_CharSettings.sliderMax <= 100 then
            --local tempCantidad = AutoScrap_CharSettings.cantidad -- al cambiar la resolución se ejecuta onvaluechange detro, la primera vez estaba a 50,5000 
            z.slider1:SetMinMaxValues(1,100)
            --AutoScrap_CharSettings.cantidad = tempCantidad
            --print("fix: ",tempCantidad)
            z.slider1:SetValueStep(1)
            z.slider1.Low:SetText(1)
            z.slider1.High:SetText(100)
            if AutoScrap_CharSettings.cantidad > 100 then
                AutoScrap_CharSettings.cantidad = 100
                z.title:SetText("100g")
            elseif AutoScrap_CharSettings.cantidad < 1 then
                AutoScrap_CharSettings.cantidad = 1
                z.title:SetText("1g")
            end
            --print("cantidad medio -> ",AutoScrap_CharSettings.cantidad)
        elseif AutoScrap_CharSettings.sliderMax <= 500 then
            z.slider1:SetMinMaxValues(5,500)
            z.slider1:SetValueStep(5)
            z.slider1.Low:SetText(5)
            z.slider1.High:SetText(500)
            if AutoScrap_CharSettings.cantidad > 500 then
                AutoScrap_CharSettings.cantidad = 500
                z.title:SetText("500g")
            elseif AutoScrap_CharSettings.cantidad < 5 then
                AutoScrap_CharSettings.cantidad = 5
                z.title:SetText("5g")
            end
        elseif AutoScrap_CharSettings.sliderMax <= 2000 then
            z.slider1:SetMinMaxValues(20,2000)
            z.slider1:SetValueStep(20)
            z.slider1.Low:SetText(20)
            z.slider1.High:SetText(2000)
            if AutoScrap_CharSettings.cantidad > 2000 then
                AutoScrap_CharSettings.cantidad = 2000
                z.title:SetText("2000g")
            elseif AutoScrap_CharSettings.cantidad < 20 then
                AutoScrap_CharSettings.cantidad = 20
                z.title:SetText("20g")
            end
        elseif AutoScrap_CharSettings.sliderMax <= 5000 then
            z.slider1:SetMinMaxValues(50,5000)
            z.slider1:SetValueStep(50)
            z.slider1.Low:SetText(50)
            z.slider1.High:SetText(5000)
            if AutoScrap_CharSettings.cantidad > 5000 then
                AutoScrap_CharSettings.cantidad = 5000
                z.title:SetText("5000g")
            elseif AutoScrap_CharSettings.cantidad < 50 then
                AutoScrap_CharSettings.cantidad = 50
                z.title:SetText("50g")
            end
        else
            z.slider1:SetMinMaxValues(250,AutoScrap_CharSettings.sliderMax)
            z.slider1:SetValueStep(250)
            z.slider1.Low:SetText(250)
            z.slider1.High:SetText(AutoScrap_CharSettings.sliderMax)
            if AutoScrap_CharSettings.cantidad > AutoScrap_CharSettings.sliderMax then
                AutoScrap_CharSettings.cantidad = AutoScrap_CharSettings.sliderMax
                z.title:SetText(AutoScrap_CharSettings.sliderMax.."g")
            elseif AutoScrap_CharSettings.cantidad < 250 then
                AutoScrap_CharSettings.cantidad = 250
                z.title:SetText("250g")
            end
        end
        --print("cantidad salida -> ",AutoScrap_CharSettings.cantidad)

        --slider
        z.slider1:SetValue(AutoScrap_CharSettings.cantidad)
        z.title:SetText(AutoScrap_CharSettings.cantidad.."g")
        ns.escribirItemsEnScrollPanel()

        ns.setIlevel()
        ns.setSellRatio()
        ns.setProtectSouldBind(AutoScrap_CharSettings.protectSouldBinds)
        ns.setProtectIlevel(AutoScrap_CharSettings.protectedIlevel)
        ns.setProtectRatio(AutoScrap_CharSettings.protectedRatio)
        ns.setConsumables(AutoScrap_CharSettings.protectedConsumables)
        ns.setRecipes(AutoScrap_CharSettings.protectedRecipes)
        ns.setCooking(AutoScrap_CharSettings.protectedCooking)
        ns.setLeather(AutoScrap_CharSettings.protectedLeather)
        ns.setCloths(AutoScrap_CharSettings.protectedCloths)
        ns.setHerbs(AutoScrap_CharSettings.protectedHerbs)
        ns.setMining(AutoScrap_CharSettings.protectedMining)
        ns.setBoxes(AutoScrap_CharSettings.protectedBoxes)
        ns.setJewelry(AutoScrap_CharSettings.protectedJewelry)
        ns.setInscription(AutoScrap_CharSettings.protectedInscription)

        ns.setAutoLoot(AutoScrap_CharSettings.AutoLoot)
        ns.setAutoSell (AutoScrap_CharSettings.autoSell)
        ns.setAutoRepair (AutoScrap_CharSettings.autoRepair)
     ---no escribir por debajo de esto update ui, es fatal error
    else --end fatal fatalError
        AutoScrap_CharSettings.autoscrapOn = false
    end

end
ns.updateUI = updateUI
--updateUI()
ocultarFrames = function ()
    ns.f:Hide() ns.frameOutterFrame:Hide()
end
local mostrarFrames = function ()
    ns.f:Show() ns.frameOutterFrame:Show()
end
ns.mostrarFrames = mostrarFrames
ns.ocultarFrames = ocultarFrames
ocultarFrames()

ns.fatalError = false
local function fatalError(...)
    local text1,text2 = ...
    ns.tabToMainForFatalError()
    autoScrapOnToOff:Hide()
    autoScrapOffToOn:Hide()
    autoScrapOff:Hide()
    autoScrapOn:Hide()
    z.slider1:Hide()
    z.bSet:Hide()
    z.anillos:Hide()
    z.blancos:Hide()
    z.grises:Hide()
    z.checkDbmarket:Hide()
    z.checkDbregion:Hide()
    z.title:Hide()
    --z.bclear:Hide()
    z.bSetRings:Hide()
    z.bSetGrays:Hide()
    z.bSetWhites:Hide()
    ns.fatalError = true
    updateUI()

    z.fatalError1 = z:CreateFontString (nil, "OVERLAY", "GameFontHighlight")
    z.fatalError1:SetPoint("TOP", z, "TOP", 0, -92)
    z.fatalError1:SetText(text1)
    z.fatalError2 = z:CreateFontString (nil, "OVERLAY", "GameFontHighlight")
    z.fatalError2:SetPoint("TOP", z, "TOP", 0, -102)
    z.fatalError2:SetText(text2)
end
--fatalError("probando","wwwww.aki y alisd d d.comwwwww.aki y alisd d d.com")
ns.fatalErrorFunction = fatalError

--setTooltip(outterFrame)
setTooltip(z.bSet,"SET", L["Sets the max range of the gold slider for better accuracy"], L["It sets the step increments according with the range"])
setTooltip(z.slider1,L["Slider"], L["Choose a gold value to flag Scrap that cost less than it"],L["Mousewheel also works"])
setTooltip(z.checkDbmarket,L["Dbmarket"],L["It uses the TSM Dbmarket data (your current server prices) to get the selling price in the auction house."],L["If dbregionmarketavg is also on, then It will get the best selling price between the 2"])
setTooltip(z.checkDbregion,L["Dbregionmarketavg"],L["It uses the TSM Dbregionmarketavg data (An average price between all your region servers) to get the selling price in the auction house."],L["If Dbmarket is also on, then It will get the best selling price between the 2"])
setTooltip(z.anillos,L["Rings, Trinkets, Necks"], L["Always Scrap all the rings, trinkets and necks, whatever is their selling price in the AH"])
setTooltip(z.grises,L["Grays"], L["Always Scrap all the gray items, no matter of their selling price in the AH"])
setTooltip(z.blancos,L["Whites"], L["Always Scrap all the white items, no matter of their selling price in the AH"])
--setTooltip(z.bclear,L["Clear Scrap"],L["It removes the current selection of Scrap items of your inventory"],L["It removes only the scrap marks, it doesn't destroy the items"])
setTooltip(autoScrapOn,L["AutoScrap"],L["When AutoScrap is set to On (bubble gum color) it will mark as Scrap all the items in your inventory when you loot them"],L["I will run automatically all the time unless you turned it off."],L["This addon only mark items as scrap, it doesn't destroy or sell them, they will get sold with the Scrap addon when you open the vender NPC"])
setTooltip(autoScrapOff,L["AutoScrap"],L["When AutoScrap is set to On (bubble gum color) it will mark as Scrap all the items in your inventory when you loot them"],L["I will run automatically all the time unless you turned it off."],L["This addon only mark items as scrap, it doesn't destroy or sell them, they will get sold with the Scrap addon when you open the vender NPC"])
setTooltip(autoScrapOnToOff,L["AutoScrap"],L["When AutoScrap is set to On (bubble gum color) it will mark as Scrap all the items in your inventory when you loot them"],L["I will run automatically all the time unless you turned it off."],L["This addon only mark items as scrap, it doesn't destroy or sell them, they will get sold with the Scrap addon when you open the vender NPC"])
setTooltip(autoScrapOffToOn,L["AutoScrap"],L["When AutoScrap is set to On (bubble gum color) it will mark as Scrap all the items in your inventory when you loot them"],L["I will run automatically all the time unless you turned it off."],L["This addon only mark items as scrap, it doesn't destroy or sell them, they will get sold with the Scrap addon when you open the vender NPC"])
setTooltip(z.bSetRings,"Set "..L["Rings, Trinkets, Necks"],L["You can setup a stop loss to sell all the Rings, Trinkets and Necks."],L["For example: You can sell all Rings but under 25,000 gold or 0.08 Sell rate insted of ANY."])
setTooltip(z.bSetGrays,"Set "..L["Grays"],L["You can setup a stop loss to sell all the gray armors and weapons."],L["For example: You can sell all Gray Weapons but under 25,000 gold or 0.08 Sell rate insted of ANY."])
setTooltip(z.bSetWhites,"Set "..L["Whites"],L["You can setup a stop loss to sell all the white armors and weapons."],L["For example: You can sell all white Armors but under 25,000 gold or 0.08 Sell rate insted of ANY."])
setTooltip(z.blizzardScrap,L["Sell default junk"],L["Blizzard marks junk items (typically gray quality) with coin icons when you talk to a vendor."],L["Enabling this option automatically sells all marked items upon opening the vendor window"])
--L[""]