VarienForm = Class.create();
VarienForm.prototype = {
    initialize: function(formId, firstFieldFocus) {
        this.form = $(formId);
        if (!this.form) {
            return;
        }
        this.cache = $A();
        this.currLoader = false;
        this.currDataIndex = false;
        this.validator = new Validation(this.form);
        this.elementFocus = this.elementOnFocus.bindAsEventListener(this);
        this.elementBlur = this.elementOnBlur.bindAsEventListener(this);
        this.childLoader = this.onChangeChildLoad.bindAsEventListener(this);
        this.highlightClass = 'highlight';
        this.extraChildParams = '';
        this.firstFieldFocus = firstFieldFocus || false;
        this.bindElements();
        if (this.firstFieldFocus) {
            try {
                Form.Element.focus(Form.findFirstElement(this.form))
            }
            catch (e) { }
        }
    },

    submit: function(url) {
        if (this.validator && this.validator.validate()) {
            this.form.submit();
        }
        return false;
    },

    bindElements: function() {
        var elements = Form.getElements(this.form);
        for (var row in elements) {
            if (elements[row].id) {
                Event.observe(elements[row], 'focus', this.elementFocus);
                Event.observe(elements[row], 'blur', this.elementBlur);
            }
        }
    },

    elementOnFocus: function(event) {
        var element = Event.findElement(event, 'fieldset');
        if (element && element.className) {
            Element.addClassName(element, this.highlightClass);
        }
    },

    elementOnBlur: function(event) {
        var element = Event.findElement(event, 'fieldset');
        if (element && element.className) {
            Element.removeClassName(element, this.highlightClass);
        }
    },

    setElementsRelation: function(parent, child, dataUrl, first) {
        if (parent = $(parent)) {
            // TODO: array of relation and caching
            if (!this.cache[parent.id]) {
                this.cache[parent.id] = $A();
                this.cache[parent.id]['child'] = child;
                this.cache[parent.id]['dataUrl'] = dataUrl;
                this.cache[parent.id]['data'] = $A();
                this.cache[parent.id]['first'] = first || false;
            }
            Event.observe(parent, 'change', this.childLoader);
        }
    },

    onChangeChildLoad: function(event) {
        element = Event.element(event);
        this.elementChildLoad(element);
    },

    elementChildLoad: function(element, callback) {
        this.callback = callback || false;
        if (element.value) {
            this.currLoader = element.id;
            this.currDataIndex = element.value;
            if (this.cache[element.id]['data'][element.value]) {
                this.setDataToChild(this.cache[element.id]['data'][element.value]);
            }
            else {
                new Ajax.Request(this.cache[this.currLoader]['dataUrl'], {
                    method: 'post',
                    parameters: { "parent": element.value },
                    onComplete: this.reloadChildren.bind(this)
                });
            }
        }
    },

    reloadChildren: function(transport) {
        var data = eval('(' + transport.responseText + ')');
        this.cache[this.currLoader]['data'][this.currDataIndex] = data;
        this.setDataToChild(data);
    },

    setDataToChild: function(data) {
        if (data.length) {
            var child = $(this.cache[this.currLoader]['child']);
            if (child) {
                var html = '<select name="' + child.name + '" id="' + child.id + '" class="' + child.className + '" title="' + child.title + '" ' + this.extraChildParams + '>';
                if (this.cache[this.currLoader]['first']) {
                    html += '<option value="">' + this.cache[this.currLoader]['first'] + '</option>';
                }
                for (var i in data) {
                    if (data[i].value) {
                        html += '<option value="' + data[i].value + '"';
                        if (child.value && (child.value == data[i].value || child.value == data[i].label)) {
                            html += ' selected';
                        }
                        html += '>' + data[i].label + '</option>';
                    }
                }
                html += '</select>';
                Element.insert(child, { before: html });
                Element.remove(child);
            }
        }
        else {
            var child = $(this.cache[this.currLoader]['child']);
            if (child) {
                var html = '<input type="text" name="' + child.name + '" id="' + child.id + '" class="' + child.className + '" title="' + child.title + '" ' + this.extraChildParams + '>';
                Element.insert(child, { before: html });
                Element.remove(child);
            }
        }

        this.bindElements();
        if (this.callback) {
            this.callback();
        }
    }
}

RegionUpdater = Class.create();
RegionUpdater.prototype = {
    initialize: function(countryEl, regionTextEl, regionSelectEl, regions, disableAction) {
        this.countryEl = $(countryEl);
        this.regionTextEl = $(regionTextEl);
        this.regionSelectEl = $(regionSelectEl);
        this.regions = regions;

        this.disableAction = (typeof disableAction == 'undefined') ? 'hide' : disableAction;

        if (this.regionSelectEl.options.length <= 1) {
            this.update();
        }

        Event.observe(this.countryEl, 'change', this.update.bind(this));
    },

    update: function() {
        if (this.regions[this.countryEl.value]) {
            var i, option, region, def;

            if (this.regionTextEl) {
                def = this.regionTextEl.value.toLowerCase();
                this.regionTextEl.value = '';
            }
            if (!def) {
                def = this.regionSelectEl.getAttribute('defaultValue');
            }

            this.regionSelectEl.options.length = 1;
            for (regionId in this.regions[this.countryEl.value]) {
                region = this.regions[this.countryEl.value][regionId];

                option = document.createElement('OPTION');
                option.value = regionId;
                option.text = region.name;

                if (this.regionSelectEl.options.add) {
                    this.regionSelectEl.options.add(option);
                } else {
                    this.regionSelectEl.appendChild(option);
                }

                if (regionId == def || region.name.toLowerCase() == def || region.code.toLowerCase() == def) {
                    this.regionSelectEl.value = regionId;
                }
            }

            if (this.disableAction == 'hide') {
                if (this.regionTextEl) {
                    this.regionTextEl.style.display = 'none';
                }

                this.regionSelectEl.style.display = '';
            } else if (this.disableAction == 'disable') {
                if (this.regionTextEl) {
                    this.regionTextEl.disabled = true;
                }
                this.regionSelectEl.disabled = false;
            }
            this.setMarkDisplay(this.regionSelectEl, true);
        } else {
            if (this.disableAction == 'hide') {
                if (this.regionTextEl) {
                    this.regionTextEl.style.display = '';
                }
                this.regionSelectEl.style.display = 'none';
                Validation.reset(this.regionSelectEl);
            } else if (this.disableAction == 'disable') {
                if (this.regionTextEl) {
                    this.regionTextEl.disabled = false;
                }
                this.regionSelectEl.disabled = true;
            } else if (this.disableAction == 'nullify') {
                this.regionSelectEl.options.length = 1;
                this.regionSelectEl.value = '';
                this.regionSelectEl.selectedIndex = 0;
                this.lastCountryId = '';
            }
            this.setMarkDisplay(this.regionSelectEl, false);
        }
    },

    setMarkDisplay: function(elem, display) {
        if (elem.parentNode) {
            var marks = Element.select(elem.parentNode, '.required');
            if (marks[0]) {
                display ? marks[0].show() : marks[0].hide();
            }
        }
    }
}

function popupCentral(f, l, a, s) {
    momentoAtual = new Date()
    var i = (screen.width - l) / 2;
    var j = (screen.height - a) / 2;
    var myWin = window.open(f, momentoAtual.getTime(), 'resizable=yes,scrollbars=' + s + ',height=' + a + ',width=' + l + ',top=' + j + ',left=' + i);
    myWin.focus();
}

function escreveFlash(URL, WIDTH, HEIGHT, ALLOWFULLSCREEN, TRANSPARENT, FLASHVARS, ID) {
    document.write(' <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="' + ID + '" ');
    document.write(' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" ');
    document.write(' width="' + WIDTH + '" height="' + HEIGHT + '">');
    document.write(' <param name="movie" value="' + URL + '" />');
    document.write(' <param name="quality" value="high" />');
    if (ALLOWFULLSCREEN) {
        document.write(' <param name="allowFullScreen" value="true" />');
    }
    if (TRANSPARENT) {
        document.write(' <param name="Wmode" value="Transparent" />');
    }
    if (FLASHVARS) {
        document.write(' <param name="FlashVars" value="' + FLASHVARS + '" />');
    }
    document.write(' <embed src="' + URL + '" quality="high" ');
    if (ALLOWFULLSCREEN) {
        document.write(' allowFullScreen = "true" ');
    }
    if (TRANSPARENT) {
        document.write(' Wmode = "transparent" ');
    }
    if (FLASHVARS) {
        document.write(' FlashVars = "' + FLASHVARS + '"');
    }
    document.write(' pluginspage="http://www.macromedia.com/go/getflashplayer" ');
    document.write(' type="application/x-shockwave-flash" width="' + WIDTH + '" height="' + HEIGHT + '"></embed> ');
    document.write(' </object>');
}

function SelectAllCheckboxes(spanChk) {

    // Added as ASPX uses SPAN for checkbox

    var oItem = spanChk.children;
    var theBox = (spanChk.type == "checkbox") ?
        spanChk : spanChk.children.item[0];
    xState = theBox.checked;
    elm = theBox.form.elements;

    for (i = 0; i < elm.length; i++)
        if (elm[i].type == "checkbox" &&
              elm[i].id != theBox.id) {
        //elm[i].click();

        if (elm[i].checked != xState)
            elm[i].click();
        //elm[i].checked=xState;

    }
}

function SelecionaParcelas(value) {
    PARCELA = document.getElementById('ctl00_ContentPlaceHolder1_hddParcelas')
    PARCELA.value = value;
}

function parcelamentos(value) {
    try {
    /*
    if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[0] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[0].set_enabled(false);
        }
        if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[1] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[1].set_enabled(false);
        }
        if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[2] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[2].set_enabled(false);
        }
        if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[3] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[3].set_enabled(false);
        }
        if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[4] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[4].set_enabled(false);
        }
        if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[5] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[5].set_enabled(false);
        }
        if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[6] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[6].set_enabled(false);
        }
        if($find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[7] != null){
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[7].set_enabled(false);
        }
*/
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').get_tabs()[value].set_enabled(true);
        $find('ctl00_ContentPlaceHolder1_UC_Parcelamentos_TabContainer').set_activeTabIndex(value);
        
        
        PARCELA = document.getElementById('ctl00_ContentPlaceHolder1_hddParcelas')
        PARCELA.value = '1';

        var theBox = document.forms[0];
        elm = theBox.elements;

        for (i = 0; i < document.forms[0].length; i++)
            if (elm[i].type == "radio" && elm[i].id != 'radio1') {
            elm[i].checked = false;
            }
        else if (elm[i].type == "radio" && elm[i].id == 'radio1') {
            elm[i].checked = true;
        }
    }
    catch (e) { }
}

function parcelamentosid(value) {
    try {       
        
        PARCELA = document.getElementById('ctl00_ContentPlaceHolder1_hddParcelas')
        PARCELA.value = '1';

        var theBox = document.forms[0];
        elm = theBox.elements;

        for (i = 0; i < document.forms[0].length; i++)
            if (elm[i].type == "radio" && elm[i].id != 'radio1') {
            elm[i].checked = false;
            }
        else if (elm[i].type == "radio" && elm[i].id == 'radio1') {
            elm[i].checked = true;
        }
    }
    catch (e) { }
}

function SelectOnlyID(ID){
try { 
    PAGAMENTO = document.getElementById(ID);
    SelectOnly(PAGAMENTO);
    }
    catch (e) { }
}

function SelectOnly(spanChk) {

    // Added as ASPX uses SPAN for checkbox

    var oItem = spanChk.children;
    var theBox = (spanChk.type == "checkbox") ?
        spanChk : spanChk;

    xStateUn = theBox.unchecked;
    elm = theBox.form.elements;

    for (i = 0; i < elm.length; i++)
        if (elm[i].type == "checkbox" &&
              elm[i].id != theBox.id) {
        elm[i].checked = xStateUn;
    }
    else if (elm[i].type == "checkbox" &&
              elm[i].id == theBox.id) {
        elm[i].checked = true;

    }

}

function SelectOnlyRd(spanChk) {

    // Added as ASPX uses SPAN for checkbox

    var oItem = spanChk.children;
    var theBox = (spanChk.type == "radio") ?
        spanChk : spanChk;

    xStateUn = theBox.unchecked;
    elm = theBox.form.elements;

    for (i = 0; i < elm.length; i++)
        if (elm[i].type == "radio" &&
              elm[i].id != theBox.id) {
        elm[i].checked = xStateUn;
    }
    else if (elm[i].type == "radio" &&
              elm[i].id == theBox.id) {
        elm[i].checked = true;

    }

}

function calculaValorVenda(chk_selecionado, PC_MAX_COMISSAO, VL_VENDA, PC_COMISSAO, VL_VENDA_CALCULADO) {
    var moz = !(document.all);
    if (moz) {
        PC_MAX_COMISSAOv = document.getElementById(PC_MAX_COMISSAO);
        VL_VENDAv = document.getElementById(VL_VENDA);

        PC_COMISSAOv = document.getElementById(PC_COMISSAO);
        VL_VENDA_CALCULADOv = document.getElementById(VL_VENDA_CALCULADO);
        if (chk_selecionado != '') {
            chk_selecionadov = document.getElementById(chk_selecionado);
        }

        if (parseInt(PC_COMISSAOv.value) > parseInt(PC_MAX_COMISSAOv.value)) {
            PC_COMISSAOv.value = PC_MAX_COMISSAOv.value;
            VL_VENDA_CALCULADOv.value = VL_VENDAv.value;
        } else {
            var valor = parseFloat(VL_VENDAv.value.replace(',', '.')) - (parseFloat(VL_VENDAv.value.replace(',', '.')) * (parseInt(PC_MAX_COMISSAOv.value) - parseInt(PC_COMISSAOv.value)) / 100);
            if (isNaN(valor)) {
                VL_VENDA_CALCULADOv.value = VL_VENDAv.value;
            } else {
                VL_VENDA_CALCULADOv.value = valor;

                VL_VENDA_CALCULADOv.value = ((Math.round(VL_VENDA_CALCULADOv.value * 100)) / 100);
                if (VL_VENDA_CALCULADOv.value.lastIndexOf('.') == -1) {
                    VL_VENDA_CALCULADOv.value = VL_VENDA_CALCULADOv.value + '.00';
                }
                if (VL_VENDA_CALCULADOv.value.lastIndexOf('.') == VL_VENDA_CALCULADOv.value.length - 2) {
                    VL_VENDA_CALCULADOv.value = VL_VENDA_CALCULADOv.value + '0';
                }
                VL_VENDA_CALCULADOv.value = VL_VENDA_CALCULADOv.value.replace('.', ',');
            }
            if (chk_selecionado != '') {
                chk_selecionadov.checked = true;
            }
        }
        if (PC_COMISSAOv.value == "") {
            PC_COMISSAOv.value = PC_MAX_COMISSAOv.value;
            if (chk_selecionado != '') {
                chk_selecionadov.checked = false;
            }
        }
    }
    else {
        PC_MAX_COMISSAOv = document.getElementById(PC_MAX_COMISSAO);
        VL_VENDAv = document.getElementById(VL_VENDA);

        PC_COMISSAOv = document.getElementById(PC_COMISSAO);
        VL_VENDA_CALCULADOv = document.getElementById(VL_VENDA_CALCULADO);
        if (chk_selecionado != '') {
            chk_selecionadov = document.getElementById(chk_selecionado);
        }

        if (parseInt(PC_COMISSAOv.value) > parseInt(PC_MAX_COMISSAOv.value)) {
            PC_COMISSAOv.value = PC_MAX_COMISSAOv.value;
            VL_VENDA_CALCULADOv.value = VL_VENDAv.value;
        } else {
            var valor = parseFloat(VL_VENDAv.value.replace(',', '.')) - (parseFloat(VL_VENDAv.value.replace(',', '.')) * (parseInt(PC_MAX_COMISSAOv.value) - parseInt(PC_COMISSAOv.value)) / 100);
            if (isNaN(valor)) {
                VL_VENDA_CALCULADOv.value = VL_VENDAv.value;
            } else {
                VL_VENDA_CALCULADOv.value = valor;

                VL_VENDA_CALCULADOv.value = ((Math.round(VL_VENDA_CALCULADOv.value * 100)) / 100);
                if (VL_VENDA_CALCULADOv.value.lastIndexOf('.') == -1) {
                    VL_VENDA_CALCULADOv.value = VL_VENDA_CALCULADOv.value + '.00';
                }
                if (VL_VENDA_CALCULADOv.value.lastIndexOf('.') == VL_VENDA_CALCULADOv.value.length - 2) {
                    VL_VENDA_CALCULADOv.value = VL_VENDA_CALCULADOv.value + '0';
                }
                VL_VENDA_CALCULADOv.value = VL_VENDA_CALCULADOv.value.replace('.', ',');
            }
            if (chk_selecionado != '') {
                chk_selecionadov.checked = true;
            }
        }
        if (PC_COMISSAOv.value == "") {
            PC_COMISSAOv.value = PC_MAX_COMISSAOv.value;
            if (chk_selecionado != '') {
                chk_selecionadov.checked = false;
            }
        }
    }
}

function ToggleHidden(value) {
    $find(value).get_tabs()[3].set_enabled(true);
    $find(value).get_tabs()[4].set_enabled(true);
    $find(value).get_tabs()[5].set_enabled(true);
    $find(value).get_tabs()[6].set_enabled(true);
    $find(value).get_tabs()[7].set_enabled(true);
    $find(value).get_tabs()[8].set_enabled(true);
}

function ToggleHiddenPedido(value) {
    $find(value).get_tabs()[4].set_enabled(true);
    $find(value).get_tabs()[5].set_enabled(true);
    $find(value).get_tabs()[6].set_enabled(true);
    $find(value).get_tabs()[7].set_enabled(true);
    $find(value).get_tabs()[8].set_enabled(true);
    $find(value).get_tabs()[9].set_enabled(true);
}


function comparaEstoque(QTD_COMPRA, QTD_ESTOQUE_TOTAL, ErrorMax) {
    QTD_COMPRAv = document.getElementById(QTD_COMPRA);
    QTD_ESTOQUE_TOTALv = document.getElementById(QTD_ESTOQUE_TOTAL)
    ErrorMaxv = document.getElementById(ErrorMax)
    ErrorMaxv.innerHTML = ''
    if (parseInt(QTD_COMPRAv.value) > parseInt(QTD_ESTOQUE_TOTALv.innerHTML)) {
        QTD_COMPRAv.value = QTD_ESTOQUE_TOTALv.innerHTML;
        ErrorMaxv.innerHTML = 'Máximo de ' + QTD_ESTOQUE_TOTALv.innerHTML + ' unidade(s)';
    }
    if (parseInt(QTD_COMPRAv.value) == 0) {
        QTD_COMPRAv.value = '1';
    }
}

function aumenta(m,g) {
    debugger;
    document.getElementById('mzoom').src = m;
    document.getElementById('zoom').href = g;
}

//global
var anterior = -1;

function switchAba(aba) {
    if (anterior != -1) {
        document.getElementById('conteudo' + anterior).style.display = 'none';
        document.getElementById('conteudo' + anterior).style.visibility = 'hidden';
        var linkinativo = document.getElementById('linkaba' + anterior);
        linkinativo.className = 'AbaInativo';
    }
    else {
        document.getElementById('conteudo0').style.display = 'none';
        document.getElementById('conteudo0').style.visibility = 'hidden';
        var linkinativo = document.getElementById('linkaba0');
        linkinativo.className = 'AbaInativo';
    }

    //link
    var linkativo = document.getElementById('linkaba' + aba);
    linkativo.className = 'AbaAtivo';

    //aba
    document.getElementById('conteudo' + aba).style.display = 'block';
    document.getElementById('conteudo' + aba).style.visibility = 'visible';

    // atribui para esconder a que abriu
    anterior = aba;
}