/*
function changeDisplay(objId, iconFlag, cycle){
    if (iconFlag == true){
        var icon = document.getElementById("displayStatus");
    }
    var obj = document.getElementById(objId);
    if (cycle == 0){
        if (obj.style.display == "none") {
            obj.style.display = "";
            if (iconFlag == true) icon.src = "/newcss/image/icon_open.gif";
        } else if (obj.style.display == "") {
            obj.style.display = "none";
            if (iconFlag == true) icon.src = "/newcss/image/icon_close.gif";
        }
    } else if (cycle == 1){
        obj.style.display = "";
    } else if (cycle == 2){
        obj.style.display = "none";
    }
}
*/

// light box
function set_overlay(event_id,event, box_width, box_height){
    if (!event_id) {
        var event_id = 'lightbox';
    }
    if (event_id == 'lightbox') {
        var eid = 'parent_box';
        hideBox('confirm');
    } else {
        var eid = 'confirm_box';
        hideBox();
    }
    window.client={
        width: document.body.clientWidth,
        height: Math.min(document.documentElement.clientHeight, document.body.clientHeight)
    };
    if (box_width && box_height)
    {
        var _top  = parseInt((window.client.height - box_height) / 2);
        var _left = parseInt((window.client.width - box_width) / 2);
    }
    else
    {
        var _top  = parseInt((window.client.height - $('#'+eid).height()) / 2);
        var _left = parseInt((window.client.width - $('#'+eid).width()) / 2);
    }
    if ($.browser.msie && parseFloat($.browser.version) < 7) {
        _top = (parseInt($(document).scrollTop())) + (parseInt(_top));
        if(event != 'click') {
            if($('#'+event_id).css('left') != 'auto') {
                _left = $('#'+event_id).css('left');
            }
        }
        $('#'+event_id).css({'left':_left,'top': _top, 'position':'absolute'}).show();
        if (event_id == 'lightbox') {
            window.onscroll= set_overlay;
        }
    } else {
        $('#'+event_id).css({'left': _left, 'top': _top, 'position': 'fixed'}).show();
    }
    dragBox();
}
function box_mousedown(e){
    var e, obj, temp;
    obj=$("#lightbox")[0];
    e=window.event?window.event:e;
    obj.startX=e.clientX-obj.offsetLeft;
    obj.startY=e.clientY-obj.offsetTop;
    document.onmousemove=box_mousemove;

    temp=document.attachEvent?document.attachEvent("onmouseup",box_mouseup):document.addEventListener("mouseup",box_mouseup,"");
}
function box_mousemove(e){
    var e, obj;
    obj=$("#lightbox")[0];
    e=window.event?window.event:e;
    
    with(obj.style){
        left=e.clientX-obj.startX+"px";
        top=e.clientY-obj.startY+"px";
    }
}
function box_mouseup(e){
    var temp;
    document.onmousemove="";
    temp=document.detachEvent?document.detachEvent("onmouseup",box_mouseup):document.removeEventListener("mouseup",box_mouseup,"");
}
var ajax_mid = '';
function showBox(mid, url,is_login, box_width, box_height) {
    if (!box_width && !box_height)
    {
        var box_height = 0;
        var box_height = 0;
    }
    if (is_login == true) {
        if (mid == ajax_mid && $('#lightbox').html()) {
            $('#lightbox').slideDown('slow');
            set_overlay('lightbox','click', box_width, box_height);
        } else {
            fadeInfo('lightbox', '<div id=\"parent_box\" class=\"binfo_parent\"></div><div id=\"box\" class=\"binfo_child\">载入中, 请稍候.......</div>');
            set_overlay('lightbox', 'click', box_width, box_height);
            $.ajax({
                url: url,
                type: 'get',
                dateType: 'json',
                success: function(response) {
                    if (mid) {
                        ajax_mid = mid;
                    }
                    if (response == 'n_login') {
                        response = '<div id=\"parent_box\" class=\"binfo_parent\"></div><div id=\"box\" class=\"binfo_child\">您还没有登陆！</div>'
                    }
                    fadeInfo('lightbox',response);
                    set_overlay('lightbox','click', box_width, box_height);
                }
            });
            return false;
        }
    } else {
        alert('您还没有登陆');
        return false;
    }
}

function delData(fid, del_url,d) {
    if(fid && del_url && d == 'a') {
        $('#confirm_ok').bind('click', function(){delData(fid,del_url,'ajax')});
    } else if(fid == 'ajax_form') {
        $('#confirm_ok').bind('click', function(){delData('','','ajax_form')})
    } else if(fid && del_url && d == false) {
        $('#confirm_ok').bind('click', function(){delData(fid,del_url,'del')});
    }
    if (d == 'ajax') {
        $('#confirm_ok').unbind("click", function() { alert("Hello"); });
        delLink(fid, del_url,'ajax');
    } else if(d == 'del') {
        delLink(fid, del_url,'del');
    } else if(d == 'ajax_form') {
        return pms_del();
    } else {
        $('#confirm').slideDown('slow');
        set_overlay('confirm','click');
    }
}
function delLink(fid, del_url,ajax)
{
    $('#confirm').hide();
    if (ajax == 'ajax') {
        $.ajax({
            url: del_url,
            type: 'get',
            dateType: 'json',
            success: function(response) {
                response = eval('(' + response + ')');
                $.each(response,function(key,value) {
                    if (key == 'del_ok') {
                        $('#favor_list'+fid).slideUp(200, function(){$(this).remove()});
                    }
                    //setTimeout(function(){hideInfo('favor_info')}, 3000);
                });
            }
        });
        return false;
    } else {
        window.location.href=del_url;
    }
}
function dragBox() {
    $('#dragbox').mousedown(function(){box_mousedown(arguments[0])});
}
function hideBox(confirm_id) {
    if (!confirm_id) {
        hideInfo('lightbox');
    } else {
        hideInfo(confirm_id);
    }
    window.onscroll = null;
}
function chgDisplay(objId, flag){
    if (flag == 1){
        $('#'+ objId).show();
    } else if (flag == 2){
        $('#'+ objId).hide();
    } else {
        $('#'+ objId).toggle();
    }
}

function chgFont(objId, flag){
    if (flag == 'small'){
        $('#'+ objId).removeClass('bigfont');
        $('#'+ objId).removeClass('midfont');
        $('#'+ objId).addClass('smallfont');
    } else if (flag == 'big'){
        $('#'+ objId).removeClass('midfont');
        $('#'+ objId).removeClass('smallfont');
        $('#'+ objId).addClass('bigfont');
    } else {
        $('#'+ objId).removeClass('smallfont');
        $('#'+ objId).removeClass('bigfont');
        $('#'+ objId).addClass('midfont');
    }
}

function setInput(objId, objInput){
    $('#'+ objId).html(objInput);
}

function checkAll(objName){
    $('input[name="' + objName + '"]').each(function(){
        $(this).attr("checked",!$(this).attr("checked"));
    });
}

function chkImage(objId){
    var x = $('#' + objId);
    if(!x || !x.val()) return;
    var patn = /\.jpg$|\.jpeg$|\.png$|\.gif$/i;
    if(!patn.test(x.val())){
        x.val("");
        alert("您选择的似乎不是图像文件。");
        return false;
    }
    return true;
}

function ajaxget(url, data, func, dtype){
    if(dtype == ''){
        dtype = "html";    
    }
    $.ajax({
        type: "get",
        url: url,
        data: data,
        dataType : dtype,
        beforeSend: function(){$("#ajaxload").show();},
        success: func,
        complete: function(){$("#ajaxload").hide();},
        error: function(){$("#ajaxerror").show();}
    });
}

//post方法ajax
function ajaxpost(url, data, func, dtype){
    if(dtype == ''){
        dtype = "html";    
    }
    $.ajax({
        type: "post",
        url: url,
        data: data,
        dataType : dtype,
        beforeSend: function(){$("#ajaxload").show(); $("#ajaxerror").hide();},
        success: func,
        complete: function(){$("#ajaxload").hide();},
        error: function(){$("#ajaxerror").show();}
    });
}
function fadeInfo(id, response, _class)
{
    if (!response) {
        $('#'+id).fadeIn();
    } else if(_class) {
        $('#'+id).html(response).removeClass().addClass(_class).fadeIn();
    } else {
        $('#'+id).html(response).fadeIn();
    }
}
function hideInfo(id, remove)
{
    if(remove) {
        $('#'+id).removeClass(remove).hide();
    } else {
        $('#'+id).hide();
    }
}
/*function refreshCode(){
        var obj=$("#span_img");
        var rand=Math.random();
        obj.html("<img src=\"includes/security_code/?"+rand+"\" alt=\"点击刷新验证码\" title=\"点击刷新验证码\"  border=0 />")
            .fadeIn();
}*/
function refreshCode()
{
    var rand=Math.random();
    $('#imgcode').attr('src',"/includes/security_code/index.php?"+rand);
    //window.setTimeout(refreshCode,1000*60*20);
}
function loginUser(done_action){
    var params = $('input').serialize();
    var u_info= $('#u_err');
    u_info.ajaxStart(function(){$(this).hide()});
    if (!$('#login_user').val() || !$('#login_pass').val()){
        u_info.html('用户名和密码不能为空').fadeIn();
        return false;
    }
    $.ajax({
        type: 'post',
        url: '/login.php?m=ajax',
        data: params,   //要传递的数据
        success: function(response){
            switch(response){
                case 'error':
                    u_info.html('用户名或密码错误').fadeIn();
                break;
                case 'no_user':
                    u_info.html('该用户名不存在').fadeIn();
                break;
                case 'user_locked':
                    u_info.html('该用户已被锁定').fadeIn();
                break;
                case 'ok':
                    u_info.html('登陆成功').fadeIn();
                    if (!done_action || done_action == "redirect")
                    {
                        window.location.href='/home.php?user=' + $('#login_user').val();
                        //window.location.href='http://www.hanmei.com/notice.php?id=15';
                    } else if (done_action == "reload") {
                        location.reload();
                    }
                    
                break;
                default:
                    //window.location.href='<{$site_path.domain}>' + response;
                break;
            }
        }
    });
    return false;
}
function addFavor()
{
    var detail = $('#detail').val();
    if (detail) {
        if (detail.length > 200) {
            fadeInfo('favor_info','描述信息限制200字以内');
            return false;
        }
    }
    $('#sub_favor').attr('disabled','disabled');
    var params = $('input,textarea').serialize();
    $.ajax({
        url: 'favorite.php',
        type: 'post',
        dateType: 'json',
        data: params,
        success: function(response) {
            $('#sub_favor').attr('disabled','');
            response = eval('(' + response + ')');
            $.each(response,function(key,value) {
                if (key != 'time_err') {
                    fadeInfo('favor_info', value);
                }
                if (key == 'update_ok') {
                    fadeInfo('content_'+$('#favor_id').val(), $('#detail').val());
                } else if (key == 'time_err') {
                    fadeInfo('favor_info', value,'error_info');
                }
                setTimeout(function(){hideBox()}, 2000);
                setTimeout(function(){$('#favor_info').removeClass().html(' ');}, 2100);
            });
        }
    });
    return false;
}
// top search
var timer = 0;
function search_show(pos,searchType,href){
    $("#" + pos + "searchtype").val(searchType);
    $("#" + pos + "sel").hide();
    $("#" + pos + "selected").html(href.innerHTML);
    try{window.clearTimeout(timer);}catch(e){}
    return false;
}
function drop_mouseover(pos){
    try{window.clearTimeout(timer);}catch(e){}
}
function drop_mouseout(pos){
    //var posSel=$("#" + pos + "sel").css('style');
    //if(posSel=="block"){
    if($("#" + pos + "sel:visible") && timer){
        timer = setTimeout("drop_hide('"+pos+"')", 3000);
    }
}
function drop_hide(pos){
    $("#" + pos + "sel").hide();
}


//comment_return_msg
function show_return(f){
    document.getElementById("comment_return_form" + f).style.display = "block";
}
function hidden_return(f){
    document.getElementById("comment_return_form" + f).style.display = "none";
    $("#return_content" + f).val("");
}
function ajax_comment_insert(f,c_id,u_id,nickname){
    
}

function ajax_comment_insert(f,c_id,u_id,nickname,host_id,model){
    var value = $("#return_content" + f).val();
    if(value == ""){
        alert("请填写内容");
        return false;
    }
    if(value.length > 200){
        alert("不能大于200个汉字！");
        return false;
    }

    $.ajax({
     type: "POST",
     url: model + ".php?act=commen_return",
     data:   "cid="+c_id+"&uid="+u_id+"&nick="+nickname+"&value="+value+"&hid="+host_id,
     success: function(msg){ 
                    hidden_return(f);
                    if(msg != "no"){
                        var most;
                        for(var i=1;i<1000;i++){
                            if(!document.getElementById("comment_remove" + f + i)){
                                most = i;
                                break;
                            }
                        }
                        var thistime = new Date();
                        var y = thistime.getFullYear();
                        var m = thistime.getMonth() + 1;
                        var d = thistime.getDate();
                        var h = thistime.getHours();
                        var s = thistime.getMinutes();
                        var timehtml = y + "-" + m + "-" + d + " " + h + ":" + s; 
                        var html = '<div id="comment_remove' + f + most + '">                <div class="comment_return">                    <span class="my_comment">我的回复：</span>                    <span class="comment_time">'+timehtml+'</span>                </div>                <p class="return_content">' + value + '</p>            </div>';
                        $("#comment_return_list" + f).append(html);
                    }else{
                        alert("服务器正忙，请稍后重试！");
                    }
                 } 
    });
}
function del_comment_return_info(id,hid,number,model){
    if(confirm('此操作不可恢复! 您确认要删除吗?')){
        $.ajax({
         type: "POST",
         url: model + ".php?act=delreturn",
         data:   "id="+id+"&hid="+hid,
         success: function(msg){ 
                        if(msg != "no"){
                            $("#comment_remove" + number).remove();
                        }else{
                            alert("服务器正忙，请稍后重试！");
                        }
                     } 
        });
    }
}

function copyLink(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) {    
               alert("您的firefox安全限制限制您进行剪贴板操作！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");    
          }    
          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);    
     }
     alert("复制成功！");
}

//处理PNG
var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);
function transPNGPic(myImage)
{
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
    var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
    var imgTitle = (myImage.title) ? 
               "title='" + myImage.title   + "' " : "title='" + myImage.alt + "' "
    var imgStyle = "display:inline-block;" + myImage.style.cssText
    var strNewHTML = "<span " + imgID + imgClass + imgTitle
                   + " style=\"" + "cursor:hand;width:" + myImage.width 
                   + "px; height:" + myImage.height 
                   + "px;" + imgStyle + ";"
                   + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                   + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
     myImage.outerHTML = strNewHTML    
    }
}
