var NWSselectImagesDir = 'imgs/';

function NWSselect (Parent, Options, Data){
    this.Ver            = '1.0';
    
    this.Parent         = $(Parent);
    this.CSSprefix      = 'NWSselect_';
    
    this.Options        = Options || {};
    if (!this.Options.Mode) this.Options.Mode   = 'SingleLine';
    if (!this.Options.Type) this.Options.Type   = 'Text';
    
    this.ValueNow       = this.Options.Selected;
    
    this.ImgDir         = this.Options.ImagesDir || NWSselectImagesDir;
    
    this.NewData        = true; // Флаг, обозначающий надо ли перерисовывать список
    // устанавливается в True при операциях над списком и изначально. После отрисовки сбрасывается
    
    if (this.Options.Mode == 'SingleLine'){

		if(Parent=='select_newsletter'){
		        this.UpDiv          = Builder.node('div', {'class' : this.CSSprefix + 'UpDiv_newsletter', 'id':'UpDiv_'+Parent});
		}else{
		        this.UpDiv          = Builder.node('div', {'class' : this.CSSprefix + 'UpDiv', 'id':'UpDiv_'+Parent});
		}
        
        this.Table          = Builder.node('table', {'class' : this.CSSprefix + 'upTable'});
        
        this.TBody          = Builder.node('tbody');
        this.TR             = Builder.node('tr', {'class' : this.CSSprefix + 'upTR'});
        this.TD1            = Builder.node('td', {'class' : this.CSSprefix + 'upTD1'});
        this.TD2            = Builder.node('td', {'class' : this.CSSprefix + 'upTD2 ' + this.CSSprefix + 'TextStyle'});
        this.TD3            = Builder.node('td', {'class' : this.CSSprefix + 'upTD3'});
        
        this.TextDiv        = Builder.node('div', {'class' : this.CSSprefix + 'TextDiv'});
        
        this.leftImg        = Builder.node('img', {'class' : this.CSSprefix + 'leftImg'});
        this.Img            = Builder.node('img', {'class' : this.CSSprefix + 'Img'});
        this.Img.alt        = '^';
        this.Img.src        = this.ImgDir + 'close.gif';
		if(Parent=='select_newsletter'){
				this.ListDiv        = Builder.node('div', {'class' : this.CSSprefix + 'ListDiv_newsletter'});
		}else{
				 this.ListDiv        = Builder.node('div', {'class' : this.CSSprefix + 'ListDiv'});
		}
       
        this.Open           = false;
        
        this.TD2.appendChild(this.TextDiv);
        this.TD3.appendChild(this.Img);
        this.TD1.appendChild(this.leftImg);
        this.TR.appendChild(this.TD1);
        this.TR.appendChild(this.TD2);
        this.TR.appendChild(this.TD3);
        this.TBody.appendChild(this.TR);
        this.Table.appendChild(this.TBody);
        
        this.UpDiv.appendChild(this.Table);
        this.UpDiv.appendChild(this.ListDiv);
        this.Parent.appendChild(this.UpDiv);
        Event.observe(this.UpDiv, 'click', this.OpenClose.bindAsEventListener(this));
        Event.observe(this.ListDiv, 'click', this.ListDiv_Click.bindAsEventListener(this));
        Event.observe(this.ListDiv, 'mousemove', this.ListDiv_MouseMove.bindAsEventListener(this));
        Event.observe(this.ListDiv, 'mouseout', this.ListDiv_MouseOut.bindAsEventListener(this));
    } else if (this.Options.Mode == 'MultiLine'){
        this.ListDiv        = Builder.node('div', {'class' : this.CSSprefix + 'ListDiv_MultilimeMode'});
        this.Parent.appendChild(this.ListDiv);
        
        Event.observe(this.ListDiv, 'click', this.ListDiv_Click.bindAsEventListener(this));
        Event.observe(this.ListDiv, 'mousemove', this.ListDiv_MouseMove.bindAsEventListener(this));
        Event.observe(this.ListDiv, 'mouseout', this.ListDiv_MouseOut.bindAsEventListener(this));
    }
    
    this.OldSelectedTR  = null;
    this.LiastDid       = null;
    this.Data           = Data;
    
    
    this.ClickEvent     = null;
    
    if (this.Data) this.Draw();
}

NWSselect.prototype.SetData = function(Data){
    this.Data = Data;
    this.NewData = true;
    this.Draw();
}


NWSselect.prototype.Draw = function(){
    if (! this.Data) return null;
    if (this.Options.Mode == 'SingleLine'){
        
        if (this.Options.Type == 'CheckBoxes'){
            this.TextDiv.innerHTML = '';
            
            var Obj = this;
            var ToPrintArray = [];
            
            if (this.Options.Selected && this.Options.Selected.first){
                this.Options.Selected.each(function(e,i){
                    if (typeof(Obj.Data[e]) == 'object'){
                        if (Obj.Data[e].Caption) ToPrintArray.push(Obj.Data[e].Caption);
                    } else {
                        if (Obj.Data[e]) ToPrintArray.push(Obj.Data[e]);
                    }
                });
            } else {
                if (typeof(this.Data[this.Options.Selected]) == 'object'){
                        if (this.Data[this.Options.Selected].Caption) ToPrintArray.push(this.Data[this.Options.Selected].Caption);
                    } else {
                        if (this.Data[this.Options.Selected]) ToPrintArray.push(this.Data[this.Options.Selected]);
                    }
            }
            
            var tempSeparator = this.Options.Separator || ',';
            if (!ToPrintArray.join(tempSeparator)){
                this.TextDiv.innerHTML = this.Options.EmptyText || 'Select, please';
            } else {
                if (this.Options.DisplayType == 'Count'){
                    this.TextDiv.innerHTML = (this.Options.DisplayCountText || 'Selected: ') + ToPrintArray.size();
                } else {
                    this.TextDiv.innerHTML = ToPrintArray.join(tempSeparator);
                }
            }
        } else {
            
            var UPValue = this.Data[this.ValueNow] || $H(this.Data).values().first();
           
            if (typeof(UPValue) == 'object'){
                this.TextDiv.innerHTML = UPValue.Caption;
                if (this.Options.Type == 'Images'){
                    this.leftImg.src = this.Options.IconsDir + UPValue.Img;
                    this.leftImg.style.display = 'block';
                }
            } else {
                this.TextDiv.innerHTML = UPValue;
            }
            
        }
        
        if (this.Open){
            this.Img.src        = this.ImgDir + 'open.gif';
            Element.addClassName(this.UpDiv, this.CSSprefix + 'List_active');
            // Однострочный селект. Открыт
            
            if (this.NewData){
                this._InsertDataIntoListDiv();
            } else {
                // Данные старые, просто покажем их
               this.ListDiv.style.display  = 'block';
            }
        } else {
            // Однострочный селект. Закрыт
            Element.removeClassName(this.UpDiv, this.CSSprefix + 'List_active');
            this.Img.src        = this.ImgDir + 'close.gif';
            this.ListDiv.style.display  = 'none';
            if (this.Options.AutoDelete){
                if (this.ListDiv.firstChild) this.ListDiv.removeChild(this.ListDiv.firstChild);
                this.NewData = true;
            }
        }
    } else if (this.Options.Mode == 'MultiLine') {
        if (this.NewData){
            this._InsertDataIntoListDiv();
        }
    }
 
}


NWSselect.prototype._InsertDataIntoListDiv = function(){
    // Данные новые, необходимо произвести перерисовку
    // Сначала очистим
    
    if (this.ListDiv.firstChild) this.ListDiv.removeChild(this.ListDiv.firstChild);
    
    if (this.Options.Type == 'Text'){
        var ListTable = Builder.node('table', {'class' : this.CSSprefix + 'ListTable'});
                    
        for (var i in this.Data){
            var tempTBody = Builder.node('tbody', {'class' : this.CSSprefix + 'ListTBody'});
            var tempTR    = Builder.node('tr', {'class' : this.CSSprefix + 'ListTR'});
            tempTR.NWSkey = true;
            var tempTD    = Builder.node('td', {'class' : this.CSSprefix + 'ListTD ' + this.CSSprefix + 'TextStyle'});
            
            if (typeof(this.Data[i]) == 'object'){
                tempTD.innerHTML = this.Data[i].Caption;
                
                if (this.Data[i].Disable){
                    Element.addClassName(tempTR, this.CSSprefix + 'DisableTR');
                    tempTR.NWSselectDisable = true;
                }
                if (this.Data[i].Styles){
                    for (var tempStyle in this.Data[i].Styles){
                        tempTR.style[tempStyle] = this.Data[i].Styles[tempStyle];
                    }
                }
            } else {
                tempTD.innerHTML = this.Data[i];
            }
             
            tempTR.NWSselectID = i;
            
            tempTR.appendChild(tempTD);
            tempTBody.appendChild(tempTR);
            ListTable.appendChild(tempTBody);   
        }
    } else if (this.Options.Type == 'Images'){
        var ListTable = Builder.node('table', {'class' : this.CSSprefix + 'ListTable'});
            
        for (var i in this.Data){
            var tempTBody = Builder.node('tbody', {'class' : this.CSSprefix + 'ListTBody'});
            var tempTR    = Builder.node('tr', {'class' : this.CSSprefix + 'ListTR'});
            tempTR.NWSkey = true;
            var tempImg   = Builder.node('img', {'class' : this.CSSprefix + 'Ico'});
            tempImg.alt   = 'Ico';
            var tempLTD   = Builder.node('td', {'class' : this.CSSprefix + 'ListLTD'});
            var tempRTD   = Builder.node('td', {'class' : this.CSSprefix + 'ListTD ' + this.CSSprefix + 'TextStyle'});
            
            if (typeof(this.Data[i]) == 'object'){
                tempRTD.innerHTML = this.Data[i].Caption;
                
                if (this.Data[i].Disable){
                    Element.addClassName(tempTR, this.CSSprefix + 'DisableTR');
                    tempTR.NWSselectDisable = true;
                }
                if (this.Data[i].Styles){
                    for (var tempStyle in this.Data[i].Styles){
                        tempTR.style[tempStyle] = this.Data[i].Styles[tempStyle];
                    }
                }
            } else {
                tempRTD.innerHTML = this.Data[i];
            }
            
            if (this.Data[i].Img && this.Options.IconsDir)
                tempImg.src = this.Options.IconsDir + this.Data[i].Img;
                        
            tempTR.NWSselectID = i;
                        
            tempLTD.appendChild(tempImg);
            tempTR.appendChild(tempLTD);
            tempTR.appendChild(tempRTD);
            tempTBody.appendChild(tempTR);
            ListTable.appendChild(tempTBody);   
        }
    } else if (this.Options.Type == 'CheckBoxes'){
        var ListTable = Builder.node('table', {'class' : this.CSSprefix + 'ListTable'});
            
        for (var i in this.Data){
            var tempTBody = Builder.node('tbody', {'class' : this.CSSprefix + 'ListTBody'});
            var tempTR    = Builder.node('tr', {'class' : this.CSSprefix + 'ListTR'});
            tempTR.NWSkey = true;
            var tempImg   = Builder.node('img', {'class' : this.CSSprefix + 'Ico'});
            tempImg.alt   = 'Ico';
            
            if (this.Options.Selected && this.Options.Selected.first){ // Если это массив
                if (this.Options.Selected.indexOf(i) != -1){
                    tempImg.src        = this.ImgDir + 'checked.gif';
                    Element.addClassName(tempTR, this.CSSprefix + 'ListTR_Selected');
                } else {
                    tempImg.src        = this.ImgDir + 'nochecked.gif';
                    Element.removeClassName(tempTR, this.CSSprefix + 'ListTR_Selected');
                }
            } else {
                if (this.Options.Selected == i){
                    tempImg.src        = this.ImgDir + 'checked.gif';
                    Element.addClassName(tempTR, this.CSSprefix + 'ListTR_Selected');
                } else {
                    tempImg.src        = this.ImgDir + 'nochecked.gif';
                    Element.removeClassName(tempTR, this.CSSprefix + 'ListTR_Selected');
                }
            }
            var tempLTD   = Builder.node('td', {'class' : this.CSSprefix + 'ListLTD'});
            var tempRTD   = Builder.node('td', {'class' : this.CSSprefix + 'ListTD ' + this.CSSprefix + 'TextStyle'});
            
            if (typeof(this.Data[i]) == 'object'){
                tempRTD.innerHTML = this.Data[i].Caption;
                
                if (this.Data[i].Disable){
                    Element.addClassName(tempTR, this.CSSprefix + 'DisableTR');
                    tempTR.NWSselectDisable = true;
                }
                if (this.Data[i].Styles){
                    for (var tempStyle in this.Data[i].Styles){
                        tempTR.style[tempStyle] = this.Data[i].Styles[tempStyle];
                    }
                }
            } else {
                tempRTD.innerHTML = this.Data[i];
            }
            
            tempTR.NWSselectID = i;
            
            tempLTD.appendChild(tempImg);
            tempTR.appendChild(tempLTD);
            tempTR.appendChild(tempRTD);
            tempTBody.appendChild(tempTR);
            ListTable.appendChild(tempTBody);   
        }
    }
    
    this.ListDiv.appendChild(ListTable);
    this.ListDiv.style.display = 'Block';
    this.NewData = false;
}

NWSselect.prototype.SetEvent = function(func,params, obj){
    this.ClickEvent = {
        'func'	: func,
    	'params': params,
	'obj'	: obj
    };
}

NWSselect.prototype.FireClickEvent = function(id){
    if (this.ClickEvent){ 
        if (this.Options.Type == 'CheckBoxes'){
            if (this.ClickEvent.obj){
                    this.ClickEvent.obj[this.ClickEvent.func](this, this.Options.Selected, this.ClickEvent.params);
            } else {
                    eval(this.ClickEvent.func + '(this, this.Options.Selected, this.ClickEvent.params);');
            }
        } else {
            if (this.ClickEvent.obj){
                    this.ClickEvent.obj[this.ClickEvent.func](this, id, this.ClickEvent.params);
            } else {
                    eval(this.ClickEvent.func + '(this, id, this.ClickEvent.params);');
            }
        }
    }
}

NWSselect.prototype.ListDiv_Click = function(event){
    Event.stop(event);
    
    var tr = Event.findElement(event, 'tr');
    var ID = tr.NWSselectID;
    
    if (tr.NWSselectDisable != true){
        if (this.Options.Type == 'CheckBoxes'){
            if (this.Options.Selected && this.Options.Selected.first){ // Если это массив
                if (this.Options.Selected.indexOf(ID) == -1){ // Такого номера еще нет в списке выделенных
                    this.Options.Selected.push(ID);
                } else {
                    delete(this.Options.Selected[this.Options.Selected.indexOf(ID)])
                }
            } else {
                if (this.Options.Selected != ID){
                    this.Options.Selected = [this.Options.Selected, ID]
                } else {
                    this.Options.Selected = null;
                }
            }
            
            this.NewData = true;
            this.Draw();
        } else {
            Element.addClassName(tr, this.CSSprefix + 'ListTR_Selected');
            if (this.OldSelectedTR) Element.removeClassName(this.OldSelectedTR, this.CSSprefix + 'ListTR_Selected');
            this.OldSelectedTR = tr;
            this.Open = false;
            this.ValueNow = ID;
            this.Draw();
        }
        this.FireClickEvent(ID);
    }
}

NWSselect.prototype.GetValue = function(){
    if (this.Options.Type == 'CheckBoxes'){
        return this.Options.Selected.without('');
    } else {
        return this.ValueNow;
    }
}


NWSselect.prototype.ListDiv_MouseMove = function(event){
    var tr = Event.findElement(event, 'tr');
    
    if (this.LastActive) Element.removeClassName(this.LastActive, this.CSSprefix + 'ListTR_hover');
    
    if (tr.tagName == 'TR' && tr.NWSkey){
        Element.addClassName(tr, this.CSSprefix + 'ListTR_hover');
        this.LastActive = tr;
    }
}

NWSselect.prototype.ListDiv_MouseOut = function(event){
    if (this.LastActive) Element.removeClassName(this.LastActive, this.CSSprefix + 'ListTR_hover');
}

NWSselect.prototype.OpenClose = function(event){
    this.Open = !this.Open;
    this.Draw();
}