// def var from my asset manager


myAssetsManager = function(){
    this.init();
};


myAssetsManager.prototype = {
    cstNum : null,
    type : 'guest',
    assetList : '',
    addAssetUrl : "myAssets/addAsset.aspx?",
    addAssetsUrl : "myAssets/addAssets.aspx?",
    removeAssetUrl : "myAssets/removeAsset.aspx?",
    getAssetUrl : "myAssets/myAssets.aspx?",
    
    addRemoveAsset :function(src,evt,e)
    {
        
        var id;
        var type;
        if(src.tagName == "INPUT")
        {
        
            id = src.id.replace("listchk","").replace("my","").replace("sa","");
            type = "chk";
        }
        else
        {
            id = evt.id.replace("display","");
            type = "div";
        }
        if(this.assetList.indexOf(id + "|") == -1)
        {
            this.addToList(id,type);
        }
        else
        {
            this.removeFromList(id);
        }
    },
    addToList : function(_id,type)
    {
        if(this.type == "guest")
        {
            if(this.assetList.split("|").length  < 6)
            {
                this.assetList+= _id+"|";
                this.cm.Write(this.assetList);
                this.markAsSelected(_id);
                map.addByAssetsId(SessionId,_id);
            }
            else
            {
                this.markAsUnSelected(_id);
                this.showEnrollMsg(_id,type);
            }
        }
        else if(this.type == "user")
        {
            
            Ext.Ajax.request({
            url : hosturl +this.addAssetUrl,
            success : function(a)
                        {
                            var ans = eval(a.responseText);
                            if(ans[0] == true)
                            {
                                this.assetList+= _id+"|";
                                this.markAsSelected(_id);
                                map.addByAssetsId(SessionId,_id);
                            }
                            else
                            {   
                                this.markAsUnSelected(_id);
                                alert(ans[1]);
                            }
                        },
            failure :function()
                        {
                            //src.checked = !src.checked;
                            this.markAsSelected(_id);
                            alert('כישלון בהוספת רשומה  אנא נסה שוב מאוחר יותר');
                        },
            params :{id:_id},
            scope : this 
            });
        }
    },
    removeFromList : function(_id)
    {
        if(confirm("? להסיר מרשימת הנכסים") == false)
        {
            this.markAsSelected(_id);
            return;
        }
        if(this.type == "guest")
        {   
                this.assetList = this.assetList.replace(_id+"|","");
                this.cm.Write(this.assetList);
                this.markAsUnSelected(_id);
                map.removeByAssetsId(_id);
        }
        else if(this.type == "user")
        {
            Ext.Ajax.request({
            url : hosturl +this.removeAssetUrl,
            success : function(a)
                        {
                            var ans = eval(a.responseText);
                            if(ans[0] == true)
                            {
                                this.assetList = this.assetList.replace(_id+"|","");
                                this.markAsUnSelected(_id);
                                map.removeByAssetsId(_id);
                            }
                            else
                            {
                                //src.checked = !src.checked;
                                this.markAsSelected(_id);
                                
                                alert(ans[1]);
                            }
                        },
            failure :function()
                        {
                            //src.checked = !src.checked;
                            this.markAsSelected(_id);
                            alert('כישלון בהוספת רשומה  אנא נסה שוב מאוחר יותר');
                        },
            params :{id:_id},
            scope : this 
            });
        }
    },
    markAsSelected : function(id)
    {
        var chk = Ext.get('listchk'+id);
        var div = Ext.get('display'+id);
        var mychk = Ext.get('mylistchk'+id);
        var sa = Ext.get('salistchk'+id);
        
        if(chk != null)
        {
            chk.dom.checked = true;
        }
        if(mychk != null)
        {
            mychk.dom.checked = true;
        }
        if(sa != null)
        {
            sa.dom.checked = true;
        }
        if(div != null)
        {
                                 
            div.dom.innerHTML = "הסר מהנכסים שלי";
            div.dom.className = "btnaremove";
        }
    },
    markAsUnSelected : function(id)
    {
        var chk = Ext.get('listchk'+id);
        var div = Ext.get('display'+id);
        var mychk = Ext.get('mylistchk'+id);
        var sa = Ext.get('salistchk'+id);
        if(chk != null)
        {
            chk.dom.checked = false;
        }
        if(mychk != null)
        {
            mychk.dom.checked = false;
        }
        if(sa != null)
        {
            sa.dom.checked = false;
        }
        if(div != null)
        {
            div.dom.innerHTML = "הוסף לנכסים שלי";
            div.dom.className = "btnadd";
        }
    },
    getAssetList : function()
    {   
       return this.assetList;
    },
    addAssetsFromCookie : function()
    {
    },
    changeType : function(type)
    {   
        if(type == "user")
        {
            Ext.Ajax.request({
            url : hosturl + this.getAssetUrl,
            success : function(a,b,c)
            {
                
                if(this.assetList != null && this.assetList!= "" )
                Ext.Ajax.request({
                    url :hosturl + this.addAssetsUrl,
                    success : function(a)
                                {
                                    var ans = eval(a.responseText);
                                    if(ans[0] == true)
                                    {   
                                        //this.assetList+= this._id+"|";
                                    }
                                    else
                                    {
                                        //src.checked = !src.checked;
                                        alert(ans[1]);
                                    }
                                },
                    failure :function()
                                {
                                    //src.checked = !src.checked;
                                    alert('כישלון בהוספת רשומה  אנא נסה שוב מאוחר יותר');
                                },
                    params :{id:this.assetList},
                    scope : this 
                    });
                    this.assetList+=a.responseText;
                    
                    map.reloadByAssetsIds(SessionId,this.assetList.substr(0,this.assetList.length-1));
                    // mark all assets on screen as selected
                    //markAsSelected
                    var markArray = this.assetList.split("|");
                    for(var i=0; i<markArray.length -1 ; i++)
                    {
                        this.markAsSelected(markArray[i]);
                    }
                    
                    this.cm.Write("",0);
            },
            failure :function(){this.assetList ='';alert('שגיאה בחיבור לשרת אנא בדוק את תקינות החיבור האינטרנט');},
            params :null,
            scope : this 
            });
        }
        else
        {
            var list = this.cm.Read();
            if(list != null)
            {
                this.assetList = list;
            }
            else
            {
                 this.assetList = '';
            }
        }
        
        this.type = type;
        
    },
    init : function()
    {
        
        var list = this.cm.Read();
        if(list != null)
        {
            this.assetList = list;
        }
        //
        this.rowTemplate = new Ext.Template(
                  '<div class="row">',
                  '<div class="{invert}">',
                        '<div class="c-PDate" >{PDate}</div>',
                        '<div class="c-vPicCount"><img src="images/x-asset_list-camera.png" class="{vPicCount}" /></div>',
                        '<div class="c-Floor">{Floor}</div>',
                        '<div class="c-EntryWhen">{EntryWhen}</div>',
                        '<div class="c-RoomNumber">{RoomNumber}</div>',
                        '<div class="c-ShekelRent">{ShekelRent}</div>',
                        '<div class="c-Street">{Street}</div>',
                        '<div class="c-city">{city}</div>',
                        '<div class="c-AssetType">{AssetType}</div>',
                        '<div class="c-cBox"><input id="mylistchk{id}" type="checkbox" style="border:none;" onclick="mam.addRemoveAsset(this,event);" {checked}  /></div>',
                   '</div>',
                   '</div>'

        );
        this.rowTemplate = this.rowTemplate.compile();
        this.currentPage = 1;
        this.pageSize = 10;
        this.pageRows = [];
        
        Ext.get('myPagePrint').on('click',this.printPage,this);
        
        
        
    },
    cm : new function()
    {
        this.CookieName = 'zazim-assets';
        this.Exp = 3;
        this.Read = function()
        {
            var nameEQ = (this.CookieName ) + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++) {
	            var c = ca[i];
	            while (c.charAt(0)==' ') c = c.substring(1,c.length);
	            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
            }
            return null;
        };
        this.Write = function(value,days)
        {
            var date = new Date();
	            date.setTime(date.getTime()+( ( days || this.Exp  )*24*60*60*1000));
	        var expires = "; expires="+date.toGMTString();
                document.cookie =  ( this.CookieName ) +"="+value+expires+"; path=/";
        };        
    },
    createMsgScreen : function(x,y,width,height)
    {
        
        this.msgScreen = new createForm({width:550,height:247,title:'הודעת מערכת'});
        var usermsg = "משתמש יקר <br> <br>" +
                            " לצורך הוספת יותר מחמישה נכסים לרשימת הנכסים שלך אנא הרשם לאתר, <br>" +                            
                            "שים לב שההרשמה היא בחינם, ובמילוי פרטים מינימלים בלבד. <br>"+
                            "משתמש רשום יכול לשמור נכסים ללא הגבלה<br>" +
                            "וכמובן גם להגדיר סוכנים חכמים באמצעות סימון על גבי מפה. <br> "+
                            "הרשמה נעימה <br>"+                            
                            "צוות אתר<br>"+
                            "זזים";
                            
        this.msgScreen.content.dom.style.backgroundColor="#ededed";
                            //background-color:#ededed;
        this.msgScreen.addDiv({style:'x-user-msg',text:usermsg});
        var tdiv = this.msgScreen.addDiv({style:'x-user-msg',width:this.msgScreen.content.dom.style.width.replace(/px/g,''),height:30});
        this.msgScreen.addDiv({style:'x-user-btn-row',width:70,height:20,target:tdiv});
        this.msgScreen.addBtn({width:150,text:'הרשמה',target:this.msgScreen.addDiv({style:'x-user-btn-row',width:150,height:20,target:tdiv})}).on('click',function(){this.msgScreen.hide();loginManager.formNewUser.show();},this);
        this.msgScreen.addDiv({style:'x-user-btn-row',width:100,height:20,target:tdiv});
        this.msgScreen.addBtn({width:150,text:'כניסה למשתמש רשום',target:this.msgScreen.addDiv({style:'x-user-btn-row',width:150,height:20,target:tdiv})}).on('click',function(){this.msgScreen.hide();loginManager.showLoginForm();},this);
        
        
        
        
        /*
        this.msgScreen = Ext.get(document.createElement('div'));
        this.msgScreen.dom.className = "x-form";
        this.msgScreen.dom.style.width =(width || 550) +   "px";
        this.msgScreen.dom.style.height =(height|| 380 ) +"px";
        
        // create top box
        var div;
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-login-title-right";
        div.appendTo(this.msgScreen);
        
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-login-title-middel";
        div.dom.style.width = (this.msgScreen.dom.style.width.replace("px","")*1) -6 + "px";
        div.appendTo(this.msgScreen);
        
        var div2 = Ext.get(document.createElement('div'));
        div2.dom.className = "close";
        div2.dom.innerHTML = "X";
        
        div2.on('click',this.hideEnrollMsg,this);
        div2.appendTo(div);
        
        var div2 = Ext.get(document.createElement('div'));
        div2.dom.className = "title";
        div2.dom.innerHTML = "הודעת מערכת";
        div2.appendTo(div);
        this.loginTitle = div;
        
        
        
        div2 = null;
        
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-login-title-left";
        div.appendTo(this.msgScreen);
        
        
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-content";
        //height:145px;
        //height:114px;
        div.dom.style.width =(this.msgScreen.dom.style.width.replace("px","")*1) -6 + "px";
        div.dom.style.height =(this.msgScreen.dom.style.height.replace("px","")*1) -31 + "px";
        div.appendTo(this.msgScreen);
        this.msgScreenContent = div;
        
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-bottom-right";
        div.appendTo(this.msgScreen);
        
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-bottom-middel";
        div.dom.style.width =(this.msgScreen.dom.style.width.replace("px","")*1) -6 + "px";
        div.appendTo(this.msgScreen);
        
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-bottom-left";
        div.appendTo(this.msgScreen);
        
        this.msgScreen.appendTo(Ext.getBody());
        this.msgScreen.dom.style.display = "none";
        
        
        
        
        div = Ext.get(document.createElement('div'));
        div.dom.className = "x-user-msg";
        div.dom.style.width =(this.msgScreen.dom.style.width.replace("px","")*1) -12 + "px";
        div.dom.innerHTML = "משתמש יקר <br> <br>" +
                            " לצורך הוספת יותר מחמישה נכסים לרשימת הנכסים שלך אנא הרשם לאתר, <br>" +
                            "על מנת שנוכל לשמור אותם עבורך באופן מסודר. <br><br>"+
                            "שים לב שההרשמה היא בחינם, ובמילוי פרטים מינימלים בלבד. <br> <br>"+
                            "משתמש רשום יכול לשמור נכסים ללא הגבלה <br> <br>" +
                            "וכמובן גם להגדיר סוכנים חכמים באמצעות סימון על גבי מפה. <br> <br>"+
                            "הרשמה נעימה <br> <br>"+
                            "בברכה<br>"+
                            "צוות אתר<br>"+
                            "זזים";
                            
        div.appendTo(this.msgScreenContent);
        
        */
    
    },
    showEnrollMsg : function(src,type)
    {
        if(!this.msgScreen)
        this.createMsgScreen();
        
        this.msgScreen.show();
        /*
        if(type == "chk")
        {
            this.msgScreen.dom.style.top = ( (Ext.get('listchk'+src).getBox().y) - (this.msgScreen.dom.style.height.replace("px","")*1)) -5 + "px";
            this.msgScreen.dom.style.left = ((Ext.get('listchk'+src).getBox().x) - (this.msgScreen.dom.style.width.replace("px","")*1) ) -5 + "px";
        }
        else
        {
            this.msgScreen.dom.style.top = ( (Ext.get('display'+src).getBox().y) + 20 )  + "px";
            this.msgScreen.dom.style.left = ((Ext.get('display'+src).getBox().x) -  100 ) -5 + "px";
        }
        
        
        this.BlookScreen();
        this.msgScreen.dom.style.display = "block";
        this.msgScreen.dom.style.zIndex = 10001;
        this.msgScreen.fadeIn();
        */
    },
    hideEnrollMsg : function()
    {
        this.msgScreen.hide();
        /*
        this.msgScreen.fadeOut({
            endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
            easing: 'easeOut',
            duration: .5,
            remove: false,
            useDisplay: true
        });
        this.msgScreen.dom.style.display = "none";
        this.unBlookScreen();
        */
    },
    createBlokeer : function()
    {
        this.blockdiv = Ext.get(document.createElement('div'));
        this.blockdiv.dom.style.width = Ext.getBody().getWidth() + "px";
        this.blockdiv.dom.style.height =   "2000px";
        this.blockdiv.dom.style.position = "absolute";
        this.blockdiv.dom.style.top=0;
        this.blockdiv.dom.style.left=0;
        this.blockdiv.dom.style.backgroundColor = "gray";
        var val=4;
        this.blockdiv.dom.style.MozOpacity = val;
        this.blockdiv.dom.style.opacity = val/10;
        this.blockdiv.dom.style.filter = 'alpha(opacity=' + val*10 + ')';
        this.blockdiv.appendTo(Ext.getBody());
        this.blockdiv.dom.style.display="none";
        this.blockdiv.dom.style.zIndex =10000;
    },
    BlookScreen : function()
    {
        if(!this.blockdiv)
        {
            this.createBlokeer();
            this.blockdiv.dom.style.display="block";
        }
        else
        {
            this.blockdiv.dom.style.display="block";
        }
        this.blockdiv.on('mousewheel',this.noScroll,this);
    },
    unBlookScreen : function()
    {
        if(this.blockdiv)
            this.blockdiv.dom.style.display="none";
    },
    noScroll : function(evt)
    {
        evt.preventDefault();
        return false;
    },
    drawPageOnChange: function()
    {   
        var combo = Ext.get('mypageSelector');
        var pageNo = combo.dom.options.selectedIndex + 1;
        this.drawPage(pageNo);
    },
    drawPage : function(pageNo,Cols)
    {
        
        if (Cols) this.rowIndex = Cols;
        if (!this.rowIndex) return;
        this.dataTable = Ext.get('x-my-asset_list');
        var combo = Ext.get('mypageSelector');
        combo.dom.onchange = null;
        combo.dom.options.length = 0;
        for (var i = this.pageSize; i <  map.getAssetsCount() + this.pageSize; i += this.pageSize )
          {
            var el = document.createElement('option');
            el.value = i/this.pageSize;
            el.text = i/this.pageSize;
            combo.dom.options[ i/this.pageSize-1] = el;
          }
              
        if ( combo.dom.options.length == 1 || combo.dom.options.length == 0)
                Ext.get('x-my-asset_list-pageSelector').dom.style.display = 'block'
            else
                Ext.get('x-my-asset_list-pageSelector').dom.style.display = 'block'; 
        
       
       if(pageNo == 0 && this.currentPage )
       {
         pageNo = this.currentPage;
         if(pageNo >  combo.dom.options.length)
         {
            pageNo = combo.dom.options.length-1;
         }   
       }
       if ( map.getAssetsCount() > 0)
        {
            if (pageNo)
            {
                if (pageNo - 1 <= combo.dom.options.length)
                {
                 this.currentPage = pageNo;
                }
                else
                {
                 this.currentPage = 1;
                }
            }
            else
            {
                this.currentPage = 1;
            }
            if (combo.dom.options.length > 1) 
            {
                combo.dom.options.selectedIndex = this.currentPage - 1;
                combo.dom.onchange = this.drawPageOnChange.createDelegate(this);
            }
        }
        
        for (var i = 0; i < this.pageRows.length; i++)
        {
            this.pageRows[i].rowId = null;
            this.pageRows[i].marker = null;
            this.pageRows[i].removeAllListeners();
            this.pageRows[i].remove();
            this.pageRows[i] = null;
            
        }
        this.pageRows = null;
        this.pageRows = [];
        this.dataTable.dom.innerHTML = '';
            
        for (var i = (this.currentPage - 1) * this.pageSize; i < (this.currentPage) * this.pageSize && i <  map.getAssetsCount(); i++)
        {   
            this.addRow(map.getAssetsRow(i),i+1);
        }
        
        
    },
    printPage : function()
    {
        var ret = new Array();
        for (var i = (this.currentPage - 1) * this.pageSize; i < (this.currentPage) * this.pageSize && i <  map.getAssetsCount(); i++)
        {   
            ret[ret.length] ={data: map.getAssetsRow(i),index: mam.rowIndex};
        }
        print.add(ret);
    },
    getPageRows : function()
    {
        
        var ret = new Array();
        for (var i = (this.currentPage - 1) * this.pageSize; i < (this.currentPage) * this.pageSize && i <  map.getAssetsCount(); i++)
        {   
            ret[ret.length] = map.getAssetsRow(i);
        }
        return ret;
    },
    addRow: function (dataCell,index)
    {
    
          var tbl = this.dataTable.dom;
          //debugger;
          var _checked = "";
          if(mam.getAssetList() != null)
            if(mam.getAssetList().indexOf(dataCell[this.rowIndex['id']] + "|") != -1)
                _checked = "checked";
          
          var el = this.rowTemplate.append(this.dataTable,
              {
                invert : (index % 2 == 0) ? 'row' : 'zeb',
                AssetType: dataCell[this.rowIndex['AssetType']],
                city: dataCell[this.rowIndex['city']] ,
                Street: dataCell[this.rowIndex['Street']] ,
                "ShekelRent": dataCell[this.rowIndex['ShekelRent']] ,
                RoomNumber: dataCell[this.rowIndex['RoomNumber']] ,
                EntryWhen: dataCell[this.rowIndex['EntryWhen']] ,
                Floor: dataCell[this.rowIndex['Floor']] ,
                vPicCount: (dataCell[this.rowIndex['vPicCount']] == '0') ? 'hide' : '' ,
                PDate: dataCell[this.rowIndex['PDate']],
                id : dataCell[this.rowIndex['id']],
                checked : _checked
              });
           el.rowId = dataCell[this.rowIndex['id']];
            
                       
            Ext.get(el).addListener("mousedown", 
                        function(p1,p2,p3)
                        {
                            //debugger; //c-cBox"><input id="mylistchk
                            if(p2.tagName == "INPUT") return;
                            if(addsDataWindow)
                                if(addsDataWindow.rowIndex)
                                {
                                       addsDataWindow.enlist(null,this.rowId,mam.getPageRows(),mam.rowIndex);
                                }
                                else
                                {      
                                       addsDataWindow.enlist(null,this.rowId,mam.getPageRows(),mam.rowIndex);
                                }
                        },
                        el);
                                            
           this.pageRows[this.pageRows.length] = Ext.get(el);
            

    }
    
    
};


//var mam = new myAssetsManager();




