/* $Id: share.js 4775 2007-03-12 06:54:34Z Aether $ */

var urlStr = window.location.pathname;
if(urlStr.substr(urlStr.length-1,1) == "/"){
	urlStr = urlStr + "index.htm";
}

function checkTime()
{
		$.get('/makehtml/makern.asp',{urlStr:urlStr},function(data){
		if (data == 1){
			$.get('/makehtml/makelink.asp',{urlStr:urlStr},function(data){
				if (data != ''){
					//window.status="正在更新您所查看的页面，请稍候...";
					$.get('/makehtml/make.asp',{pageFlag:data,pageName:urlStr,action:'make'},function(data){});
					//$("#all").show();
				}
				else{
					location.herf = "/";
				}
			});
		}
	});
}

function makestatic(){
	$.get('/makehtml/makelink.asp',{urlStr:urlStr},function(data){
		if (data != ''){
			dynPage = data;
			window.status="正在生成您所查看的页面，请稍候...";
			$.get('/makehtml/make.asp',{pageFlag:data,pageName:urlStr,action:'make'},function(data){
				if (data != ''){
					location.reload();
				}
				else{
					$("#mmm").show();
					document.all.mmm.src = "/moudles" + dynPage;
				}
			});
		}
		else{
			$("#mmm").show();
			document.all.mmm.src = "/404/info.htm";
		}
	});
}

function hackCSS(){try{
	var s='<link rel="stylesheet" type="text/css" href="/static/lexrus/styles/';
	with(document)if($.browser.safari){
		write(s+'_safari.css"/>');
		$(function(){
			$('.nav_searchInput:first').after('<input type="search" placeholder="搜索" autosave="starokok.com" results="7" name="kw" style="margin:6px"/>').remove();
			$('.search_submit:first').remove();
		});
		$.fn.fadeIn = $.fn.show;
	}else if($.browser.mozilla){
		write(s+'_mozilla.css"/>');
	}else if($.browser.opera){
		write(s+'_opera.css"/>');
	}
}catch(e){}
}
hackCSS();

function redirectSignIn(){
    var _i='';
    if(typeof uid!='undefined')
        _i='userid='+(uid|0)+'&';
	if(typeof loginURL=='undefined')
		setTimeout(function(){location.href='/passport/'},100);
	else
		setTimeout(function(){location.href=loginURL},100);
	return false;
}

//Schema
var porgramInList=['id','title','pubDate','duration','views','comments','pic','deny_download','ownerName'];

//CacheFactory
var setFactoty = function() {
	var o={},a=arguments;
	var s=a[0];
	for(var i=1;i<=s.length;i++){
		o[s[i-1]]=a[i];
	}
	return o;
}
var _f = setFactoty;

//initHoverArea
function inithoverText() {
	$("input[@type='text'], input[@type='password'], textarea").addClass("input").focus(function(){
		$(this).addClass("text_focus")
	}).blur(function(){
		$(this).removeClass("text_focus")
	});
}

//Tool kits
function copyText(id) {
	try{
		var targetText = document.getElementById(id);
		targetText.focus();
		targetText.select();
		var clipeText = targetText.createTextRange();
		clipeText.execCommand("Copy");
	}catch(e){}
}
function reloadPage(){
	location.reload();
}

//Extended Javascript
String.prototype.trim = function() { 
	return this.replace(/(^\s*)|(\s*$)/g, ""); 
}
var _st = window.setTimeout;
window.setTimeout = function(fRef, mDelay) {
	if(typeof fRef == 'function'){
		var argu = Array.prototype.slice.call(arguments,2);
		var f = (function(){ fRef.apply(null, argu); });
		return _st(f, mDelay);
	}
	return _st(fRef,mDelay);
}
Array.prototype.unique=function(){
	var a={},b=[];
	for(var i=0;i<this.length;i++)
		a[this[i]]=this[i];
	for(var c in a)
		b[b.length]=a[c];
	return b;
}

//Extended jQuery
$.fn.cleanSpaces=function(){
	this.each(function(){
		$(this).html(String(""+$(this).html()).replace(/[\t ]/g,''));
	});
	return this;
}

$.fn.hideDetail=function(n){
    this.each(function(){
        var o=$(this);
        var s=o.html().trim();
        var m=(Math.random()*10000)|0;
        if(s.length>n){
            o.html(
                '<div id="summary'+m+'">'+o.text().trim().substr(0,n)+((o.text().trim()+'').length>n?'... <a href="javascript://" onclick="$(\'#detail'+m+'\').show();$(this).parent().hide()">全部</a>':'')+'</div>'+
                '<div id="detail'+m+'" style="display:none">'+s+'<a href="javascript://" onclick="$(\'#summary'+m+'\').show();$(this).parent().hide()">隐藏</a></div>');
        }
    });
    return this;
}

$.fn.hoverClass = function(c) {
	this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
	return this;
}

$.fn.border = function(prefix)
{
	var classNames = [
		'north',
		'east',
		'south',
		'west', 
		'northeast', 
		'southeast', 
		'southwest', 
		'northwest'];
	
	this.each(
		function()
		{
			var borderElement = null;
			var currentElement;
			var firstElement;
			var nodeList = this.childNodes;
			var nodeArray = new Array();
							
			for (var index = classNames.length - 1, className; className = classNames[index]; index--) 
			{				
				if (prefix != null)
				{ 
					className = prefix + className;
				}
				
				borderElement = document.createElement('div');
				$(borderElement).addClass(className).css({display: 'block'});
				
				if (!firstElement) firstElement = currentElement;
				
				if (currentElement) borderElement.appendChild(currentElement);
				currentElement = borderElement;
			}
			
			this.parentNode.insertBefore(currentElement, this);			
			firstElement.appendChild(this);
			
			/* IE Hack:
			 *     IE collapses the bottom and top margins
			 *     rendering the next sibbling partially
			 *     inside of the previous sibbling element.
			 */
			
			/*@cc_on
			$(currentElement).css({zoom: '1'});
			@*/
		}
	);
		
	return this;
};

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) {
            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.toGMTString(); // use expires attribute, max-age is not supported by IE
        }
        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;
    }
};

$.fn.tudouDig=function(){
	this.each(function(o){
		var _0=$(this);
		if (_0.id()!="")
		{
			_0.html('<a href="/passport/"><strong>'+(_0.html()|0)+'</strong><span>我顶</span></a>').addClass('digBtn');
		}else{
			_0.html('<strong>'+(_0.html()|0)+'</strong><span>顶过了</span>').addClass('digBtn').addClass("diged").fadeIn(500);
			if(typeof iid!='undefined') $(".shareButton").fadeIn();
		}
		_0.find('a').click(function(){
			if((typeof isGuest!='undefined' && isGuest) || (typeof uid!='undefined' && uid<=0)){
				return confirm('你还没登录呢，是否现在登录？')
			}else{
				var _1=$(this).parent();
				var _id=_1.id().substr(3)|0;
				if(_id<=0)_id=iid;
				if(_id>0)
				if(typeof digupPortal!='undefined')
					$.get(digupPortal,{itemID:_id,iid:_id,action:'w'});
				else
					$.get('/util/ajax/wm_ops.asp',{itemID:_id,iid:_id,action:'w'});
				_1.html($(this).html()).find('span').html('顶过了').parent().addClass("diged").fadeIn(500);
				var _2=_1.find('strong');
				_2.html((_2.html()|0)+1);
				if(typeof iid!='undefined') $(".shareButton").fadeIn();
				return false;
			}
		});
	});
	return this;
}

Array.prototype.unique=function(){
	var a={},b=[];
	for(var i=0;i<this.length;i++)
		a[this[i]]=this[i];
	for(var c in a)
		b[b.length]=a[c];
	return b;
}

//*/ by lex
function markAsPlayed(id){
	var n='playedClips';
	id=id|0;
	if(id<=0)return false;
	var c=($.cookie(n)==null)?'':$.cookie(n);
	var l='';
	if(typeof lid!='undefined' && typeof iid!='undefined'){
		id=iid|0;
		if(id<=0 || lid<=0)return false;
		l='/'+lid.toString(36);
		var r=new RegExp("\\d+/"+lid.toString(36),'g');
		var _m=c.match(r);
		if(_m!=null && _m.length>=5){
			c=c.split('').reverse().join('');
			r=new RegExp("(,?\\d+/"+lid.toString(36)+'|\\d+/"'+lid.toString(36)+',?)');
			c=c.replace(r,'');
			c=c.split('').reverse().join('');
		}
	}
	var p=c.split(',') || c;
	if(p.length>0){
		p.reverse().push((id).toString(36)+l);
		p.reverse();
		if(p[0]==null)p.shift(0);
		p=p.unique();
	}else if(!p.length){
		p=(id).toString(36)+l
	}else{
		p=(id).toString(36)+l+','+p;
	}
	if(p.length>=40){
		p.pop();
	}
	$.cookie(n,p.toString().replace(/,$/,''),{expires:7,domain:'starokok.com',path:'/'});
}
//*/

function markAsPlayedList(id){try{
    markAsPlayed(id,1);
}catch(e){}}

function juid(){
	return (new Date().getTime()*10000+Math.random(1)*10000).toString(32).substr(0,11);
}

var juidStr=juid();
if($.cookie('juid')==null || $.cookie('juid')==''){
	$.cookie('juid',juidStr,{expires:365*100,domain:'starokok.com',path:'/'});
}else{
    juidStr=$.cookie('juid');
}

function toggleQuick(code,obj){
	var quick = $.cookie("quickListClips");
	var na=$("#quickNum");
	var n = na.html()|0;

	if (quick==null) {
		$.cookie('quickListClips',code+',',{domain:'starokok.com',path:'/'});
		na.html(n+1)
	}else{
		var index = quick.indexOf(code);
		if (index>=0) {
			//remove
			if (obj!=null)
			{
				$.cookie('quickListClips',quick.replace(code+',',""),{domain:'starokok.com',path:'/'});
				na.html(n-1);
				if($(".saveListAs").rel()==1) {
					obj.parent().parent().parent().remove();
				}
			}else{
				setTimeout(playQuick,100)
				return false;
			}
		}else{
			if (n>=40) {
				if (confirm("你只能在便利点播单中暂存40个节目，你可以删除一些，然后再继续添加。\n想去便利点播单删除一些节目吗？")) {
					setTimeout(function(){location.href="/moudles/playlist/history.asp?method=getqui"},100);
				}
				return false;
			}else{
				//add
				$.cookie('quickListClips',quick+code+',',{domain:'starokok.com',path:'/'});
				na.html(n+1)
			}
		}
	}
	return true;
	function playQuick(){
		location="/moudles/playlist/playQuicklist.asp";
	}
}

function initQuick(){
try{
	var quick = $.cookie("quickListClips");
	if (quick==null) {
		var n=0;
		quick="";
	}else {
		var n = quick.length/12;
	}
	$("#quickNum").html(n);

	$(".pack_clipImg").parent().wrap("<div></div>").parent().prepend("<div class='quickBtn'><a href='javascript://' title='添加到便利点播单'></a></div>").addClass("quickList");
	$(".pack_clipImg").hover(
		function(){ $(this).parent().prev().addClass("quickBtnAhover") },
		function(){ $(this).parent().prev().removeClass("quickBtnAhover") }
	)
	$(".quickBtn a").each(function(){
		var code=$(this).parent().next("a").href().replace(".htm","/").replace(/.*\/([^\/]+)\/.*/g,"$1").replace("view-","");
		var index = quick.indexOf(code);
		if (index >=0)
			$(this).title("播放便利点播单").parent().toggleClass("quickAdded");
		$(this).click(function(){
			if (toggleQuick(code,null)) {
				$(this).title("播放便利点播单").parent().toggleClass("quickAdded");
			}
		})
	})
}catch(e){}
}

function initLogin(){
try{
	var uid = $.cookie("uid");
	if (uid!=null) {
		$("#login_info").html(
			'你好，<a href="/home/'+$.cookie("user")+'/">'+$.cookie("nick")+'</a> | '+
			'<a href="/my/messages/" id="msg_num">短信箱</a> | '+
			'<a href="/passport/logout_passport.asp">退出</a>'
		);
		$("#inner").html(
			'<div class="caption fix"><span><a href="/my/messages/" class="newmsg" id="newmsg">你有新短信(0)</a></span><h2 class="logind">你好，'+$.cookie("nick")+'</h2></div>'+
			'<div class="dashboard fix"><div class="director"><a href="/passport/logout_passport.asp"><img src="/static/lexrus/images/index/logout.gif" style="float:right;margin:5px 10px 0 0;" /></a></div>'+
			'<a href="/my/setting/"><img src="'+$.cookie("avator")+'" class="pack_userImg"/></a>'+
			'<ul><li>收视数：<span id="lib_program_views_count">-</span></li><li>被订阅：<span id="lib_subscribers_count">-</span></li><li>主页被浏览：<span id="lib_views_count">-</span></li></ul></div>'+
			'<div class="more"><a href="/my/setting/info.asp">修改个人信息</a></div>'
		);
		$.getJSON('/moudles/home/index_counts.asp', { user_id: uid }, function($json) {
			$('#lib_program_views_count').html($json.homepage_program_views_count);
			$('#lib_subscribers_count').html($json.homepage_subscribers_count);
			$('#lib_views_count').html($json.homepage_views_count);
		});
		initMsg();
		isGuest = false;
	}
	else {
		isGuest = true;
	}
}catch(e){}
}

function initMsg() {
	var uid = $.cookie("uid");
	if (uid)
	{
		$.get("/util/uusmc.asp?user_id="+uid,function(e){
			if (e > 0) {
				$("#msg_num").html(e+"条新短信");
				$("#newmsg").html("你有新短信("+e+")");
			}
		})
	}
}

//Navigation&Global
$(function(){
	try{
		initLogin();
		inithoverText();
		/*$(".search_submit").mouseover(function(){
			$(this).src("/static/lexrus/styles_images/global/search_hover.png")
		}).mouseout(function(){
			$(this).src("/static/lexrus/styles_images/global/search_normal.png")
		});*/

		setTimeout(initQuick,200);
		$(".nav_tabs li").hoverClass("nav_tabs_lihover");  //fixd IE6

	}catch(e){}
})

var ReSizeImg=function(ImgW){
	var Allimg=document.getElementsByTagName("img");
	for (var i in Allimg) {
		DrawImage(Allimg[i],ImgW);
	}
}
var DrawImage= function(ImgD,ImgW){ 
	var image=new Image(); 
	image.src=ImgD.src;
	if(image.width>0 && image.height>0){ 
		flag=true;
		if(image.width>=ImgW){ 
			ImgD.width=ImgW; 
			ImgD.height=(image.height*ImgW)/image.width; 
		}else{ 
			ImgD.width=image.width; 
			ImgD.height=image.height; 
		}
	}
}