/*banmasenlin javascript libaray
 *version 0.01
 */
//start;
result = null;  //globe  return data  value;
options = {type:'post',dataType:'html',timeout:1000,async:false,error:function (XMLHttpRequest, textStatus, errorThrown) {}};
tip = ['确定吗?','请问您确定要离开编辑器吗？离开前请注意是否已保存。'];
title_name = ['添加标签','添加地址','添加成品书','上传图片','编缉成品书','参加活动'];
return_tip = ['标签保存成功','标签保存失败','地址添加失败','地址添加成功','地址删除失败','作品添加成功','作品添加失败','投票成功','投票失败','请先登陆或注册','参加失败','信息不完整'];
calc_tip = ['请选择类别','请选择装订方式','请选择封面覆膜','d'];
function in_array(what,where){
  var a=false;
  for(var i=0;i<where.length;i++){
    if(what == where[i]){
      a=true;
      break;
    }
  }
  return a;
}

function mic_ajax(){
  result =jQuery.ajax(options).responseText;
}

function mic_confirm()
{
  result = window.confirm(tip[0]);
}

function mic_reload()
{
  window.location.reload(true);
}

function mic_open_window(url){
  window.open(url);
}

function mic_goto(url){
  window.location.href=url;
}

function js_copy(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("被浏览器拒绝！\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("复制成功！");
  }
}
//end
//template filter
function show(size){	
  $("div[id^='tpl']").hide();
  $("div[id*='tpl-"+size+"']").show();
}

function showall()
{
  $("div[id^='tpl']").show();
}
//end template
function btn_book_del(b_id){
  var bln = window.confirm("确定吗?");   
  if(!bln)	return false;
  $.ajax({
    type: 'GET',     url:  '/mine/delete/b_id/'+b_id,
    dataType: 'html',      timeout:2000,      async:false,
    success: function(data){
      if(data == 'true'){
        alert('删除成功!');
        window.location.reload(true);
      }else{alert('删除失败!');} },
    error:function (XMLHttpRequest, textStatus, errorThrown) {alert('删除失败!');}
  });
}


function btn_add_collect(b_id){
  $.ajax({
    type: 'GET',
    url:  '/mine/addcollect/b_id/'+b_id,
    dataType: 'html',
    timeout:2000,
    async:false,
    success: function(data){
      if(data == 'true'){
        alert('收藏成功!');
        mic_reload();
      }else{alert('收藏失败或你已经收藏!');} },
    error:function (XMLHttpRequest, textStatus, errorThrown) {alert('收藏失败!');}
  });
}

function btn_del_collect(b_id){
  var bln = window.confirm("确定吗?");   
  if(!bln)	return false;
  $.ajax({
    type: 'GET',     url:  '/mine/delcollect/b_id/'+b_id,
    dataType: 'html',      timeout:2000,      async:false,
    success: function(data){
      if(data == 'true'){$('#books_item_'+b_id).remove();alert('删除成功!');
      }else{alert('删除失败!');} },
    error:function (XMLHttpRequest, textStatus, errorThrown) {alert('删除失败!');}
  });
}

function btn_add_recmd(b_id){
  $.ajax({
    type: 'GET',     url:  '/mine/addrecmd/b_id/'+b_id,
    dataType: 'html',      timeout:2000,      async:false,
    success: function(data){
      if(data == 'true'){alert('推荐成功!');
      }else{alert('推荐失败!');} },
    error:function (XMLHttpRequest, textStatus, errorThrown) {alert('推荐失败!');}
  });
}

function rf(){
  $('#btn_rf').remove();
  $.ajax({
    type: 'GET',     url:  '/contacts/RF/rnd/ddo',
    dataType: 'html',      timeout:2000,      async:false,
    success: function(data){
      $('#result').html(data);
    },
    error:function (XMLHttpRequest, textStatus, errorThrown) {$('#result').html('失败');}
  });	
}

function btn_resend_mail(uid)
{
  $.ajax({
    type: 'GET',     url:  '/site/resend/uid/'+uid,
    dataType: 'html',      timeout:2000,      async:false,
    success: function(data){
      $('#result').html(data);
    },
    error:function (XMLHttpRequest, textStatus, errorThrown) {$('#result').html('重发失败');}
  });	
}

function  setpublish(){
  $('#publish_submit').attr("disabled","disabled");
  $.ajax({
    type: 'GET',
    url:  '/mine/publish_submit',
    data: ({
      b_id : $('#b_id').val(),
      key : $('#key').val(),
      c_id : $('#c_id').val(),
      b_access : $('#b_access').val()      	
    }),
    dataType: 'html',
    timeout:2000,
    async:false,
    success: function(data){
      if(data =='true'){
        $("#result").html("更改成功！");
      }else{
        $("#result").html("更改失败!");
      }
    },
    error:function (XMLHttpRequest, textStatus, errorThrown) {}
  }); 
}

function btn_del_comment_mine(cm_id){
  options.url = '/mine/deleteMycomment';
  options.data = ({cm_id:cm_id});
  mic_ajax();
  if(result == 'true'){
    mic_reload();
  }else{
    alert('删除失败!');
  }
}

function btm_del_pdf(pdf_id){
  options.url = '/mine/delpdf';
  options.data = ({pdf_id:pdf_id});
  mic_ajax();
  if(result == 'true'){
    mic_reload();
  }else{
    alert('删除失败!');
  }
}

function btn_del_gcomment_mine(gc_id){
	options.url = '/gallery/deleteMycomment';
	options.data = ({gc_id:gc_id});
	mic_ajax();
	if(result == 'true'){
		mic_reload();
	}else{
		alert('删除失败!');
	}
}
function btn_del_comment(b_id,cm_id){
  $.ajax({
    type: 'POST',
    url:  '/mine/deletecomment',
    data: ({
      b_id : b_id,
      cm_id : cm_id
    }),
    dataType: 'html',
    timeout:2000,
    async:false,
    success: function(data){
      if(data =='true'){
        mic_reload();
      }else{

      }
    },
    error:function (XMLHttpRequest, textStatus, errorThrown) {}
  }); 
}

function btn_add_comment(b_id){
  var cm_comment = $("#cm_comment").val();
  if(cm_comment==''){alert('评论不能为空');return ;}
  $("#sendcomment_div").hide();	
  $.ajax({
    type: 'POST',
    url:  '/Book/AddComment',
    data: ({
      b_id : b_id,
      cm_comment : cm_comment
    }),
    /**
     * time: 2009-07-27 16:51
     * dataType: 'html',
     */
    dataType: 'json',
    timeout:2000,
    async:false,
    success: function(data){
      if(data.state =='true'){
        if ($("#commentlist li").length > 0) {
    	    $("#commentlist li:last-child").after(data.html); 
        } else {
            $("#commentlist").append("<li></li>"); 
            $("#commentlist li:last-child").after(data.html); 
        }
        
        $("#result_sendcomment_div").html("<span><a href=\"javascript:window.location.reload(true);void(0)\">继续发言<span>");
      }else{
        if(data.state == 'false')	alert('评论失败!');
      /*
        else $("#result_sendcomment_div").html(data);
      */
      }
    },
    error:function (XMLHttpRequest, textStatus, errorThrown) {}
  }); 
}

function btn_get_password()
{
  $('#btn_get_password').html("处理中...");
  $.ajax({
    type: 'POST',
    url:  '/site/getRandPassowrd',
    data: ({
      u_email : $('#email').val()
    }),
    dataType: 'html',
    timeout:2000,
    async:false,
    success: function(data){
      if(data =='true'){
        $('#getPasswrdForm').html('请到'+ $('#email').val() +' 查看斑马森林发给你的随机密码，登陆后重新设置你的密码。<br/>谢谢你对斑马森林的爱护：）');
      }else{
        alert('失败!');
        window.location.reload(true);
      }
    },
    error:function (XMLHttpRequest, textStatus, errorThrown) {}
  }); 
}

function btn_save_tags(b_id,tag_val)
{
  result = $.ajax({
    type: 'POST',
    url:  '/mine/save_tags',
    data: ({
      b_id :b_id,
      tag_val : tag_val
    }),
//    dataType: 'json',
    timeout:2000,
    async:false
  }).responseText;
}


function flash_btn_collect(b_id){
  options.type = 'GET';options.url = '/mine/addcollect/b_id/'+b_id;
  mic_ajax(); if(result == 'true'){alert('收藏成功!');}else{alert('收藏失败或你已经收藏!');}
}

function flash_btn_recommand(b_id){
  options.type = 'GET';options.url = '/mine/addrecmd/b_id/'+b_id;
  mic_ajax(); if(result == 'true'){alert('推荐成功!');}else{alert('推荐失败!');}
}

function flash_btn_edit(b_id){
  mic_open_window("/mine/editide/bookid/"+b_id);    
}

function btn_save_title(b_id,title)
{
  var title_val = title.val();
  options.url = '/mine/editsave';
  options.data = ({b_id:b_id,b_name : title_val});
  mic_ajax();
}

/*
 *	BM ajax libaray for banmasenlin
 *  v 0.01
 */
bm ={
  votedelete:function()
  {
    options.url = '/poll/blogdelete';
    mic_ajax();
    mic_reload();
  },
  vote:function(pb_id){
    options.url = '/poll/blogvote';
    options.data = ({pb_id:pb_id});
    mic_ajax();
    if(result == 'true'){
      alert(return_tip[7]);
      setTimeout('mic_reload()', 500);
    }else{
      alert(return_tip[8]);
    }
  },
  poll_upload:function(){
    options.url='/poll/BlogUploadview';
    mic_ajax();
    new Dialog({
      title: '上传blog图标（150x100像素,72DPI,100KB)',
      content:result,
      buttons:false
      });
  },
  poll_join_dialog:null,
  poll_join:function(){
    options.url = '/poll/Blogdo';
    mic_ajax();
    if(result == 'false'){
      new Dialog({
        content:return_tip[9]
      });
    }else{
      this.poll_join_dialog = new Dialog({
        title: title_name[5],
        content:result,
        buttons:{
          '提交':function(){
            options.url='/Poll/BlogSave';
            var data_array=[];
            var return_false=0;
            $.each($("input[id^='id_blog_']"),function(){
              if($(this).val()) data_array.push($(this).attr('name')+":'"+$(this).val()+"'");
              else{ return_false = 1;}
            });
            if(return_false){
              new Dialog({content:return_tip[11]});
            }else{
              var data_string = data_array.join();
              eval("var data={"+data_string+"}");
              options.data = (data);
              mic_ajax();
              if(result=='false') $("#join_output").html(return_tip[10]);
              else setTimeout("bm.poll_upload()",100);
            }
          }
        }
      });
    }
  },
  gallery_deleteimage:function(g_id,node){
    mic_confirm();
    if(!result) return void(0);
    options.url = '/gallery/delete_image';
    options.data = ({g_id:g_id,node:node});
    mic_ajax();
    if(result == 'true'){
      mic_reload();
    }else{
      alert('delete image error');
    }
  },
  gallery_delete:function(g_id){
    options.url = '/gallery/delete';
    options.data = ({g_id:g_id});
    mic_ajax();
    if(result == 'true'){
      mic_reload();
    }else{
      alert('delete error');
    }
  },

  gallery_uploadinfo_dialog:null,
  gallery_uploadInfo:function(id){
    options.url='/gallery/uploadinfo/g_id/'+id;
    mic_ajax();
    this.gallery_uploadinfo_dialog = new Dialog({
      content:result,
      buttons:{
        'Save':function(){
          options.url='/gallery/saveuploadinfo/g_id/'+id;
          var data_array =[];
          $.each($("input[id^='gallery_']"),function(){
            if($(this).val()) data_array.push($(this).attr('name')+":'"+$(this).val()+"'");
          });
          var data_string = data_array.join();
          eval("var data={"+data_string+"}");
          data.g_desc = $('#gallery_desc').val();
          options.data = (data);
          mic_ajax();
          if(result=='false') $("#gallery_output").html(return_tip[6]);
          else mic_reload();
        }
      }
    })
  },

  gallery_upload_dialog:null,
  gallery_upload:function(){
    options.url='/gallery/upload';
    mic_ajax();
    this.gallery_upload_dialog = new Dialog({
      title: title_name[2],
      content: result,
      buttons:{
        'Save':function(){
          options.url = '/gallery/save';
          var data_array =[];
          $.each($("input[id^='gallery_']"),function(){
            if($(this).val()) data_array.push($(this).attr('name')+":'"+$(this).val()+"'");
          });
          var data_string = data_array.join();
          eval("var data={"+data_string+"}");
          data.g_desc = $('#gallery_desc').val();
          options.data = (data);
          mic_ajax();
          if(result=='false') $("#gallery_output").html(return_tip[6]);
          else{
            $("#gallery_output").html(return_tip[5]);
            setTimeout('bm.gallery_uploadImage("' + result + '")', 500);
          }
        }
      }
    });
  },
  gallery_uploadImage:function(id){
    try{
      this.gallery_upload_dialog.close();
    }catch(e){}
    options.url = '/gallery/uploadimage/g_id/'+id;
    mic_ajax();
    this.gallery_upload_dialog = new Dialog({
      title: title_name[3],
      content: result,
      buttons: null
    });
  },

  gallery_uploadImagelist:function(id){
    options.url = '/gallery/uploadimagelist/g_id/'+id;
    mic_ajax();
    this.gallery_upload_dialog = new Dialog({
      title: title_name[3],
      content: result,
      buttons: null
    });
  },
  topay:function(orderid){
	  alert("因网站调整，暂停订单功能，抱歉。");
	  exit;
/*
    var payment = $("input[@name='payment'][@checked]").val();
    if(payment == "bank"){
        $.ajax({
            type: 'POST',
            url:  '/api/updatestatus',
            data: ({
                pay_id : orderid,
                s : 7
            }),
           success: function(msg){
               mic_goto('/pay');
           }
        })
    }else{
      options.url = '/pay/topay';
      options.data = ({orderid:orderid,payment:payment});
      mic_ajax();
      mic_open_window(result);
    }
*/
  },
  deliverdelete:function(d_id){
      $('#pay-deliver').hide();
      $('h4').remove();
      $('.pay-deliver').remove();
    options.url = '/pay/deliverdelete';
    options.data = ({d_id:d_id});
    mic_ajax();
    if(result =='true'){
      setTimeout("bm.deliver_address_table()",100);
    }else{
      alert(result_tip[4]);
    }
  },
  deliverdelete_reload:function(d_id){
      
    options.url = '/pay/deliverdelete';
    options.data = ({d_id:d_id});
    mic_ajax();
    if(result =='true'){
        mic_reload();
    }else{
      alert(result_tip[4]);
    }
  },

  deliver_address_table:function(){
    options.url='/pay/getaddresstable';
    options.data = null;
    mic_ajax();
    jQuery('#address_table').html(result);
  },

  deliver_address_Dialog: null,
  deliver_address:function(){
    options.url = '/pay/DeliverAddress';
    options.data = null;
    mic_ajax();
    this.deliver_address_Dialog = new Dialog({
      title: title_name[1],
      content: result,
      buttons:{
        '保存': function(){
          options.url = '/pay/DeliverAddress';
          var data_array =[];
          $.each($("input[id^='from_']"),function(){
            if($(this).val()) data_array.push($(this).attr('name')+":'"+$(this).val()+"'");
          });
          var data_string = data_array.join();
          eval("var data={"+data_string+"}");
          options.data = (data);
          mic_ajax();

          if(result =='true'){
            $('#result').html(return_tip[3]);
            try{
              setTimeout("bm.deliver_address_Dialog.close();",1);
            }catch(e){log.debug('dialog close error');}
            setTimeout("bm.deliver_address_table()",100);
          }else{
            $('#result').html(return_tip[2]);
          }
        },
        '取消': Dialog.prototype.close
      }
    });
  },

  mic_unlock:function(pay_id){
    options.url ='/pay/unlock';
    options.data= ({pay_id:pay_id});
    mic_ajax();
    if(result == 'true'){
      new Dialog({
        title: '订单取消成功',
        content: '',
        buttons:false
      });
    }else{
      new Dialog({
        title: '订单取消失败',
        content: '',
        buttons:false
      });
    }
    setTimeout("bm.deliver_address_table()",2000);
  },
  mic_submit_pay:function(pay_id){
    options.url = '/pay/ordersubmit';
    options.data = ({pay_id:pay_id});
    mic_ajax();
    mic_reload();
  },
  mic_pay_flush:function(pay_id){
    options.url = '/pay/orderupdate';
    options.data = ({pay_id:pay_id});
    mic_ajax();
    mic_reload();
  },

  mic_pay_info:function(pay_id){
    options.url = '/pay/payinfo';
    options.data = ({pay_id:pay_id});
    mic_ajax();
    new Dialog({
      title: '订单信息',
      content: result,
      buttons: {
        '关闭': Dialog.prototype.close
      }
    });
  },
  mic_note_info:function(pay_id){
    options.url = '/pay/noteinfo';
    options.data = ({pay_id:pay_id});
    mic_ajax();
    new Dialog({
      title: '订单信息',
      content: result,
      buttons: {
        '关闭': Dialog.prototype.close
      }
    });
  },
  //mic_calc_easy_net()
  mic_calc_easy_net:function(pay_id){
    var b_type    = parseInt($('#b_type_'+pay_id).val());
    var b_binding = parseInt($('#b_binding_'+pay_id).val());
    var b_film    = parseInt($('#b_film_'+pay_id).val());
    var b_number  = parseInt($('#b_number_'+pay_id).val());
    var b_write   = parseInt($('#b_write_'+pay_id).val());
    
    if(b_type == 0){alert(calc_tip[0]);return;}
    if(b_write == 0 ) { alert('请选择空白内页');return; }
    if(b_binding == 0){alert(calc_tip[1]);return;}
//    if(b_film == 0){alert(calc_tip[2]);return;}
    if(b_number == 0){alert(calc_tip[3]);return;}
    if(pay_id == 0){alert(calc_tip[4]);return;}
    options.url = '/pay/calc';
    options.data = ({
        b_type:b_type,
        b_write:b_write,
        b_binding:b_binding,
        b_film:b_film,
        b_number:b_number,
        pay_id:pay_id
    });
    mic_ajax();
    $('#order_price').html(result);
    
    return parseFloat(result);
  },
  //tags;
  event_select_tags:function(t){
    var tags_val =$.trim($('#book_tags_val').val());
    book_tags = tags_val.split(/\s+/);
    book_tags =$.unique(book_tags);
    input_book_tags_val = book_tags.join(' ');
    $('#book_tags_val').val(input_book_tags_val);
    t_val = $.trim($(t).text());
    if($(t).hasClass('selected')){
      book_tags = $.grep(book_tags, function(n){ return (n != t_val);	});
    }else{
      book_tags.push(t_val);
    }
    $.each($("span[name='"+t_val+"']"),function(){
      if($(this).hasClass('selected')){		
        $(this).removeClass('selected');
      }else{
        $(this).addClass('selected');
      }	
    });
    book_tags =$.unique(book_tags);
    input_book_tags_val = book_tags.join(' ');
    $('#book_tags_val').val(input_book_tags_val);
  },
  tagsDialog: null,
  
  tagsForm: function(title,content) {
    this.tagsDialog = new Dialog({
      title: title,
      content: content,
      buttons: {
        '保存': function() {
          var tag_val = $('#book_tags_val').val();
          var b_id	 = $('#b_id').val();
          btn_save_tags(b_id,tag_val);
          /*  */
          if(result == 'true') {
        	  mic_reload();
          } else {
        	  mic_reload();
          }
        },
        '取消': Dialog.prototype.close
      }
    });
  },

  addtagsDialog: null,
  addtagsFrom:function(){
    options.url = '/mine/AddTags';
    mic_ajax();
    this.addtagsDialog = new Dialog({
      title: title_name[0],
      content: result,
      buttons:{
        '保存': function() {
          var tag_name = $('#tag_name').val();
          options = {
              url:'/mine/SaveNewtag',
              type:'post',
              data: ({
            	  tag_name : tag_name
              }),
              dataType:'html',
              timeout:3000,
              async:false
          };
          mic_ajax();
          if(result == 'true') {
        	  mic_reload();
          } else {
        	  $('#tag_output').html(return_tip[1]);
          }
        },
        '取消': Dialog.prototype.close
      }					
    });
  },
  /** 2009-07-31 author: 夏鑫 **/
    print_message:function(){
        options.url = '/msg/printmessage';
        mic_ajax();
        if(result == 'false'){
        	new Dialog({
        		content:'请求失败'
        	})
        }else{
        	this.poll_join_dialog = new Dialog({
        		title: '抱歉！',
        		content:result,
        		buttons:{
        			'关闭': Dialog.prototype.close
        		}
        	})
	    }
    },
    
    book_not_show:function(n) {
        new Dialog({
            content:'<div style="height:90px; margin-left:8px;"><div style="float:left;"><img src="/images/header/Sorry.png" /></div><div style="float:right; width:275px;"><BR><h1><b>抱歉！</b></h1>' + n + ' 只允许他(她)的友们可阅读本书。</div><div style="clean:both;"></div><div>'
        })
    },
    
    edit_deliver_address : function(pid, obj) {
		$('#pay-deliver').html("");
		$('#pay-deliver').hide();
        options.url = '/pay/EditDeliverAddress';
        options.data = {pid:pid};
        mic_ajax();
		$('#edit-deliver').show();
        $('#edit-deliver').html(result);
    },
    
    edit_deliver_address_t : function(pid, obj) {
        options.url = '/pay/PEditDeliverAddress';
        options.data = {pid:pid};
        mic_ajax();
        $('.pay-deliver').remove();
        $('h4').remove();
        $('#pay-deliver').html(' ');
//        $('#pay-deliver').after(result);
        $('#pay-deliver').html(result);
    },
    
    ebank : function(obj) {
        if (obj.checked == true) {
            $('#ebank_button').show();
        }
    },
    cancel_pay : function(pid) {
        $.ajax({
            type: 'POST',
            url:  '/pay/cpcontent',
            data: ({ pay_id : pid }),
            success: function(html){
                new Dialog({
                    width: 500,
                    height: 400,
                    title: '取消订单',
                    content: html,
                    buttons:{
                        '确定': function(){
                            options.url ='/pay/unlock';
                            options.data= ({pay_id:pid});
                            mic_ajax();
                            if(result == 'true'){ new Dialog({
                                title: '订单取消成功',
                                content: '',
                                buttons:false
                            }); }else{ new Dialog({
                                title: '订单取消失败',
                                content: '',
                                buttons:false
                            }); }
                            setTimeout(mic_goto('/pay'),2000);
                        },
                        '取消': Dialog.prototype.close
                  }
                });
           }
        });
    },
    deliver_submit : function() {
       if (!bm.pay_deliver_check()) { return false; }
	   
          options.url = '/pay/DeliverAddress';
          var data_array =[];
          jQuery.each(jQuery("input[id^='deliver_']"),function(){
              if(jQuery(this).attr('id')=='deliver_address') {
                  if(jQuery(this).val()) {
                      //data_array.push(jQuery(this).attr('name')+":'"+jQuery("select[id=a1] option:selected").html() + '-' + jQuery("select[id=a2] option:selected").html() + '-' + jQuery("select[id=a3] option:selected").html() + '-' + jQuery(this).val()+"'");
					  data_array.push(jQuery(this).attr('name')+":'"+ $("select[name='province'] :selected").text() + '-' + $("select[name='city'] :selected").text() + '-' + $("select[name='area'] :selected").text() + '-' + jQuery(this).val()+"'");
                  }
              }else {
                    if(jQuery(this).val()) data_array.push(jQuery(this).attr('name')+":'"+jQuery(this).val()+"'");
              }
          });
                
          var data_string = data_array.join();
          eval("var data={"+data_string+"}");
          options.data = (data);
          mic_ajax();
          if(result =='true'){
              jQuery('.pay-deliver').remove();
              this.deliver_address_table();
              jQuery('#pay-deliver').hide();
              jQuery('#address_table label:first-child :input').attr('checked', true);
              jQuery('#result').html(return_tip[3]);
              return result;
          }else{
            jQuery('#result').html(return_tip[2]);
          }
    },
    
    deliver_update : function(d_id) {
		var d_id = (typeof d_id == 'undefined')?'':d_id;
        if (!bm.pay_deliver_check()) { return false; }
        var id = d_id;
        var username = $('#deliver_username').val();
        var postcode = $('#deliver_postcode').val();
        var phone = $('#deliver_phone').val();
        var mobile = $('#deliver_mobile').val();
        var address = $('#deliver_address').val();

		var province	= $("select[name='province'] :selected").text();
		var city			= $("select[name='city'] :selected").text();
		var area			= $("select[name='area'] :selected").text();
		
		var rt = $.ajax({            
           type: "POST",
           url: "/pay/UpdateDeliverAddress",
           data: {
               b_id : id,
               username : username,
               postcode : postcode,
               phone : phone,
               mobile : mobile,
               address : province + '-' + city + '-' + area  + '-' + address
           },
            async : false,
           success: function(d){
              if(d =='true'){
                  bm.deliver_address_table();
                  jQuery('.pay-deliver').remove();
              }else{
                jQuery('#result').html(return_tip[2]);
              }
              return d;
           }
        }).responseText; 
		mic_reload();
        return rt;
    },
    banmasenlin_contact : function() {
        new Dialog({
            width: 500,
            height: 400,
            title: '联系方式',
            content: '<ol style="padding-left:20px; list-style-type:decimal;">'
                    +'<li>客服热线：010-65575047 （周一至周五 9:00-18:00）</li>'
                    +'<li>传真：010-65575047 （请注明客服部收）</li>'
                    +'<li>客服E-mail: service@banmasenlin.com</li>'
                    +'<li>事务与建议E-mail: support@banmasenlin.com</li>'
                    +'<li>QQ：1181087137</li>'
                    +'<li>msn：service@banmasenlin.com</li>'
                    +'</ol>',
            buttons:false
        });
    },
    pay_over : function(orderid) {
        $.ajax({
            type: 'POST',
            url:  '/api/updatestatus',
            data: ({
                pay_id : orderid,
                s : 5
            }),
           success: function(msg){
               mic_goto('/pay');
           }
        })
    },
    pay_deliver_check : function() {
        if ($("#deliver_username").val().length == 0) {
            alert('请输入用户名');
            return false;
        }

		var province	= $("select[name='province'] :selected").text();
		var city			= $("select[name='city'] :selected").text();
		var area			= $("select[name='area'] :selected").text();
		
		var __province	=	'省份';
		var __city			=	'城市';
		var __area			=	'地区';
		
		if( province === __province  || city === __city || area ===__area || province=="" || city=="" || area==""){
			alert("收件人地址:省份/城市/地区 请选择");
			return false;
		}

        if ($("#deliver_address").val().length == 0 || $("#deliver_address").val() == '街道') {
            alert('请输入收件人地址');
            return false;
        }
        
        if ($("#deliver_postcode").val().length == 0) {
            alert('请输入邮政编码');
            return false;
        } else if($("#deliver_postcode").val().length !=6 ) {
            alert('输入的邮政编码不是6位数字');
            return false;
        }

        if ($("#deliver_phone").val().length == 0 && $("#deliver_mobile").val().length == 0) {
            alert('请输入 固定电话 或 移动电话 中的一项目');
            return false;
        }
        
        if ($("#deliver_mobile").val().length != 0 && $("#deliver_mobile").val().length != 11) {
            alert('手机号码应为11位数');
            return false;
        }

        return true;
    }
};




//  省份数据
var __province = {}

//  选择省触发函数
function _select_province(id) {
	if (null === id) { return false; }
	$.ajax({ type:"POST", url:"/payapi/area/action/province",dataType:"json", success:function(result) {
		_result_province_html(id, result);
		_select_city();
	}})
}

//  处理省的HTML
function _result_province_html(id, data) {
	//  结果数据
	var result = '<option>省份</option>';
    for(group in data) {
    	result += '<optgroup label="'+group+'">';
        for (province in data[group]) {
        	result += '<option value="' + data[group][province] + '"'
                   +  ' id="province_' + province + '" num="' + province + '">'
                   +  data[group][province]
                   +  '</option>';
        	
        }
        result += '</optgroup>';
    }
	$(id).html(result);
	//  绑顶方法
    $("#a1").bind("click", _select_city);
}

//  选择城市
function _select_city() {
	var num = $('select[id=a1] option:selected').attr('num');
	if ( 'undefined' === typeof num ) { return false; }
	
	
	if ('undefined' !== typeof __province[num] ) {
		_result_city_html('#a2', __province[num]);
	} else {
		$.ajax({ type: "POST", url: "/payapi/area/action/city", data : 'city=' + num, dataType: "json", success: function(result){
			//  缓存数据
			__province[num] = result;
			_result_city_html('#a2', result);
		}});
	}
}

//  选择城市HTML
function _result_city_html(id, data) {
	var result = '';
    for(city in data) {
    	result += '<option value="' + city + '" id="city_' + city + '">' + city + '</option>';
    }
    $(id).html(result);
    
    $("#a2").bind("click", function() {
        _select_area('#a3', data);
    });
    _select_area('#a3', data);
}

//  选择地区
function _select_area(id, data) {
	var result = '';
	var value = $('select[id=a2] option:selected').val();
    for(area in data[value]) {
        result += '<option>' + data[value][area] + '</option>';
    }
    $(id).html(result);
}
