function start(){
    wi(1);
    ci(1);
    mi(1);
    fi(1);
    //pi(1);
    setInterval(show_st,1000);
    //show_st()
    //g1i(1) because changed unit produce way, now it's no use. consider later.
}

function wi(t){
    //wood increase
    var w = document.getElementById('w');
    var wood = w.innerHTML;
    inc = document.getElementById('winc').innerHTML;
    limit = document.getElementById('rl').innerHTML;
    if (inc>0) {
    increase = inc/3600;
    if(wood != limit)
    {
    setTimeout("wi(0)", 1/increase*1000);
    if(t == 0){document.getElementById('w').innerHTML = parseInt(wood) + 1;}
    }
    }
}

function ci(t){
    //clay increase
    var clay = document.getElementById('c').innerHTML;
    var inc = document.getElementById('cinc').innerHTML;
    limit = document.getElementById('rl').innerHTML;
    if (inc>0) {
    increase = inc/3600;
    if(clay != limit)
    {
    setTimeout("ci(0)", 1/increase*1000);
    if(t == 0){document.getElementById('c').innerHTML = parseInt(clay) + 1;}
    }
    }
}

function mi(t){
    //mine increase
    var mine = document.getElementById('m').innerHTML;
    var inc = document.getElementById('minc').innerHTML;
    limit = document.getElementById('rl').innerHTML;
    if (inc>0) {
    increase = inc/3600;
    if(mine != limit)
    {
    setTimeout("mi(0)", 1/increase*1000);
    if(t == 0){document.getElementById('m').innerHTML = parseInt(mine) + 1;}
    }
    }
}

function fi(t){
    //food increase
    var food = document.getElementById('f').innerHTML;
    var inc = document.getElementById('finc').innerHTML;
    limit = document.getElementById('fl').innerHTML;
    if (inc>0) {
    increase = inc/3600;
    if(food != limit)
    {
    setTimeout("fi(0)", 1/increase*1000);
    if(t == 0){document.getElementById('f').innerHTML = parseInt(food) + 1;}
    }
    }
}

function pi_old(t){ //cancelled!
    //pop increase, now using different way to increase in page, with the way for other resources.
    myElement = document.getElementById('p');
    if(myElement != null)
    {
    d = myElement.innerHTML.split("<br>");
    pop = parseInt(d[0]); //population
    limit = parseInt(d[1]); //pop limit
    inc = myElement.title/3600;
    if(pop != limit)
    {
    setTimeout("pi(0)", 1/inc*1000);
    if(t == 0){myElement.innerHTML=pop + 1 + "<br>" + limit;}
    }
    }
}

function valid(num)
{
//alert("here");
if(isNaN(num) == true) {num = 0;}
document.form1.num1.value=num
//return num;
}

function minus_res(wood,clay,mine,food,silver,pop) {//minus resources and pop on page.
    $("#s").html(parseInt($("#s").html())-silver);
    $("#f").html(parseInt($("#f").html())-food);
    $("#w").html(parseInt($("#w").html())-wood);
    $("#c").html(parseInt($("#c").html())-clay);
    $("#m").html(parseInt($("#m").html())-mine);
    $("#p").html(parseInt($("#p").html())-pop);
}

function refresh_base_old() { //ajax refresh base info, for current city, including city info and city goods.
    $.post("/city_base/",{
                method: 'POST'
            }, function(data) {
                    $("#w").html(data.res_wood);
                    $("#c").html(data.res_clay);
                    $("#m").html(data.res_mine);
                    $("#f").html(data.res_food);
                    $("#s").html(data.res_silver);
                    $("#city_civ").html(data.civ);
                    $("#winc").html(data.wood_inc);
                    $("#cinc").html(data.clay_inc);
                    $("#minc").html(data.mine_inc);
                    $("#finc").html(data.food_inc);

        },'json');
        //return false;
};

function base_event_refresh() { //ajax refresh base info, for current city, including city info and city goods.
    tt = new Date();
    $("#event_shows").load("/base_event/"+"?t=" + tt.getTime());
};
function refresh_city_bld_nouse(building_id) { //ajax refresh building id in city map. the only one param is id of building
    tt = new Date();
    $.load("/base_event/"+"?t=" + tt.getTime());
};



//add a random counter for timer count down, to avoid counter in ajax page's conflict!!!
//need a event_time_container span on page.
function add_timer(time_remain,counter,in_base_event,request_url,bld_position_id,bld_level) {
    //time_remain is in seconds, counter is fixed value in page. only there 2 params is must be provide.
    // in_base_event decides if in base event frame or not,
    // request_url is the url which will return when count down to 0.
    // bld_position_id is position id of city building, if event is building update, this will be true
    // bld_level is building's original level (before update).
    var randint = Math.floor(Math.random()*1000);
    var etr = "<span id=event_time_remain" + randint + "></span>";
    $("#event_time_container"+counter).append(etr);
    event_timer(time_remain,randint,in_base_event,request_url,bld_position_id,bld_level);
}

function event_timer(time_remain,counter,in_base_event,request_url,bld_position_id,bld_level) {
    //if it's called by add_timer, note here counter is random int created by add_timer.
    //$("#event_table_"+counter).remove();
    rt = parseInt(time_remain) + 1; //compensation for server dealing time...try
    eventid=document.getElementById('event_time_remain'+counter);
    //alert(eventid);
    if (rt == 0) 
    {
        //refresh_base(); // now all timer ends, refresh base page info....optimize this later.
        //alert('1');
        //var temp = document.getElementById('event_table_'+counter);
        //alert($("#event_table_"+counter));
        //alert(counter);
        if(in_base_event==1) { //for event table, remove it.
            //$("#event_table_"+container_id).remove();
            base_event_refresh();
            if (bld_position_id) {
                //refresh_city_bld(bld_position_id)
                //alert('here'); //check, will come here twice???
                $("#bld_upd_"+bld_position_id).remove();
                new_level = parseInt(bld_level) + 1;
                $("#bldl_img"+bld_position_id).attr("src","/site_media/img/building/l" + new_level +".gif")
            }
        }
        else {
            if (request_url != 'undefined'){
                $.openMain({"loadUrl":request_url});
                
            }
            else {window.location.reload();} //temp., if not in event table, such as in produce sequences, reload page. not good.
        }
    }
    else 
    {  
       if (eventid) {
       eventid.innerHTML = time_format(rt);
       time_remain = time_remain - 1
       setTimeout("event_timer('" + time_remain + "','" + counter + "','" + in_base_event + "','" + request_url + "','" + bld_position_id + "','" + bld_level + "')",1000)
    }
    }
}

function event_timer_wonder(time_remain,counter) { //for wonder event, no reload page after it arrives!
    rt = parseInt(time_remain) + 2 //compensation for server dealing time...try
    eventid=document.getElementById('event_time_remain'+counter);
    if (rt > 0)
    {  
       eventid.innerHTML = time_format(rt);
       time_remain = time_remain - 1
       setTimeout("event_timer_wonder('" + time_remain + "','" + counter + "')",1000) 
    }
    else {
        eventid.innerHTML = "0:00:0x";
    }
}

function time_format(s) {
//from seconds to hh:mm:ss format. if more than 1 day, show xx天.
var t;
if(s > -1){
    hour = Math.floor(s/3600);
    min = Math.floor(s/60) % 60;
    sec = s % 60;
    day = parseInt(hour / 24);
    if (day > 0) {
        hour = hour - 24 * day;
        t = day + "天," + hour + ":";
        }
    else t = hour + ":";
    
    if(min < 10){t += "0";}
        t += min + ":";
    if(sec < 10){t += "0";}
        t += sec;}
else
    {t = "0:00:0x";}
return t;
}

function CurentTime(){  
    var mm = now.getMinutes();  
    var ss = now.getTime() % 60000;ss = (ss - (ss % 1000)) / 1000;  
    var clock = now.getHours() +':';  
    if (mm < 10) clock += '0'; 
    clock += mm+':';  
    if (ss < 10) clock += '0';  
    return(clock + ss); 
    //clock += mm;
    //return clock //temp, coz now no second tick...
}  

function show_st(){ //show server time
    document.getElementById('server_time_id').innerHTML = CurentTime();now.setSeconds(now.getSeconds()+1); 
    //setTimeout("show_st()", 1000); 
} 

function live_combat_timer(time_remain) {
    //timer for live combat, now in testing!
    //note:because js count month from 0 to 11, so in template, use format as: |date:"Y,m-1,d,H,i,s"
    var rt = parseInt(time_remain) + 5 //compensation for server dealing time...try
    
    eventid=document.getElementById('next_round_time_remain'); 
    if (rt == 0) 
    {
        window.location.reload();
    }
    else 
    {  
        if (eventid) { 
            eventid.innerHTML = time_format(rt);
            time_remain = time_remain - 1
            setTimeout("live_combat_timer('" + time_remain + "')",1000) 
        }
    }
}

function add_train(gid,n){document.getElementById('soldier_number'+gid).value=document.getElementById('m'+gid).innerHTML;}

//trade transfer
function add_res(rid,rname,number) {
    var c;
    if (document.transform.caravan_left.value==0) {
        if (rname != 'silver') {return 0}
        }
    
    switch (rname)
         {
            case 'wood_number':
                c = document.transform.wood_number.value;
                document.getElementById("caravan_left2").innerHTML = document.getElementById("caravan_left2").innerHTML - 1;
                document.getElementById("caravan_left3").innerHTML = document.getElementById("caravan_left3").innerHTML - 1;
                document.getElementById("caravan_left4").innerHTML = document.getElementById("caravan_left4").innerHTML - 1
            break;
            case 'clay_number':
                c = document.transform.clay_number.value;
                document.getElementById("caravan_left1").innerHTML = document.getElementById("caravan_left1").innerHTML - 1;
                document.getElementById("caravan_left3").innerHTML = document.getElementById("caravan_left3").innerHTML - 1;
                document.getElementById("caravan_left4").innerHTML = document.getElementById("caravan_left4").innerHTML - 1
            break;
            case 'mine_number':
                c = document.transform.mine_number.value;
                document.getElementById("caravan_left1").innerHTML = document.getElementById("caravan_left1").innerHTML - 1;
                document.getElementById("caravan_left2").innerHTML = document.getElementById("caravan_left2").innerHTML - 1;
                document.getElementById("caravan_left4").innerHTML = document.getElementById("caravan_left4").innerHTML - 1
            break;
            case 'food_number':
                c = document.transform.food_number.value;
                document.getElementById("caravan_left1").innerHTML = document.getElementById("caravan_left1").innerHTML - 1;
                document.getElementById("caravan_left2").innerHTML = document.getElementById("caravan_left2").innerHTML - 1;
                document.getElementById("caravan_left3").innerHTML = document.getElementById("caravan_left3").innerHTML - 1
            break;
            case 'silver':
                c = document.transform.silver.value;
            break;
         } 

    if (c=='') {
        a = 0
    }
    else {
        if (isNaN(parseInt(c))){
            a= 0
        }
        else {
            a = parseInt(c)
        }
    }
    a = a + number
    rid.value = a
    
    document.transform.caravan_left.value = document.transform.caravan_left.value - 1
    //alert(document.transform.caravan_left.value);
    
}

function multi_res(rid) {
    var ta = 0 //judge if reset all x to 0
    if (document.transform.caravan_left.value==0) {
        return 0;
    }
    if (rid==1) {
        if (document.transform.wood_number.value !='') {
            ta=1;document.transform.wood_number.value = parseInt(document.transform.wood_number.value) * document.getElementById("caravan_left1").innerHTML
        }
    }
    if (rid==2) {
        if (document.transform.clay_number.value !='') {
            ta=1;document.transform.clay_number.value = parseInt(document.transform.clay_number.value) * document.getElementById("caravan_left2").innerHTML
        }
    }
    if (rid==3) {
        if (document.transform.mine_number.value !='') {
            ta=1;document.transform.mine_number.value = parseInt(document.transform.mine_number.value) * document.getElementById("caravan_left3").innerHTML
        }
    }
    if (rid==4) {
        if (document.transform.food_number.value !='') {
            ta=1;document.transform.food_number.value = parseInt(document.transform.food_number.value) * document.getElementById("caravan_left4").innerHTML
        }
    }
    if (ta==1) {
        document.getElementById("caravan_left1").innerHTML = 0;
        document.getElementById("caravan_left2").innerHTML = 0;
        document.getElementById("caravan_left3").innerHTML = 0;
        document.getElementById("caravan_left4").innerHTML = 0;
        document.transform.caravan_left.value = 0;
    }
    
}

function multi_silver(n) {
    if (document.transform.silver.value !='') {
        document.transform.silver.value = parseInt(document.transform.silver.value) * n
    }
}

function checkAll(name)
//check all the checkbox...
{
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++)
    {
        if((el[i].type=="checkbox") && (el[i].name==name))
        {
            el[i].checked = true;
        }
    }
}
function clearAll(name) 
{
    var el = document.getElementsByTagName('input');
    var len = el.length;
    for(var i=0; i<len; i++)
    {
        if((el[i].type=="checkbox") && (el[i].name==name))
        {
            el[i].checked = false;
        }
    }
}

function SetCookie(name,value)
{
var Days = 30; //30 days
var exp = new Date(); // or .... new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function getCookie(name)
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}

function delCookie(name)
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

function updateMsg(channel,rep) {
    var time_now = new Date();
    //alert('updateMsg');
    //alert($("#max_message_number"+channel).length);
    if ($("#max_message_number"+channel).length > 0)  {
    $.getJSON("/chat/" + channel + "/?t="+time_now.getTime()+"&m="+ $("#max_message_number"+channel).val(),
      function(data){
        if (data.messege != '') {
            $("#chatwindow"+channel).append(String(data.messege));
            $.each(data.messege, function(i,messege){
              if ( i == 3 ) return false;
            });
            //document.chatform.max_message_number.value = data.user_max_mes;
            document.getElementById("max_message_number"+channel).value = data.user_max_mes;
            scroll_to_bottom(channel);
            $('#chatwindow1 a').unbind();//must!
            base_ajax_event($("#chatwindow1"));
        }
      });
    if (channel != 0) { if (rep==1) {setTimeout('updateMsg('+chat_channel+','+rep+')', 5000);}}
    }
    //scroll_to_bottom(channel);
};

function scroll_to_bottom(channel) {
    var objDiv = document.getElementById("chatwindow"+String(channel));
    objDiv.scrollTop = objDiv.scrollHeight;
    objDiv.scrollTop = objDiv.scrollHeight;
}

function sim_process(data) { //battle simulator process
    //alert(data);
    $("#result").html('');
    $("#anum_error").html('');
    $("#dnum_error").html('');
    $("#aforce_error").html('');
    $("#dforce_error").html('');
    $("#a_ladder_error").html('');
    if (data.attacker_number) {
        $("input[name='attacker_number']").after("<div class='error'>" + data.attacker_number +"</div>");
      //document.getElementById("anum_error").innerHTML=data.attacker_number
    }
    if (data.defender_number) {
        $("input[name='defender_number']").after("<div class='error'>" + data.defender_number +"</div>");
      //document.getElementById("dnum_error").innerHTML=data.defender_number
    }
    if (data.attacker_force) {
        $("input[name='attacker_force']").after("<div class='error'>" + data.attacker_force +"</div>");
      //document.getElementById("aforce_error").innerHTML=data.attacker_force
    }
    if (data.defender_force) {
        $("input[name='defender_force']").after("<div class='error'>" + data.defender_force +"</div>");
      //document.getElementById("dforce_error").innerHTML=data.defender_force
    }
    
    if (data.a_ladder_number) {
        $("input[name='a_ladder_number']").after("<div class='error'>" + data.a_ladder_number +"</div>");
      //document.getElementById("a_ladder_error").innerHTML=data.a_ladder_number
    }
    if (data.sub_type==3) {
          $("#result").append(data.death_result);
    }
    else {
        if (data.result1) {
          $("#result").append(data.result1);
        }
        if (data.result2) {
          $("#result").append(data.result2);
        }
    }
    if (data.total_result) {
        $("#result").append('***************<br>');
        $("#result").append(data.total_result);
    }
    if (data.sub_type!=1) {
      if (data.attacker_casulty) {
          $("input[name='attacker_number']").attr("value", $("input[name='attacker_number']").val()-data.attacker_casulty)
      }
      if (data.defend_casulty) {
          $("input[name='defender_number']").attr("value", $("input[name='defender_number']").val()-data.defend_casulty)
      }
    }
}

function soldier_train(general_id) {
    $.post("/military/train/",{
                train_number: document.getElementById('soldier_number'+general_id).value,
                general_id: general_id,
                method: 'POST'
            }, function(data) {
                if (data.body[0][0] == "error") {
                    //document.getElementById('train_error'+data.body[1][1]).innerHTML = data.body[0][1];
                    $("#train_error"+data.body[1][1]).html(data.body[0][1]);
                }
                else {
                    document.getElementById('rb'+data.body[0][1]).disabled=false;
                    minus_res(data.body[1][1],data.body[2][1],data.body[3][1],data.body[4][1],data.body[5][1],data.body[6][1]);
                    document.getElementById('in_traing'+data.body[0][1]).innerHTML = data.body[7][1];
                    document.getElementById('train_error'+data.body[0][1]).innerHTML = "";
                    document.getElementById('soldier_number'+data.body[0][1]).value="";
                    
                }
        },'json');
        return false;
};

jQuery.swordsman_add_skill = function(sid,skillid) {
    $.post("/military/swordsman_as/",{
                sid: sid,
                skillid: skillid,
                method: 'POST'
            }, function(data) {
                if (data.body[0][0] == "success") {
                    a = document.getElementById(data.body[2][1]+'_' + data.body[1][1])
                    b = parseInt(a.innerHTML)
                    aa = document.getElementById(data.body[2][1]+'_un')
                    var sp_left = parseInt(aa.innerHTML)-1
                    if (sp_left >= 0 ){ /*must, or will have display error */
                        a.innerHTML = b + 1
                        aa.innerHTML = sp_left
                    }
                    if (sp_left == 0) {
                        document.getElementById(data.body[2][1]+'_1_plus').innerHTML = "(<b>+</b>)"
                        document.getElementById(data.body[2][1]+'_2_plus').innerHTML = "(<b>+</b>)"
                        document.getElementById(data.body[2][1]+'_3_plus').innerHTML = "(<b>+</b>)"
                    }
                    }
                else {
                    window.location.reload()
                    }
                
        },'json');
        return false;
};

jQuery.general_add_property = function(gid,pid) {
    $.post("/military/general_add_property/",{
                gid: gid,
                pid: pid,
                method: 'POST'
            }, function(data) {
                if (data.body[0][0] == "success") {
                    a = document.getElementById(data.body[2][1]+'_' + data.body[1][1])
                    b = parseInt(a.innerHTML)
                    aa = document.getElementById(data.body[2][1]+'_un')
                    var pp_left = parseInt(aa.innerHTML)-1
                    if (pp_left >= 0 ){ /*must, or will have display error */
                        a.innerHTML = b + 1
                        aa.innerHTML = pp_left
                        if (data.body[1][1]==1) { //added dominion, change max. soldier number
                            document.getElementById('max_sn'+data.body[2][1]).innerHTML = parseInt(document.getElementById('max_sn'+data.body[2][1]).innerHTML)+50
                        }
                    }
                    if (pp_left == 0) {
                        document.getElementById(data.body[2][1]+'_1_plus').innerHTML = "(<b>+</b>)"
                        document.getElementById(data.body[2][1]+'_2_plus').innerHTML = "(<b>+</b>)"
                        document.getElementById(data.body[2][1]+'_3_plus').innerHTML = "(<b>+</b>)"
                    }
                    }
                else {
                    window.location.reload()
                    }
                
        },'json');
        return false;
};


//in city. change background color when mouse on empty building place. 
function change_color(position_id,background_id,title) {
var myi = document.getElementById("myimg");
var mya = document.getElementById("myimga");
myi.style.display='';
myi.title = title;
//myi.src="/site_media/img/red_bg_" + background_id +".gif";
myi.src="/site_media/img/red_bg2.gif";
myi.className="bld" + position_id;
mya.href="/building/" + position_id +"/";
//mya.onMouseOut="alert('a')";
}

function no_color() {//now no use...
var myi = document.getElementById("myimg");
myi.style.display='none';
}

//for emotin in online chat.
function ins_emo(eid){
    var o = document.getElementById("chatmsg");
    o.focus();
    var v = "\\" + eid;
    if(document.selection) {document.selection.createRange().text = v;}
    else {o.value = o.value.substr(0, o.selectionStart) + v + o.value.substr(o.selectionEnd);}
    $("#emotion_frame").css({'display':'none'});
}

function refresh_building(pid,btypeid,isupdate,level,alt_title) {
    //refresh on city and outer city the building's status. 5 params are: position id, type id, is updating or not, building's level, alt and title string
    //Now only used for new building creation.
    if(!$(".bld"+pid).length) {
        var bld_pic = '<a id="bld_url' + pid + '" alt="' + alt_title + '" title="'+ alt_title + '" href="/building/' + pid + '/"><img src="/site_media/img/building/' + btypeid + '.gif" class="bld'+pid+'"></a>'
        $(".city_map").append(bld_pic);
        $('#bld_url'+pid).click(function(){ //class for GET way, ajax html result
        $.openMain({"loadUrl":this.href});
        return false;
        }); 
        
        //alert("ok");
    }
    if(!$("#bldl_img"+pid).length) { // for level > 1, not good, change later.
        var bld_lvl_pic = '<img alt="' + alt_title + '" title="' + alt_title + '" src="/site_media/img/building/l' + level + '.gif" class="bldl' + pid + '" id="bldl_img' + pid + '">'
        $(".city_map").append(bld_lvl_pic);
        //alert("ok");
    }
    
    if (isupdate) {
        var updating_pic = '<img src="/site_media/img/building/updating.gif" class="bld_updating" id="bld_upd_'+pid+'">'
        $("#bld_pic").append(updating_pic);

        v1 = parseInt(($("#bldl_img"+pid).css("left")).replace("px", ""));
        v2 = parseInt(($("#bldl_img"+pid).css("top")).replace("px", ""));
        
        $("#bld_upd_"+pid).css({"left":String(v1+20)+"px","top":String(v2+10)+"px"});
        
        
    }
    
}

//popup main window
(function($){
$.openMain = function(options){
	var defaults = {
        title:"",  
        bWidth:document.body.clientWidth+"px",   //背景宽度
		bHeight:document.body.clientHeight+"px", //背景高度
		oWidth:762,                              //弹出窗口宽度
		oHeight:472                              //弹出窗口高度
	};
    //alert($("#content").height());
	$.extend(defaults,options);
    //if($("#main_pop_frame").length) $("#main_pop_frame").remove(); //no use....
	//绑定div到body
	//var pop_title = "<div id='main_pop_title'><img src='/site_media/images/close.gif'/></div>";
	
    var pop_title = "<div id='main_pop_title'><img src='/site_media/images/close.gif' class='togimg' alt='关闭' title='关闭' />"+defaults.title+"</div>";
    	
	//alert(defaults.title);
	
	//var pop_frame = "<div id='pop_frame'>"+pop_title+"<div id='pop_content'>loading...</div></div>";
    var pop_frame = "<div id='main_pop_frame'>"+pop_title+"<div id='main_pop_content'><img style='align:center' src='/site_media/img/loading.gif' /></div></div>";
	if(!($("#main_pop_frame").length))$("#main").append(pop_frame);
    
    tt = new Date();
    var durl = defaults.loadUrl;
    if (durl.indexOf("?") >= 0) {load_url = durl + "&t=" + tt.getTime()} else {load_url = durl + "?t=" + tt.getTime()}
    $("#main_pop_content").load(load_url,function(){
    //$("#main_pop_content").load(defaults.loadUrl,function(){ //old 
        base_ajax_event($("#main_pop_frame"));
    });
    
	$("#main_pop_title>img").css({"cursor":"pointer","float":"right","margin-top":"5px","margin-right":"5px"}).click(function(){$("#main_pop_background").remove();$("#main_pop_frame").remove();});
    
    //$("#pop_title>img").css({"cursor":"pointer","float":"right"}).click(function(){$("#pop_background").remove();$("#pop_frame").hide(2000,function(){$("#pop_frame").remove()});});
    	
	
	//$("#pop_title").css({"font-size":"12px","background":"#ccc","color":"#777","margin":"5px","padding":"5px"});
	//$("#content").css({"text-algin":"left","font-size":"14px","padding":"10px 10px 10px 10px","overflow-x":"hidden","overflow-y":"auto","width":defaults.oWidth+"px","height":defaults.oHeight+"px"});
	//alert($("#main").position());
	$("#main_pop_frame").css({"width":defaults.oWidth+"px","height":defaults.oHeight+"px","left":$("#main").offset().left+50+"px"});
    //$("#main_pop_frame").append("<div id='ccc'>aa<script>base_ajax_event()</script></div>")

};
})(jQuery);

//popup window
(function($){
$.openWindow = function(options){
    $("#pop_frame").remove(); //erase old pop frame, so the new title can appear...
	//$("#pop_title").html();
    
	var defaults = {
		title:"",                           //标题
		content:"Content",                       //显示内容
		loadUrl:"",                              //调用url
		bColor:"#777",                           //背景色
		bWidth:document.body.clientWidth+"px",   //背景宽度
		bHeight:$("#allwrap").height()+"px", //背景高度
		oColor:"#eee",                           //弹出窗口颜色
		oWidth:500,                              //弹出窗口宽度
		oHeight:200                              //弹出窗口高度
	};
    //alert($("#allwrap").height());
	$.extend(defaults,options);
	//绑定div到body
    
    //$("#pop_title").remove();
	var pop_title = "<div id='pop_title'><img src='/site_media/images/close.gif' class='togimg' alt='关闭' title='关闭' />"+defaults.title+"</div>";
	//var pop_frame = "<div id='pop_frame'>"+pop_title+"<div id='pop_content'>loading...</div></div>";
    //alert(pop_title);
    
    var pop_frame = "<div id='pop_frame'>"+pop_title+"<div id='pop_content'><img style='float:center' src='/site_media/img/loading.gif' /></div></div>";
	if(!($("#pop_frame").length))$("body").append(pop_frame);
    
    if (defaults.loadUrl) {
        tt = new Date();
        var durl = defaults.loadUrl;
        if (durl.indexOf("?") >= 0) {load_url = durl + "&t=" + tt.getTime()} else {load_url = durl + "?t=" + tt.getTime()}
        $("#pop_content").load(load_url,function(){
        //$("#pop_content").load(defaults.loadUrl,function(){ //old....
            base_ajax_event($("#pop_frame"));
        });
    }
    else {
        $("#pop_content").html(defaults.content);base_ajax_event($("#pop_frame"));
    }
    	 
	$("#pop_title>img").css({"cursor":"pointer","float":"right","margin-top":"5px","margin-right":"5px"}).click(function(){$("#pop_background").remove();$("#pop_frame").remove();});
    
    //$("#pop_title>img").css({"cursor":"pointer","float":"right"}).click(function(){$("#pop_background").remove();$("#pop_frame").hide(2000,function(){$("#pop_frame").remove()});});
    	
	
	//$("#pop_title").css({"font-size":"12px","background":"#ccc","color":"#777","margin":"5px","padding":"5px"});
	//$("#content").css({"text-algin":"left","font-size":"14px","padding":"10px 10px 10px 10px","overflow-x":"hidden","overflow-y":"auto","width":defaults.oWidth+"px","height":defaults.oHeight+"px"});
	$("#pop_frame").css({"width":defaults.oWidth+"px","top":((document.documentElement.clientHeight-defaults.oHeight)/2+document.documentElement.scrollTop-80)+"px","left":(document.body.clientWidth-defaults.oWidth)/2+50+"px"});
    
    //for background...
    var pop_background = "<div id='pop_background'></div>";
    if(!($("#pop_background").length))$("body").append(pop_background);
	$("#pop_background").css({"width":defaults.bWidth,"height":$("body").height()+"px"});
    //this is original.....$("#pop_background").css({"background":defaults.bColor,"width":defaults.bWidth,"height" : defaults.bHeight,"z-index":"9998","position":"absolute","filter":"alpha(opacity:40)","-moz-opacity":"0.4","left":0,"top":0});
    

};
})(jQuery);

function base_ajax_event(frame) { //frame is the div container, usually by ajax.main页面中，主要是ajax定义.must call this on every ajax page!
    frame.find('.ajax_url').click(function(){ //class for GET way, ajax html result
    $.openMain({"loadUrl":this.href});$("#pop_background").remove();$("#pop_frame").remove();
    return false;
    });
    
    frame.find('.ajax_url_a').click(function(){ //class for GET way, ajax html result, for url which already have param.
    $.openMain({"loadUrl":this.href});$("#pop_background").remove();$("#pop_frame").remove();
    return false;
    }); 

    frame.find('a[href*="/user_profile/"]:not(".ajax_url")').click(function(){ //class for GET way, ajax html result, for url which already have param.
    $.openWindow({"loadUrl":this.href,"title":"玩家信息"});
    return false;
    }); 
    
    frame.find('a[href*="/alliance/"]:not(".ajax_url")').click(function(){ //class for GET way, ajax html result, for url which already have param.
    $.openMain({"loadUrl":this.href});$("#pop_background").remove();$("#pop_frame").remove();
    return false;
    }); 
    
    frame.find('a[href*="/map/?l="]').click(function(){ //class for GET way, ajax html result, for url which already have param.
    $.openWindow({"loadUrl":this.href,"title":"地图"});
    return false;
    }); 
    
    frame.find('.my_ajax_form').ajaxForm({ //class for POST, ajax html result.
        target: '#main_pop_content', 
        success: function() { 
            $('#main_pop_frame').fadeIn('slow');$("#pop_background").remove();$("#pop_frame").remove();base_ajax_event($('#main_pop_frame'));
        }
    });
    
    frame.find('.my_ajax_form_a').ajaxForm({ //for this, will call refresh_base after success.
        target: '#main_pop_content', 
        success: function() { 
            $('#main_pop_frame').fadeIn('slow');$("#pop_background").remove();$("#pop_frame").remove();base_ajax_event($('#main_pop_frame'));refresh_base();
        }
    });
    
    /*
    $("form#noteform").submit(function(){
      $.post("/vip/note_pad/",{
            note_content: $("#note_content").val(),
            method: 'POST'
          }, function() {
                var s=document.getElementById('note_hid');s.style.display='none';
                document.getElementById('note_text').innerHTML=$("#note_content").val();
            });
      return false;
    });
    */
    frame.find('.pop_a').click(function(){
        //tt = new Date();
        $.openWindow({"loadUrl":this.href,"title":this.title});return false;
    });
    
    frame.find('.ajax_us').click(function(){ //for new unit(general, swordsman) update and revive...
        time_now = new Date();
        var a = $(this);
        $.get($(this).attr('href') + '&t=' + time_now.getTime(),
                function(data){
                    //$('.aj_table:first').after('<div class="event_class">'+data+'</div>');
                    //a.after('<div class="event_class">'+data+'</div>');//for new unit!!!!

                    //$('.uupd_table:first').remove();
                    //a.prev(".uupd_table").remove();
                    //alert($athis.prev(".uupd_table:first"));
                    //$athis.prev(".uupd_table:first").css({"background-color":"#f99"});
                    //alert(a.prev(".stand_table").style());
                    
                    //$athis.prev(".uupd_table:first").remove();
                    //a.after('<div class="event_class">单位开始升级</div>');
                    a.after('<div class="event_class">'+data+'</div>');//for new unit!!!!
                    
                    a.remove();
                    //$("#pop_background").remove(); //only none-pop window use this!!!!
                    //$("#pop_frame").remove();
                    
                    base_event_refresh();
                });
        return false;
    });
    
    
    /* can't use in ajax window....
    frame.find('.togimg').hover ( //hover图片名称必须是原名称加 "_hover"
        function (event) {
           //alert(this);
           //alert('1 '+tmpstr);
           tmpstr = $(event.target).attr("src").split(".");
           hoverstr = tmpstr[0]+'_hover.';
            $(event.target).attr("src",hoverstr+tmpstr[1]) 
        },
        function (event) {
           tmpstr = $(event.target).attr("src").split(".");
           //alert('2 '+tmpstr);
           hoverstr = tmpstr[0].split('_hover')[0]+'.';
           
            $(event.target).attr("src",hoverstr+tmpstr[1]) 
        }
    );
    */    
}

$(document).ready(function(){ //带base.html的页面

    //$('a:not(.no_ajax_url').click(function(){ 
        $('.ajax_url').click(function(){ //class for GET way, ajax html result
        
        $("#main_pop_frame").remove(); //???
        //$("#main").load(this.href+"?t=" + tt.getTime());
        $.openMain({"loadUrl":this.href,'title':this.title});
        return false;
        }); 
        $("#show_current_goods").click(function(){
            tt = new Date();
            $("#show_goods").load("/refresh_goods/?t=" + tt.getTime())
        });
        $('.ajax_url_a').click(function(){ //class for GET way, ajax html result, for url which already have param.
        
        //$("#main").html(); //???
        //$("#main").load(this.href+"&t=" + tt.getTime());
        $.openMain({"loadUrl":this.href});
        return false;
        }); 
        
        /* no need to be in base.
        $('a[href*="user_profile"]').click(function(){ //class for GET way, ajax html result, for url which already have param.
        tt = new Date();
        //$("#main").html(); //???
        //$("#main").load(this.href+"&t=" + tt.getTime());
        $.openMain({"loadUrl":this.href+"?t=" + tt.getTime()});
        return false;
        }); 
        */
        
        
         $("img:.togimg").hover ( //hover图片名称必须是原名称加 "_hover"
             function (event) {
                //alert(this);
                //alert('1 '+tmpstr);
                tmpstr = $(event.target).attr("src").split(".");
                hoverstr = tmpstr[0]+'_hover.';
                 $(event.target).attr("src",hoverstr+tmpstr[1]) 
             },
             function (event) {
                tmpstr = $(event.target).attr("src").split(".");
                //alert('2 '+tmpstr);
                hoverstr = tmpstr[0].split('_hover')[0]+'.';
                
                 $(event.target).attr("src",hoverstr+tmpstr[1]) 
             }
         );
                
        /* pages with base won't have .my_ajax_form...???
        $('.my_ajax_form').ajaxForm({ //class for POST, ajax html result.
            target: '#main', 
            success: function() { 
                //alert('here');
                $('#main').fadeIn('slow'); 
            }
        });
        */
    
        $("form#noteform").submit(function(){
          $.post("/vip/note_pad/",{
                note_content: $("#note_content").val(),
                method: 'POST'
              }, function() {
                    var s=document.getElementById('note_hid');s.style.display='none';
                    document.getElementById('note_text').innerHTML=$("#note_content").val();
                    $('#note_text').css({'display':''});
                });
          return false;
        });
        
        $('.pop_a').click(function(){
         $.openWindow({"loadUrl":this.href});return false;
        });
        
        /* won't have ajax_us in base....
        $(".ajax_us").click(function(){ //for unit(general, swordsman) update and revive...
            time_now = new Date();
            var a = $(this);
            $.get($(this).attr('href') + '&t=' + time_now.getTime() + '/',
                    function(data){
                       //$("#pop_background").remove(); //only none-pop window use this!!!!
                       //$("#pop_frame").remove();
                       a.after('<div class="event_class">'+data+'</div>');
                       a.remove();
                    });
            return false;
        });
        */
    
});


//pop general skill description
function pop_skills(skill_id){
    if(skill_id != 0) {
        $.openWindow({"loadUrl":"/ingame_help/general_skill/" + skill_id + "/","title":"武将技能"});
    }
}

//pop general skill description
function pop_skills_book(item_id){
    if(item_id != 0) {
        $.openWindow({"loadUrl":"/ingame_help/skill_book/" + item_id + "/","title":"武将技能书"});
    }
}

//toggle building level
var ib = 0;
function toggle_bl(a) {
var s = document.getElementById('bld_pic').style;
if (ib==1) {
    ib = 0;
    s.display = '';
    a.src="/site_media/img/no_show.gif";
}
else {s.display = 'none';ib=1;a.src="/site_media/img/show.gif";}
}

function anti_addicted_pop(timeout, pop_words) {
    $.openWindow({"content":pop_words,"title":"防沉迷系统温馨提示"});
    setTimeout('anti_addicted_pop(' + timeout + ',"' + pop_words + '")',timeout*1000);
}

function anti_addicted_pop_start(total_online_seconds) {
    //alert( 44 < total_online_seconds <= 3 * 3600);
    online_hour = parseInt(total_online_seconds / 3600);
    will_pop = 0;
    if (total_online_seconds <= 3 * 3600) {
        pop_words = '您累计在线时间已满' + (online_hour+1) + '小时。'
        pop_time = total_online_seconds % 3600
        if (pop_time == 0) { //整点，弹出
            if (online_hour == 3) {
                pop_words = '您累计在线时间已满3小时，已进入不健康游戏时间，请您暂离游戏进行适当的休息和运动，合理安排您的游戏时间，点击<a href="/logout/">确定</a>退出游戏';
            }
            else {
                pop_words = '您累计在线时间已满' + (online_hour) + '小时。'
            }
            will_pop = 1;
        }
    }
    
    else if (3 * 3600 < total_online_seconds < 5 * 3600) {
        pop_words = '您已经进入疲劳游戏时间，您的游戏收益将降为正常值的50％，请您尽快下线休息，做适当身体活动。'
        pop_time = total_online_seconds % 1800
        //alert(online_hour);
        if (pop_time == 0) { //整半点，弹出
            if (online_hour == 5) {
                pop_words = '您已进入不健康游戏时间，请您立即下线休息。如不下线，您的身体健康将受到损害，您的收益已降为零。';
                window.location.href = '/logout/';
            }
            will_pop = 1;
        }
    }
    
    else {
        pop_words = '您已进入不健康游戏时间，请您立即下线休息。如不下线，您的身体健康将受到损害，您的收益已降为零。'
        pop_time = total_online_seconds % 900
        if (pop_time == 0) { //整刻钟。。。，弹出
            will_pop = 1;
        }
        
    }
    if (will_pop) $.openWindow({"content":pop_words,"title":"防沉迷系统温馨提示"});
    total_online_seconds = total_online_seconds + 1;
    setTimeout('anti_addicted_pop_start(' + total_online_seconds + ')',1000);
}

function anti_addicted_pop_start_old(timeout, status_code,total_online_seconds) {
    //timeout = 5;
    if (status_code == 1) {
        online_hour = parseInt(total_online_seconds / 3600);
        if (online_hour == 3) {
            $.openWindow({"content":'您累计在线时间已满3小时，已进入不健康游戏时间，请您暂离游戏进行适当的休息和运动，合理安排您的游戏时间，点击<a href="/logout/">确定</a>退出游戏',"title":"防沉迷系统温馨提示"});
        }
        else {
            //alert(online_hour);
            pop_words = '您累计在线时间已满' + online_hour + '小时。'
        }
    }
    else if (status_code == 2) {
        pop_words = '您已经进入疲劳游戏时间，您的游戏收益将降为正常值的50％，请您尽快下线休息，做适当身体活动。'
    }
    else {
        pop_words = '您已进入不健康游戏时间，请您立即下线休息。如不下线，您的身体健康将受到损害，您的收益已降为零。'
    }
    setTimeout('anti_addicted_pop(' + timeout + ',"' + pop_words + '")',timeout*1000);
}

function show_online_time(time_online){  //防沉迷系统在线时间显示
    new_rt = parseInt(time_online);
    chenmi_time_id=document.getElementById('chenmi_time');
    chenmi_time_id.innerHTML = time_format(new_rt);
    //alert(time_online);
    time_new = new_rt + 1;
    setTimeout("show_online_time('" + time_new + "')",1000)
}

