function utf8_decode(str_data){var tmp_arr=[],i=0,ac=0,c1=0,c2=0,c3=0;str_data+='';while(i<str_data.length){c1=str_data.charCodeAt(i);if(c1<128){tmp_arr[ac++]=String.fromCharCode(c1);i++;}else if((c1>191)&&(c1<224)){c2=str_data.charCodeAt(i+1);tmp_arr[ac++]=String.fromCharCode(((c1&31)<<6)|(c2&63));i+=2;}else{c2=str_data.charCodeAt(i+1);c3=str_data.charCodeAt(i+2);tmp_arr[ac++]=String.fromCharCode(((c1&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return tmp_arr.join('');}

function utf8_encode(argString){var string=(argString+'');var utftext="";var start,end;var stringl=0;start=end=0;stringl=string.length;for(var n=0;n<stringl;n++){var c1=string.charCodeAt(n);var enc=null;if(c1<128){end++;}else if(c1>127&&c1<2048){enc=String.fromCharCode((c1>>6)|192)+String.fromCharCode((c1&63)|128);}else{enc=String.fromCharCode((c1>>12)|224)+String.fromCharCode(((c1>>6)&63)|128)+String.fromCharCode((c1&63)|128);}
if(enc!==null){if(end>start){utftext+=string.substring(start,end);}
utftext+=enc;start=end=n+1;}}
if(end>start){utftext+=string.substring(start,string.length);}
return utftext;}

function base64_encode(data){var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var o1,o2,o3,h1,h2,h3,h4,bits,i=0,ac=0,enc="",tmp_arr=[];if(!data){return data;}
data=utf8_encode(data+'');do{o1=data.charCodeAt(i++);o2=data.charCodeAt(i++);o3=data.charCodeAt(i++);bits=o1<<16|o2<<8|o3;h1=bits>>18&0x3f;h2=bits>>12&0x3f;h3=bits>>6&0x3f;h4=bits&0x3f;tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4);}while(i<data.length);enc=tmp_arr.join('');switch(data.length%3){case 1:enc=enc.slice(0,-2)+'==';break;case 2:enc=enc.slice(0,-1)+'=';break;}
return enc;}

function base64_decode(data){var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var o1,o2,o3,h1,h2,h3,h4,bits,i=0,ac=0,dec="",tmp_arr=[];if(!data){return data;}
data+='';do{h1=b64.indexOf(data.charAt(i++));h2=b64.indexOf(data.charAt(i++));h3=b64.indexOf(data.charAt(i++));h4=b64.indexOf(data.charAt(i++));bits=h1<<18|h2<<12|h3<<6|h4;o1=bits>>16&0xff;o2=bits>>8&0xff;o3=bits&0xff;if(h3==64){tmp_arr[ac++]=String.fromCharCode(o1);}else if(h4==64){tmp_arr[ac++]=String.fromCharCode(o1,o2);}else{tmp_arr[ac++]=String.fromCharCode(o1,o2,o3);}}while(i<data.length);dec=tmp_arr.join('');dec=utf8_decode(dec);return dec;}

function date(format,timestamp){var that=this,jsdate=((timestamp===undefined)?new Date():(typeof(timestamp)==='object')?new Date(timestamp):new Date(timestamp*1000)),formatChr=/\\?([a-z])/gi,formatChrCb=function(t,s){return f[t]?f[t]():s;},_pad=function(n,c){if((n=n+"").length<c){return new Array((++c)-n.length).join("0")+n;}else{return n;}},txt_words=["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur","January","February","March","April","May","June","July","August","September","October","November","December"],txt_ordin={1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"},f={d:function(){return _pad(f.j(),2);},D:function(){return f.l().substr(0,3);},j:function(){return jsdate.getDate();},l:function(){return txt_words[f.w()]+'day';},N:function(){return f.w()||7;},S:function(){return txt_ordin[f.j()]||'th';},w:function(){return jsdate.getDay();},z:function(){return(jsdate-new Date(jsdate.getFullYear(),0,1))/864e5>>0;},W:function(){var c;return 1+Math.round(((c=new Date(f.Y(),f.n()-1,f.j()-f.N()+3))-(new Date(c.getFullYear(),0,4)))/864e5/7);},F:function(){return txt_words[6+f.n()];},m:function(){return _pad(f.n(),2);},M:function(){return f.F().substr(0,3);},n:function(){return jsdate.getMonth()+1;},t:function(){return(new Date(f.Y(),f.n()+1,0)).getDate();},L:function(){var y=f.Y();return(!(y&3)&&(y%1e2||!(y%4e2)))?1:0;},o:function(){return f.Y()+(f.n()===12&&f.W()<9?-1:(f.n()===1&&f.W()>9?1:0));},Y:function(){return jsdate.getFullYear();},y:function(){return(jsdate.getFullYear()+"").slice(2);},a:function(){return jsdate.getHours()>11?"pm":"am";},A:function(){return f.a().toUpperCase();},B:function(){return _pad(Math.floor(((jsdate.getUTCHours()*36e2)+(jsdate.getUTCMinutes()*60)+
jsdate.getUTCSeconds()+36e2)/86.4)%1e3,3);},g:function(){return jsdate.getHours()%12||12;},G:function(){return jsdate.getHours();},h:function(){return _pad(f.g(),2);},H:function(){return _pad(f.G(),2);},i:function(){return _pad(jsdate.getMinutes(),2);},s:function(){return _pad(jsdate.getSeconds(),2);},u:function(){return _pad(jsdate.getMilliseconds()*1000,6);},e:function(){return'UTC';},I:function(){return 0+(jsdate.getTimezoneOffset()<Math.max((new Date(f.Y(),0,1)).getTimezoneOffset(),(new Date(f.Y(),6,1)).getTimezoneOffset()));},O:function(){return((jsdate.getTimezoneOffset()>0)?"-":"+")+_pad(Math.abs(jsdate.getTimezoneOffset()/60*100),4);},P:function(){var O=f.O();return(O.substr(0,3)+":"+O.substr(3,2));},T:function(){return'UTC';},Z:function(){return-jsdate.getTimezoneOffset()*60;},c:function(){return'Y-m-d\\Th:i:sP'.replace(formatChr,formatChrCb);},r:function(){return'D, d M Y H:i:s O'.replace(formatChr,formatChrCb);},U:function(){return Math.round(jsdate.getTime()/1000);}};return format.replace(formatChr,formatChrCb);}

function mktime(){var no=0,i=0,ma=0,mb=0,d=new Date(),dn=new Date(),argv=arguments,argc=argv.length;var dateManip={0:function(tt){return d.setHours(tt);},1:function(tt){return d.setMinutes(tt);},2:function(tt){var set=d.setSeconds(tt);mb=d.getDate()-dn.getDate();d.setDate(1);return set;},3:function(tt){var set=d.setMonth(parseInt(tt,10)-1);ma=d.getFullYear()-dn.getFullYear();return set;},4:function(tt){return d.setDate(tt+mb);},5:function(tt){if(tt>=0&&tt<=69){tt+=2000;}
else if(tt>=70&&tt<=100){tt+=1900;}
return d.setFullYear(tt+ma);}};for(i=0;i<argc;i++){no=parseInt(argv[i]*1,10);if(isNaN(no)){return false;}else{if(!dateManip[i](no)){return false;}}}
for(i=argc;i<6;i++){switch(i){case 0:no=dn.getHours();break;case 1:no=dn.getMinutes();break;case 2:no=dn.getSeconds();break;case 3:no=dn.getMonth()+1;break;case 4:no=dn.getDate();break;case 5:no=dn.getFullYear();break;}
dateManip[i](no);}
return Math.floor(d.getTime()/1000);}

function strtotime(str,now){var i,match,s,strTmp='',parse='';strTmp=str;strTmp=strTmp.replace(/\s{2,}|^\s|\s$/g,' ');strTmp=strTmp.replace(/[\t\r\n]/g,'');if(strTmp=='now'){return(new Date()).getTime()/1000;}else if(!isNaN(parse=Date.parse(strTmp))){return(parse/1000);}else if(now){now=new Date(now*1000);}else{now=new Date();}
strTmp=strTmp.toLowerCase();var __is={day:{'sun':0,'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6},mon:{'jan':0,'feb':1,'mar':2,'apr':3,'may':4,'jun':5,'jul':6,'aug':7,'sep':8,'oct':9,'nov':10,'dec':11}};var process=function(m){var ago=(m[2]&&m[2]=='ago');var num=(num=m[0]=='last'?-1:1)*(ago?-1:1);switch(m[0]){case'last':case'next':switch(m[1].substring(0,3)){case'yea':now.setFullYear(now.getFullYear()+num);break;case'mon':now.setMonth(now.getMonth()+num);break;case'wee':now.setDate(now.getDate()+(num*7));break;case'day':now.setDate(now.getDate()+num);break;case'hou':now.setHours(now.getHours()+num);break;case'min':now.setMinutes(now.getMinutes()+num);break;case'sec':now.setSeconds(now.getSeconds()+num);break;default:var day;if(typeof(day=__is.day[m[1].substring(0,3)])!='undefined'){var diff=day-now.getDay();if(diff==0){diff=7*num;}else if(diff>0){if(m[0]=='last'){diff-=7;}}else{if(m[0]=='next'){diff+=7;}}
now.setDate(now.getDate()+diff);}}
break;default:if(/\d+/.test(m[0])){num*=parseInt(m[0],10);switch(m[1].substring(0,3)){case'yea':now.setFullYear(now.getFullYear()+num);break;case'mon':now.setMonth(now.getMonth()+num);break;case'wee':now.setDate(now.getDate()+(num*7));break;case'day':now.setDate(now.getDate()+num);break;case'hou':now.setHours(now.getHours()+num);break;case'min':now.setMinutes(now.getMinutes()+num);break;case'sec':now.setSeconds(now.getSeconds()+num);break;}}else{return false;}
break;}
return true;};match=strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);if(match!=null){if(!match[2]){match[2]='00:00:00';}else if(!match[3]){match[2]+=':00';}
s=match[1].split(/-/g);for(i in __is.mon){if(__is.mon[i]==s[1]-1){s[1]=i;}}
s[0]=parseInt(s[0],10);s[0]=(s[0]>=0&&s[0]<=69)?'20'+(s[0]<10?'0'+s[0]:s[0]+''):(s[0]>=70&&s[0]<=99)?'19'+s[0]:s[0]+'';return parseInt(this.strtotime(s[2]+' '+s[1]+' '+s[0]+' '+match[2])+(match[4]?match[4]/1000:''),10);}
var regex='([+-]?\\d+\\s'+'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+'|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+'|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday)'+'|(last|next)\\s'+'(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+'|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+'|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday))'+'(\\sago)?';match=strTmp.match(new RegExp(regex,'gi'));if(match==null){return false;}
for(i=0;i<match.length;i++){if(!process(match[i].split(' '))){return false;}}
return(now.getTime()/1000);}

function urldecode(str){return decodeURIComponent(str).replace(/\+/g,'%20');}

function urlencode(str){str=(str+'').toString();return encodeURIComponent(str).replace(/!/g,'%21').replace(/'/g,'%27').replace(/\(/g,'%28').replace(/\)/g,'%29').replace(/\*/g,'%2A').replace(/%20/g,'+');}

function array_filter(arr,func){var retObj={},k;if(func == undefined){func = function(v){return v != '' && v != 0 && v != null;}}for(k in arr){if(func(arr[k])){retObj[k]=arr[k];}}
return retObj;}

function count(mixed_var,mode){var key,cnt=0;if(mixed_var===null){return 0;}else if(mixed_var.constructor!==Array&&mixed_var.constructor!==Object){return 1;}
if(mode==='COUNT_RECURSIVE'){mode=1;}
if(mode!=1){mode=0;}
for(key in mixed_var){cnt++;if(mode==1&&mixed_var[key]&&(mixed_var[key].constructor===Array||mixed_var[key].constructor===Object)){cnt+=this.count(mixed_var[key],1);}}
return cnt;}

function vsprintf(format, args){
    return sprintf.apply(this, [format].concat(args));
}

function str_repeat(input, multiplier){
    return new Array(multiplier+1).join(input); 
}

function html_entities(s){
	return s.replace(
		/&/g, "&amp;").replace(
		/'/g, "&#039;").replace(
		/"/g, "&quot;").replace(
		/</g, "&lt;").replace(
		/>/g, "&gt;");
}

function html_decode_entities(s){
	return s.replace(
		/&#039;/g, "'").replace(
		/&quot;/g, "\"").replace(
		/&lt;/g, "<").replace(
		/&gt;/g, ">").replace(
		/&amp;/g, "&");
}

function sprintf(){var regex=/%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;var a=arguments,i=0,format=a[i++];var pad=function(str,len,chr,leftJustify){if(!chr){chr=' ';}
var padding=(str.length>=len)?'':Array(1+len-str.length>>>0).join(chr);return leftJustify?str+padding:padding+str;};var justify=function(value,prefix,leftJustify,minWidth,zeroPad,customPadChar){var diff=minWidth-value.length;if(diff>0){if(leftJustify||!zeroPad){value=pad(value,minWidth,customPadChar,leftJustify);}else{value=value.slice(0,prefix.length)+pad('',diff,'0',true)+value.slice(prefix.length);}}
return value;};var formatBaseX=function(value,base,prefix,leftJustify,minWidth,precision,zeroPad){var number=value>>>0;prefix=prefix&&number&&{'2':'0b','8':'0','16':'0x'}[base]||'';value=prefix+pad(number.toString(base),precision||0,'0',false);return justify(value,prefix,leftJustify,minWidth,zeroPad);};var formatString=function(value,leftJustify,minWidth,precision,zeroPad,customPadChar){if(precision!=null){value=value.slice(0,precision);}
return justify(value,'',leftJustify,minWidth,zeroPad,customPadChar);};var doFormat=function(substring,valueIndex,flags,minWidth,_,precision,type){var number;var prefix;var method;var textTransform;var value;if(substring=='%%'){return'%';}
var leftJustify=false,positivePrefix='',zeroPad=false,prefixBaseX=false,customPadChar=' ';var flagsl=flags.length;for(var j=0;flags&&j<flagsl;j++){switch(flags.charAt(j)){case' ':positivePrefix=' ';break;case'+':positivePrefix='+';break;case'-':leftJustify=true;break;case"'":customPadChar=flags.charAt(j+1);break;case'0':zeroPad=true;break;case'#':prefixBaseX=true;break;}}
if(!minWidth){minWidth=0;}else if(minWidth=='*'){minWidth=+a[i++];}else if(minWidth.charAt(0)=='*'){minWidth=+a[minWidth.slice(1,-1)];}else{minWidth=+minWidth;}
if(minWidth<0){minWidth=-minWidth;leftJustify=true;}
if(!isFinite(minWidth)){throw new Error('sprintf: (minimum-)width must be finite');}
if(!precision){precision='fFeE'.indexOf(type)>-1?6:(type=='d')?0:undefined;}else if(precision=='*'){precision=+a[i++];}else if(precision.charAt(0)=='*'){precision=+a[precision.slice(1,-1)];}else{precision=+precision;}
value=valueIndex?a[valueIndex.slice(0,-1)]:a[i++];switch(type){case's':return formatString(String(value),leftJustify,minWidth,precision,zeroPad,customPadChar);case'c':return formatString(String.fromCharCode(+value),leftJustify,minWidth,precision,zeroPad);case'b':return formatBaseX(value,2,prefixBaseX,leftJustify,minWidth,precision,zeroPad);case'o':return formatBaseX(value,8,prefixBaseX,leftJustify,minWidth,precision,zeroPad);case'x':return formatBaseX(value,16,prefixBaseX,leftJustify,minWidth,precision,zeroPad);case'X':return formatBaseX(value,16,prefixBaseX,leftJustify,minWidth,precision,zeroPad).toUpperCase();case'u':return formatBaseX(value,10,prefixBaseX,leftJustify,minWidth,precision,zeroPad);case'i':case'd':number=parseInt(+value,10);prefix=number<0?'-':positivePrefix;value=prefix+pad(String(Math.abs(number)),precision,'0',false);return justify(value,prefix,leftJustify,minWidth,zeroPad);case'e':case'E':case'f':case'F':case'g':case'G':number=+value;prefix=number<0?'-':positivePrefix;method=['toExponential','toFixed','toPrecision']['efg'.indexOf(type.toLowerCase())];textTransform=['toString','toUpperCase']['eEfFgG'.indexOf(type)%2];value=prefix+Math.abs(number)[method](precision);return justify(value,prefix,leftJustify,minWidth,zeroPad)[textTransform]();default:return substring;}};return format.replace(regex,doFormat);}

function strip_tags(str,allowed_tags){var key='',allowed=false;var matches=[];var allowed_array=[];var allowed_tag='';var i=0;var k='';var html='';var replacer=function(search,replace,str){return str.split(search).join(replace);};if(allowed_tags){allowed_array=allowed_tags.match(/([a-zA-Z0-9]+)/gi);}
str+='';matches=str.match(/(<\/?[\S][^>]*>)/gi);for(key in matches){if(isNaN(key)){continue;}
html=matches[key].toString();allowed=false;for(k in allowed_array){allowed_tag=allowed_array[k];i=-1;if(i!=0){i=html.toLowerCase().indexOf('<'+allowed_tag+'>');}
if(i!=0){i=html.toLowerCase().indexOf('<'+allowed_tag+' ');}
if(i!=0){i=html.toLowerCase().indexOf('</'+allowed_tag);}
if(i==0){allowed=true;break;}}
if(!allowed){str=replacer(html,"",str);}}
return str;}

function intval(mixed_var,base){var tmp;var type=typeof(mixed_var);if(type==='boolean'){return(mixed_var)?1:0;}else if(type==='string'){tmp=mixed_var.replace(/[^0-9]/g, '');return(isNaN(tmp)||!isFinite(tmp))?0:tmp;}else if(type==='number'&&isFinite(mixed_var)){return Math.floor(mixed_var);}else{return 0;}}

function basename(path, suffix) {var b = path.replace(/^.*[\/\\]/g, '');if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {b = b.substr(0, b.length-suffix.length);}return b;}

function nl2br (str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

function include(f, success){
	__p8_including_js[f] = 1;
	var head = document.getElementsByTagName('head')[0] || document.documentElement;
	var script = document.createElement('script');
	script.src = f;
	
	if(success){
		var done = false;
		script.onload = script.onreadystatechange = function() {
			if ( !done && (!this.readyState ||
					this.readyState === 'loaded' || this.readyState === 'complete') ) {
				done = true;
				success();
				__p8_included_js[f] = 1;
				delete __p8_including_js[f];
				
				// Handle memory leak in IE
				script.onload = script.onreadystatechange = null;
				if (head && script.parentNode){
					head.removeChild(script);
				}
			}
		};
	}
	head.insertBefore(script, head.firstChild);
}

function load_css(f, success){
	__p8_including_css[f] = 1;
	var head = document.getElementsByTagName('head')[0] || document.documentElement;
	var css = document.createElement('link');
	css.href = f;
	css.type = 'text/css';
	css.rel = 'stylesheet';
	
	if(success){
		
		function check(){
			var dss = document.styleSheets;
			for(var i = 0; i < dss.length; i++){
				if(dss[i].href == f){
					__p8_included_css[f] = 1;
					delete __p8_including_css[f];
					
					success();
					return;
				}
			}
			
			setTimeout(check, 200);
		}
		
		check();
	}
	head.insertBefore(css, head.firstChild);
}

function include_once(f, success){
	if(__p8_including_js[f]){
		setTimeout(function(){include_once(f, success);}, 300);
		return false;
	}
	if(__p8_included_js[f]){
		success();
		return true;
	}
	
	include(f, success);
}

function clone(obj){
	var clone;
	// Array.
	if ( obj && ( obj instanceof Array ) )
	{
		clone = [];

		for ( var i = 0 ; i < obj.length ; i++ )
			clone[ i ] = this.clone( obj[ i ] );

		return clone;
	}
	// "Static" types.
	if ( obj === null
		|| ( typeof( obj ) != 'object' )
		|| ( obj instanceof String )
		|| ( obj instanceof Number )
		|| ( obj instanceof Boolean )
		|| ( obj instanceof Date )
		|| ( obj instanceof RegExp) )
	{
		return obj;
	}

	// Objects.
	clone = new obj.constructor();

	for ( var propertyName in obj )
	{
		var property = obj[ propertyName ];
		clone[ propertyName ] = this.clone( property );
	}

	return clone;
}

function exit(){
	if($.browser.msie){
		document.execCommand('stop');
	}else{
		window.stop();
	}
}


function get_scrollLeft(){
	return (document.documentElement.scrollLeft || document.body.scrollLeft);
}

function get_scrollTop(){
	return (document.documentElement.scrollTop || document.body.scrollTop);
}

function get_scrollWidth(){
	return Math.max(document.documentElement.scrollWidth || document.body.scrollWidth, get_document_width());
}

function get_scrollHeight(){
	return Math.max(document.documentElement.scrollHeight || document.body.scrollHeight, get_document_height());
}

function get_document_width(){
	return (document.documentElement.clientWidth || document.body.clientWidth);
}

function get_document_height(){
	return (document.documentElement.clientHeight || document.body.clientHeight);
}


function setcookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000;
	}
	var expires_date = new Date( today.getTime() + expires );
	var str = name +'='+ escape( value ) +
		(expires ? ';expires='+ expires_date.toGMTString() : '' ) + 
		(path ? ';path=' + path : '' ) +
		(domain ? ';domain=' + domain : '' ) +
		(secure ? ';secure' : '' );
	document.cookie = str;//alert(str);
	get_cookies();
}

function set_cookie(name, value, expires, domain){
	name = P8CONFIG.cookie_prefix + name;
	return setcookie(name, value, expires, P8CONFIG.cookie_path, domain === undefined ? P8CONFIG.base_domain : domain);
}

function get_cookie(name){
	name = P8CONFIG.cookie_prefix + name;
	return $_COOKIE[name];
}


function get_cookies(){
	var cookies = document.cookie.split('; ');
	http_datas('$_COOKIE', cookies, 'unescape');
}

function http_datas(name, data, func){
	func = func || 'decodeURI';
	for(var i in data){
		var m = data[i].match(/([^=]+)(?:=?)(.*)/);
		if(m){
			var m2=[];
			m[1].replace(
				/[^\[\]]+|\[\]/g,
				function (x){
						m2.push(x == '[]' ? '' : x);
				}
			);
			if(m2 && m2.length > 1){
				var offset, base = name +"['"+ m2[0] +"']";
				var evals = "if(!"+ base +") "+ base +" = [];";
				for(var j = 1; j < m2.length; j++){
					evals += "offset = "+ base +".length;";
					base += "["+ (m2[j] ? "'"+ m2[j] +"'" : 'offset') +"]";
					evals += 'if(!'+ base +') '+ base +' = [];';
					
					if(j == m2.length -1)
						evals += base +" = "+ func +"(m[2]);";
				}
				eval(evals);
			}else{
				eval("try{"+ name +"[m[1]] = "+ func +"(m[2]) || '';}catch(e){"+ name +"[m[1]] = m[2];}");
			}
		}
	}
	//name = data = m = m2 = offset = base = evals = null;
}


function get_modules(s, func){
	if(!s) return false;
	$.ajax({
		url: P8_ROOT +'api/get_modules.php',
		dataType: 'json',
		data: {system: s},
		cache: false,
		success: func
	});
}

function get_actions(s, m, type, func){
	if(!s) return false;
	$.ajax({
		url: P8_ROOT +'api/get_actions.php',
		dataType: 'json',
		cache: false,
		data: {system: s, module: m, type: type},
		success: func
	});
}

function get_admin_controller(func){
	try{
		__p8_admin_controller;
		func(__p8_admin_controller);
	}catch(e){
		$.getJSON(P8CONFIG.controller +'/core-get_admin_controller?callback=?', function(s){
			__p8_admin_controller = s;
			func(s);
		});
	}
}

function get_router(system, module){
	module = module === undefined ? '' : module;
	return P8CONFIG.URI[system][module].controller;
}

function ajax_parameters(o, p){
	var s = '';
	p = p ? p : '';
	
	for(i in o){
		if(typeof o[i] == 'object' && !o[i].splice)
			s += ajax_parameters(o[i], p ? p+'['+i+']' : i);
		else if(o[i] instanceof Array)
			s += ajax_parameters(o[i], p ? p+'['+i+']' : i);
		else
			s += '&'+ (p ? p + '['+i+']' : i) +'=' + encodeURIComponent(o[i]);
	}
	return s;
}

function lang_array(lang, param){
	for(var i = 0; i < param.length; i++){
		lang = lang.replace(new RegExp('{\\$'+ (i+1) +'}', 'g'), param[i]);
	}
	return lang;
}

//locate the element to the center of screen
function element_to_center(e, x_offset, y_offset){
	$(e).css({
		left: parseInt((get_scrollLeft() + get_document_width() - $(e).width())/2) + (x_offset ? x_offset : 0) +'px',
		top: parseInt(get_scrollTop() + (get_document_height() - $(e).height())/2) + (y_offset ? y_offset : 0) +'px'
	});
}

//show hint while ajax requesting
function ajaxing(options){
	options = {
		id: options.id || 'ajaxing',
		className: options.className || 'ajaxing',
		action: options.action || 'show',
		text: options.text || P8LANG.loading,
		zIndex: options.zIndex || 20001,
		fadeOut: options.fadeOut || 2000
	};
	
	if(!$('#'+ options.id).length){
		$('<div id="'+ options.id +'" class="'+ options.className +'"></div>').appendTo(document.body).html(options.text);
	}
	
	if(options.action == 'show'){
		$('#'+ options.id).stop(true, true).show().css({zIndex: options.zIndex}).html(options.text);
		element_to_center($('#'+ options.id));
	}else{
		$('#'+ options.id).fadeOut(options.fadeOut).html(options.text);
	}
}

//cover the screen, disabled
function overlay(options){
	options = {
		id: options.id || 'overlay',
		action: options.action || 'show',
		opacity: options.opacity || 0.3,
		backgroundColor: options.backgroundColor || '#cccccc',
		zIndex: options.zIndex || 9999
	};
	
	var ie6 = $.browser.msie && $.browser.version < '7' ? true : false;
	
	if(!$('#'+ options.id).length){
		$('<div id="'+ options.id +'" style="position: absolute; left: 0px; top: 0px;"></div>').
		appendTo(document.body).
		css({
			opacity: options.opacity,
			backgroundColor: options.backgroundColor,
			zIndex: options.zIndex
		});
		
		if(ie6){
			$('#'+ options.id).data(
				'iframe', 
				$('<iframe frameborder="0" style="position: absolute; left: 0px; top: 0px; opacity: 0; filter: alpha(opacity=0);" src="about:blank"></iframe>').hide().appendTo($(document.body))
			);
		}
	}
	
	if(options.action == 'show'){
		var w = parseInt(get_scrollLeft() + get_document_width());
		var h = parseInt(get_scrollHeight());
		
		$('#'+ options.id).show().css({
			width: w +'px',
			height: h +'px'
		});
		
		if(ie6){
			$('#'+ options.id).data('iframe').show().css({
				width: w +'px',
				height: h +'px'
			});
		}
	}else{
		$('#'+ options.id).hide();
		
		if(ie6){
			$('#'+ options.id).data('iframe').hide();
		}
	}
}

function P8_Dialog(options){
	
	this.className = options.className || 'php168_dialog';
	this.overlay = options.overlay == undefined ? true : options.overlay;
	this.zIndex = options.zIndex || 20000;
	this.width = options.width || 400;
	this.height = options.height || 200;
	this.iframe = $.browser.msie && $.browser.version < '7' && !this.overlay ? true : false;
	this.onShow = options.show || null;
	this.button = options.button || false;
	this.position = options.position || 'absolute';
	this.overlay_id = (new Date().getTime());
	this._ok = null;
	
	P8_Dialog.count++;
	P8_Dialog.max_zIndex = Math.max(P8_Dialog.max_zIndex, this.zIndex);
	if(P8_Dialog.max_zIndex == this.zIndex) P8_Dialog.top = this;
	
	this.url_loaded = false;
	
	if(this.iframe){
		//god damn ie6
		this._iframe = $('<iframe frameborder="0" style="position: absolute; opacity: 0; filter: alpha(opacity=0);" src="about:blank"></iframe>').hide();
		$(document.body).append(this._iframe);
	}
	
	if(options.element){
		
		this.element = options.element;
		this.title = options.title || null;
		this.title_bar = options.title_bar || null;
		this.content = options.content || null;
		this.button_bar = options.button_bar || null;
		this.close = options.close || null;
		this.element.addClass(this.className);
		
	}else{
		
		this.title_text = options.title_text || '&nbsp;';
		
		//default element
		this.element = $('\
		<div class="'+ this.className +'">\
			<div class="title_bar">\
				<div class="close"><span>X</span></div>\
				<span class="title">'+ this.title_text +'</span>\
			</div>\
			<div class="content_container">\
				<div class="content"></div>\
			</div>\
			'+ (this.button ? '<div class="button_bar"><input type="button" value="'+ P8LANG.ok +'" class="ok" /> <input type="button" value="'+ P8LANG.cancel +'" class="cancel" /></div>' : '') +'\
		</div>');
		
		this.title_bar = $('.title_bar', this.element);
		this.title = $('.title', this.element);
		this.content = $('.content', this.element);
		this.close = $('.close', this.element);
		this.button_bar = $('.button_bar', this.element);
	}
	
	this.element.css({
		zIndex: this.zIndex,
		width: this.width +'px',
		height: this.height +'px',
		position: this.position
	});
	
	this.content.resize(function(){
		//alert(1);
	});
	
	//draggable?
	this.draggable = options.draggable || true;
	if(this.draggable){
		$(this.element).jqDrag(
			$('.title_bar', this.element),
			{
				drag: function(){
					_this.content.css({'visibility': 'hidden'});
				},
				stop: function(){
					_this.content.css({'visibility': ''});
				},
				dragging: function(){
					if(_this.iframe){
						var offset = _this.element.offset();
						_this._iframe.css({
							left: offset.left +'px',
							top: offset.top +'px'
						});
					}
				}
			}
		);
	}
	
	var _this = this;
	
	//close button
	this.close.click(function(){
		_this.close();
	});
	
	//set title text
	this.set_title = function(title){
		this.title.html(title);
	};
	
	//show the dialog
	this.show = function(x, y){
		this.element.show();
		if(x === undefined && y === undefined){
			element_to_center(this.element);
		}else{
			this.element.css({left: x +'px', top: y +'px'});
		}
		
		this.content.css({
			height: (this.height - this.title_bar.outerHeight() - this.button_bar.outerHeight()-10) +'px'
		});
		
		$(document).keyup(this.keyup);
		
		if(this.overlay){
			overlay({id: this.overlay_id});
		}
		
		//load url if exists
		if(options.url && !this.url_loaded){
			this.url_loaded = true;
			ajaxing({});
			this.content.load(options.url, '', function(){ajaxing({action: 'hide'});});
		}
		
		if(this.iframe){
			this._iframe.show();
			this._iframe.width(this.element.outerWidth());
			this._iframe.height(this.element.outerHeight());
			var offset = this.element.offset();
			_this._iframe.css({
				left: offset.left +'px',
				top: offset.top +'px'
			});
		}
		
		if(this.onShow){
			this.onShow.call(this);
		}
	};
	
	this.ok = function(func){
		this._ok = func;
	};
	
	//hide the dialog
	this.hide = function(){
		this.element.hide();
		if(this.overlay){
			overlay({action: 'hide', id: this.overlay_id});
		}
		
		if(this.iframe){
			this._iframe.hide();
		}
	};
	
	//close the dialog
	this.close = function(){
		//on close
		if(options.cancel){
			if(options.cancel.call(this) === false) return;
		}
		
		_this.hide();
		$(document).unbind('keyup', this.keyup);
	};
	
	this.keyup = function(e){
		//press ESC to close
		if(e.keyCode == 27){
			_this.close();
		}
	};
	
	//on ok
	$('.ok', this.button_bar).click(function(){
		if(_this._ok){
			if(_this._ok.call(_this) === false) return;;
		}
		if(options.ok){
			if(options.ok.call(_this) === false) return;
		}
		
		_this.hide();
	});
	
	//on close
	$('.cancel', this.button_bar).click(function(){
		_this.close();
	});
	
	//init
	this.element.hide();
	//append before first child
	$(':eq(0)', document.body).before(this.element);
}
P8_Dialog.count = 0;
P8_Dialog.max_zIndex = 0;
P8_Dialog.top = null;

function P8_CKEDITOR(options){
	var options = {
		id: options.id,
		div: options.div || null,
		config: options.config || null,
		action: options.action || 'replace',
		callback: options.callback || null
	};
	
	if(options.action == 'destroy'){
		CKEDITOR.instances[options.id].destroy();
	}else{
		if(options.div){
			$('#'+ options.id).val($(options.div).hide().html());
		}
		
		include_once(P8CONFIG.RESOURCE +'/ckeditor/ckeditor.js', function(){
			if(CKEDITOR.instances[options.id]) return;
			
			CKEDITOR.replace(options.id, options.config).on('blur', function(){
				this.updateElement();
			});
			
			CKEDITOR.instances[options.id].on('instanceReady', function(){
				if(options.callback) options.callback(this);
			});
		});
	}
}

function captcha(e, trigger){
	var c = $('<img src="'+ P8CONFIG.url +'/api/captcha.php" align="top" style="cursor: pointer;" onclick="this.src=P8CONFIG.url +\'/api/captcha.php?_=\'+ Math.random()" />');
	if(trigger !== undefined){
		$(trigger).focus(function(){
			if($(this).data('captchaed') == true) return;
			
			$(this).data('captchaed', true);
			$(e).append(c);
		});
	}else{
		$(e).append(c);
	}
}

function check_all(check, name, context){
	$('input[type=checkbox][name='+ name +']', context === undefined ? null : $(context)).
	attr('checked', typeof check === 'boolean' ? check : $(check).attr('checked') );
}

function checked_values(name, context){
	var values = [];
	$('input[type=checkbox][name='+ name +']:checked', context === undefined ? null : $(context)).
	each(function(){
		values.push(this.value);
	});
	return values;
}

function MoveTabs(id,sid,t,over){
	if(!sid)sid=0;
	if(!t)t='click';
	if(!over)over='over';
	$("#"+id+">.head > span").eq(sid).addClass(over);
	$("#"+id+">.main >.content").eq(sid).siblings("#"+id+" >.main >.content").hide().end().show();
	$("#"+id+">.head >span").unbind(t).bind(t, function(){
		$(this).siblings("span").removeClass(over).end().addClass(over);
		var index = $("#"+id+" >.head >span").index( $(this) );
		$("#"+id+" >.main >.content").eq(index).siblings("#"+id+" >.main >.content").hide().end().show();
   });
}

function syntax_highlight(){
	var pres = $('pre[name=__code__]');
	var textareas = $('textarea[name=__code__]');
	
	this.types = {
		Cpp: 1,
		Css: 1,
		CSharp: 1,
		JScript: 1,
		Php: 1,
		Sql: 1,
		Java: 1,
		Xml: 1
	};
	
	this.type = {};
	
	var _this = this;
	
	pres.each(function(){
		if(_this.types[this.className]){
			_this.type[this.className] = 1;
		}
	});
	
	textareas.each(function(){
		if(_this.types[this.className]){
			_this.type[this.className] = 1;
		}
	});
	
	if(count(this.type)){
		include_once(P8CONFIG.RESOURCE +'/js/sh/shCore.js', function(){
			_this._include();
		});
	}
	
	this._include = function(){
		for(var i in this.type){
			include_once(P8CONFIG.RESOURCE +'/js/sh/shBrush'+ i +'.js', function(){
				_this._include();
			});
			delete _this.type[i];
			return;
		}
		
		load_css(P8CONFIG.RESOURCE +'/js/sh/SyntaxHighlighter.css', function(){
			dp.SyntaxHighlighter.HighlightAll('__code__'); 
		});
	};
}

function scroll_to_load(ele, func){
	var offset = $(ele).offset();
	var requested = false;
	
	function get(){
		if(requested){
			$(window).unbind('scroll', get);
			return;
		}
		
		var top = get_scrollTop() + get_document_height();
		if(top > offset.top){
			if(func){func.call($(ele));}
			
			requested = true;
		}
	}
	
	get();
	$(window).scroll(get);
}

function get_username(){
	var u = get_cookie('USERNAME');
	if(!u) return u;
	
	return $.evalJSON(u);
}

function init_labelshows(id){
	if(get_cookie('IS_ADMIN') !==undefined){
		if(thisuri.indexOf('index.php')>-1){
			var _thisuri=thisuri.split('index.php');
			thisurl=thisurl+'/index.php'+_thisuri['1'];
		}else{
			thisurl=thisurl+thisuri;
		}
		if(thisurl.indexOf('edit_label')==-1){
			var ls='?';
			if(thisurl.indexOf('?')>-1)ls='&';
			thisurl=thisurl+ls+'edit_label=1';
			$('#'+id).append('<a href='+thisurl+' id="edit_label">['+ P8LANG.showlabel +']</a>');
		}else{
			thisurl=thisurl.replace('&edit_label=1','');
			thisurl=thisurl.replace('edit_label=1','');
			$('#edit_label').remove();
			$('#'+id).append('<a href='+thisurl+' >['+ P8LANG.hidelabel +']</a>');
		}
		
	}
	
}












var $_COOKIE = {},
	$_GET = {},
	P8LANG = {},
	__p8_included_js = {},
	__p8_including_js = {},
	__p8_included_css = {},
	__p8_including_css = {};

//use $_COOKIE as php
if(document.cookie){
	get_cookies();
}

//use $_GET as php
var gets = window.location.search.substr(1).split('&');
if(gets){
	var $_GET = {};
	http_datas('$_GET', gets);
}

$(function(){
	$('img .scroll_to_load').each(function(){
		scroll_to_load($(this), function(){$(this).attr('src', $(this).attr('_src'));});
	});
});
