/* common javascript */

function confirm_del() {
	return confirm('您确认删除吗？');
}

/*判断浏览器类型*/
var Browser_Name=navigator.appName;
var is_IE=(Browser_Name == "Microsoft Internet Explorer");//判读是否为ie浏览器
var is_NN=(Browser_Name == "Netscape");//判断是否为netscape浏览器
var is_op=(Browser_Name == "Opera");//判断是否为Opera浏览器

//thickbox on click
function tb_click(th) {
	var t = th.title || th.name || null;
	var a = th.href || th.alt;
	var g = th.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
}

//loading
function loading() {
	var object = $('#f_loading');
	var width = $('body').width();
	var left = (width/2) - 85;
	$(object).css('left', left);
	$(object).show();
	return false;
}

function loading_position() {
	var object = $('#f_loading');
	var offsetTop = 160 + $(window).scrollTop() + 'px';
	$(object).animate({top : offsetTop },{ duration:500 , queue:false });
}

function unloading() {
	$('#f_loading').hide();
}

$(function() {
	autoTheme();
	$('#head_nav a').click(function(){
		loading();
	});
	$('#topnav a').click(function(){
		loading();
	});
	$('.leftbox a').click(function(){
		loading();
	});
	$('.step1 a').click(function(){
		loading();
	});
	$('.step1_son a').click(function(){
		loading();
	});
	$('.step2 a').click(function(){
		loading();
	});
	$('.step3 a').click(function(){
		loading();
	});
})

//加载报表信息列表等
function load_report(objid, url, getdata) {
	var object = $('#'+objid);
	object.html('<div class="loading"> <img align="absmiddle" src="/static/images/loader.gif" border="0" /> 正在加载... </div>');
	object.load(url, getdata);
}

//加载flash图片
function load_flash(objid, url, width, height, post_data) {
	$('#P_'+objid).html('<div id="'+objid+'"><div class="loading"> <img align="absmiddle" src="/static/images/loader.gif" border="0" /> 正在加载... </div></div>');
	var object = $('#'+objid);

	$.post(url, post_data, function(data){
		if (data == 'err') {

		}else {
			object.html('');
			swfobject.embedSWF("/static/swf/open-flash-chart.swf", objid, width, height, "9.0.0", "expressInstall.swf",
				{"data-file":data+"?code="+Math.random(),"loading":"数据加载中,请稍后..."},{'wmode':'transparent','menu':'false'}
			);
			if(!is_IE){
				object.append( '<param name="movie" value="" />' );
				object.append( '<param name="wmode" value="transparent" />' );
			}
		}
	});
}

/* tab */
function setTab(name,cursel,n) {
	for(i=1; i<=n; i++) {
		var menu = document.getElementById(name+i);
		var con = document.getElementById("con_"+name+"_"+i);
		menu.className = i==cursel ? "hover" : "";
		con.style.display = i==cursel ? "block" : "none";
	}
}

/* show export */
function show_export(objid) {
	if($('#'+objid).css('display') == 'none') {
		$('#'+objid).show();
	}else {
		$('#'+objid).hide();
	}
}

//读写cookie函数
function GetCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end   = document.cookie.indexOf(";",c_start);
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return null
}

function SetCookie(c_name,value,expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" +escape(value) + ';path=/' +((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()); //使设置的有效时间正确。增加toGMTString()
}

/* 设置模板样式 */
function setTheme(name) {
	var theme = GetCookie('MyUnoticeTheme');
	var cssUrl = '/static/css/style_'+name+'.css';
	if(theme != null) {
		$('#setTheme_'+theme).attr('class', 'skin_'+theme);
	}else {
		$('#setTheme_blue').attr('class', 'skin_blue');
	}
	$('#setTheme_'+name).attr('class', 'skin_'+name+'_selected');
	SetCookie('MyUnoticeTheme', name, 365);

	$('#themeCSS').attr('href', cssUrl);
}

/* 自动调用样式 */
function autoTheme() {
	var theme = GetCookie('MyUnoticeTheme');
	if(theme != null) {
		var cssUrl = '/static/css/style_'+theme+'.css';
		$('#setTheme_'+theme).attr('class', 'skin_'+theme+'_selected');
	}else {
		$('#setTheme_blue').attr('class', 'skin_blue_selected');
		var cssUrl = '/static/css/style_blue.css';
	}

	$('#themeCSS').attr('href', cssUrl);
}

/* 检测是否有数据 */
var checkDialog =  '';
function check_status(model, num, total) {
	var post_url = site_url('client/home/check_status');
	$.ajax({
		type: "POST",
		url: post_url,
		data: {m:model, n:num, t:total},
		dataType: 'json',
		success: function(res) {
			if(res.stat == 'ok') {
				if (typeof(checkDialog) == 'object') {
					checkDialog.close();
				}
				checkDialog = false;

				//加载数据
				doLoadData();

				clearInterval(checkInterval);
				return true;
			}else {
				//alert(typeof(checkDialog));
				var content = '<div style="line-height:30px;font-size:14px;font-weight:bold;"><img src="/static/images/progress.gif" align="absmiddle" />&nbsp;数据分析中，已完成 '+res.data.progress+' %<br />预计结束时间'+res.data.end_time+'<br />请耐心等待....</div>';
				if (typeof(checkDialog) == 'object') {
					$('#checkDialogcontent').html(content);
				}else {
					checkDialog = art.dialog({
						id: 'checkDialog',
						content: content,
						skin: 'aero',
						title: false,
						width: 400,
						lock: false,
						esc: false,
						fixed: true
					});
					//clearInterval(checkInterval);

					doWaiting();
				}
				return false;
			}
		}
	});
}

//切换绑定的微博账号
function doActiveAccount(bind_id) {
	$.ajax({
		type: "POST",
		url: site_url('client/bind/do_active'),
		data: {bid:bind_id},
		dataType: 'json',
		success: function(res) {
			window.location = window.location;
		}
	});
}

//选中文本中指定部分
var set_caret_position = function(obj, start, end){
	if(document.selection) {
		if(obj.tagName == 'TEXTAREA'){
			var i = obj.value.indexOf("\r", 0);
			while(i != -1 && i < end) {
				end--;
				if(i < start) {
					start--;
				}
				i = obj.value.indexOf("\r",i+1);
			}
		}
		var range = obj.createTextRange();
		range.collapse(true);
		range.moveStart('character', start);
		if(end != undefined) {
			range.moveEnd('character', end-start);
		}
		range.select();
	}else {
		obj.selectionStart = start;
		var sel_end = end == undefined ? start : end;
		obj.selectionEnd = Math.min(sel_end, obj.value.length);
		obj.focus();
	}
};


/**
 * UI工具集合
 * @author tangwenming
 */
var UI = {
	DEFAULTS: {
		modal: true,
		unloadOnHide: true,
		closeText: '关闭',
		fixed: false,
		afterShow: function(){
			UI.unloading();
		}
	},
	NOTIFY_DEFAULTS: {
		type: 'success',
		sticky: false,
		position: 'middle-center',
		stayTime : 2000
	},
	confirm: function(msg, callback) {
		Boxy.confirm(msg, callback, {title: '信息'});
	},
	alert: function(msg, callback){
		Boxy.alert(msg, callback, {title: '信息'});
	},
	prompt: function(msg, callback){
		var input = window.prompt(msg);
		if (callback) callback(input);
	},
	load: function(url, options){
		this.options = jQuery.extend({}, UI.DEFAULTS, options || {});
		Boxy.load(url, this.options);
	},
	dialog: function(object, options) {
		this.options = jQuery.extend({}, UI.DEFAULTS, options || {});
		new Boxy($(object).html(), this.options);
	},
	loading: function() {
		 $.blockUI({ message: '<h2><img src="/static/images/loading.gif" /> Loading...</h2>', css: { border: 'none', padding: '15px', backgroundColor: '#000', opacity: .5, color: '#fff'}, overlayCSS :{opacity: 0, cursor: 'default'}});
	},
	title: function(target) {
		$(target).tipsy({gravity: 's'})
	},
	unloading: function() {
		$.unblockUI();
	},
	scrollTo: function(target){
		$.scrollTo(target, 1000);
	},
	hide: function(object) {
		Boxy.get(object).hide();
	},
	notify: function(msg, type, timeout) {
		timeout = 5000;
		this.options = jQuery.extend({}, UI.NOTIFY_DEFAULTS, {text: msg, type: type, stayTime: timeout} || {});
		$().toastmessage('showToast', this.options);
	},
	retwitt: function(status_id) {
		UI.loading();
		UI.load('/client/util/retwitt?status_id=' + status_id, {title: '转发微博'});
	}
};

// 初始信息
$(function(){
	$('.comments .new textarea').live('click', function(){
		$(this).autoGrow();
	});
	$('input:checkbox').checkbox({empty: '/static/images/empty.png',cls:'jquery-safari-checkbox'});
	$('input[data-value]').each(function () {
		$(this).watermark($(this).attr('data-value'), {className: 'watermark', useNative: false});
	});

	$('#do_post').click(function(){
		UI.loading();
		UI.load('/client/util/post', {title: '发布微博'});
		//$.fancybox({type: 'ajax', href: '/client/util/post'});
	});

	UI.title($('[title]'));
})

function reply(msg,status_id) {
	$('#comm_'+status_id).val(msg).focus();
}

// @copyright by twm, don't copy!
var show_id = 0;
var e;

$(function(){
	function hide_card(){show_id = 0;$('body .mbox').remove();}
	function hide_ecard(){show_id = 0;$('body .embox').hide();}
	function hide_scard(){show_id = 0;$('body .smbox').remove();}
	
	$('a[data-id]').mouseover(function(){
		clearTimeout(e);
		var id     = $(this).attr('data-id');
		var offset = $(this).find('img').offset();
		var cwidth = $(this).find('img').attr('width');

		if (id == show_id) return;
		show_id = id;
		$('body .mbox').remove();
		$.get('/client/card', {id: id}, function(data){
			$('body').append(data);
			$('.mbox').css({left: offset.left-(cwidth/2-15), top: offset.top-145}).show();
		});
	}).mouseout(function(){e = setTimeout(hide_card, 1500);});
	
	$('em[events-id]').click(function(){
		clearTimeout(e);
		var id     = $(this).attr('events-id');
		var offset = $(this).find('a').offset();
		var ids = id.split("#");
		if($('.embox').css('display')=="none"){
			$('.embox').css({left: offset.left, top: offset.top-85}).show();
		}else if($('.embox').css('display')=="block"){
			$('body .embox').hide();
			$('.embox').css({left: offset.left, top: offset.top-85}).show();
		}else{
			$.get('/client/event_card', {user_id: ids[0],event_id: ids[1]}, function(data){
				$('body').append(data);
				$('.embox').css({left: offset.left, top: offset.top-85}).show();
			});
		}
	});
	
	$('em[side-id]').click(function(){
		clearTimeout(e);
		var id     = $(this).attr('side-id');
		var offset = $(this).find('a').offset();
		var ids = id.split("#");
		if($('.smbox').css('display')=="block"){
			hide_scard();
		}else{
			$.get('/client/side_card', {status_id: ids[0],side_id: ids[1]}, function(data){
				$('body').append(data);
				$('.smbox').css({left: offset.left, top: offset.top-85}).show();
			});
		}
	});
	
	$('.mbox .close').live('click', function(){hide_card();});
	$('.embox .eclose').live('click', function(){hide_ecard();});
	$('.smbox .sclose').live('click', function(){hide_scard();});
	$('.mbox').live('mouseover', function(){clearTimeout(e);}).live('mouseout', function(){e = setTimeout(hide_card, 1500);});
	$('.embox').live('mouseover', function(){clearTimeout(e);}).live('mouseout', function(){e = setTimeout(hide_ecard, 3000);});
	$('.smbox').live('mouseover', function(){clearTimeout(e);}).live('mouseout', function(){e = setTimeout(hide_scard, 3000);});
});

// 字数统计
function count_chars() {
	//var length = $('.post-box .post-textarea textarea').val().length;
	var comm_text = $('.post-box .post-textarea textarea').val();
	var alpha_len = comm_text.match(/\w|\[|\s|\]|\#|\'|\(|\)|\./g)?comm_text.match(/\w|\[|\s|\]|\#|\'|\(|\)|\./g).length:0;
	var length = comm_text.length - parseInt(alpha_len/2);
	var len = (140-length);
	if (len >=0 ) {
		$('.key-tips').removeClass('out140').html('您还可以输入<span>' + len + '</span>字');
	} else {
		var outlen = (length - 140);
		$('.key-tips').addClass('out140').html('已超出<span>' + outlen + '</span>字');
	}
}
// 发微博
$(function() {
	var options = {
		url: site_url('client/util/do_post'),
		dataType: 'json',
		beforeSubmit: function(){
			$('.post-box .share-btn').unbind('click').addClass('share-btn-disable');
		},
		success: function(responseText, statusText, xhr, $form) {
			if (responseText.stat == 'ok') {
				Boxy.get('.share-btn').hide();
				UI.notify(responseText.data, 'success');
			} else {
				//UI.alert(responseText.data, {title:'信息提醒'});
				UI.notify(responseText.data, 'error');
				$('.post-box .share-btn').removeClass('share-btn-disable');
			}
		}
	};

	$('.post-box .share-btn').live('click', function(){
		var textarea = $('.post-box .post-textarea textarea');
		//var length = $(textarea).val().length;
		var comm_text = $(textarea).val();
		var alpha_len = comm_text.match(/\w|\[|\s|\]|\#|\'|\(|\)|\./g)?comm_text.match(/\w|\[|\s|\]|\#|\'|\(|\)|\./g).length:0;
		var length = comm_text.length - parseInt(alpha_len/2);
		var bind_ids = $('#up_bids').val();
		if (length < 1) {
			//$(textarea).focus();
			UI.alert('请输入微博内容', function(){$(textarea).focus();});
		} else if (length > 140) {
			UI.alert('超出140个字数限制', function(){$(textarea).focus();});
		} else if (bind_ids == '' || bind_ids == ',') {
			UI.alert('请至少选择一个要发布微博的账号', function(){$(textarea).focus();});
		}else {
			$('#post-form').ajaxSubmit(options);
			$('#is_do_update').show();
			$(this).hide();
		}
	});
	//立即发送
	$('.post-box #post-nor-input').live('click', function(){
		//Boxy.get(this).tween(580, 280);
		$('.post-box .datetime').fadeOut();
	});

	//定时发送
	$('.post-box #post-sch-input').live('click', function(){
		//Boxy.get(this).tween(580, 330);
		$('.boxy-wrapper').animate({height: 330});
		$('.post-box .datetime').fadeIn();
	});

	//账号选择
	$('#post-profile-wrapper li img').live('click', function(){
		//alert($(this).attr('bind-id'));
		var bid = $(this).attr('bind-id');
		var check_bids = $('#up_bids').val();
		var parent_obj = $(this).parent();
		var parent_title = parent_obj.attr('title')
		var reg = new RegExp(bid+',', "g");
		if(parent_obj.attr('class') == 'checked') {
			parent_obj.attr('class', '');
			parent_obj.attr('title', parent_title.replace(/取消/g, '同时'));
			check_bids = check_bids.replace(reg, '');
		}else {
			parent_obj.attr('class', 'checked');
			parent_obj.attr('title', parent_title.replace(/同时/g, '取消'));
			check_bids += bid+',';
		}
		$('#up_bids').val(check_bids);
	});

	//话题
	$("#post-topic").live('click', function() {
		var tmp_content = $('#status_textarea').val();
		var start_pos = tmp_content.length+1;
		var end_pos = start_pos + 5;
		$('#status_textarea').val(tmp_content+'#自定义话题#');
		set_caret_position(document.getElementById('status_textarea'), start_pos, end_pos);
	});
	//表情
	$("#post-face").live('click', function() {
		var offset = $(this).offset();
		if ($("#insert_face_div").is(':visible') == true) {
			$("#insert_face_div").hide();
		}else {
			$("#insert_face_div").css('left', offset.left).css('top', offset.top+25).show();
		}
	});
	$("#insert_face_div li").click(function() {
		var tmp_content = $('#status_textarea').val();
		var face = $(this).attr('title');
		if(face == '') {
			face = $(this).attr('original-title');
		}
		$('#status_textarea').val(tmp_content+'['+face+']');
		$("#insert_face_div").hide();
		count_chars();
	});

	//图片
	$('#insert_picture').live('click', function() {
		$("#up_upload").toggle();
	});
	$("#up_picture").live('change', function() {
		doUpload();
		return false;
	});
});

// 发表评论
function post_comment(status_id) {
    var comment = $("#comms_"+status_id).val();
        if (!comment) {
            $("#comms_"+status_id).focus();
            return false;
        }else {
            $.ajax({
                type: "POST",
                url: site_url('client/opinion/post_comment'),
                data: {status_id:status_id, comment:encodeURI(comment)},
                dataType: 'json',
                success: function(res) {
                    if(res.stat == 'ok') {
                        $("#comms_"+status_id).val('');
                        $("#list_"+status_id).prepend(res.data);
                    }
                }
            });
        }
}

// 切换微博账号
function changeWeibo(bid) {
	UI.loading();
	$.post('/client/bind/do_active', {bid: bid}, function(d) {
		if (d.stat = 'ok') {
			window.location.reload();
		}
	}, 'json');
}
/* 微博营销 - 微博发送 - 上传图片等start */
function doUpload() {
	$('#upload-status').show();
	$('.upload').hide();
	$('#uploadPicture').ajaxSubmit({
		url: site_url('client/tools/pic_upload'),
		dataType: 'json',
		success: function(json) {
			if (json.stat == 'ok') {
				$('#uploadpic').val(json.data.image);
				$('#upload-status').hide();
				$('#is_upload').html('已上传').show();
				$('#preview_picture').html('<img id="up_img_file" style="cursor:pointer;" title="点击删除此图片" onclick="deleteUploadPicture();" width="200" src="'+json.data.image+'" /> <a href="javascript:void(0);" onclick="deleteUploadPicture();">删除图片</a>').show();
			} else {
				alert(json.data);
				deleteUploadPicture();
			}

		}
	});
}

function deleteUploadPicture() {
	$('#upload-status').hide();
	$('.upload').show();
	$('#up_picture').val('');
	$('#uploadpic').val('');
	$('#preview_picture').html('').hide();
	$('#is_upload').html('').hide();
}
/* 微博营销 - 微博发送 - 上传图片等end */
