﻿var ImageObj = new Image();
var Lat = {
    Data: {
        "0": null
    },
    Cache: {},
    _Data: null,
    DefaultDesk: 0,
    State: 0,
    DragState: 0,
    User: {},
    PosData: {},
    ContainerPos: {},
    Draging: false,
    DragElement: 0,
    TargetElement: null,
    TempElement: null,
    AddSiteId: null,
    SiteFormData: {},
    ShowAction: false,
    ActionName: null,
    init: function(data) {
        jQuery.extend(this.Data, this._Data[this.DefaultDesk].data);
        this.ContainerPos = $('#site-container').position();
        $("#dropBox").easydrag(true);
        $("#dropBox").ondrop(function(e, element) {
            if (Lat.ActionName) {
                Lat.cmd(Lat.ActionName);
            } else {
                Lat._drag(element);
            }
            setTimeout(function() {
                $('#search-box').show();
            },
            300);
            return false;
        }).mouseover(function(e) {
            if ($.browser.msie) window.status = Lat.Data[Lat.DragElement][2];
            return false;
        }).mouseout(function(e) {
            Lat.mouseOutBox();
            return false;
        }).ondrag(function(e) {
            Lat.Draging = true;
            if (!Lat.ShowAction) Lat._dragShowAction();
            Lat._getTarget(e);
            return false;
        }).click(function(e) {
            Lat.clickBox(Lat.DragElement);
            return false;
        });
        $('#site-container .site-box').mouseover(function(e) {
            Lat.mouseOverBox(this);
            return false;
        });
        $('.dialogCancel').click(function(e) {
            tb_remove();
            return false;
        });
        $("#addIcon").click(function(e) {
            Lat.addSite();
        }).mouseout(function(e) {
            $(this).css({
                left: -5000
            });
            return false;
        });
        this.initDesk();
        this.initDeskTab();
        if (this.State == 2) {
            this.initAddSite();
            this.initSetDeskBg();
        }
        if (this.State > 0) {
        	this.initSetting();
            this.initSetting2();
            this.initCopySite();
            this.initAddDesk();
            this.initRSS();
        }
        if (this.State == 0) {
            this.initLogin();
            this.initReg();
        }
        setInterval('Lat.resize()', 1000);
        if(IfLocked){perfu=window.setInterval("Lat.lockp()",1100);}
        if(!IfLocked&&document.per==false){ perfu=window.setInterval("Lat.checkp()",1100);}
    },
    checkp: function(){
	try
	{
	tb_show("访问受限","#TB_inline?width=320&height=150&inlineId=limitp");
	clearInterval(perfu);}
	catch(e){}
	}
    ,
    lockp: function(){
	try
	{document.per=false;
	tb_show("访问受限","#TB_inline?width=320&height=120&inlineId=LockedUser");
	clearInterval(perfu);}
	catch(e){}
	}
    ,
    resize: function() {
        var temp = $H(Lat.ContainerPos);
        this.ContainerPos = $('#site-container').position();
        if (this.ContainerPos.left != temp.left) {
            $('#dropBox').hide();
            $H(this.PosData).each(function(p, index) {
                Lat.PosData[index][0] = p.value[0] - (temp.left - Lat.ContainerPos.left);
                Lat.PosData[index][3] = p.value[3] - (temp.left - Lat.ContainerPos.left);
            });
        }
    },
    showMessage: function(msg, closeDialog, showTime) {
        var m = $('#systemMessage');
        var w = $(window);
        var l = (w.width() - m.outerWidth(true)) / 2;
        var t = $(document).scrollTop() + (w.height() - m.outerHeight(true)) / 2;
        m.html(msg).css({
            left: l,
            top: t
        }).show().fadeOut(showTime || 4000);
        if (closeDialog) tb_remove();
        return false;
    },
    initSetting: function() {    
        $('#settingOk').click(function(e) {
        try{
        t=document.getElementById("domain_").value;
        if(t.length!=0){
        
        if(t.length<4){$('#settingErr').html("个性域名长度不能少于4位！");return false;}
        
        ifs=true;
      	voidChar = "'\"><_=+':;/?.,~!@#$%^&*()";
      	for(i = 0 ; i < voidChar.length; i ++){
    aChar = voidChar.substring(i, i + 1);
    if(t.indexOf(aChar) > -1){
      ifs=false;
    }
}
if(!ifs){$('#settingErr').html("域名含非法字符！");return false;}
        var n=0;   
      	for(var i=0;i<t.length;i++)   
      	{   
      	//charCodeAt()可以返回指定位置的unicode编码,这个返回值是0-65535之间的整数   
        if(t.charCodeAt(i)>128) n++; 
      	}
        if(n>0){$('#settingErr').html("域名不能含中文！");return false;}
        
        }
        }catch(e){}
        
            var data = $('#settingForm').serialize();
            jQuery.post('/?action=userSetting', data,
            function(result) {
                if (result.err) {
                    $('#settingErr').html(result.err);
                } else {
                    Lat.showMessage('设置成功', true);
                    location.reload();
                }
            },
            'json');
            return false;
        });
    },
    initSetting2: function() {
        $('#settingOk2').click(function(e) {
            var data = $('#settingPass').serialize();
            jQuery.post('/?action=userSetting2', data,
            function(result) {
                if (result.err) {
                    $('#settingErr2').html(result.err);
                } else {
                	$('#settingErr2').html("");
                    Lat.showMessage('设置成功', true);
                    location.reload();
                }
            },
            'json');
            return false;
        });
    },
    initCopySite: function() {
        $('#copySiteOk').click(function(e) {
            var dataStr = $('#copySiteForm').serialize();
            jQuery.post('/?action=copySite', dataStr,
            function(result) {
                if (result.err) {
                    Lat.showMessage(result.err);
                } else {
                    var pram = dataStr.toQueryParams();
                    for (var i = 0; i < 52; i++) {
                        if (!Lat._Data[pram.targetDeskId].data[i]) {
                            Lat._Data[pram.targetDeskId].data[i] = Lat.Data[pram.siteIndex];
                            break;
                        }
                    }
                    Lat.showMessage('成功复制到目标桌面', true);
                }
            },
            'json');
            return false;
        });
    },
    //////////////////RSS///////////////////
     initRSS: function() {     
     $('#addRSSClick').click(function(e) {
     		$('#addRSSDiv').html("<br>类别载入中..");
           jQuery.post('/?action=GetRSSGroup', "",
            function(result) {
                if (result.err) {
                    $('#addRSSDiv').html(result.err);
                    document.getElementById('RSSsub2').value="其他类别";
                } else {
                    Lat.showMessage('RSS类别载入失败', true);
                }
            },
            'json');
		 return false;
        });
        
     $('#editRSSClick').click(function(e) {
     		$('#editRSSsub').html("<br>类别载入中..");
           jQuery.post('/?action=initRSSGroup', "",
            function(result) {
                if (result.err) {
                    $('#editRSSsub').html(result.err);
                    document.getElementById('RSSsub1').value="其他类别";
                    document.getElementById('RSSsub1').onchange=function(){
/////////////////
						$('#editRSSXML').html("<br>该类RSS载入中..");
						var data = $('#editRSSForm').serialize();
                       jQuery.post('/?action=GetRSSList', data,
            			function(result) {
                			if (result.err) {
                    			$('#editRSSXML').html(result.err);
                    			document.getElementById('RSSList').onchange();
                			} else {
                    			Lat.showMessage('该类RSS载入失败，请重新选择！', true);
                			}
            			},
            			'json');
            			return false;
///////////////
                    }
                    document.getElementById('RSSsub1').onchange();
                } else {
                    Lat.showMessage('RSS类别载入失败', true);
                }
            },
            'json');
		return false;
        });

        $('#editRSS .showAddRSS').click(function(e) {
            tb_remove();
            setTimeout(function() {
            $('#addRSSClick').click();
            },
            300);
            return false;
        });
        $('#AddRSS .ShoweditRSS').click(function(e) {
            tb_remove();
            setTimeout(function() {
                $('#editRSSClick').click();
            },
            300);
            return false;
        });
        $('#AddRSSOk').click(function(e) {
             $('#AddRssErr').html("请稍后...");
            var data = $('#AddRSSForm').serialize();
            jQuery.post('/?action=AddRSS', data,
            function(result) {
                if (result.err) {
                    $('#AddRssErr').html(result.err);
                } else {
                    Lat.showMessage('上传成功，并已订阅！', true);
                    $('#AddRssErr').html("");
                    document.getElementById('AddRSSForm').reset();
                    RSSHOW();
                }
            },
            'json');
            return false;
		});
		 $('#editRSSOk').click(function(e) {
		   	$('#EditRssErr').html("请稍后...");
            var data = $('#editRSSForm').serialize();
            jQuery.post('/?action=editRSS', data,
            function(result) {
                if (result.err) {
                    $('#EditRssErr').html(result.err);
                } else {
                    Lat.showMessage('订阅成功', true);
                    $('#EditRssErr').html("");
                    document.getElementById('editRSSForm').reset();
                    RSSHOW();
                }
            },
            'json');
            return false;
		});
		$('#CopyOk').click(function(e) {
            jQuery.post('/?action=CopyRSS',"",
            function(result) {
                if (result.err) {
                	Lat.showMessage(result.err, true);
                } else {
                	location.reload();
                }
            },
            'json');
            return false;
		});
		$('#ConfirmOk').click(function(e) {
				var list="";
				shell=document.getElementById("col_1");
	 			alldiv=shell.getElementsByTagName('DIV');
	 			divs=[];
					for (var i=0;i<alldiv.length;i++ ) {
			if(alldiv[i].className=='drag_div'){
				list+=alldiv[i].lang+",";}
			}
            jQuery.post('/?action=ConfirmRSS', "list="+list,
            function(result) {
                if (result.err) {
                    Lat.showMessage(result.err, true);
                    RSSHOW();
                } else {
                    Lat.showMessage('保存成功', true);
                }
            },
            'json');
            return false;
		});
$('#settin2 .showsettingDialog').click(function(e){
tb_remove();
setTimeout(function(){
$('#settingb').click();
},300);
return false;
});


$('#setting .showsetting2Dialog').click(function(e){
tb_remove();
setTimeout(function(){
$('#setting2b').click();
},300);
return false;
}); 

	},
    /////////////////RSS END////////////////

    initDeskTab: function() {
    		document.Ranktype="score";
               	$('#ClickRank').click(function(e) {
       		Lat.initDesk("ShowRank");
        	$('#RSS-container').html("<table width=100% height=100%><tr><td align=center><img src='"+ThemesPath+"/style/images/loading_image_BLACK.gif'></td></tr></table>");
            document.getElementById("site-container").style.display = 'none';
            document.getElementById("RSS-container").style.display = 'block';
            jQuery.post('/?action=ShowRank', "userName="+thisUserName+"&Rtype="+document.Ranktype,
            function(result) {
                if (result.err) {
                	Lat.showMessage(result.err, true);
                } else { 
                	$('#RSS-container').html(result.out);
                }
            },
            'json');
            return false;
        });
    
        $('#desk-bar a').click(function(e) {
            var id = $(this).blur().attr('rel');
            if(id=="RSS"&&thisState==0){window.setTimeout("Lat.showMessage('友情提示：登陆后您可以自主订阅RSS！', true);",1000);}
            if (id != Lat.DefaultDesk) Lat.initDesk(id);
            return false;
        }).mouseover(function(e) {
            var element = $(this);
            var deskId = element.attr('rel');
            if (Lat.DefaultDesk == deskId) {
                Lat.Cache.showDeskOpt = true;
                var pos = element.position();
                /////////////////////////////////////
                if (deskId == "RSS") {
                    $('#deskOpt2').css({
                        left: pos.left + 1,
                        top: pos.top + element.outerHeight()
                    }).show();
                    return false;
                }
                /////////////////////////////////////
                $('#deskOpt').css({
                    left: pos.left + 1,
                    top: pos.top + element.outerHeight()
                }).show();
            }
            return false;
        }).mouseout(function(e) {
            var element = $(this);
            var deskId = element.attr('rel');
            if (Lat.DefaultDesk == deskId) {
                Lat.Cache.showDeskOpt = false;
                setTimeout(function() {
                    ///////////////////////////////////////////////////////////
                    if (!Lat.Cache.showDeskOpt) {
                        $('#deskOpt').hide();
                        $('#deskOpt2').hide();
                    }
                },
                100);
            }
            return false;
        });
        //////////////////////////////////
        $('#deskOpt2 a').mouseover(function(e) {
            Lat.Cache.showDeskOpt = true;
            return false;
        }).mouseout(function() {
            Lat.Cache.showDeskOpt = false;
            setTimeout(function() {
                if (!Lat.Cache.showDeskOpt) $('#deskOpt2').hide();
            },
            100);
            return false;
        });
        //////////////////////////////////////////////
        $('#deskOpt a').mouseover(function(e) {
            Lat.Cache.showDeskOpt = true;
            return false;
        }).mouseout(function() {
            Lat.Cache.showDeskOpt = false;
            setTimeout(function() {
                if (!Lat.Cache.showDeskOpt) $('#deskOpt').hide();
            },
            100);
            return false;
        });
        $('#search-box img').click(function(e) {
            $('#search-box img').show();
            var target = $(this).hide().attr('alt');
            $('#search-box').attr('class', 'search-box ' + target);
            $('#search-iframe').attr('src', $('#search-iframe').attr('src').replace(/[^_]*\.html/, target + '.html'));
            return false;
        });
    },
    initDesk: function(id) {
    
         $('#limitOK').click(function(e) {
           $('#LimitErr').html("请稍后...");
            var data = $('#limitForm').serialize();
            jQuery.post('/?action=limitCheck', data,
            function(result) {
                if (result.err==false) {
                    $('#LimitErr').html("密码错误");
                } else {
                	$('#LimitErr').html("验证成功");
                    Lat.showMessage('请稍后...', true);
                    location.reload();
                }
            },
            'json');
            return false;
        });
        $('#ReportOK').click(function(e) {
           $('#ReportErr').html("请稍后...");
            var data = $('#ReportForm').serialize();
            jQuery.post('/?action=ReportAdd', data,
            function(result) {
            $('#ReportErr').html("");
                if (!result.err) {
                    Lat.showMessage('举报提交成功！', true);
                }else{Lat.showMessage(result.err, true);}
            },
            'json');
            return false;
        });
        
        id = id || this.DefaultDesk;
        if (id) {

            $('#desk-bar a').each(function() {
                var e = $(this);
                if (e.attr('rel') == id) {
                    e.parent().addClass('on');
                } else {
                    e.parent().removeClass('on');
                }
            });
            $("#dropBox").hide();
            $("#addIcon").hide();
            this.DefaultDesk = id;
            ////////////////////////////
            if (id == "ShowRank"){return;}
            if (id == "RSS") {
                document.getElementById("site-container").style.display = 'none';
                document.getElementById("RSS-container").style.display = 'block';
                RSSHOW();
                return;
            } else {
                document.getElementById('site-container').style.display = 'block';
                document.getElementById("RSS-container").style.display = 'none';
            }
            ////////////////////////////
            this.Data = this._Data[id].data;
        } else {
            id = this.DefaultDesk;
        }
        $('#site-container .site-box').each(function(index) {
            Lat.initBox(index);
            if (Lat.PosData['51']) return;
            var pos = $(this).position();
            Lat.PosData[index] = [pos.left, pos.top + 10, pos.left + 80, pos.top + 90];
        })
    },
    initBox: function(id) {
        var data = this.Data[id];
        if (data) {
            ImageObj.src = data[4];
            $('#' + id).html('<div class="icon ' + data[3] + '"><div class="icon-content" style="background-image:url(' + data[4] + ');' + (data[5] ? ' color:' + data[5] : '') + '" rel="' + data[2] + '" UrlId="'+data[0]+'"><div class="icon-inner">' + data[1] + '</div></div></div>');
        } else {
            $('#' + id).empty();
        }
    },
    initAddDesk: function() {
        $('#addDeskOk').click(function(e) {
            tb_remove();
            jQuery.post('/?action=updateDesk', $('#addDeskForm').serialize(),
            function(id) {
                location.href = '?' + id;
            });
            return false;
        });
        $('#editDeskOk').click(function(e) {
            tb_remove();
            var data = $('#editDeskForm').serialize().toQueryParams();
            data.defaultDesk = data.defaultDesk || 0;
            data.noShare = data.noShare || 0;
            $('#desk-bar .on a').html(data.title);
            Object.extend(Lat._Data[Lat.DefaultDesk], data);
            jQuery.post('/?action=updateDesk', $H(data).toQueryString());
            return false;
        });
        $('#delDeskOk').click(function(e) {
            if ($H(Lat._Data).size() == 1) {
                Lat.showMessage('老兄，您已经只有一个桌面了，就放过它吧');
            } else {
                $('#desk-bar li.on').remove();
                var deskId = $C(Lat.DefaultDesk);
                Lat._Data = $H(Lat._Data).lost(deskId);
                Lat.initDesk(Lat._Data.keys()[0]);
                tb_remove();
                jQuery.post('/?action=delDesk', 'id=' + deskId);
            }
            return false;
        });
        $('#copyDeskOk').click(function(e) {
            jQuery.post('/?action=updateDesk', 'sourceId=' + Lat.DefaultDesk + '&' + $('#copyDeskForm').serialize(),
            function() {
                if (Lat.State == 2) {
                    location.reload();
                } else {
                    Lat.showMessage('桌面复制成功', true);
                }
            });
            return false;
        });
        $('#deskOpt .edit').click(function(e) {
            initForm(Lat._Data[Lat.DefaultDesk], 'editDeskForm');
        });
    },
    initLogin: function() {
        $('#login .showRegDialog').click(function(e) {
            tb_remove();
            setTimeout(function() {
                $('#regDialog').click();
            },
            300);
            return false;
        });
        $('#loginOk').click(function(e) {
            var data = $('#loginForm').serialize();
            jQuery.post('/?action=userLogin', data,
            function(result) {
                if (result.err) {
                    $('#loginErr').html(result.err);
                } else {
                    location.reload();
                }
            },
            'json');
            return false;
        });
    },
    initReg: function() {
        $('#reg .showLoginDialog').click(function(e) {
            tb_remove();
            setTimeout(function() {
                $('#loginDialog').click();
            },
            300);
            return false;
        });
        $('#regOk').click(function(e) {
        regerr="";
        
        var q=document.getElementById("QQ_").value;
		if(q.length > 13 || q.length < 6)regerr="QQ长度需要6-13位";
		if(q.length==0)regerr="";
		q=document.getElementById("Email_").value;
		if(q!=0 && q.indexOf("@")==-1){regerr="Email填写错误！";}
		p=document.getElementById("password_").value;
		if(p.length > 12 || p.length < 6)regerr="密码需为6-12位数字字母";
		ifs=true;
      	voidChar = "'\"><_=+':;/?.,~!@#$%^&*()";
      	for(i = 0 ; i < voidChar.length; i ++){
    aChar = voidChar.substring(i, i + 1);
    if(p.indexOf(aChar) > -1){
      ifs=false;
    }
}
if(!ifs) regerr="密码有非法字符";
		p=document.getElementById("userName_").value;
		if(p.length > 18 || p.length < 3)regerr="用户名需为3-18位";
		
		if(regerr.length!=0){
		$('#regErr').html(regerr);
		return false;
		}
            jQuery.post('/?action=userReg', $('#regForm').serialize(),
            function(result) {
                if (result.err) {
                    $('#regErr').html(result.err);
                    if (result.err == '验证码填写错误！') $('#validateCode').click();
                } else {
                    Lat.showMessage(result.msg, true);
                    setTimeout(function() {
                        $('#loginDialog').click();
                    },
                    300);
                }
            },
            'json');
            return false;
        });
        $('#validateCode').click(function(e) {
            var codeKey = new Date().getTime();
            $('#codeKey').val(codeKey);
            this.src = this.src.replace(/\d+$/, codeKey);
        });
    },
    initAddSite: function() {
        var demo = $('#site-icon-demo');
        $('#site-name').keyup(function(e) {
            $('.icon-inner', demo).html($(this).val());
        });
        $('#icon-bg-selete a').click(function(e) {
            var color = $(this).attr('color');
            Lat.SiteFormData.bgColor = color;
            demo.attr('class', 'icon ' + color);
            return false;
        });
        $('#addSiteOk').click(function(e) {
        if(!IfAdmin&&LockedList.indexOf(","+Lat.UpdateSiteId+",")!=-1){Lat.showMessage('该格子被锁定，不能修改！', true);return false;}
            Lat.SiteFormData.url = $('#site-url').val();
            Lat.SiteFormData.title = $('#site-name').val();
            Lat.SiteFormData.lock=$('#Sitelock').val();
            Lat.updateSite(Lat.UpdateSiteId, Lat.SiteFormData);
            Lat.showMessage('添加成功', true);
            return false;
        });
        $("#icon-type-default, #icon-type-upload").click(function(e) {
            $("#icon-upload, #icon-default").hide();
            $('#' + $(this).attr('id').replace('-type', '')).show();
        });
        $('#uploadForm .submit').click(function(e) {
            if ($("#uploadForm input[name='file']").val()) {
                $('#uploadForm').submit();
            }
            return false;
        });
        $('#showRecommendSiteDialog').click(function(e) {
            Lat.Cache.DragElement = Lat.DragElement;
            tb_remove();
            setTimeout(function() {
                $('#recommendSiteDialog').click();
            },
            300);
            return false;
        });
        $('#showAddSiteDialog').click(function(e) {
            tb_remove();
            setTimeout(function() {
                $('#addIconDialog').click();
            },
            300);
            return false;
        });
        $('#recommendSite .icon').click(function(e) {
            var site = $(this);
            var data = site.attr('data').split('^');
            Lat.SiteFormData.title = data[0];
            Lat.SiteFormData.url = data[1];
            Lat.SiteFormData.bgColor = data[2];
            Lat.SiteFormData.icon = data[3];
            Lat.SiteFormData.titleUrl = data[4];
            Lat.updateSite(Lat.UpdateSiteId, Lat.SiteFormData);
            Lat.showMessage('添加成功', true);
            return false;
        });
    },
    initAddSiteData: function(o) {
        var demo = $('#site-icon-demo');
        if (o) {
            o = {
                id: o[0],
                title: o[1],
                url: o[2],
                bgColor: o[3],
                icon: o[4],
                titleColor: o[5],
                lock:o[6]
            };
        }
        var data = {
            url: 'http://',
            title: '',
            bgColor: 'white',
            icon: '',
            titleColor: '',
            lock:''
        }
        jQuery.extend(data, o);
        this.SiteFormData = data;
        $('#site-name').val(data.title);
        $('#site-url').val(data.url);
        demo.attr('class', 'icon ' + data.bgColor);
        $('.icon-content', demo).css({
            'background-image': 'url(' + data.icon + ')',
            'color': data.titleColor
        });
        $('.icon-inner', demo).html(data.title);
        if ($('#default-icon-selete').html() == '') {
            var str = $R(1, 76).map(function(n) {
                ImageObj.src = '/Public/Site/Icon/' + n + '.gif';
                return '<a href="#" id="default-icon-' + n + '" style="background-image:url(/Public/Site/Icon/' + n + '.gif);" icon="/Public/Site/Icon/' + n + '.gif"></a>';
            }).join('');
            $('#default-icon-selete').html(str);
            $('#default-icon-selete a').click(function(e) {
                var icon = $(this).attr('icon');
                Lat.SiteFormData.icon = icon;
                $('.icon-content', demo).css('background-image', 'url(' + icon + ')');
                return false;
            });
        }
        try{
        if(data.lock=="1"){document.getElementById("Sitelock").value=1;}else{document.getElementById("Sitelock").value='';}
        }
        catch(e){}
        if ($('#color-picker').html() == '') {
            $('#color-picker').html(colorPicker());
            $('#color-seleter').click(function(e) {
                $('#color-picker').toggle();
                return false;
            });
            $(document).click(function() {
                if ($('#color-picker').css('display') != 'none') $('#color-picker').hide();
            });
            $('#color-picker td').click(function(e) {
                var color = $(this).attr('bgcolor');
                Lat.SiteFormData.titleColor = color;
                $('#color-picker').hide();
                $('.icon-content', demo).css({
                    'color': color
                });
                return false;
            });
        }
        $("#icon-type-default").click();
    },
    iconUpload: function(result) {
        var errMark = 'err:';
        if (result.indexOf(errMark) == 0) {
            return this.showMessage('上传失败：' + result.replace(errMark, ''));
        }
        this.SiteFormData.icon = result;
        $('#site-icon-demo .icon-content').css('background-image', 'url(' + result + ')');
    },
    initSetDeskBg: function() {
        $('#setDeskBgOk').click(function() {
            $('#setDeskBgForm').attr('action', '/?action=deskBgUpload&deskId=' + Lat.DefaultDesk + '&bgType=' + ($('#bgType').attr('checked') ? 1 : 0)).submit();
            $('#setDeskBgPress').html('上传中，请稍候...');
            return false;
        });
    },
    deskBgUpload: function(result) {
        $('#setDeskBgPress').html('整图上传成功，现在转入桌面...');
        setTimeout(function() {
            location.href = '?' + Lat.DefaultDesk;
        },
        500);
    },
    exchange: function(sourceId, targetId) {
    	if(this.Data[sourceId][6]=="1" && !IfAdmin){Lat.showMessage('该图标被锁定，不能移动！', true);return false;}
        Lat.DragElement = Lat.TargetElement;
        var sourceElement = $('#' + sourceId);
        var targetElement = $('#' + targetId);
        targetElement.removeClass('dragOver');
        var _html = targetElement.html();
        targetElement.html(sourceElement.html());
        sourceElement.html(_html);
        var _data = Lat.Data[sourceId];
        Lat.Data[sourceId] = Lat.Data[targetId];
        Lat.Data[targetId] = _data;
        if (this.State != 2) return;
        var data = $R(0, 51).map(function(id) {
            return Lat.Data[id] ? Lat.Data[id][0] : 0;
        }).join(',');
        jQuery.post('/?action=editDesk', 'id=' + this.DefaultDesk + '&data=' + data);
    },
    updateSite: function(id, data) {
	data.url=data.url.replace(/&/g,'flexsand');
        data.id = data.id || 0;
        this.updateSiteData(id, data);
        Lat.initBox(id);
        var queryStr = 'deskId=' + this.DefaultDesk + '&index=' + id + '&data=' + this.Data[id].join(',');
	data.url=data.url.replace(/flexsand/g,'&');
        data.id = data.id || 0;
        this.updateSiteData(id, data);
        Lat.initBox(id);
        jQuery.post('/?action=updateDeskSite', queryStr,
        function(result) {
            if (result) {
                data.id = parseInt(result);
                if (!data.id) return false;
                Lat.updateSiteData(id, data);
            }
        });
    },
    updateSiteData: function(id, data) {
    	if (data) data = [data.id, data.title, data.url, data.bgColor, data.icon, data.titleColor, data.lock];
        this.Data[id] = data;
        this._Data[this.DefaultDesk].data[id] = data;
    },
    addSite: function(id) {
        if (this.State == 0) return $('#loginDialog').click();
        Lat.initAddSiteData();
        $('#addIconDialog').click();
    },
    editSite: function(id) {
    	if(!IfAdmin&&LockedList.indexOf(","+id+",")!=-1){Lat.showMessage('该格子被锁定，不能修改！', true);return false;}
    	if(this.Data[id][6]=="1"  && !IfAdmin){Lat.showMessage('该图标被锁定，不能修改！', true);return false;}
        this.UpdateSiteId = id;
        this.initAddSiteData(this.Data[id]);
        $('#addIconDialog').click();
    },
    delSite: function(id) {
    	if(!IfAdmin&&LockedList.indexOf(","+id+",")!=-1){Lat.showMessage('该格子被锁定，不能删除！', true);return false;}
    	if(this.Data[id][6]=="1"  && !IfAdmin){Lat.showMessage('该图标被锁定，不能删除！', true);return false;}
        this.updateSiteData(id, null);
        Lat.initBox(id);
        jQuery.post('/?action=delDeskSite', 'deskId=' + this.DefaultDesk + '&index=' + id);
    },
    copySite: function(id) {
        $("#copySiteIndex").val(id);
        $("#copySiteId").val(this.Data[id][0]);
        var html = '';
        if (this.State == 2) {
            this._Data.each(function(desk) {
                var data = desk.value;
                if (data.id != Lat.DefaultDesk) {
                    html += '<option value="' + data.id + '">' + data.title + '</option>';
                }
            });
        } else if (this.State == 1) {
            this.MyDesks.each(function(data) {
                html += '<option value="' + data.id + '">' + data.title + '</option>';
            });
        }
        $('#copySiteForm select').html(html);
        $('#copySiteDialog').click();
    },
    
    _dragAction: function(action) {
        if (action == this.ActionName) return;
        $('#' + this.TempElement).removeClass('dragOver');
        this.TempElement = null;
        this.ActionName = action;
        $('#' + action).addClass('hover');
    },
    cmd: function(action) {
        var id = this.DragElement;
        if (this.State == 0) {
            $('#loginDialog').click();
        } else {
            this[action.split('-')[1] + 'Site'](id);
        }
        this.ShowAction = false;
        this.ActionName = null;
        setTimeout(function() {
            $('#' + action).removeClass('hover');
            $("#dropBox").hide();
            $('#' + (Lat.State == 2 ? 'opt-mine': 'opt-common')).hide();
            Lat.Draging = false;
        },
        action == 'mine-del' ? 0 : 500);
    },
    _dragShowAction: function() {
        this.ShowAction = this.Draging;
        $('#search-box').hide();
        if (this.Draging) {
            if (this.State == 2) {
                $('#opt-mine').show();
            } else {
                $('#opt-common').show();
            }
        } else {
            if (this.State == 2) {
                $('#opt-mine').hide();
            } else {
                $('#opt-common').hide();
            }
        }
    },
    _getTarget: function(e) {
        var pos = $.getMousePosition(e);
        var x = pos.x - this.ContainerPos.left;
        var y = pos.y - this.ContainerPos.top;
        var id = this._getTargetId(x, y);
        if (id == null) return;
        this.DragState = 1;
        if (typeof id == 'string') {
            if (id != this.ActionName) $('#' + this.ActionName).removeClass('hover');
            this._dragAction(id);
            return false;
        }
        if (this.ActionName) {
            $('#' + this.ActionName).removeClass('hover');
            this.ActionName = null;
        }
        id = id - 1;
        Lat.TargetElement = id;
        if (Lat.TargetElement == this.TempElement) return;
        this.dragOverBox(Lat.TargetElement);
        this.TempElement = Lat.TargetElement;
    },
    _getTargetId: function(x, y) {
        var _x = x % 90;
        var _y = y % 90;
        var xn = Math.ceil(x / 90);
        var yn = Math.ceil(y / 90);
        if (yn >= 3 && yn <= 4 && xn >= 4 && xn <= 7) {
            if (y < 90 * 2 + 10 || x > 90 * 7) return null;
            if (this.State == 2) {
                if (x <= 90 * 3 + 116) return 'mine-edit';
                if (x <= 90 * 3 + 116 + 118) return 'mine-del';
                return 'mine-copy';
            } else {
                return 'common-copy';
            }
        }
        if (_x < 10 || _y > 80) return null;
        if (yn <= 2) return 10 * (yn - 1) + xn;
        if (yn >= 5) return 32 + 10 * (yn - 5) + xn;
        if (xn <= 3) return 20 + 3 * (yn - 3) + xn;
        if (xn >= 8) return 26 + 3 * (yn - 3) + (xn - 7);
        return null;
    },
    _drag: function(e) {
        var id = Lat.TargetElement;
        if (id < 0 || id > 51) {
            id = Lat.TargetElement = Lat.DragElement;
        }
        $('#dropBox').animate({
            left: Lat.PosData[id][0],
            top: Lat.PosData[id][1]
        },
        200,
        function() {
            Lat.Draging = false;
            if (Lat.TargetElement != Lat.DragElement) {
                Lat.exchange(Lat.DragElement, Lat.TargetElement);
            } else {
                $('#' + id).removeClass('dragOver');
            }
            Lat._dragShowAction();
        });
    },
    mouseOverBox: function(e) {
        if (this.Draging) return;
        if (!this.MouseOut) this.mouseOutBox();
        this.MouseOut = false;
        var id = e.id;
        if (!this.Data[id]) {
            this.UpdateSiteId = id;
            $("#addIcon").css({
                left: this.PosData[id][0],
                top: this.PosData[id][1]
            }).show();
        } else {
            $("#addIcon").css({
                left: -5000
            });
            this.DragElement = this.TempElement = this.TargetElement = id;
            var dragHTML = $(e).html().replace(/id=[^> ]*/img, '');
            $('.icon-inner', e).addClass('on');
            $("#dropBox").html(dragHTML).css({
                left: this.PosData[id][0],
                top: this.PosData[id][1]
            }).show();
        }
    },
    mouseOutBox: function(e) {
        if (this.Draging) return;
        $("#dropBox").hide();
        if ($.browser.msie) window.status = '';
        $('#' + this.DragElement + ' .icon-inner').removeClass('on');
        this.MouseOut = true;
    },
    clickBox: function(id) {
        if (this.Draging) return;
var url = $('#' + id + ' .icon-content').attr('rel');
if(url.indexOf("?action=BoxShow")!=-1){
//data.id=url.replace("?action=BoxShow&id=");
            jQuery.post('/?action=GetBoxContent', url.replace("?action=BoxShow&","").replace("http://",""),
            function(result) {
                if (!result.type) {
                    Lat.showMessage('网络异常!', true);
                    return false;
                } else {
                if(result.type=="盒子信息" || result.type=="盒子网址"){
				tb_show(result.title,"#TB_inline?width="+result.width+"&height="+result.height);
				$("#TB_ajaxContent").html(result.Content);}
				if(result.type=="盒子页面"){
				tb_show(result.title,result.Content+"?TB_iframe=ture&width="+result.width+"&height="+result.height);
				}
                }
            },
            'json');
return false;
}
//window.open(url, '');
if(LinkOut=='1'){
var Goform = document.getElementById("goUrl");
Goform.action="?action=goUrl&UID="+$('#' + id + ' .icon-content').attr('UrlId');
Goform.UrlId.value=$('#' + id + ' .icon-content').attr('UrlId');
Goform.submit();}
else{window.open(url,'');}
if(IOsum=='1')jQuery.post('/?action=outUrl', 'UID='+$('#' + id + ' .icon-content').attr('UrlId'),function(result) {}, 'json');
    },
    dragOverBox: function(id) {
        $('#' + this.TempElement).removeClass('dragOver');
        $('#' + id).addClass('dragOver');
    }
};
$(document).ready(function() {
    setTimeout(function() {
        if (location.href.include('?')) {
            var deskId = location.href.split('?')[1];
            if (deskId && 　Lat._Data[deskId]) Lat.DefaultDesk = deskId;
        }
        Lat.init();
    },
    1000);
});
function initForm(data, form) {
    form = $E(form);
    for (var key in data) {
        if (!form[key]) continue;
        var value = data[key];
        if (value === null) continue;
        if (typeof(value) != 'array') value = [$C(value)];
        $(form[key]).val(value);
    }
}
function colorPicker() {
    var arr_color1 = ['00', '33', '66'];
    var arr_color2 = ['00', '33', '66', '99', 'cc', 'ff'];
    var arr_color3 = ['000000', '333333', '666666', '999999', 'cccccc', 'ffffff', 'ff0000', '00ff00', '0000ff', 'ffff00', 'ff00ff', '00ffff'];
    var html = '<table cellpadding="0" cellspacing="1" border="0" bgcolor="#000000">';
    var idx = 0;
    for (var k = 0; k < arr_color2.length; k++) {
        html += '<tr>';
        html += '<td bgcolor="#' + arr_color3[idx] + '"></td>';
        idx++;
        for (i = 0; i < arr_color1.length; i++) {
            for (j = 0; j < arr_color2.length; j++) {
                html += '<td bgcolor="#' + arr_color1[i] + arr_color2[j] + arr_color2[k] + '"></td>';
            }
        }
        html += '</tr>';
    }
    var arr_color1 = ['99', 'cc', 'ff'];
    for (k = 0; k < arr_color2.length; k++) {
        html += '<tr>';
        html += '<td bgcolor="#' + arr_color3[idx] + '"></td>';
        idx++;
        for (i = 0; i < arr_color1.length; i++) {
            for (j = 0; j < arr_color2.length; j++) {
                html += '<td bgcolor="#' + arr_color1[i] + arr_color2[j] + arr_color2[k] + '"></td>';
            }
        }
        html += '</tr>';
    }
    html += '</table>';
    return html;
}
YscaleH=0;
dragDrop={
	absPos:function(node){
		var x=y=0;
		do	{
			x+=node.offsetLeft;
			y+=node.offsetTop;
		}
		while(node=node.offsetParent);
		return {
			'x':x,
			'y':y
		};		
	}

	,isIntersect:function(x,y,node){
		var m=this.absPos(node),
			xx=m.x,
			yy=m.y-YscaleH;
		return !(x<xx||
			y<yy||
			x>(xx+node.offsetWidth)||
			y>(yy+node.offsetHeight)
		);
	}

	,drag:function(hander,ini){
		var def={dir:'xy',minIndex:1,end:String,isMove:true};
		ini=ini||{};
		for(var key in ini )def[key]=ini[key];
		ini=def;
		
		var dragObj=moveObj=ini.win||hander;
		var $me=moveObj;
		if(ini.isMove)moveObj.style.position="absolute";
		hander=document.getElementById(dragObj.id+"h")
		hander.onmousedown=function (e){
			this.style.cursor="pointer";
			if(ini.box!=undefined){
				var rect=document.createElement('DIV')
					,pos=dragDrop.absPos($me);
				rect.style.cssText='top:'+pos.y+';left:'+pos.x
					+'height:'+$me.offsetHeight+'px;'			
					+'width:'+$me.offsetWidth+'px;background:none;position:absolute;cursor: pointer;'+ini.box;
				var pos=dragDrop.absPos(dragObj);
				rect.style.top=pos.y+'px';
				rect.style.left=pos.x+'px';
				moveObj=document.body.appendChild(rect);
				moveObj.innerHTML=dragObj.innerHTML;
			};
			e=window.event||e;
			this.prevOverObj_x=e.clientX;
			this.prevOverObj_y=e.clientY;
			this.x=e.clientX-moveObj.offsetLeft;
			this.y=e.clientY-moveObj.offsetTop;
			moveObj.style.zIndex=(dragDrop.zIndex?
				dragDrop.zIndex++:
				dragDrop.zIndex=1)+ini.minIndex;
			if(document.all){
				hander.onlosecapture=dragStop;
				e.cancelBubble=true;
				hander.setCapture();
			}else{window.onblur=dragStop;e.stopPropagation()};

			dragDrop.onBegin.call(dragObj,moveObj);/* my Event */

			document.onmousemove=function(e){
				e=e||window.event;
				var $x=undefined,$D=document,$W=window;
				var x=e.clientX-hander.x,y=e.clientY-hander.y;
				if($x!=ini.left)x=Math.max(x,ini.left);
				if($x!=ini.top)y=Math.max(y,ini.top);
				if($x!=ini.right)x=Math.min(x,ini.right-dragObj.offsetWidth+45);
				if($x!=ini.bottom)y=Math.min(y,ini.bottom-dragObj.offsetHeight);
				if(ini.dir.indexOf('x')!=-1)moveObj.style.left=x+"px";
				if(ini.dir.indexOf('y')!=-1)moveObj.style.top=y+"px";

				if($D.all){hander.setCapture();e.cancelBubble=true;
				}else{window.onblur=dragStop;e.stopPropagation()}
				$W.getSelection && $W.getSelection().removeAllRanges();	
				dragDrop.onDrag.call(dragObj,moveObj,e.clientX,e.clientY);/* my Event */
			};

			function dragStop(e){
				var $D=document;
				e=window.event||e;
				$D.onmousemove=$D.onmouseup=null;
				if($D.all){hander.onlosecapture=null;hander.releaseCapture();
				}else{window.onblur=null}
				if(ini.box!=undefined){
					if(ini.isMove){
						$me.style.left=parseInt(moveObj.style.left)+'px';
						$me.style.top=parseInt(moveObj.style.top)+'px';
					}
					$D.body.removeChild(rect);	
				};
				dragDrop.onDrop.call(dragObj);/* my Event */
			};

			document.onmouseup=dragStop;
		};
		return this;
	}

	,onIntersect:function(){}
	,onDrag:function(){}
	,onBegin:function(){}
	,onDrop:function(){}
	,U:{prevOverObj:null}

};

dragDrop.onDrag=function (mover,x,y){
	for (var i=0;i<divs.length;i++ ) {
		if(dragDrop.isIntersect(x,y,divs[i])){
			dragDrop.onIntersect.call(this,divs[i]);
			break;
		}
	}
};

dragDrop.onBegin=function (){
	YscaleH=document.body.scrollTop||document.documentElement.scrollTop;
	this.style.visibility='hidden';
}

dragDrop.onDrop=function (){
	var __this=this,i=0;
	this.style.visibility='visible';
	dragDrop.U1.style.background='';
	dragDrop.U1.style.border="";
	if(this==dragDrop.U1)return;
	var pos=dragDrop.U1.nextSibling;
	if(pos==this){
		this.parentNode.insertBefore(this,dragDrop.U1);
	}else{
		this.parentNode.insertBefore(dragDrop.U1,this);
		this.parentNode.insertBefore(this,pos);	
	}
}

dragDrop.onIntersect=function(overObj){

	if(dragDrop.U1)
		dragDrop.U1.style.border="";
	if(overObj!==this){
		overObj.style.border="1px dotted #ffffff";
	};
	dragDrop.U1=overObj;
};





function RSSHOW() {
	$('#RSS-container').html("<table width=100% height=100%><tr><td align=center><img src='"+ThemesPath+"/style/images/loading_image_BLACK.gif'></td></tr></table>");
    jQuery.post('/?action=ShowRSS', "username="+thisUserName,
    function(result) {
       if (result.err) {
                    $('#RSS-container').html(result.err);
                    window.setTimeout("RSSHOWinit();DragRSSinit();",500)
                    
       } else {
       Lat.showMessage('目前暂无任何RSS资源，请及时添加！', true);
       $('#RSS-container').html("");
       }
       },
   'json');
   return false;
}
function RSSHOWinit(){
IDlist=document.getElementById('allID').lang
temp=IDlist.split(",")
 for (i=0;i<temp.length ;i++ )    
     {    
		if(i<3&&temp[i]!=""){
		window.setTimeout("oneRSSHOW("+temp[i]+")",0)
		}
     }  
}
function DragRSSinit(){
try{
shell=document.getElementById("col_1");
	 alldiv=shell.getElementsByTagName('DIV');
	 divs=[];
	for (var i=0;i<alldiv.length;i++ ) {
		if(alldiv[i].className=='drag_div')divs.push(alldiv[i])
	}
	g=dragDrop.absPos(shell);
	g2=g.x+shell.offsetWidth-45;
	g3=g.y+shell.offsetHeight;
	for (var i=0;i<divs.length;i++ ) {
		dragDrop.drag(
			divs[i],{
				box:'filter:alpha(opacity=80);opacity:0.8',
				cursour:'pointer',
				cursor:'pointer',
				isMove:0,
				left:g.x,
				top:g.y,
				right:g2,
				bottom:g3
		});
	}}
	catch(e){}
}
function oneRSSHOW(id) {
$('#RSS_content'+Math.abs(id)).html("<img src='"+ThemesPath+"/style/images/search_indicator.gif'/>");
document.getElementById('RSS_'+Math.abs(id)+'b').style.display=id>0?'block':'none';
document.getElementById('RSSimg_'+Math.abs(id)).src=id>0?ThemesPath+'/style/images/desktop_open.gif':ThemesPath+'/style/images/desktop_add.gif';
document.getElementById('RSSimg_'+Math.abs(id)).lang=-id;
if(id<0){DragRSSinit();return false;}

    jQuery.post('../../include/plugin/RSS/?action=oneShowRSS&id='+Math.abs(id)+'&rnd='+Math.random(), "xml="+document.getElementById('RSS_content'+Math.abs(id)).lang,
    function(result) {
       if (result.err) {
       $('#RSS_content'+Math.abs(id)).html(result.err);
       } else {
       $('#RSS_content'+Math.abs(id)).html(result.out);
       try
{
document.getElementById('oneRssIMG'+Math.abs(id)).onerror=function(){this.src=this.src+'?'+Math.random()}
document.getElementById('oneRssIMG'+Math.abs(id)).onload=function(){ImgSizeInit('oneRssIMG'+Math.abs(id));DragRSSinit();}
}
catch(err){}
       
       };DragRSSinit();
       },
   'json');
   return false;
}

function delOneRSS(i) {
Delobj=document.getElementById("drag_"+i)
id=Delobj.lang
Delobj.style.hidden="none"
    jQuery.post('/?action=delOneRSS', "id="+id,
    function(result) {
       if (result.err) {
		Lat.showMessage('删除失败：'+result.err+'！', true);
		Delobj.style.hidden="block"
       } else {
		Delobj.parentNode.removeChild(Delobj);
		Delobj=document.getElementById("drag_"+i+"block")
		Delobj.parentNode.removeChild(Delobj);
       }
       },
   'json');
   return false;
}

function ImgSizeInit(sm){try{
      pich=document.getElementById(sm).height;
      picw=document.getElementById(sm).width;
      var lith=100;
      var litw=200;
      if(pich>lith){
      picw=picw*lith/pich;
      pich=lith;
      }
      if(picw>litw){
      pich=pich*litw/picw;
      picw=litw;
      }
      document.getElementById(sm).height=pich;
      document.getElementById(sm).width=picw;
      }
      catch(e){}
}


copy2Clipboard=function(txt){
	if(window.clipboardData){
		window.clipboardData.clearData();
		window.clipboardData.setData("Text",txt);
	}
	else if(navigator.userAgent.indexOf("Opera")!=-1){
		window.location=txt;
	}
	else if(window.netscape){
		try{
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		}
		catch(e){
			Lat.showMessage("您的firefox安全限制限制您进行剪贴板操作，请打开’about:config’将signed.applets.codebase_principal_support’设置为true’之后重试，相对路径为firefox根目录/greprefs/all.js", true);
			return false;
		}
		var clip=Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if(!clip)return;
		var trans=Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if(!trans)return;
		trans.addDataFlavor('text/unicode');
		var str=new Object();
		var len=new Object();
		var str=Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		var copytext=txt;str.data=copytext;
		trans.setTransferData("text/unicode",str,copytext.length*2);
		var clipid=Components.interfaces.nsIClipboard;
		if(!clip)return false;
		clip.setData(trans,null,clipid.kGlobalClipboard);
	}
}
function copyxml(txt){
if(copy2Clipboard(txt)!=false){Lat.showMessage('已复制RSS源！', true);}
else{Lat.showMessage('复制失败！', true);}
}
function copywords(txt){
if(copy2Clipboard(txt)!=false){Lat.showMessage('已复制邀请代码！', true);}
else{Lat.showMessage('复制失败！', true);}
}