$(function (){
	$('.del').click(del);
	$('.all').click(checked);
	$('.details').click(details);
	//country/city select linkage
	$('select[name=country_id]').change(countryChange).change();
	$('#changeloc').change(changeloc);
	$('#index').hover(function (){$('#icohome').show();}, function (){$('#icohome').hide();});
	$('.album li a').click(itemSelect);
	$('.audit').click(audit);
	//Tabs 
	$(".tabsmenu a").click(function (){
		var p = $(this).parents('.itemDiv');
		p.find('a').removeClass('currentpage');
		$(this).addClass('currentpage');
		p.find('.tabblock').hide();
		var v = $(this).attr('rel');
		p.find('.'+v).show();
		slide();
	});
	if(control=='index' && action=='index') {
		$('.changeDay').click(changeDay);
		$('.changeMonth').click(changeMonth);
	}
	
	//switch language
	$('#language').change(language);
	$('.logout').click(function (){
		$.get(ROOT+'user/logout',function (data){
			location.href = ROOT+'user/login';
		});
	});
    
	function pfoot_show(){    
  	  $('#footer_r3_c6').hide('slow'); 
	  $('#footer_r3_c6_on').show('slow'); 
	} 
	function pfoot_hide(){  
	  $("#powered_by").unbind("mouseout"); 
	  $('#footer_r3_c6_on').hide('slow');   
	  $('#footer_r3_c6').show("show");    	 	  
	  $("#powered_by").bind("mouseover", pfoot_show);   
	}; 
    
	/* slide logo footer -- todo ?? */  	 
	$("#powered_by").mouseover( function() { 
	  // $("#powered_by").unbind("mouseover");   
	  // pfoot_show(); 
	  // $("#footer_r3_c6_on").bind("mouseout", pfoot_hide); 
	}); 

});
function slide() {
	$('.slider').each(function (k, e){
		var ul = $(e).parent().find('ul');
		ul.width(getWidth(ul));
		var slideVal = ul.innerWidth() - ul.parent().outerWidth();
		if(slideVal <= 0) slideVal = 0;
		if(ul.parents('.tabblock').css('display') == 'none') return;
		if(ul.parent().attr('binde')) return ;
		ul.parent().attr('binde', 1);
		$(e).slider({
			max: slideVal,
			handle: '.handle',
			stop: function (event, ui) {
				ul.animate({'left' : ui.value * -1}, 500);
				//ul.css('left', ui.value * -1);
			},
			slide: function (event, ui) {
				ul.css('left', ui.value * -1);
			}
		});
		//$(e).slider("moveTo",1,0);
	});
}
function getWidth(e)
{
	var width = 0;
	e.find('li').each(function (k, e){
		width += $(e).width() + 26;
	});
	return width;
}
function itemSelect(){
	if(this.href != 'javascript:;') return;
	var p = $(this).parent();
	var eid = p.attr('eid');
	var cid = p.attr('cid');
	var uid = p.attr('uid');
	if(cid) var id = cid;
	else if(eid) var id = eid;
	else if(uid) var id = uid;
	var audit = p.attr('audit');
	var type = p.parent().attr('className');
	$('.itemDiv li.current').removeClass('current')
	p.addClass('current');
	$('.details').attr('itemId', id).attr('itemType', type).click();
}
function countryChange(){
	var cid = this.value;
	var city_id = $('select[name=city_id]').attr('default');
	$.get(ROOT+'city/option/'+cid+'/'+city_id, function (data){
		$('select[name=city_id]').html(data);
	});
}

//链接在表格的td中的通用删除法
function del()
{
	if(!confirm('Confirm delete?')) return false;
	var p = $(this).parent().parent();
	$.get(this.href,function (data){
		if(data==1) {
			p.remove();
		}else{
			$.tip('Delete fail', 3000);
		}
	});
	return false;
}
//approved/rejected
function audit(){
	var e = $('#content .tabblock:visible li.current');
	if(!e.length) return;
	var div = e.parents('.itemDiv');
	var eid = e.attr('eid');
	var cid = e.attr('cid');
	var uid = e.attr('uid');
	if(cid) var id = cid;
	else if(eid) var id = eid;
	else if(uid) var id = uid;
	
	var funding = e.attr('funding');
	var audit = e.attr('audit');
	var action = this.id;	//Approved or Rejected
	var type = e.parent().attr('className');
	disabled($(this));
	$.loading();
	$.get(ROOT+"?m=patron&a=audit&action="+action+'&id='+id, function(data){
		if(data.length > 20) {
			enabled($(this));
			return $.tip('Operate fail');	//error
		}
		if(action == 'setAsFeatured') {
			$.tip('Current featured event for('+data+')', 1000);
			return setTimeout("$('#dialog').dialog('close')", 1000);
		}
		if(action == 'approvedFriend' || action == 'approvedContent' || action == 'approvedEvent' || action == 'approvedUpdate') {
			audit = 1;
			$.tip('That '+type+' is approved', 2000);
			if(action == 'approvedEvent' && funding == 1) {
				e.prependTo($('#fundDiv .Pending ul'));
				$('#fundDiv .Pending, #fundDiv .Approved').attr('binde', 0);
				slide(); 
			}else{
				e.prependTo(div.find('.Approved ul'));
			}
			e.attr('audit', audit);
			return $('#dialog').dialog('close');
		}
		audit = -1;
		if(action == 'patronRejectedFund' || action == 'DiageoRejectedFund') {
			$.tip('That event funding is rejected', 2000);
			e.prependTo(div.find('.Rejected ul'));
		}else{
			$.tip('That '+type+' is rejected', 2000);
			e.prependTo(div.find('.Rejected ul'));
		}
		e.attr('audit', audit);
		$('#dialog').dialog('close');
	});
}
//select all/abnegate all
function checked()
{
	var table = $(this).parents('table');
	var checkbox = $('.tabblock:visible input[type=checkbox]');
	var c = true;
	if($(this).attr('action') == 'clear') c = false;
	checkbox.each(function (k,e){
		e.checked = c;
	});
}
//user/event/content details dialog
function details()
{
	var type = $(this).attr('itemType');
	var id = $(this).attr('itemid');
	if(!id) return;
	var url = ROOT+"?a=detail&type="+type+"&label=detail&id="+id;
	if(type == 'Assessment' && role == 'Patron') {
		//modify by jianping
		if($('#patronAudit').length){
			var pattern = /^[\d]+$/;
			if(!pattern.exec($('#patronAudit').val())) {
				$.tip('Please Enter Validate Number');
				$('#patronAudit').focus();
				return false;
			}
		}
		//end edit
		url += '&patronAudit='+$('#patronAudit').val();
	}
	if(type == 'Assessment' && role == 'Diageo') {
		if($('#DiageoAudit').length){
			var pattern = /^[\d]+$/;
			if(!pattern.exec($('#DiageoAudit').val())) {
				$.tip('Please Enter Validate Number');
				$('#DiageoAudit').focus();
				return false;
			}
		}
		url += '&DiageoAudit='+$('#DiageoAudit').val();
	}
	$.dialog({
		url: url,
		title: type+" Details",
		width: 700,
		height: 400,
		modal: true,
		overlay: {background: '#000', opacity: 0.5},
		cb: function (){
			$('.audit').click(audit);
			$('.details').click(details);
			$('.jqMsg').remove();
		}
	});
}
//change calender
function changeDay()
{
	var my = $(this);
	var city_id = /[\d]+/.exec(location.pathname);
	if(city_id) url = ROOT+"?a=getCalendar&city_id="+city_id;
	else url = ROOT+"?a=getCalendar";
	if(my.attr('day')) {
		var d = my.attr('day');
		var m = my.attr('month');
		var y = my.attr('year');
		//$.loading();
		$('#eventCalendar').load(url, {day:d, month:m, year:y});
	}else{
		if(my.attr('id') == 'arrow-left') {
			var action = 'prev';
		}else{
			var action = 'next';
		}
		var time = $('#time').val();
		$('#eventCalendar').load(url, {action:action, time:time});
	}
}
//change month for the home page
function changeMonth()
{
	var url = this.href+"&a=changeMonth";
	$('#navigation').load(url, function (){
		$('.changeMonth').click(changeMonth);
		$('.changeDay').click(changeDay);
	});
	return false;
}
//change city
function changeloc()
{
	var id = $(this).val();
	var type = $(this).find('option[value='+id+']').attr('type');
	if(type != 'city') return;
	location.href=langRoot+id;
}
$.extend({
	loading : function (){
		$.tip('<img src="'+ROOT+'res/css/images/loading.gif" alt="loading..."/>', 99999);
		//esc to close
		$(document).one('keydown', function(e){
			if (e.keyCode == 27) {
				$('.jqMsg').remove();
			}
		});
	},
	//扩展ui.dialog插件，增加prepend(前置内容),append(后置内容),url(load url),o(load此对象内容),cb选项,自适应宽高
	//依赖: jquery,jquery.core,dialog,draggable,resizable,autoSize方法,scroll方法
	dialog : function (options){
		$('#dialog').dialog('close');
		$('.ui-dialog').remove();
		//扩展参数默认值(标准参数的默认值由ui#dialog负责)
		param = $.extend({url: null, o: null, prepend: null, append: null, cb: function (){}}, options || {});
		//添加dialog容器
		if(!$('#dialog').length) $('body').append('<div id="dialog"></div>');
		//载入内容
		if(param.url) {
			$.loading();
			return $('#dialog').load(param.url, function (){
				if(param.prepend) $('#dialog').prepend(param.prepend);
				if(param.append) $('#dialog').append(param.append);
				$('#dialog').dialog(param);
				param.cb.call();
				setTimeout(autoSize, 0);
				$('.jqMsg').remove();
			});
		}else if(param.o) {
			$('#dialog').html(param.o.html());
			if(param.prepend) $('#dialog').prepend(param.prepend);
			if(param.append) $('#dialog').append(param.append);
		}
		$('#dialog').dialog(param);
		param.cb.call();
		setTimeout(autoSize, 0);
		$('.jqMsg').remove();
	},
	//扩展ui.dialog，主要用于提示文本msg=提示文本，delay=延时毫秒数 url=延时跳转的url    delay和url参数无顺序
	msg : function(msg, delay, url)
	{
		$('#dialog').dialog('close');
		$('.ui-dialog ui-draggable').remove();
		//调整参数
		if(url) {
			if(typeof delay == 'string') {
				var temp = url;
				url = delay;
				delay = temp;
			}
		}else {
			if(typeof delay == 'string') {
				url = delay;
				delay = null;
			}
		}
		
		//添加dialog
		if(!$('#dialog').length) $('body').append('<div id="dialog"><div>'+msg+'</div></div>');
		$('#dialog').dialog({
			close: function (){
				if(url) location.href=url;
			},
			modal: true,
			resizable: false
		});
		$('.ui-dialog').css('border', '1px solid #699').css('display', 'block');
		$('.ui-dialog').css('background', '#fff');
		$('.ui-dialog-titlebar').height(0);
		$('.ui-dialog-titlebar-close').hide();
		//自动调整宽高。默认为200,300
		var h = $('#dialog div').height();
		if (h < 200) $('.ui-dialog').height(h + 60);
		else $('#dialog').css('overflow', 'auto').css('margin', 5).width(290).height(160);
		//淡入淡入与延时、跳转
		$('.ui-dialog').show();
		//延时关闭或跳转
		if(delay) {
			setTimeout(function (){$('.ui-dialog').fadeOut();}, delay-500);
			setTimeout(function (){$('#dialog').dialog('close');}, delay);
			if(url) setTimeout(function (){location.href=url}, delay);
		}
	},
	//显示在窗口中间上方的提示
	tip : function(str, time, url){
		if(typeof ti != 'undefined') {
			clearInterval(ti);
		}
		if(!$('.jqMsg').length) {
			$('body').append('<div class="jqMsg" style="z-index: 1500;padding: 20px 40px;position: fixed;text-align:center;background: #fff;line-height: 20px;color: #F00;display: none;border: 1px solid #AABBCC"></div>');
		}
		if(typeof time != 'number') time = 2000;
		var pageSize = $.pageSize();
		var scroll = $.scroll();
		
		if(str.length < 5) var w = 50;
		else if(str.length < 10) var w = 100;
		else if(str.length < 50) var w = 150;
		else if(str.length < 80) var w = 200;
		else var w = 300;
		
		$('.jqMsg').width(w).html(str);
		$('.jqMsg').show();
		
		var top = (pageSize.y - $('.jqMsg').height()-40)/2;
		var left = (pageSize.x - $('.jqMsg').width() - 80)/2;
		if($.browser.ie6) {
			$('.jqMsg').css('position', 'absolute');
			top += scroll.y;
			left += scroll.x; 
		}
		$('.jqMsg').css('top', top);
		$('.jqMsg').css('left', left);
		var endTime = +new Date + time;
		ti = setInterval("timing("+endTime+")", 1000);
		if(url) {
			setTimeout("top.location.href='"+url+"'", time);
			setTimeout("location.href='"+url+"'", time);
		}
	},
	//弹出框。依赖$.pageSize方法.如果用对象对位，还依赖scroll方法 place=o 根据o对象定位
	//例子：$.box({o:$('.mainItem .itemContent'), width: 580, height: 430});	$.box({url: 'http://www.xinye.com/?m=music&a=form&s_id=34', width: 580, height: 430});
	box : function(options)
	{
		param = $.extend({width: 600,height: 400, title: '', bc:function(){}}, options || {});
		$('#jqBox').remove();
		var jqBox = '<div id="jqBox" style="overflow: auto; border: 3px solid #ab6; z-index: 100; position: fixed; width: '+param.width+'px; height: '+param.height+'px; background: #fff;"></div>';
		$('body').append(jqBox);
		if($.browser.ie6) {
			$('#overlay').css('position', 'absolute');
			$('#jqBox').css('position', 'absolute');
			$('html').css('overflow', 'hidden');
		}
		var page = $.pageSize();
		if (!param.place) {
			//覆盖层
			var overlay = '<div id="overlay" style="top: 0;left: 0;z-index: 99; width: 100%; height: 100%; background: #000; opacity: 0.5; position: fixed;FILTER: alpha(opacity=50);"></div>';
			$('body').append(overlay);
			var top = (page.y-$('#jqBox').height())/2;
			var left = (page.x-$('#jqBox').width())/2;
		}else{
			var scroll = $.scroll();
			var offset = param.place.offset();
			var top = offset.top - param.height -scroll.y -5;
			if(top < 0) {
				top += param.height+20;
				if($.browser.ie6) top += scroll.y;
			}
			var left = offset.left;
			if(left + param.width > page.x) left = offset.left - param.width;
		}
		
		$('#jqBox').css('top', top);
		$('#jqBox').css('left', left);
		$('#jqBox').html(
			'<div style="height: 20px; line-height: 20px; text-align: right; background: #efe;">'	//标题行
				+'<div style="float:left;color: #369;">&nbsp;'+param.title+'</div><a href="javascript:;" id="jqBoxClose">Close</a> Or Esc Key&nbsp;<hr/>'
			+'</div>'
			+'<div style="padding: 10px;height: '+(param.height-60)+'px;" id="jqBoxMain">' //主容器
				+'<img style="margin-left: '+(param.width/2-15)+'px; margin-top: '+(param.height/2-37)+'px;" alt="loading..." src="'+ROOT+'res/css/images/loading.gif"/>' //loading图片
			+'</div>'
		);
		$('#jqBoxClose').click(function (){
			$('#overlay').remove(); 
			$('#jqBox').remove();
			if($.browser.ie6) $('html').css('overflow-y', 'auto');
			return false;
		});
		//esc关闭,并取消默认动作
		$(document).one('keydown', function(e){
			if (e.keyCode == 27) {
				$('#jqBoxClose').click();
				return false;
			}
		});
		if(param.url != undefined){
			$('#jqBoxMain').load(param.url, param.bc);
		}
		if(param.o != undefined) {
			$('#jqBoxMain').html(param.o.html());
		}
	},
	//保存cookie.expires为秒数,secure为是否通过https连接
	setCookie : function(name, value, expires, path, domain, secure){
		if(!name) return false;
		if(name == "") return false;
		if(!expires) expires = 3600;	//默认保存一小时
		//秒数转为GMT时间
		var today = new Date();
		expires = new Date(today.getTime()+expires*1000).toGMTString();
		//组合参数串
		var 	cv = name+"="+escape(value)+";"
			+ ((expires) ? " expires="+expires+";" : "")
			+ ((path) ? "path="+path+";" : "")
			+ ((domain) ? "domain="+domain+";" : "")
			+ ((secure && secure != 0) ? "secure" : "");
		if(cv.length > 4096) return false;
		document.cookie = cv;
		return true;
	},
	//取得cookie.没有做删除cookie方法,用set空值代替吧
	getCookie : function(name){
		var cv = document.cookie.split("; ");//使用"; "分割Cookie
		var cva = [], temp;
		for(i=0; i<cv.length; i++){
			temp = cv[i].split("=");
			cva[temp[0]] = unescape(temp[1]);
		}
		if(name) return cva[name]; //输出单个或所有
		return cva;
	},
	//取url参数 例：alert($.getPara('id')); 省略第二个参数则取当前页面url
	getPara : function(para, url){
		if(!url) var url = location.href;
		var rs = new RegExp('[\&|\?]{1}'+para+'=([\\w]+)').exec(url);
		if(rs == null) return null;
		return rs[1];
	},
	//取FCK的值 参数是FCK的name
	getFckVal : function (name){
		var oEditor = FCKeditorAPI.GetInstance(name);
		return oEditor.GetXHTML(true);
	},
	pageSize : function (){
		var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){
			xScroll=window.innerWidth+window.scrollMaxX;
			yScroll=window.innerHeight+window.scrollMaxY;
		}else if(document.body.scrollHeight>document.body.offsetHeight){
			xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;
		}else{
			xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;
		}
		var windowWidth,windowHeight;
		if(self.innerHeight){
			if(document.documentElement.clientWidth){
				windowWidth=document.documentElement.clientWidth;
			}else{
				windowWidth=self.innerWidth;
			}
			windowHeight=self.innerHeight;
		}else if(document.documentElement&&document.documentElement.clientHeight){
			windowWidth=document.documentElement.clientWidth;
			windowHeight=document.documentElement.clientHeight;
		}else if(document.body){
			windowWidth=document.body.clientWidth;
			windowHeight=document.body.clientHeight;
		}
		if(yScroll<windowHeight){
			pageHeight=windowHeight;
		}else{
			pageHeight=yScroll;
		}
		if(xScroll<windowWidth){
			pageWidth=xScroll;
		}else{
			pageWidth=windowWidth;
		}
		return {X:pageWidth, Y:pageHeight, x:windowWidth, y:windowHeight};
	},
	scroll :  function (){
		var xScroll,yScroll;
		if(self.pageYOffset){
			yScroll=self.pageYOffset;xScroll=self.pageXOffset;
		}else if(document.documentElement&&document.documentElement.scrollTop){
			yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;
		}else if(document.body){
			yScroll=document.body.scrollTop;
			xScroll=document.body.scrollLeft;
		}
		arrayPageScroll=new Array(xScroll,yScroll);
		return {x:xScroll, y:yScroll};
	},
	delay : function (ms){
		var date=new Date();
		curDate=null;
		do{
			var curDate=new Date();
		}
		while(curDate-date<ms);
	}
});
$.fn.extend({
	/**
	 * $('#btn').hoverClass('btnHover');
	 */
	hoverClass : function(c)
	{
		this.each(function(){
			$(this).hover(
				function() { $(this).addClass(c);  },
				function() { $(this).removeClass(c); }
			);
		});
		return this;
	},
	/**
	 * 判断鼠标是否在元素内部 
	 * if($('#jqBox').hasMouse()) alert('在');
	 */
	hasMouse : function(e){
		var bool = false;
		this.each(function(){
			var o = $(this);
			if(!o[0]) return false;
			var offset = o.offset();
			var left = parseInt(offset.left);
			var top = parseInt(offset.top);
			if(e.clientX > left && e.clientX < left+o.width() && e.clientY > top && e.clientY < top+o.height()) {
				bool=true;
			}
		});
		return bool;
	},
	//取checkbox己选定数组，返回数组
	checkbox: function (action){
		var ids = '';
		var length = this.find('input[type=checkbox]:checked').length;
		this.find('input[type=checkbox]:checked').each(function (k,i){
			if(k == length - 1) {
				ids += $(this).val();
			}else{
				ids += $(this).val() + ',';
			}
		});
		return ids;
	}
});
//普通js函数 g(id) = document.getElementById("lrc");
function g(id) {
	return document.getElementById(id);
}
//dialog autosize
function autoSize()
{
	if(!$('#dialog>div').length) return;
	var p = $('#dialog').parent().parent();
	var h = p.height();
	var w = p.width();
	var H = $('#dialog>div').height() + 60;
	var W = $('#dialog>div').width() + 30;
	var top = parseInt(p.css('top')) - (H - h) / 2;
	var left = parseInt(p.css('left')) - (W - w) / 2;
	var scroll = $.scroll();
	if(top < scroll.y) top = scroll.y;
	if(left < scroll.x) left = scroll.x;
	p.animate({height: H, width: W, top: top, left: left}, 300);
}
//disabled the button object(jquery obj)
function disabled(o)
{
	o[0].disabled = true;
	o.css('border', '1px inset #B38E3F').css('background', '#aaa');
}
function enabled(o)
{
	o[0].disabled = false;
	o.css('border', '1px outset #B38E3F').css('background', '#C7AC7B');
}
function timing(endTime){
	if(+new Date > endTime) {
		$('.jqMsg').remove();
		clearInterval(ti);
	}
}
function language()
{
	var lang = $(this).find('option:selected').val();
	if(!lang) return ;
	$.get(ROOT+"?a=lang&lang="+lang, function (data){
		if(data == 1) location.reload();
	});
}
function include_js(path,reload)
{
	var scripts = document.getElementsByTagName("script");
	if (!reload)
	for (var i=0;i<scripts.length;i++) {
		if (scripts[i].src && scripts[i].src.toLowerCase() == path.toLowerCase()) return;
	}
	var sobj = document.createElement('script');
	sobj.type = "text/javascript";
	sobj.src = path;
	var headobj = document.getElementsByTagName('head')[0];
	headobj.appendChild(sobj);
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
