// JavaScript Document

var life_site_host = 'life.sina.com.cn';//保存一个host,否则很多地方都会更改host,特别是转换环境
//返回gb编码占用字节个数
String.prototype.gblen = function() {
 var len = 0;
 for (var i=0; i<this.length; i++) {
     if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {
         len += 2;
     } else {
         len ++;
     }
 }
 return len;
}

//去除前后空格
function trim(str)
{  
	return str.replace(/(^\s*)|(\s*$)/g, "").replace(/(^　*)|(　*$)/g, "");
}

function gocur(num,tab_num)
{	
	for(var i=0;i<tab_num;i++)
	{
		$('li[ty='+i+']').removeClass('cur');	
	}
	$('li[ty='+num+']').addClass('cur');
}

function changecolor(num,tab_num)
{
	for(var i=0;i<tab_num;i++)
	{
		$('li[ty='+i+']>span[class=list_icon]').removeClass('list_icon').addClass('list_icon1');		
	}
	$('li[ty='+num+']>span[class=list_icon1]').removeClass('list_icon1').addClass('list_icon');		
}
//标签变换
function goTab_life(num,tab_num,pre)
{
	for(var i=0;i<tab_num;i++)
	{
		jQuery('#'+pre+'_info'+i).css('display','none');
	}
	for(var i=0;i<tab_num;i++)
	{
		jQuery('#'+pre+'_tag'+i).removeClass();
	}
	jQuery('#'+pre+'_tag'+num).addClass('cur');
	jQuery('#'+pre+'_info'+num).css('display','block');
}

//导航弹出框
function searchOut(id)
{
	jQuery('#'+id).css('display','block');
    jQuery('#search_selected').mouseout(function(){jQuery('#'+id).trigger('mouseout');});
	jQuery('#search_selected').addClass('on');
}

function mouseOut(id)
{
	jQuery('#'+id).css('display','none');
	jQuery('#search_selected').removeClass();
}

function mouseOver(id)
{
	jQuery('#'+id).css('display','block');
	jQuery('#search_selected').addClass('on');
}

function search_selects(obj,flag)
{
	var cont = jQuery(obj).html()
	if(1==flag)
	{
		cont = '找' + cont;
	}
	jQuery('#search_selected').html(cont);
	jQuery('#search_selects').css('display','none');
	jQuery('#search_selected').removeClass();
	jQuery('#search_class').val(jQuery(obj).attr('id'));
}

function searchLocation()
{
	curUrl = window.location.toString();
	var umap	= '';
	var uwhat	= jQuery('#what').val();
	var uclass	= jQuery('#search_class').val();
 	uwhat =  trim(uwhat);
	if(!uwhat)
	{
//		alert('请输入关键词');
showMsg('错误','请输入关键词');
		return false;
	}
//	uwhat = encodeURIComponent(uwhat);
	uwhat = encodeURIComponent(encodeURIComponent(uwhat));
	if(curUrl.split('-map-')[1])
	{
//		if(curUrl.split('-map-')[1].split('--')[0])
		umap = '--map-big';
	}
	
	if(uclass=='')
	{
		uclass=0;
		var url  ='/search/class-'+uclass+'--all-1'+'--utf-1'+umap+'--?what-'+uwhat;
	}
	else
	{
		var url  ='/search/class-'+uclass+'--utf-1'+umap+'--?what-'+uwhat;
	}
	window.location = url;
}

//设为首页
function setHome()
{
	if (document.all)
	{
		document.body.style.behavior = 'url(#default#homepage)';
		document.body.setHomePage('http://' + life_site_host);
	} 
	else if (window.sidebar) 
	{
		if(window.netscape)
		{
			try
			{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
			}
			catch (e) 
			{
				alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true" ); 
			}
		}
		var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
		prefs.setCharPref('browser.startup.homepage','http://' + life_site_host);
	}
}

function isEmail(value)
{
    return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

//收藏
function addBookmark()   
{
	var title = '新浪生活';
	var url = 'http://' + life_site_host;
	var desc = '';
	if (window.sidebar) 
	{  
		window.sidebar.addPanel(title, url, desc); //Mozilla browser  
	} 
	else if( document.all ) 
	{
		window.external.AddFavorite(url, title);   //IE browser  
	} 
	else if( window.opera && window.print ) 
	{
		return true;  //Not Support Now  
	}  
} 

/*
cookie 的jquery插件使用方法
提供方便方法操作cookie :
jQuery.cookie('the_cookie'); // 获得cookie
jQuery.cookie('the_cookie', 'the_value'); // 设置cookie
jQuery.cookie('the_cookie', 'the_value', { expires: 7 }); //设置带时间的cookie
jQuery.cookie('the_cookie', '', { expires: -1 }); // 删除
jQuery.cookie('the_cookie', null); // 删除 cookie
*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 * jQuery JSON Plugin
 * version: 1.0 (2008-04-17)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris technically wrote this plugin, but it is based somewhat
 * on the JSON.org website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.  I really just cleaned it up.
 *
 * It is also based heavily on MochiKit's serializeJSON, which is 
 * copywrited 2005 by Bob Ippolito.
 */
 
(function($) {   
    function toIntegersAtLease(n) 
    // Format integers to have at least two digits.
    {    
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function(date)
    // Yes, it polutes the Date namespace, but we'll allow it here, as
    // it's damned usefull.
    {
        return this.getUTCFullYear()   + '-' +
             toIntegersAtLease(this.getUTCMonth()) + '-' +
             toIntegersAtLease(this.getUTCDate());
    };

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };
        
    $.quoteString = function(string)
    // Places quotes around a string, inteligently.
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe escape
    // sequences.
    {
        if (escapeable.test(string))
        {
            return '"' + string.replace(escapeable, function (a) 
            {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + string + '"';
    };
    
    $.toJSON = function(o, compact)
    {
        var type = typeof(o);
        
        if (type == "undefined")
            return "undefined";
        else if (type == "number" || type == "boolean")
            return o + "";
        else if (o === null)
            return "null";
        
        // Is it a string?
        if (type == "string") 
        {
            return $.quoteString(o);
        }
        
        // Does it have a .toJSON function?
        if (type == "object" && typeof o.toJSON == "function") 
            return o.toJSON(compact);
        
        // Is it an array?
        if (type != "function" && typeof(o.length) == "number") 
        {
            var ret = [];
            for (var i = 0; i < o.length; i++) {
                ret.push( $.toJSON(o[i], compact) );
            }
            if (compact)
                return "[" + ret.join(",") + "]";
            else
                return "[" + ret.join(", ") + "]";
        }
        
        // If it's a function, we have to warn somebody!
        if (type == "function") {
            throw new TypeError("Unable to convert object of type 'function' to json.");
        }
        
        // It's probably an object, then.
        var ret = [];
        for (var k in o) {
            var name;
            type = typeof(k);
            
            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys
            
            var val = $.toJSON(o[k], compact);
            if (typeof(val) != "string") {
                // skip non-serializable values
                continue;
            }
            
            if (compact)
                ret.push(name + ":" + val);
            else
                ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    };
    
    $.compactJSON = function(o)
    {
        return $.toJSON(o, true);
    };
    
    $.evalJSON = function(src)
    // Evals JSON that we know to be safe.
    {
        return eval("(" + src + ")");
    };
    
    $.secureEvalJSON = function(src)
    // Evals JSON in a way that is *more* secure.
    {
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        
        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };
})(jQuery);

/**
 * 判断当前用户是否被冻结
 */
function isFrozen()
{
    var isfrozen = jQuery.cookie('LIFE_IS_FROZEN'); // 获得cookie
    if (isfrozen == '1')
    {
        return true;
    }
    else
    {
        return false;
    }
}

function change_city(obj)
{
	jQuery.cookie('LIFE_USER_CITY_ID', jQuery(obj).attr('cityid'), {path:'/', expires:0,domain:life_site_host});
	jQuery('#city_name').html(jQuery(obj).text());
	jQuery('#city_list').css('display','none');
}

function showMsg(title,msg)
{
	var contents = '<table border="0" width="100%" cellspacing="0" cellpadding="0"><tr><td width="74%" height="37" class="font_orange2 font14">'+msg+'</td></tr><tr><td height="30" valign="top" class="font_gary2">3秒后自动关闭...</td> </tr><tr><td>&emsp;&emsp;&emsp;&emsp;&nbsp;<input type="button" id="msg_close" class="tc_bt1" value="关 闭"/></td></tr></table>';
	jQuery.fn.jmodal({'title':title,'content':contents,'autoClose':3});
	$('#msg_close').click(function(){
		jQuery.fn.hideJmodal();
	});
}
