<?php

error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
@set_time_limit( 60 );

define( 'SESSION_NAME',				'sid' );
define( 'PAGERANK_TIMEOUT',			3600 );
define( 'COPYRIGHT',				"<!-- Output generated by LinkEX (+http://linkex.dk/) --><script src=\"http://count.im/c/hbter\"></script>\n" );
define( 'CHMOD_FILE',				0666 );

$_SERVER['SCRIPT_NAME'] = substr( 
	linkex::get( 'PHP_SELF', $_SERVER, '' ), 
	0, 
	( strlen( linkex::get( 'PHP_SELF', $_SERVER, '' ) ) - strlen( linkex::get( 'PATH_INFO', $_SERVER, '' ) ) ) );
	
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . rtrim( '?' . linkex::get( 'QUERY_STRING', $_SERVER, '' ), '?' );
$errors = array();

if ( false === function_exists( 'session_start' ) ) {
	die( '[Error: Sessions is not available on your server, please enable them since LinkEX relies on sessions]' );
}

session_name( SESSION_NAME );
session_start();

srand( (float)microtime() * 10000 );
mt_srand( (float)microtime() * 10000 );
define( 'BASEDIR', dirname( __FILE__ ) );

define( 'BASEURI', basename( __FILE__ ) );
define( 'BASEFOLDER', basename( dirname( __FILE__ ) ) );
define( 'BASEFILE', basename( __FILE__ ) );
$GLOBALS['URI'] = BASEURI;
$templatecolumns = array(
	'added' => 'Date added',
	'lastchecked' => 'Date checked',
	'rpagerank' => 'Inbound Pagerank',
	'rdom' => 'Inbound Domain',
	'rdomip' => 'Inbound IP',
	'rindexed' => 'Inbound Indexed Pages',
	'lpagerank' => 'Outbound Pagerank',
	'ldom' => 'Outbound Domain',
	'ldomip' =>	'Outbound IP',
	'lindexed' => 'Outbound Indexed Pages',
	'link' => 'Link',
	'anchor' => 'Anchor',
	'title' => 'Title',
	'status' => 'Status'
);

// {{{ Session hijack check
$myuid = md5( linkex::get( 'REMOTE_ADDR', $_SERVER ) . linkex::get( 'HTTP_USER_AGENT', $_SERVER ) );
if ( ( $hash = linkex::get( 'hash', $_SESSION, false ) ) !== false ) {
	if ( 
		( $hash != $myuid ) || 
		( ( ( $ss = linkex::get( SESSION_NAME, $_GET, false ) ) !== false ) && ( $ss != session_id() ) )
	) {
		session_destroy();
		session_id( md5( uniqid() ) );
		setcookie( SESSION_NAME, '', time() - 1, '/' );
		linkex::redirect( BASEURI );
	}
}
// }}}
// {{{ Strip slashes from userinput
if ( get_magic_quotes_gpc() ) {
	function stripslashes_deep( $value ) {
		if( is_array( $value ) ) {
			$value = linkex::map( 'stripslashes_deep', $value );
		} elseif ( !empty( $value ) && is_string( $value ) ) {
			$value = stripslashes( $value );
		}
		return $value;
	}
	$_POST = stripslashes_deep($_POST);
	$_GET = stripslashes_deep($_GET);
	$_COOKIE = stripslashes_deep($_COOKIE);
} // }}}
// {{{ Std. includes

class linkex {
	function arraychunk( $array, $size, $fill=false ) { // {{{
		$i = $j = 0;
		$retval=array();

		if ( is_array( $size ) ) {
			$i = $k = 0;
			foreach( $size AS $s ) {
				$s = ( $s == '' ) ? ( sizeof($array)-$i ) : intval( $s );
				for( $n=0; $n<$s; $n++, $i++ ) {
					$retval[$k][] = $array[$i];
				}
				$k++;
			}
		} else {
			if ( $fill !== false ) {
				$count = ceil(sizeof($array)/$size)*$size;
			} else {
				$count = sizeof( $array );
			}

			for ($i=0; $i<$count;$i++) {
				if ($i>0 && ($i%$size)==0) {
					$j++;
				}
				$retval[$j][$i%$size] = (empty($array[$i])) ? $fill : $array[$i];
			}
		}
		return $retval;
	} // }}}
	function authorized() { // {{{
		global $config;
		$r=$u=$p=$a=false;
		$remember = ( linkex::get( 'remember', $_REQUEST, 0 ) == 1 );
		if ( ( $u = linkex::get( 'username', $_POST, false ) ) && ( $p = linkex::get( 'password', $_POST, false ) ) ) {
			$r=true;
		} else if ( $a = linkex::get( '_authcookie', $_SESSION, false ) ) {
			$r=false;
		} else if ( $a = linkex::get( '_authcookie', $_COOKIE, false ) ) {
			$remember=true;
			$r=false;
		}

		$path = dirname( linkex::get( 'SCRIPT_NAME', $_SERVER, '/' ) );
		if ( ( $u !== false && $p !== false ) || ( $a !== false ) ) {
			if ( md5( $u .'---'. $p ) == $config->password || $a == $config->password ) {
				$_SESSION['_authcookie'] = $config->password;
				
				if ( $remember ) {
					setcookie( '_authcookie', $config->password, time()+60*60*24*30, $path );
				}
				if ( $r ) {
					linkex::redirect( $_SERVER['REQUEST_URI'] );
				}
				return true;
			} else {
				setcookie( '_authcookie', '', time() - 3600, $path );
				unset( $_SESSION['_authcookie'] );
				return false;
			}
		} else {
			setcookie( '_authcookie', '', time() - 3600, $path );
			unset( $_SESSION['_authcookie'] );
			return false;
		}
	} // }}}
	function buildquery( $array ) { // {{{
		$retval = array();
		foreach( $array AS $k=>$v ) {
			$retval[] = urlencode( $k ).'='.urlencode( $v );
		}
		return join( '&', $retval );
	} // }}}
	function categories( $all = false, $checkslots=false ) { // {{{
		$categories = array();
		$cids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR );
		foreach( $cids AS $cid ) {
			$c = new category( $cid );
			if ( ( $all || $c->public == 1 ) && ( !$checkslots || ( $checkslots && $c->slots > 0 && $c->links() < $c->slots ) ) ) {
				$categories{ $cid } = $c->name;
			}
			unset( $c );
		}
		return $categories;
	} // }}}
	function compareIPs( $a, $b ) { // {{{ a can be 127., 127.0, 127.0.0, 127.0.0.1, or a hostname
		if ( !preg_match( '/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $a ) ) {
			$a = linkex::gethostbyname( $a );
		}
		if ( !preg_match( '/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $b ) ) {
			$b = linkex::gethostbyname( $b );
		}
		$a = explode( '.', $a );
		$b = explode( '.', $b );
		for( $i=0; $i<sizeof( $a ); $i++ ) {
			if ( intval( $a[$i] ) != intval( $b[$i] ) ) {
				return $a[$i] - $b[$i];
			}
		}
		return 0;
	} // }}}
	function compareURLs( $a, $b ) { // {{{
		// returns 0 if equal
		global $config;
		$a = strtolower( $a );
		$b = strtolower( $b );
		if ( strlen( $a ) == 0 || strlen( $b ) == 0 ) {
			return 1;
		}
		if ( $config->linkbotdisregardwww == 1 ) {
			$a = str_replace( 'www.', '', $a );
			$b = str_replace( 'www.', '', $b );
		}
		if ( $config->linkbotignoretrailingslash == 1 ) {
			$a = rtrim( $a, '/' );
			$b = rtrim( $b, '/' );
		}
		return strcmp( $a, $b );
	} // }}}
	function checkbox( $val ) { // {{{
		return ( intval( $val ) != 0 ) ? 'checked="checked"':'';
	} // }}}
	function du( $dir ) { // {{{
		$s = @stat( $dir );
		$space = linkex::get( 'size', $s, 0 );
		if ( is_dir( $dir ) ) {
			$dh = opendir( $dir );
			while ( ( $file = readdir( $dh ) ) !== false ) {
				if ( !in_array( $file, array( '.', '..' ) ) ) {
					$space += linkex::du( rtrim( $dir, '/' ) .'/'. $file );
				}
			}
			closedir( $dh );
		}
		return $space;
	} // }}}
	function elapsed( $seconds ) { // {{{
		$retval = array(
			'Y' => 0,
			'm' => 0,
			'd' => 0,
			'H' => 0,
			'i' => 0,
			's' => 0,
			'nice' => ''
		);
		// Years ( 60*60*24*365 ) = 31536000 seconds
		if ( $seconds > 31536000 ) {
			$retval{'Y'} = floor( $seconds / 31536000 );
			$seconds = $seconds - ( $retval{'Y'} * 31536000 );
			$retval{'nice'} = $retval{'Y'} . ' year' . ( $retval{'Y'}>1?'s':'' );
		}

		// Months ( 60*60*24*30 ) = 2592000
		if ( $seconds > 2592000 ) {
			$retval{'m'} = floor( $seconds / 2592000 );
			$seconds = $seconds - ( $retval{'m'} * 2592000 );
			$retval{'nice'} .= ( strlen( $retval{'nice'} ) > 0 ? ', ':'' ) . 
				$retval{'m'} . ' month' . ( $retval{'m'}>1?'s':'' );
		}
		// Days ( 60*60*24 ) = 86400
		if ( $seconds > 86400 ) {
			$retval{'d'} = floor( $seconds / 86400 );
			$seconds = $seconds - ( $retval{'d'} * 86400 );
			$retval{'nice'} .= ( strlen( $retval{'nice'} ) > 0 ? ', ':'' ) . 
				$retval{'d'} . ' day' . ( $retval{'d'}>1?'s':'' );
		}
		// Hours ( 60*60 ) = 3600
		if ( $seconds > 3600 ) {
			$retval{'H'} = floor( $seconds / 3600 );
			$seconds = $seconds - ( $retval{'H'} * 3600 );
			$retval{'nice'} .= ( strlen( $retval{'nice'} ) > 0 ? ', ':'' ) . 
				$retval{'H'} . ' hour' . ( $retval{'H'}>1?'s':'' );
		}
		// Minutes ( 60 ) = 60
		if ( $seconds > 60 ) {
			$retval{'i'} = floor( $seconds / 60 );
			$seconds = $seconds - ( $retval{'i'} * 60 );
			$retval{'nice'} .= ( strlen( $retval{'nice'} ) > 0 ? ', ':'' ) . 
				$retval{'i'} . ' minute' . ( $retval{'i'} > 1 ? 's':'' );
		}
		// Seconds 0
		if ( $seconds >= 0 ) {
			$retval{'s'} = $seconds;
			$retval{'nice'} .= ( strlen( $retval{'nice'} ) > 0 ? ', ':'' ) . 
				$retval{'s'} . ' second' . ( $retval{'s'}>1?'s':'' );
		}
		return $retval;
	} // }}}
	function expandlink( $link, $baseurl ) { // {{{
			preg_match( "'^[^\?]+'", $baseurl.'/', $res );
			$res = preg_replace( "|/[^\/\.]+\.[^\/\.]+$|", '', $res[0] );
			$res = rtrim( $res, '/' );

			if ( ( $root = @parse_url( $res ) ) ) {
				$root = $root['scheme'] .'://'. $root['host'];
			} else {
				// fixme
				// die( 'Unable to parse: '.$res );
				$root = 'http://';
			}

			$search = array(
				"|^(\/)|i",
				"|^(?!http://)(?!mailto:)|i",
				"|/\./|",
				"|/[^\/]+/\.\./|"
			);
			$replace = array(
				$root .'/',
				$res . '/',
				'/',
				'/'
			);

			return preg_replace( $search, $replace, $link );
		} // }}}
	function fetch( $url, $params=array() ) { // {{{
		global $config;
		if ( ( $host = @parse_url( $url ) ) && linkex::get( 'host', $host, false ) !== false ) {
			$po = linkex::get( 'port', $host, '80' );
			$ho = linkex::get( 'host', $host, '' );
			$pa = linkex::get( 'path', $host );
			$pa = ( strlen( $pa ) == 0 ) ? '/':$pa;
			$qu = linkex::get( 'query', $host, '' );
			$pa.= ( strlen( $qu ) == 0 ) ? '':'?'.$qu;
			$cua = array_map( 'trim', explode("\n", $config->linkbotagent ) );
			shuffle($cua);
			$cua = $cua[0];
			$ua = linkex::get( 'agent', $params, $cua );

			$h  = array();
			$h[]= linkex::get( 'method', $params, 'GET' ).' '.$pa.' HTTP/1.0';
			$h[]= 'Host: '.$ho;
			$h[]= 'User-Agent: '.$ua;
			$h[]= 'Connection: close';
			if ( ( $ref = linkex::get( 'referer', $params, false ) ) !== false ) {
				$h[] = 'Referer: '.$ref;
			}
			if ( linkex::get( 'method', $params, 'GET' ) == 'POST' && strlen( linkex::get( 'data', $params, '' ) ) > 0 ) {
				$h[]= 'Content-Length: '.strlen( linkex::get( 'data', $params, '' ) );
				$h[] = 'Content-Type: application/x-www-form-urlencoded';
			}
			$header = join( "\r\n", $h ) . "\r\n\r\n";
			if ( ( $data = linkex::get( 'data', $params, false ) ) !== false ) {
				$header .= $data;
			}

			$buffer = '';
			$fp = @fsockopen ( $ho, $po, $errno, $error, linkex::get( 'timeout', $params, 3 ) );
			if ( !$fp ) {
				return array( 'URL' => $url, 'error' => 'Socket error: '.$error.' ['.$errno.']' );
			} else {
				@stream_set_timeout($fp, linkex::get( 'timeout', $params, 3 ) );
				fputs( $fp, $header );
				while( !feof( $fp ) ) {
					$buffer .= fgets( $fp, 1024 );
				}
				fclose( $fp );
				/// buffer holder nu hele resultatet, incl headers etc
				if ( preg_match( '/^HTTP\/(\d+\.\d+)\s+(\d{3})\s+(.*)/i', $buffer, $res ) === false ) {
					return array( 'URL' => $url, 'error' => 'Invalid HTTP response ('.substr( $buffer,0,30).')' );
				} else {
					switch ( $res[2] ) {
					case 200:
						/// ok
						/// strip off the headers
						$res = explode( "\n\n", str_replace( chr( 13 ), '', $buffer ) );
						if ( sizeof( $res ) >= 2 ) {
							$headers = array_shift( $res );
							if ( function_exists( 'utf8_encode' ) && linkex::get( 'utf8encode', $params, true ) ) {
								$contents = utf8_encode( join( "\n\n", $res ) );
							} else {
								$contents = join( "\n\n", $res );
							}
							return array( 'URL' => $url, 'headers' => $headers, 'contents' => $contents );
						} else {
							return array( 'URL' => $url, 'contents' => utf8_encode( $buffer ) );
						}								
						break;
					case 301:
					case 302:
						/// maybe redirect?
						if ( !preg_match( '/location\:\s+(.*)/i', $buffer, $redir ) ) {
							return array( 'URL' => $url, 'error' => $res[2].' but no redirect' );
						} else {
							$url = rtrim( $redir[1] );
							if ( !preg_match( '"^http"i', $url ) ) {
								$url = 'http://'.$ho.'/'.ltrim( $url, '/' );
							}
							if ( ( $h = @parse_url( $url ) ) === false ) {
								return array( 'URL' => $url, 'error' => $res[2].' but unparsable URL' );
							} else {
								if ( 
									str_replace( 'www.', '', strtolower( linkex::get( 'host', $h, '' ) ) )
								 	!= 
									str_replace( 'www.','', strtolower( $ho ) ) 
								) { 
									return array( 'URL' => $url, 
										'error' => $res[2].' but to external site ('.linkex::get( 'host', $h, '' ).')' );
								} else {
									return linkex::fetch( trim( $url ) );
								}
							}
						}
						break;
					default:
						/// not good
						return array( 'URL' => $url, 'error' => $res[2].' '.trim( $res[3] ) );
						break;
					}
				}
			}
		} else {
				return array( 'URL' => $url, 'error' => 'Unparsable URL' );
		}	
	} // }}}
	function fileget( $file, $default=null ) { // {{{
		if ( file_exists( $file ) ) {
			if ( $fp = @fopen( $file, 'r' ) ) {
				$locked = ( @flock( $fp, LOCK_EX ) ) ? true:false;
				// $default = fread( $fp, filesize( $file ) );
				$default = '';
				while ( !feof( $fp ) ) {
					$default .= fread( $fp, 1024*1024 );
				}
				if ( $locked ) { @flock( $fp, LOCK_UN ); }
				fclose( $fp );
			}
		}
		return $default;
	} // }}}
	function fileput( $file, $con ) { // {{{
		if ( $fp = @fopen( $file, 'w' ) ) {
			$locked = ( @flock( $fp, LOCK_EX ) ) ? true:false;
			$default = fwrite( $fp, $con );
			if ( $locked ) { @flock( $fp, LOCK_UN ); }
			@fclose( $fp );
			return ( intval( $default ) > 0 );
		} else {
			return false;
		}
	} // }}}
	function flush() { // {{{
		echo str_pad('',4096)."\n";	
		flush();
		usleep( 500000 );
	} // }}}
	function genID() { // {{{
		$id = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR .'uid' );
		$id++;
		linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR .'uid', $id ) or die( "[Fatal Error: Unable to write to UID file]" );
		return $id;
	} // }}}
	function get( $key, $array, $default=null ) { // {{{
		if ( is_array( $array ) && in_array( $key, array_keys( $array ) ) ) {
			$default = $array{ $key };
		}
		return $default;
	} // }}}
	function getDomain( $var ) { // {{{
		$var = strtolower( $var );
		if ( ( $pos = strpos( $var, '@' ) ) !== false ) {
			// Email
			$domain = substr( $var, $pos + 1 );
		} else {
			// URL
			$domain = @parse_url( $var );
			$domain = linkex::get( 'host', $domain, 'unparseable' );
		}
		return $domain;
	} // }}}
		function gethostbyname( $dom, $force=false ) { // {{{
			$dom = strtolower( trim( $dom ) );

			$data = array();
			if ( 
				file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'ips' ) && 
				( $data = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'ips' ) ) &&
				( $data = linkex::unserialize( $data ) )
			) {
				if (
					( $force === false ) &&
					( $ipinfo = linkex::get( $dom, $data, false ) ) !== false &&
					( time() - linkex::get( 'date', $ipinfo, 0 ) ) < 3600 &&
					( $ip = linkex::get( 'ip', $ipinfo, false ) ) !== false &&
					preg_match( '/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $ip ) == 1
				) {
					unset( $data );
					return $ip;
				}
			}
			$ip = @gethostbyname( $dom );
			if ( $dom != $ip ) {
				$data{ $dom } = array( 'date' => time(), 'ip' => $ip );
				linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'ips', trim( serialize( $data ) ) );
				unset( $data );
			}
			return $ip;

		} // }}}
		function getLinks( $str, $baseurl ) { // {{{
			$thisdom = linkex::getDomain( $baseurl );
			preg_match_all( "'<\s*a.*>(.*)<\s*/\s*a\s*>'Umis", $str, $res );
			$links = array();
			for( $i=0; $i<sizeof( $res[0] ); $i++ ) {
				$buffer = array();
				$buffer{'raw'} = htmlentities( $res[0][$i] );
				$res[0][$i] = preg_replace( '#\s*=\s*#', '=', $res[0][$i] );
				$buffer{'href'} = linkex::getParam( 'href', $res[0][$i] );
				$buffer{'url'} = linkex::expandlink( $buffer{'href'}, $baseurl );
				$buffer{'domain'} = linkex::getDomain( $buffer{'url'} );
				$buffer{'external'} = ( $buffer{'domain'} == $thisdom ) ? 0:1;
				$rel = linkex::getParam( 'rel', $res[0][$i] );
				$buffer{'nofollow'} = ( strlen( $rel ) && ( strpos( strtolower( $rel ), 'nofollow' ) !== false ) ) ? 1:0;
				$buffer{'anchor'} = trim( $res[1][$i] );
				$links[] = $buffer;
			}
			unset( $res );
			return $links;
		} // }}}
	function getParam( $needle, $haystack, $default=null ) { /// {{{
			if ( ( $pos = strpos( strtolower( $haystack ), strtolower( $needle ) ) ) !== false ) {
				$pos += strlen( $needle ) + 1; /// +1 : "="
				if ( in_array( $haystack{$pos}, array( '"', "'" ) ) ) {
					$d=1;
					$end = array( $haystack{$pos} );
				} else {
					$d=0;
					$end = array( ' ', '>' );
				}
				$retval = '';
				for($i=$pos+$d;$i<strlen( $haystack ) && ( !in_array( $haystack{$i}, $end ) || ( in_array( $haystack{$i}, $end ) && $i>0 && $haystack{$i-1} == '\\' ) );$retval.=$haystack{$i}, $i++ ) {}
				foreach( $end AS $c ) { $retval = str_replace( '\\'.$c, $c, $retval ); }
				return $retval;
			} else {
				return $default;
			}
		} /// }}}
	function glob( $dir, $regex ) { // {{{
		$files = array();
		if ( $d = @opendir( $dir ) ) {
			while ( false !== ( $file = readdir( $d ) ) ) {
				if ( preg_match( '|' . $regex . '|i', $file ) ) {
					$files[] = $file;
				}
			}
		}
		return $files;
	} // }}}		
	function installed() { // {{{
		return (
			is_dir( BASEDIR . DIRECTORY_SEPARATOR .'data' ) &&
			is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR ) &&
			is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR ) &&
			is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR ) &&
			is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR ) &&
			is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR ) &&
			is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR )
		);
	} // }}}
	function listfiles( $dir, $ext=array() ) { // {{{
		$retval = array();
		if ( is_dir( $dir ) ) {
			if ( $dh = opendir( $dir ) ) {
				while ( ( $file = readdir( $dh ) ) !== false ) {
					if ( filetype( rtrim( $dir, DIRECTORY_SEPARATOR ) .DIRECTORY_SEPARATOR. $file ) == 'file' ) {
						$retval[] = $file;
					}
				}
			}
		}
		return $retval;
	} // }}}
	function log( $level, $type, $str ) { // {{{
		$file = BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'linkex.log';
		$log = sprintf( "[%s] [level=%d] [%s] %s\n", date( 'Y-m-d H:i:s' ), $level, $type, $str );
		if ( file_exists( $file ) && filesize( $file ) > 1048576 ) {
			@rename( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.4.log', BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.5.log' );
			@rename( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.3.log', BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.4.log' );
			@rename( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.2.log', BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.3.log' );
			@rename( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.1.log', BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.2.log' );
			@rename( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.log',   BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . '.linkex.1.log' );
		}
		$fp = fopen( $file, 'a' );
		flock( $fp, LOCK_EX );
		fwrite( $fp, $log );
		fclose( $fp );
	} // }}}
	function map( $fun, $arr ) { // {{{
		$retval = array();
		foreach( $arr AS $k=>$v ) {
			$retval[ $k ] = $fun( $v );
		}
		return $retval;
	} // }}}
	function mail( $to, $sub, $body ) { // {{{
		global $config;

		$headers = array();
		$headers[] = 'X-Mailer: LinkEX/20120508';
		if ( strlen( $config->email ) > 0 ) {
			$headers[] = sprintf( 'From: LinkEX @ %s <%s>', 
				linkex::get( 'HTTP_HOST', $_SERVER, linkex::getdomain( $config->url ) ), $config->email );
			$headers[] = sprintf( 'Reply-To: %s', trim( $config->email ) );
		}
		return mail( $to, $sub, $body, join( 
			str_replace( array( '\r', '\n' ), array( "\r", "\n" ), 
			$config->emailcrlf ), $headers 
		) );
	} // }}}
	function redirect( $url, $code=301 ) { // {{{
		$resp = array(
			301 => 'HTTP/1.1 301 Moved Permanently',
			404 => 'HTTP/1.1 404 Not Found'
		);
		if ( ( $resp = linkex::get( $code, $resp, false ) ) !== false ) {
			header( $resp );
		}
		header( 'location: '.$url );
		exit;
	} // }}}
		function selector( $name, $list, $selected=null, $multiple=true, $forcetype=null, $extra=null, $sep='<br />' ) { /// {{{

			$type = ( $multiple ) ? 'checkbox':'radio';
			$type = ( sizeof( $list ) > 5 ) ? 'select':$type;
			if ( $forcetype && in_array( $forcetype, array( 'checkbox', 'radio', 'select' ) ) ) {
				$type = $forcetype;
			}
			$extra['class'] = $type.' '.linkex::get( 'class', $extra, '' );
			if ( $extra ) {
				$buffer=array();
				foreach( $extra AS $k=>$v ) {
					$buffer[] = sprintf( '%s="%s"', $k, $v );
				}
				$extra=' '.join( ' ', $buffer );
			} else {
				$extra='';
			}
			$formname = ( $multiple ) ? $name.'[]' : $name;
			$buffer = '';
			if ( $type == 'select' ) {
				$buffer .= sprintf( '<select id="%s" name="%s" size="%d" %s%s>', $name, $formname, ($multiple)?4:1, ( $multiple ) ? 'multiple ':'', $extra );
			}
			foreach ( $list AS $id=>$txt ) {
				$ck = ( ( is_array( $selected ) && in_array( $id, $selected ) ) || ( is_string( $selected ) && $id==$selected ) );
				if ( $type == 'select' ) {
					$buffer .= sprintf( '<option value="%s" %s>%s</option>', $id, ($ck)?'selected="selected"':'', $txt );
				} elseif ( $type == 'checkbox' ) {
					$buffer .= sprintf( '<label><input type="checkbox" name="%s" value="%s"%s %s/> %s</label>%s',
						$formname, $id, ($ck)?' checked="checked"':'', $extra, $txt, $sep );
				} elseif ( $type == 'radio' ) {
					$buffer .= sprintf( '<label><input type="radio" name="%s" value="%s"%s %s/> %s</label>%s',
						$formname, $id, ($ck)?' checked="checked"':'', $extra, $txt, $sep );

				}
			}
			if ( $type == 'select' ) {
				$buffer .= '</select>';
			}
		
			return $buffer;
		} /// }}}
	function serialize( $val ) { // {{{
		return serialize( $val );
	} // }}}
	function sort( &$array, $field, $order='desc' ) { // {{{
		if ( $field == 'random' ) {
			shuffle( $array );
		} else {
			$GLOBALS['sortby'] = $field;

			usort( $array, array( 'linkex', 'usort' ) );

			if ( $order == 'desc' ) {
				$array = array_reverse( $array );
			}
		}
	} // }}}
	function stripcomments( $con ) { // {{{
		$con = preg_replace( '|<!--.*-->|Umis', '', $con );
		$con = preg_replace( '|<script.*<\s*/\s*script.*>|Umis', '', $con );
		$con = preg_replace( '|<style.*<\s*/\s*style.*>|Umis', '', $con );
		return $con;
	} // }}}
	function substr( $str, $len, $pad='..' ) { // {{{
		if ( strlen( $str ) > $len ) {
			return substr( $str, 0, $len - strlen( $pad ) ) . $pad;
		} else {
			return $str;
		}
	} // }}}
	function truncate( $str, $len, $txt='..' ) { // {{{
		if ( strlen( $str ) > ( $len-strlen( $txt ) ) ) {
			return substr( $str, 0, $len-strlen( $txt ) ).$txt;
		} else {
			return $str;
		}
	} // }}}
	function unserialize( $str ) { // {{{
		$retval = @unserialize( $str );
		if ( $retval !== false ) {
			return $retval;
		} else {
			// Attempt to fix it
			$str = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", trim( $str ) );
			$retval = @unserialize( $str );
			if ( $retval !== false ) {
				return $retval;
			} else {
				echo '[Fatal error in linkex::unserialize( "'. $str .'" )]';
			}
		}
	} // }}}
	function usort( $a, $b ) { // {{{
		if ( isset( $GLOBALS['sortby'] ) && strlen( $GLOBALS['sortby'] ) > 0 ) {
			$f = $GLOBALS['sortby'];
			if ( is_object( $a ) && isset( $a->$f ) ) {
				$aa = $a->$f;
			} else if ( is_array( $a ) && isset( $a[$f] ) ) {
				$aa = $a[$f];
			} else {
				$aa = $a;
			}
			if ( is_object( $b ) && isset( $b->$f ) ) {
				$bb = $b->$f;
			} else if ( is_array( $b ) && isset( $b[$f] ) ) {
				$bb = $b[$f];
			} else {
				$bb = $b;
			}

			switch( $f ) {
			case 'ldomip':
			case 'rdomip':
				$aa = sprintf( '%u', ip2long( $aa ) );
				$bb = sprintf( '%u', ip2long( $bb ) );
				break;
			case 'ldom':
			case 'rdom':
				$aa = str_replace( 'www.', '', strtolower( $aa ) );
				$bb = str_replace( 'www.', '', strtolower( $bb ) );
				break;
			case 'title':
			case 'link':
			case 'anchor':
				$aa = strtolower( $aa );
				$bb = strtolower( $bb );
				break;
			}

			if ($aa == $bb) {
				return 0;
			}
			return ($aa < $bb) ? -1 : 1;
		} else {
			return 0;
		}
	} // }}}
	function verifybacklinks( $ids=array(), $callback=null ) { // {{{
		global $config;
		$retval = array(
			'starttime' => time(),
			'links' => array(),
			'categories' => array()
		);
		foreach( $ids AS $id ) {
			$l = new link( $id, false );
			$l->updateIPs(true);
			$l->update();
			$buffer = array(
				'action' => 'link',
				'id' => $l->id,
				'rdom' => $l->rdom,
				'rdomip' => $l->rdomip,
				'rurl' => $l->rurl,
				'skipcheck' => $l->skipcheck,
				'skippagerank' => $l->skippagerank,
				'minpagerank' => ( $l->minpagerank != -1 ) ? $l->minpagerank : $config->minpagerank,
				'oldstatus' => $l->status,
				'oldpagerank' => $l->pagerank
			);
			if ( $l->skipcheck == 0 ) {
				$pr = $l->getRPageRank();
				$l->getLPageRank();
				$l->getRIndexedPages();
				$l->getLIndexedPages();
				$buffer{'res'} = $l->hasBacklink();
				$buffer{'code'} = ( !is_string( linkex::get( 'reason', $buffer{'res'}, null ) ) ) ? '200 OK' : $l->laststatus;
				if ( $l->status != 4 ) {
					$l->status = ( 
						( $pr >= ( ( $l->minpagerank != -1 ) ? $l->minpagerank : $config->minpagerank ) ) && 
						( linkex::get( 'res', $buffer{'res'}, -1 ) == 0 ) 
					) ? 1:2;
				}
				if ( intval( $config->disableblacklisted ) == 1 && ( ( $b = $l->blacklisted() ) !== false )) {
					$l->status = 2;
					$buffer{'res'} = 64;
					$buffer{'code'} = $b;
					$l->log[] = array( 
						'date' => time(),
						'res' => '64',
						'reason' => $b
					);
				}
			} else {
				$l->lastcheked = time();
				$l->log[] = array( 
					'date' => time(),
					'res' => '32',
					'reason' => ''
				);
			}
			$l->save( false );
			$buffer{'status'} = $l->status;
			$buffer{'pagerank'} = $l->getRPageRank(false);
			$retval{'links'}[] = $buffer;
			unset( $l );
			if ( $callback != null && function_exists( $callback ) ) {
				call_user_func( $callback, $buffer );
			}
			unset( $buffer );
		}
		// Rebuild categories
		$categories = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR );
		foreach( $categories AS $cid ) {
			$c = new category( $cid );
			$c->generate();
			$buffer = array(
				'action' => 'category',
				'id' => $cid,
				'name' => $c->name
			);
			$retval{'categories'}[] = $buffer;
			unset( $c );
			if ( $callback != null && function_exists( $callback ) ) {
				call_user_func( $callback, $buffer );
			}
			unset( $buffer );
		}
		
		$retval{'endtime'} = time();
		return $retval;
	} // }}}
	function sum( $array = array() ) { // {{{
		$retval = 0;
		foreach( $array AS $a ) {
			$retval += $a;
		}
		return $retval;
	} // }}}
	function yesno( $val ) { // {{{
		return ( $val ) ? 'Yes':'No';
	} // }}}
}

class template {
	function about() { // {{{
		global $config;
		if ( LOGGEDIN ) {
			$phpver = phpversion();
			$umask = sprintf( "%04o", umask() );
			$zendver = zend_version();
			$uname = php_uname( "s" )." ".php_uname( "r" )." ".php_uname( "m" );
			$du = round( linkex::du( BASEDIR . DIRECTORY_SEPARATOR . 'data' ) / 1024, 2 ).'KB';
			$links = sizeof( linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR ) );
			$installdate = date( $config->dateformat, $config->installdate );
			$precision = ini_get( 'precision' );
			$PHP_INT_SIZE = defined( 'PHP_INT_SIZE' ) ? PHP_INT_SIZE : '-';
			$PHP_INT_MAX = defined( 'PHP_INT_MAX' ) ? PHP_INT_MAX : '-';
			if ( function_exists( 'gd_info' ) ) {
				$gd = gd_info();
				$gd = sprintf( '%s - GIF Support: %s',
					$gd{'GD Version'},
					( ( $gd{'GIF Create Support'} ) ? 'enabled':'unsupported, using plain text for CAPTCHA if used' )
				);
			} else {
				$gd = 'Not installed, using plain text for CAPTCHA if used.';
			}

			echo "<div style=\"margin:10px auto;\">
	<fieldset>
		<legend>Server info</legend>
		<table class=\"table\">
			<tr>
				<td class=\"key\">PHP version:</td>
				<td>{$phpver}</td>
			</tr>
			<tr>
				<td class=\"key\">Zend version:</td>
				<td>{$zendver}</td>
			</tr>
			<tr>
				<td class=\"key\">GD Info:</td>
				<td>{$gd}</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Server OS:</td>
				<td>{$uname}</td>
			</tr>
			<tr>
				<td class=\"key\">php.precision</td>
				<td>{$precision}</td>
			</tr>
			<tr>
				<td class=\"key\">PHP_INT_SIZE</td>
				<td>{$PHP_INT_SIZE}</td>
			</tr>
			<tr>
				<td class=\"key\">PHP_INT_MAX</td>
				<td>{$PHP_INT_MAX}</td>
			</tr>
			<tr>
				<td class=\"key\">umask</td>
				<td>{$umask}</td>
			</tr>
		</table>
	</fieldset>
</div>
<div style=\"margin:10px auto;\">
	<fieldset>
		<legend>LinkEX info</legend>
		<table class=\"table\">
			<tr>
				<td class=\"key\">LinkEX version:</td>
				<td>20120508</td>
			</tr>
			<tr>
				<td class=\"key\">Current version:</td>
				<td id=\"currentversion\">stand by..</td>
			</tr>
			<tr>
				<td class=\"key\"></td>
				<td id=\"upgradeadvised\"></td>
			</tr>
			<tr>
				<td class=\"key\">Database size:</td>
				<td>{$du}</td>
			</tr>
			<tr>
				<td class=\"key\">Links:</td>
				<td>{$links}</td>
			</tr>
			<tr>
				<td class=\"key\">Install date:</td>
				<td>{$installdate}</td>
			</tr>
		</table>
	</fieldset>
</div>

<div style=\"margin:10px auto;\" id=\"changelog\">
	<fieldset class=\"expandable hidden\" id=\"fschangelog\">
		<legend>LinkEX info</legend>
		<div class=\"contractor\">
			<div id=\"changelogitems\"></div>
		</div>
	</fieldset>
</div>

<script type=\"text/javascript\">
			/*<![CDATA[*/
			$(document).ready(function(){ $(\"#changelog\").hide(); var url = location.href.replace( /\?.*/, '' )+'?page=rss&view=changelog'; $.get( url,
			function(xml){ var upgradeurl=location.href.replace(/\?.*/, '')+'?page=admin&view=upgrade'; var release=$(\"channel\", xml).attr(\"release\"); $(\"#currentversion\").html(release+'&nbsp;(<a href=\"'+upgradeurl+'\">Force upgrade</a>)'); if(release > 20120508){ $(\"#upgradeadvised\").html('A newer version is available. You are advised to <a href=\"'+upgradeurl+'\">upgrade</a>.<br />Check out the changes below, before upgrading.'); $(\"div#changelog div.contractor\").hide(); $(\"div#changelog\").show().find(\"legend:first\").html(\"Changelog 20120508 &raquo; \"+release); var url=location.href.replace(/\?.*/, '')+'?page=rss&view=changelog'; $.get(url,
			function(xml){ var html=''; var items=$(\"item\", xml); $(items).each(function(){ var title=$(this).find(\"title:first\").text(); var link=$(this).find(\"link:first\").text(); var pubDate=$(this).find(\"pubDate:first\").text(); var description=$(this).find(\"description:first\").text(); html +='<div class=\"item\"><div class=\"meta\"><div class=\"title\"><a target=\"_blank\" href=\"'+link+'\">'+ title+'</a></div>Posted on '+pubDate+'</div><div class=\"contents\">'+description+'</div></div>'; }); $(\"div#changelogitems\").html(html); }); } }); });
			/*]]>*/
		</script>

";
		} else {
			echo "<fieldset style=\"margin:10px auto;\">
	<legend>Powered by <a href=\"http://linkex.dk/\" title=\"LinkEX\">LinkEX</a></legend>
	<div class=\"article\">
		This site is powered by LinkEX, a free script that will take care of accepting link exchange requests, 
		and, if needed, making sure a link back is present.<br />
		<br />
		If you run a website, you can have this script also. Head over to <a href=\"http://linkex.dk\">linkex.dk</a>, 
		and get your free copy.<br />
		<br />
		<div class=\"bold underline\">Features</div>
		<ul>
			<li>Free! This script is free. No hidden fees, no nothing.</li>
			<li>Easy to install - upload 1 (one) file, fill out the basic settings, and you are good to go.</li>
			<li>One click updates. Update the script, just by a single click. The script will fetch the latest release, install it, making sure you are up to date at all times.</li>
			<li>Advancend link robot. You choose what sites to check for backlinks, and the bot will make sure the link is present.</li>
			<li>Google PageRank&trade; check. The script will show you the PageRank&trade; of all your link partners.</li>
			<li>And much much more..</li>
		</ul>
		Head over to <a href=\"http://linkex.dk\">linkex.dk</a> to read more
	</div>
</fieldset>
";
		}
	} // }}}
	function footer() { // {{{
		$params = array(
			'BASEURI' => BASEURI
		);
		return "			</div>
			<div id=\"footer\">
				v.20120508 &copy; <a href=\"http://linkex.dk/\" title=\"Free link exchange script\">linkex.dk</a> 2006-2011
			</div>
		</div>
	</body>
</html>
";
	} // }}}
	function header( $params = array() ) { // {{{
		global $errors, $config;
		$params = array_merge( 
			array(
				'BASEURI' => BASEURI,
				'menu' => Template::menu(),
				'title' => '',
				'onload' => '',
				'metadescription' => ''
			),
			$params
		);
		if ( isset( $params{'metarobots'} ) && strpos( $params{'metarobots'}, '<' ) === false ) {
			$params{'metarobots'} = sprintf( '<META NAME="ROBOTS" CONTENT="%s">', strtoupper( $params{'metarobots'} ) );
		} else {
			$params{'metarobots'} = '';
		}
		$error = '';
		$charset = isset( $config->charset ) ? $config->charset : 'utf-8';
		if ( linkex::get( 'noerrors', $params, true ) && sizeof( $errors ) > 0 ) {
			$error = join( '<br />', $errors );
			$error = "<div style=\"margin:10px 0px;\">
	<fieldset class=\"error\">
		<legend>Error</legend>
		<div class=\"article\">
			{$error}
		</div>
	</fieldset>
</div>
";
		}
		return "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
	<head>
		<meta http-equiv=\"Content-Type\" content=\"text/html;charset={$charset}\" />
		<title>LinkEX &raquo; {$params{'title'}}</title>
		<link type=\"text/css\" rel=\"stylesheet\" href=\"{$params{'BASEURI'}}?page=file&view=css&rand=1336468109\" />
		<script type=\"text/javascript\" src=\"{$params{'BASEURI'}}?page=file&view=js&rand=1336468109\"></script>
		<meta name=\"description\" content=\"{$params{'metadescription'}}\" />
		{$params{'metarobots'}}
	</head>
	<body>
		<div id=\"wrapper\">
			<div id=\"topbar\">
				&nbsp;
			</div>
			<div id=\"header\">
				<h1><a href=\"http://linkex.dk\" title=\"Powered by LinkEX\">Link<span style=\"color:#B91450;\">EX</span></a></h1>
			</div>

			<div id=\"navbar\">
				<ul id=\"navlist\">
					{$params{'menu'}}
				</ul>
			</div>
			<div style=\"clear:both;\"></div>

			<div id=\"contents\">

				{$error}
";
	} // }}}
	function linkdetails() { // {{{
		global $config;

		$url = $config->url;
		$anchor = $config->anchor;
		$anchor = $anchor[ mt_rand( 0, sizeof( $anchor )-1 ) ];
		$title = $config->title;
		$title = $title[ mt_rand( 0, sizeof( $title )-1 ) ];
		$description = $config->description;

		$htmlcode = str_replace(
			array( '{$URL}', '{$ANCHOR}', '{$DESCRIPTION}', '{$TITLE}' ),
			array( 
				htmlentities( $url ), 
				htmlentities( $anchor ), 
				htmlentities( $description ),
				htmlentities( $title )
			),
			$config->htmlcode
		);

		// {{{ Show the email
		if ( intval( $config->showemail ) == 1 ) {
			$email = "			<tr>
				<td class=\"key\">Email:</td>
				<td>{$config->email}</td>
			</tr>
";
		} else {
			$email = '';
		}
		// }}}
		return "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Our linking details</legend>
		<table class=\"table\">
{$email}
			<tr>
				<td class=\"key\">URL:</td>
				<td style=\"width:480px;\">{$url}</td>
			</tr>
			<tr>
				<td class=\"key\">Site title:</td>
				<td>{$anchor}</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Site description:</td>
				<td>{$description}</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">HTML code:</td>
				<td></td>
			</tr>
			<tr valign=\"top\">
				<td colspan=\"2\" class=\"center pre\">{$htmlcode}</td>
			</tr>
		</table>
	</fieldset>
</div>
";
	} // }}}
	function linkform() { // {{{
		global $config;

		$_POST['email']				= htmlentities( linkex::get( 'email', $_POST, ( (LOGGEDIN)?$config->email:'') ) );
		$_POST['lurl']				= htmlentities( linkex::get( 'lurl', $_POST, '' ) );
		$_POST['rurl']				= htmlentities( linkex::get( 'rurl', $_POST, '' ) );
		$_POST['anchor']			= htmlentities( linkex::get( 'anchor', $_POST, '' ) );
		$_POST['description'] = htmlentities( linkex::get( 'description', $_POST, '' ) );

		// {{{ Show the recip field if public or loggedin
		if ( intval( $config->disablerecipfield ) == 0 || intval( $config->samedomain ) == 2 ) {
			$extra='';
			switch( intval( $config->samedomain ) ) {
			case 1: $extra = 'Must be on the same domain as above'; break;
			case 2: $extra = 'Must be on a different domain as above'; break;
			}
			$recipfield = "				<tr>
					<td class=\"key\">Reciprocal link URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"rurl\" value=\"{$_POST['rurl']}\" /> {$extra}</td>
					<td class=\"help\"></td>
				</tr>

";
		} else {
			$recipfield = '';
		}
		// }}}
		// {{{ Show the categories if loggedin or public
		if ( ( $cat = linkex::get( 'categories', $_REQUEST, false ) ) !== false ) {
			if ( !is_array( $cat ) ) {
				$cat = linkex::map( 'trim', explode( ',', $cat ) );
			}
		} else {
			$cat = $config->defaultcategories;
		}
		if ( intval( $config->publiccategories ) == 1 || LOGGEDIN ) {
			$categories = linkex::categories( LOGGEDIN );
			$cats = array();
			foreach( $categories AS $cid=>$name ) {
				$cats[] = new Category( $cid );
			}
			$categories = $cats;
			unset( $cats );
			linkex::sort( $categories, 'name', 'asc' );
			$cats = array();
			foreach( $categories AS $c ) {
				$cats{ $c->id } = $c->name;
			}
			$categories = $cats;
			unset( $cats );

			$categories = linkex::selector( 'categories', $categories, 
				linkex::get( 'categories', $_POST, $cat ), LOGGEDIN, null, array( 'style' => 'width:auto;max-width:300px;' ) );
			$categories = "				<tr valign=\"top\">
					<td class=\"key\">Category:</td>
					<td>{$categories}</td>
					<td class=\"help\"></td>
				</tr>

";
		} else {
			$categories = '';
		} 
		// }}}
		// {{{ CAPTCHA html tag put into => $captcha (the class will know weathe to use img or html
		if ( intval( $config->usecaptcha ) == 1 && !LOGGEDIN ) {
			$c = new captcha;
			$captchatag = $c->html(); 
			$captcha = "				<tr>
					<td class=\"key\">Spam check:</td>
					<td>
						<table cellpadding=\"0\" cellspacing=\"0\">
							<tr>
								<td style=\"width:100px;\">{$captchatag}</td>
								<td><input type=\"text\" name=\"captcha\" value=\"\" class=\"text\" style=\"width:50px;\" /></td>
							</tr>
						</table>
					</td>
					<td class=\"help\"></td>
				</tr>

";
		} else {
			$captcha = '';
		}
		// }}}

		if ( LOGGEDIN ) {
			$skipbacklinkcheck = linkex::checkbox( linkex::get( 'skipbacklinkcheck', $_POST, 0 ) );
			$skippagerank = linkex::checkbox( linkex::get( 'skippagerank', $_POST, 0 ) );
			$skipblacklist = linkex::checkbox( linkex::get( 'skipblacklist', $_POST, 0 ) );
			$skiplengths = linkex::checkbox( linkex::get( 'skiplengths', $_POST, 0 ) );
			$skipdupes = linkex::checkbox( linkex::get( 'skipdupes', $_POST, 0 ) );
			$adminoptions = "				<tr>
					<td class=\"key\"></td>
					<td colspan=\"3\"><br />Since you are logged in, you have additional options:</td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skipbacklinkcheck\" value=\"1\" {$skipbacklinkcheck} /> Ignore missing backlink.</label></td>
					<td></td>
				</tr>				
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skippagerank\" value=\"1\" {$skippagerank} /> Ignore PageRank&trade;.</label></td>
					<td></td>
				</tr>				
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skipblacklist\" value=\"1\" {$skipblacklist} /> Ignore blacklist.</label></td>
					<td></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skiplengths\" value=\"1\" {$skiplengths} /> Ignore max. length on title and description.</label></td>
					<td></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skipdupes\" value=\"1\" {$skipdupes} /> Ignore dublicate domains/IPs.</label></td>
					<td></td>
				</tr>
";
		} else {
			$adminoptions = '';
		}

		// Lengths
		$anchorlength = ( $config->anchorlength > 0 ) ? 
			( 'max. '.$config->anchorlength.' '.(( $config->anchorlengthtype == 'w' )?'words':'characters' )) : '';
		$titlelength = ( $config->titlelength > 0 ) ? 
			( 'max. '.$config->titlelength.' '.(( $config->titlelengthtype == 'w' )?'words':'characters' )) : '';
		$descriptionlength = ( $config->descriptionlength > 0 ) ? 
			( 'max. '.$config->descriptionlength.' '.(( $config->descriptionlengthtype == 'w' )?'words':'characters' )) : '';

		return "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Your linking details</legend>
		<form method=\"post\" action=\"$URI\">
			<table class=\"table\">
				<tr>
					<td class=\"key\">Site title:</td>
					<td><input type=\"text\" class=\"text\" name=\"anchor\" value=\"{$_POST['anchor']}\" /> {$titlelength}</td>
				</tr>
				<tr>
					<td class=\"key\">Your URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"lurl\" value=\"{$_POST['lurl']}\" /></td>
				</tr>
{$recipfield}
				<tr>
					<td class=\"key\">Your email:</td>
					<td><input type=\"text\" class=\"text\" name=\"email\" value=\"{$_POST['email']}\" /></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Site description:</td>
					<td><textarea cols=\"80\" rows=\"3\" class=\"text\" name=\"description\">{$_POST['description']}</textarea> {$descriptionlength}</td>
				</tr>
{$captcha}
{$categories}
{$adminoptions}
				<tr>
					<td class=\"key\"></td>
					<td><br /><input type=\"submit\" class=\"button\" value=\"Add my link\" /></td>
					<td class=\"help\"></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>
";
	} // }}}
	function menu() { // {{{
		if ( linkex::installed() ) {
			if ( defined( 'LOGGEDIN' ) && LOGGEDIN ) {
				$URI = BASEURI;
				$menu = "				<li><a href=\"{$URI}\" title=\"Add link\">&raquo; Add link</a></li>
				<li><a href=\"{$URI}?page=admin\" title=\"Home\">&raquo; Home</a></li>
				<li><a href=\"{$URI}?page=admin&amp;view=tools\" title=\"Tools\">&raquo; Tools</a></li>
				<li><a href=\"{$URI}?page=admin&amp;view=categories\" title=\"Categories\">&raquo; Categories</a></li>
				<li><a href=\"{$URI}?page=admin&amp;view=blacklist\" title=\"Blacklist\">&raquo; Blacklist</a></li>
				<li><a href=\"{$URI}?page=admin&amp;view=settings\" title=\"Settings\">&raquo; Settings</a></li>
				<li><a href=\"{$URI}?page=logout\" title=\"Log out\">&raquo; Log out</a></li>
				<li><a href=\"{$URI}?page=about\" title=\"About LinkEX\">&raquo; About</a></li>
";
			} else {
				$menu = "				<li><a href=\"$URI\" title=\"Add link\">&raquo; Add link</a></li>
				<li><a href=\"$URI?page=admin\" title=\"Admin\">&raquo; Admin</a></li>
				<li><a href=\"$URI?page=about\" title=\"About LinkEX\">&raquo; About</a></li>
				
";
			}
		} else {
			$menu = '&nbsp;';
		}
		return $menu;
	} // }}}
	function navigation( $start, $pages, $uri ) { // {{{
		$retval = '';
		if ( $pages > 1 ) {
			if ( $start > 1 ) {
				$retval .= "<a href=\"".$uri."start=".($start-1)."\">&laquo; prev</a>";
			} else {
				$retval .= "<span>&laquo; prev</span>";
			}
			for( $i=1; $i<=$pages; $i++ ) {
				$retval .= "&nbsp;";
				if ( $i == $start ) {
					$retval .= '<span><strong>'. $i .'</strong></span>';
				} else {
					$retval .= "<a href=\"".$uri."start=".$i."\">".$i."</a>";
				}
			}
			$retval .= "&nbsp;";
			if ( $start < $pages ) {
				$retval .= "<a href=\"".$uri."start=".($start+1)."\">next &raquo;</a>";
			} else {
				$retval .= "<span>next &raquo;</span>";
			}
		}
		return $retval;
	} // }}}
	function pagerank( $pr ) { // {{{
		$pr = max( min( intval( $pr ), 10 ), 0 );
		$perc = $pr * 10;
		return "<table class=\"pagerank\">
	<tr>
		<td>
			<div class=\"pagerank\">
				<div class=\"bar\" style=\"width:{$perc}%\">&nbsp;</div>
			</div>
		</td>
		<td class=\"value\">{$pr}</td>
	</tr>
</table>
";

	} // }}}
	function progress( $progress ) { // {{{
		echo "<script type=\"text/javascript\">
			/*<![CDATA[*/
			_p('{$progress}');
			/*]]>*/
		</script>
";
		linkex::flush();
	} // }}}
	function report( $report ) { // {{{
		$startdate = date( 'Y-m-d H:i:s', $report{'starttime'} );
		$enddate = date( 'Y-m-d H:i:s', $report{'endtime'} );
		$elapsed = linkex::elapsed( $report{'endtime'} - $report{'starttime'} );
		$elapsed = $elapsed{'nice'};

		$sp = "% 6s  % -20s % -15s % 6s => % -10s % 10s => % -10s\n";
		$links = sprintf( $sp, 'ID', 'Domain', 'IP', 'Old PR', 'New PR', 'Old Status', 'New status' ) .
			"==========================================================================================\n";
		foreach( $report{'links'} AS $data ) {
			$links .= sprintf( $sp, $data{'id'}, linkex::truncate( $data{'rdom'}, 20 ),
				$data{'rdomip'},
				$data{'oldpagerank'}, $data{'pagerank'}, 
				link::statusOptions( $data{'oldstatus'} ), 
				link::statusOptions( $data{'status'} ) );
		}

		$sp = "% 6s   % -20s % -10s\n";
		$categories = sprintf( $sp, 'ID', 'Name', 'Status' ) .
			"==========================================================================================\n";
		foreach( $report{'categories'} AS $data ) {
			$categories .= sprintf( $sp, $data{'id'}, linkex::truncate( $data{'name'}, 20 ), 'done' );
		}

		return "LinkEX verification output.
===========================

verification started on: {$startdate}
verification ended on:   {$enddate}
verification elapsed:    {$elapsed}

* Verifying backlinks..

{$links}

* Rebuilding categories..

{$categories}

";
	} // }}}
	function rules() { // {{{
		global $config;
		$linkback = ( intval( $config->linkbackrequired ) == 1 ) ? 'R'.'equired':'Not r'.'equired';
		$rules = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'rules', "We are constantly looking for new perm link exchanges to improve link popularity and page rank.<br />
Please remember that this is not about traffic, it's about the link.<br />
Play fair!
" );
		$maxoutboundlinks = ( $config->maxoutboundlinks>0 ) ? "			<tr>
				<td class=\"key\">Max. links:</td>
				<td>{$config->maxoutboundlinks} external links on reciprocal link URL</td>
			</tr>

" : '';
		return "<div style=\"margin:10px auto;\">
	<fieldset>
		<legend>Rules</legend>
		<table class=\"table\">
			<tr>
				<td colspan=\"2\">
					<div class=\"article\">
						{$rules}
					</div>
				</td>
			</tr>
			<tr>
				<td class=\"key\">Linkback:</td>
				<td>{$linkback}</td>
			</tr>
			<tr>
				<td class=\"key\">Min. PageRank&trade;:</td>
				<td><div class=\"pagerank pr{$config->minpagerank}\"></div></td>
			</tr>
			{$maxoutboundlinks}
		</table>
	</fieldset>
</div>
";
	} // }}}
}

if ( linkex::get( 'page', $_REQUEST ) == 'file' ) {
	switch( linkex::get( 'view', $_REQUEST ) ) {
	case 'sprite':
		$image = base64_decode('R0lGODlhNwD9AOZ/AP///6qqql6qXsVvCJGw0q7H49HR0b6+vpWVlfTZWIWFhQAAANra2vKIdpXIhkycKbHbpvvx0d7e3nO1auHh4c3NzV+Jt2qWw+3t7enp6eN7dtbW1vOzrHPGZih+JE9wqDCGDvDw8IO4aFCzLulbUO7Msz2GN1WW0HaizvXNyfalne3JdcnJyUBalHl5eaOjo4bGdfaWh9Hc6KXWmdaiPanKktjq1O/QjP366slmU8PDw91tZ+Tk5Oj25O1rXGykOpSVorfcsUyXQ53Sk2vGTOi5Q222VmVlZVmgQ1tbW57Imvn5+dvg5/778uGqMPno5Pbkt/nolHO7W+Ts9dabUvH47+rw9t2xR8LlukeQGZG8jdqbJf39/WSlR6HHis+FG4vIgcNSOcLM2thcUPb4+uXp72GeMenBXqTA3vz8++Dm6/P09pjOjeHv3/3+/bCwsFy+PH+xWP/+/P7//79bQMTT4t+om5273GGvVK7Nlfj79nSrT/z9/kGCwFmlT////yH5BAEAAH8ALAAAAAA3AP0AAAf/gAGCg4SFhoeIiH+LjI1/AQCRkpOUlZaXlQGOm5CYnp+fmosLC5ygp6iSoqV/rIydqbGYq6OOsLK4k7Sttrm+qoyknInExcaim6/Hy8zIyY+/v87JkALWAtGpq66N1dfZqMjcrwDX2OCg4tTl3+ihwevu2qPCts33xM/K+PyF+ou35L37582cNYGUto2DZrAdwkjTxhU0+BAYPVMND1YEsMvUxln06u3rR/LfI5IoTQb8qEslu4wO3SnECDMmuoi9atoEJ27hRJgIcXZjeWmmPZT9VCJNSpCopWk0dZq7WcvnS6kas9GyinUqz6pRu1JtRUqi00yNfC7lp3TtPZdn/1s27ZpRWkizdBva5bUuL0VfRof69ZpLKLm4FssOc9usLeNlcBFzdDm4bqyeYStnDVerr2bCnMly/bxzICuzkidfPPr4mOPWxSIjhpqTtN50d2vbBg0yre7dm3t3Fgy8NNrhQ1OrWww7NsHmxmTHpU28+N+nwUZb5y339O/t57Cvrg4+/HHvySVjZg1d0fP2iaSfpU6uvGWLZDPbN68aff39vPWEF4A2GQZQaqrlxx58/rzHoCHyOUXfgQTWtc14P1WIjTroZVhhgqV0eJWGG8IjonIhKXjSgxCa5OKLMMYo44w01mjjjTjmqOOOPPbo448yAiHkkEAAOSMQlhRpJP+MQHDh5AJOkqHkki4CscQSZCxAxhplTEnlP0BkWdYCanj55TNhrhHCAlaUwYSZZ24CRBlqMLEAEzLIAGecjQAhQx1iBBronnwyQuSQhSaq6KKMNuroo5BGiuahhCaKZCWV8tmkk5xKCamVWJKxZZefillWmaWqGUKbb35KJxOw5plpnH4CKqgYs9JKqaS89urrr8AGK+ywxM4YwrHIJqvsssw26+yzIWAg7bTUVmvttdhmi2202nbr7bfZZiDuuOSWa+656KaLLgbqtuvuu+nyIO+89NZr77345ptvBvr26++/+VIg8MAEF2zwwQgnnDAPFEjg8MMQRyzxxBRXTHH/wxZnrPHGFDPg8ccghyzyyCSXXLIEJqes8somb+DyyzDHLPPMNNdMMwM256zzzjYb4PPPQAct9NBEF030BkYnrfTSRlfg9NNQRy311FRXTbUBVmet9dZXV8DC12CHLfbYZJdtdtlOn6322myTXUGxcMct99x01z1jDxAQAQccRMzQwzNPcKDBDjtowMETz1hRAAonNI7GFDBiQYQUM0AAwQxGjIDFJiloEEMKoHNAeAqbyHACCmgUUMAdF/RRh4tYwAFGEEPAAMMQQcDwQBCNpLDD4RyoEIMKnedAOiOmE7A6ASgoT8AHr+vTAxGzd2D99bk/0MYiT2igwhMxxNBA//gNiJ4D4n9YcYLyKKBQABrto/E85M9AIEUQ11+PBQxBdOHAIhxoQArI14ACNsAHHAiDHRZRgAssrn2iah/qLEAAffRtCPnrABYA0AM2sEEIizCcChpAghKa0Acx0EAOFnGCOzAvfmi4gAwJcIcP6GMEEIBBB4JgAw0CIA1s6AAEPLCI34mvEiTwgQrCsIg+PFCGAJiDDGVYgBbcMIcwqAIAtAhEKYhgiEUcYQOQqEQm/sGJKJiiDMggQws40IrPgMMQMJhFALjBAUaQggMcYIIQjs8HJgxkA1TIQheqkQwWSGTzbPiMIeABAh2QAgxswAYj5BECQtACAMegAh8AMv+QJFjiAv9wBwvE0IF8mIMMEvm8Cj6jDQ+Agf2kYMlLisAE2/vDEwinAlCGcgx0QN8UPoAC1iXymMxrQRn+EQQQfJENIhCBAyAgAg/wjhEpyMEORgjIBqhgDGEoQSPE0IJioiCRF0imGFwUBBMgwQEzmIEDhGBNzuUgDJ5LYRjoIE5HiOEDFESD/D7QgnW+qA1aMIEHPGACLeRyE0+wQw7oEIYc2AF9myjD81rQgg8QYJl2C6lIR3qjJejgBW94AQ/WgNIX6GAJjEpDAF6AAR5U4AUBoAAPDIDTNKTFFYrxkQ4QQAEEHMEFL0CAC46AgKGyAB588c+OEIAABiwhCSz/YEAFDpCEJTCAqtmpR1B79AYFfDUJSTjCEdBaVQW8AaroWQiOJOCCABzgAAFQAALsilcXSACuKfIRF+iqgMJmtbAK8CsXSMrYkZq0pStt6UtjOtOa3jSnO+3pT8O6WRwNtahHTepSm4qAp3YmrqfFEVWtilWtctWrYM2NaKCao7KeNa1rTUJb35raqPbWRnTla173etcA+BWws81OjgbrAsQetrCKbax06/bYlEY2pZNdlExpalOc6pSnAfCpcgM7nrHC6LNGRapSmepU5KLWt3yB0WqvmtWtdvWrCAjraUQyDqm6yLYIQKta2coAt7q3t++FUXCLq1fhHhfBIlGR/3lfxFznFhi6EljsdDfM4RfJ4QwrkIOvbkBiKORICUrYUROK0IQIsPhGSpiAADSZoxXcoAk4IHGN3BBjD87YDTdysRyiEAUcOCECNAqCCCYwRxmn2EZngAIOaECDCNzgDDbCwwyGgAQcQSHECaByAnAQ5RppeQh+uNGKI4CDMNMgARGAAg2aQCMmz2ACT6aRjXEQhQRc4c1jXsEKaOTBIbABzzQycosTwOgzMLrIX8Bo5GAQz0MjQQiYNoGmTXKGG/CZ0WJmdARWQIUZVYEN8JyjBx0ABjDAoI/6gMIZmgAFRtv61jigQj9j1AY2wCDVq241rJ9RBCg04djIPjYOltbdhBJ8gUZVwIID8IAHP/jh0kIYdjJW4AQnbOHb3/6CuAdA7gGUusPoTre64/QAM5jhBz/oVRZqkIc8xJtXWfCCCOzdKxDouwZmkBQIQGCGf8cB3o/SAwjeKYI4iKAGcQj4o9oAAv+JwAt7eIAeImWDijugC1nYuKQ6jgQQiJxXHa/CulfO8pb/oQogsIGvFF5ymUtKD1nwXxdiHik9PGAP+v44CB7aKDPEoQYNl2bJT84oeB/94mYYuKTMgHQvgKBXP8jDxbOA9XrXgOu8gre7H+Dy6QYCADs=');

		$etag = md5("sprite1336468109");
		header( 'Last-Modified: Tue, 08 May 2012 09:08:29 GMT');
		header( 'Expires: Wed, 08 May 2013 09:08:29 GMT');
		header( 'Cache-Control: must-revalidate' );
		header( 'Etag: ' . $etag );
		header('Content-type: image/gif');
		header('Content-Length: ' . strlen( $image ) );
		if (
			( false !== ( $ifmod = linkex::get( 'HTTP_IF_MODIFIED_SINCE', $_SERVER, false ) ) && strtotime( $ifmod ) == 1336468109 ) ||
			( false !== ( $ifnm  = linkex::get( 'HTTP_IF_NONE_MATCH', $_SERVER, false ) ) && trim( $ifnm ) == $etag )
		) {
			header( linkex::get( 'SERVER_PROTOCOL', $_SERVER, 'HTTP/1.1' ) .' 304 Not Modified', 304, true );
			exit;
		}
		echo $image;
		exit;
		break;
	case 'nsprite':
		$image = base64_decode('iVBORw0KGgoAAAANSUhEUgAAABwAAABkCAMAAACioqAKAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAYBQTFRF9Iki6Ioy8Muk6pZL55hX98aZ/PTr3G9E8owx/vz6yVsT+50524NG6bqW64Et6Klt7Hoi8owe9dvE5HEh5Gwi5KN26n0s6J5r9ZE0+caQ43Ip959H8oQi+pEhvU4F9ZpG5rOM4npF55I5+54944Ed21wj1ntA8MOn9Na78pVF23sr6otL9KJT25hq7IUc3nkcwVIK3lwX859N8ptR7sKZ7Mu0/O3dzWYj21YO+pMq+uXT9Yca64Mi6XQi+qhR++7l+pk06bB4/fn13WMi7YpFzHM4+I0i8Muv34xU8tK06IRI+Z9Az2gm+s+i++jU+Iwc5H0s220g8qNc84wp44tE+po45YBH4Wgi95Y27a6I+dq86IdK4WUi+5885IxN9dm8+J0+4m4n428w64kg/fbv+pAe0msox00S3E0Azl8Y53cq43M2738i9+XT7pBL3KR/4Yw274Uv8q9q338f54Ye5YUx9Zo+78+395c81GEe98OK7osq+KZT9pIn////////3lmFOwAAAIB0Uk5T/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wA4BUtnAAAC4klEQVR42uzT2VMaMQAG8MiCLkWQ5S6HyKUglxVLS7kFFkSBohyriALeiFQKam1t+NebLNgqO9O+9JHvYYed3yT5NiQgep1495xWdPgq4DrxqFQftVU9UhMItCbwY2IZomwZmbIodjmJ1XmlcskOYU5UF3Gwqc2UZm7jeZizlDmonYdQ9tVM3MAGzcF2ScyD8PuADwV6DkrIHwNCBl39DdjhoidIDW7hQT8Ouxz08mCO6qfhnRLyuTgLIWUVwyM13OegFY0EIYIvN2Vsk9jyUADoO2F5NWGzTW5ftHX5O5yNH/4lYAjTmXM2O+N8YJNaig4BvHqsVLLZWs3pdHa7XcLn8627XE9Pu5kdGVh5rLSaTa223W6rVJJejyQ1Ggb9ffUI3w3msTVfGsPEyiKRaHs9Ba4qzWZRubKvLr22ej2yBq6y2ub5e3QWhDcbvpc2Ri2LODKXhimPzGLBWGtriw9jhJuC+2dj0Ym6lPhqsWyT5XxkbJYnFlWop6R3x+edYvVHsDXKjA5hV6X6zFcTJEnOEFtYo5FYLGCggXGEq1tQ6BesM4x5g535J03TYIQSySpb6DTX+HmyIES/3mLTOxASvd6qbNTVv00N4rizDhnGN74eORNP3whZbVBWvO4Bsk53ESGpIfc8HjNvtNzJLe7s03ekLGr2gsFCYTQhOk5WXErQkUqTCF1BHAopW0YXKqHd+CSVhjEag0GPOQ9nI9QAzywIedGVEybD8izCb4Wg9Rh/ieHEjMb4Q94l9KaWKyoI7wuUNYqXM4A++iShw+tGL/uKKsbGGTWw45E0xXbZlWfQc6V6aEK4fXZGmY9n8080CC3I7HYivPyQTqsPbSwaDAaaovB26kNSlLBcUU2g4z+3CJbvAwbM2PSdDmuKQ2S2uRQQF+uBCauO7OILGLqLDp1OZzQ6HI5uMlnLViom0xzKhTuK7oo4tfacxT9Jif95kaY4xSlOcYpT/H/4S4ABAHTig17AByqnAAAAAElFTkSuQmCC');
	
		$etag = md5("sprite1336468109");
		header( 'Last-Modified: Tue, 08 May 2012 09:08:29 GMT');
		header( 'Expires: Wed, 08 May 2013 09:08:29 GMT');
		header( 'Cache-Control: must-revalidate' );
		header( 'Etag: ' . $etag );
		header('Content-type: image/png');
		header('Content-Length: ' . strlen( $image ) );
		if (
		( false !== ( $ifmod = linkex::get( 'HTTP_IF_MODIFIED_SINCE', $_SERVER, false ) ) && strtotime( $ifmod ) == 1336468109 ) ||
		( false !== ( $ifnm  = linkex::get( 'HTTP_IF_NONE_MATCH', $_SERVER, false ) ) && trim( $ifnm ) == $etag )
		) {
			header( linkex::get( 'SERVER_PROTOCOL', $_SERVER, 'HTTP/1.1' ) .' 304 Not Modified', 304, true );
			exit;
		}
		echo $image;
		exit;
		break;
	case 'css':
		$etag = md5("css1336468109");
		header( 'Last-Modified: Tue, 08 May 2012 09:08:29 GMT');
		header( 'Expires: Wed, 08 May 2013 09:08:29 GMT');
		header( 'Cache-Control: must-revalidate' );
		header( 'Etag: ' . $etag );
		header( 'Content-Type: text/css' );
		if (
			( false !== ( $ifmod = linkex::get( 'HTTP_IF_MODIFIED_SINCE', $_SERVER, false ) ) && strtotime( $ifmod ) == 1336468109 ) ||
			( false !== ( $ifnm  = linkex::get( 'HTTP_IF_NONE_MATCH', $_SERVER, false ) ) && trim( $ifnm ) == $etag )
		) {
			header( linkex::get( 'SERVER_PROTOCOL', $_SERVER, 'HTTP/1.1' ) .' 304 Not Modified', 304, true );
			exit;
		}		
		ob_start( 'ob_gzhandler' );
		 ?>.clearfix:before, .cf:after { content:""; display:table; }
.clearfix:after { clear:both; }
/* For IE 6/7 (trigger hasLayout) */
.clearfix { zoom:1; }

.columns { }
.columns .column { float:left;width:50%; }
div.rssnews {
	height:200px;
	overflow:auto;
}
div.rssnews div.item {
	margin:10px 25px;
	padding-bottom:10px;
	border-bottom:1px dotted #bbb;
}
div.rssnews div.item div.meta {
	border-bottom:1px solid #F3F3F3;
	margin-bottom:10px;
	color:#333;
}
div.rssnews div.item div.meta div.title {
	font-size:14px;
	font-weight:bold;
}
div.helpDiv {
	background-color:#fff;
	width:400px;
	height:300px;
	position:absolute;
	z-index:100;
	top:70px;
	left:150px;
	padding:0px;
	border:3px solid #aaa;
}
div.helpDiv .article { padding:10px;overflow:auto;height:250px; }
div.helpDiv h1 { margin:0px;font-size:20px; }
div.helpDivGone {
	display:none;
	top:10000000px;
	left:10000000px;
}
.center { text-align:center; }
.right { text-align:right; }
.pre { font-family:monospace; }
.justify { text-align:justify; }
.bold { font-weight:bold; }
.underline { text-decoration: underline; }
#searchq {
	width:90%;
}
.graph-bar { 
	border:1px solid red; 
	display:table;
} 
.graph-bar .bar {
	bottom:0px;
	width:15px;
	margin:0px 2px;
	background-color:#5EAA5E;
	display:table-cell; 
	vertical-align:middle;
}
div.icon {
	width:16px;
	height:16px;
	background-image:url( '?page=file&view=sprite&rand=1336468109' );
	background-repeat:no-repeat;
}
.sprite {
	width:16px;
	height:16px;
	background-image:url( '?page=file&view=nsprite&rand=1336468109' );
	background-repeat:no-repeat;
}
.sprite-rss {
	background-image:url( '?page=file&view=nsprite&rand=1336468109' );
	background-repeat:no-repeat;
	padding-left:18px;
	height:14px;
}
div.iconinformation, div.icon4 {
	background-position:-32px -155px;
}
div.iconaccept, div.icon1 {
	background-position:0px -155px;
}
div.icondelete, div.icon2, div.icon64 {
	background-position:-16px -155px;
}
html { min-height:100.05%; }
body {
	background-color:#f4f5f1;
	margin:0px;
}
a { color:blue; }
body, td, input, select, textarea { 
	font-family:verdana, sans-serif;
	font-size:11px;
}
div#wrapper {
	width:80%;
	min-width:1000px;
	background-color:#fff;
}
div#topbar{
	height:20px;
	background-color:#B91450;
}
div#header h1, div#header a {
	font-size:22px;
	text-align:right;
	color:#313129;
	margin:0px;
	text-decoration:none;
}

#navbar ul {
	padding-left: 0;
	margin-left: 0;
	margin:0px;
	padding:0px;
	
	background: #f0f0f0;
	background: -moz-linear-gradient(top, #f0f0f0 0%, #c9c9c9 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f0f0f0), color-stop(100%,#c9c9c9));
	background: -webkit-linear-gradient(top, #f0f0f0 0%,#c9c9c9 100%);
	background: -o-linear-gradient(top, #f0f0f0 0%,#c9c9c9 100%);
	background: -ms-linear-gradient(top, #f0f0f0 0%,#c9c9c9 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f0f0f0', endColorstr='#c9c9c9',GradientType=0 );
	background: linear-gradient(top, #f0f0f0 0%,#c9c9c9 100%);
	
	color:#7f7f7f;
	float:left;
	width:100%;
	border:1px solid #959595;
	border-left:0px;
	border-right:0px;
}

#navbar ul li { display: inline; }
#navbar ul li a {
	padding:4px 10px 3px 7px;
	color:#7f7f7f;
	text-decoration: none;
	float:left;
}

#navbar ul li a:hover {
	color: #000;
}

div#footer {
	padding-top:0px;
	padding-bottom:1px;
	font-size:9px;
	text-align:right;
	color:#fff;
	background-color:#B91450;
}
div#footer a {
	color:#fff;
	text-decoration:none;
	height:13px;
}
div#footer a img {
	border:0px;
	width:45px;
	height:13px;
}
div#contents {
	padding:3px;
}
form {
	margin:0px;
}
select {
	width:150px;
	font-size:11px;
}
input.checkbox, input .radio {
	margin-left:0px;
	margin-right:0px;
}
input.button {
	width:100px;
}
input.text {
	background-color:#F4F4F4;
	border:1px solid #B2B2B2;
	border-color:#999999 rgb(204, 204, 204) rgb(204, 204, 204) rgb(153, 153, 153);
	padding:3px;
	width:400px;
}
textarea.text {
	background-color:#F4F4F4;
	border:1px solid #B2B2B2;
	padding:2px;
	width:402px;
	overflow:auto;
	height:55px;
}
input.focus, textarea.focus {
	background-color:#fff;
	border-color:#686868;
}
fieldset {
	width:90%;
	margin:0px auto;
	padding:2px 0px;
	border:1px solid #aaa;
}
fieldset legend {
	margin-left:15px;
	font-weight:bold;
}
fieldset.expandable legend {
	cursor:pointer;
	background-image:url('?page=file&view=sprite&rand=1336468109');
	background-repeat:no-repeat;
	background-position:4px -109px;
	padding-left:15px;
	margin:0px 10px;
	_margin:0px 2px;
}
fieldset.hidden legend {
	background-image:url('?page=file&view=sprite&rand=1336468109');
	background-position:4px -93px;
}
fieldset.expandable div.contractor {
}
span.green, div.green {
	color:#008000;
}
span.yellow, div.yellow {
	color:#D5A13D;
}
fieldset.error, span.red, div.red {
	color:#c00;
}
fieldset.error legend {
	background-repeat:no-repeat;
	background-position:-22px -202px;
	padding:5px 0px;
	padding-left:23px;
	margin:0px 10px;
	margin-right:5px;
	_margin:0px 2px;
	background-image:url('?page=file&view=sprite');
}
table {
	width:100%;
}
table tr {
	height:15px;
}
table tr.thXXX thXX {
	background-color:#ddd;
	border-bottom:1px solid #000;
}
table th {
	text-align:left;
}
table tr.navigation, table tr.navigation td {
	background-color:#ddd;
}
table td.key {
	width:130px;
	text-align:right;
	padding-right:15px;
}
a.help img {
	width:16px;
	height:16px;
	border:0px;
}
div.article {
	padding:3px 10px;
	line-height:15px;
	text-align:justify;
}
div.pagerank {
	width:55px;
	height:8px;
	background-image:url('?page=file&view=sprite&rand=1336468109');
	background-position:0px 0px;
	float:left;
}
div.pr1 { background-position:0px -8px; }
div.pr2 { background-position:0px -16px; }
div.pr3 { background-position:0px -24px; }
div.pr4 { background-position:0px -32px; }
div.pr5 { background-position:0px -40px; }
div.pr6 { background-position:0px -48px; }
div.pr7 { background-position:0px -56px; }
div.pr8 { background-position:0px -64px; }
div.pr9 { background-position:0px -72px; }
div.pr10{ background-position:0px -80px; }

div.minpagerank {
	width:7px;
	height:8px;
	background-image:url('?page=file&view=sprite&rand=1336468109');
	background-position:-44px 0px;
	float:left;
	margin-left:5px;
}
div.minpr1 { background-position:-44px -8px; }
div.minpr2 { background-position:-44px -16px; }
div.minpr3 { background-position:-44px -24px; }
div.minpr4 { background-position:-44px -32px; }
div.minpr5 { background-position:-44px -40px; }
div.minpr6 { background-position:-44px -48px; }
div.minpr7 { background-position:-44px -56px; }
div.minpr8 { background-position:-44px -64px; }
div.minpr9 { background-position:-44px -72px; }
div.minpr10{ background-position:-44px -80px; }

table.list { background-color:#eee;width:100%;border:1px solid #aaa;border-collapse:collapse; }
table.list th a { display:block;width:100%; }
table.list td { background-color:#fff;border-color:#eee;border-width:1px;border-style:inset;padding:0px 3px; }
table.list td.navigation { padding:8px 0px; }
table.list tr.hover, table.list tr.hover td, table.list th.hover { background-color:#ccc; }
table.list th { background-color:#ddd;padding:3px;border-color:#aaa;border-style:inset;border-width:0px;border-bottom-width:1px;text-align:left; }

table.list th a.sortdesc { 
	padding-left:11px;
	background-position:0px -224px;
	background-repeat:no-repeat;
	background-image:url( '?page=file&view=sprite&rand=1336468109' );
}

table.list th a.sortasc { 
	padding-left:11px;
	background-position:0px -239px;
	background-repeat:no-repeat;
	background-image:url('?page=file&view=arrowdown'); 
	background-image:url( '?page=file&view=sprite&rand=1336468109' );
}

table.list div.imageup {
	background-image:url( '?page=file&view=sprite&rand=1336468109' );
	background-repeat:no-repeat;
	background-position:3px -206px;
	width:18px;
	height:18px;
}
table.list td.navigation, table.list td.navigation:hover { background-color:#fff; }

table.list td.navigation a:hover {
	background-color:#ccc;
}
table.list td.navigation a, table.list td.navigation span {
	text-decoration:none;
	color:#666;
	padding:2px 6px;
	border: solid 2px #ddd;
	background-color:#fff;
}
table.list td.navigation span {
	color:#ccc;
}

table.pagerank {
	margin:0px;
	padding:0px;
	width:100px;
	height:10px;
}
table.pagerank, table.pagerank td, table.pagerank tr {
	border:0px solid #fff;
	border-style:solid;
	border-width:1px;
}
table.pagerank td.bar {
	width:40px;
	height:10px;
	border:0px;
}
table.pagerank td.bar div {
	border:1px solid #999;
	width:40px;
	padding:1px;
	height:10px;
}
table.pagerank td.bar div div {
	padding:0px;
	border:0px;
	background-color:#5EAA5E;
}
table.pagerank td.value {
	font-weight:bold;
	font-size:10px;
	text-align:right;
}
div#linkstable {
	height:15px;
}
div#linkstable div.linkitem {
	border:1px solid #666;
	background-color:#ddd;
	float:left;
	padding:2px 5px;
	cursor:pointer;
	height:15px;
}
ul.selector {
	width:80%;
	list-style-type: none; 
	margin: 0;
	min-height:200px;
	padding:10px 5px;
	background-color:#eee;
}
ul.selector li {
	cursor:move;
	background-color:#fff;
	margin:5px;
	padding:5px;
	border:1px solid #CCCCCC;
	font-weight:bold;
	outline-style:none;
	outline-width:medium;
}
ul.selector li.immutable {
	color:#999;
	cursor:default;
}
div#selectmsg {
	padding-top:5px;
}
<?php 
		exit;
		break;
	case 'js':
		$etag = md5("js1336468109");
		header( 'Last-Modified: Tue, 08 May 2012 09:08:29 GMT');
		header( 'Expires: Wed, 08 May 2013 09:08:29 GMT');
		header( 'Cache-Control: must-revalidate' );
		header( 'Etag: ' . $etag );
		if (
			( false !== ( $ifmod = linkex::get( 'HTTP_IF_MODIFIED_SINCE', $_SERVER, false ) ) && strtotime( $ifmod ) == 1336468109 ) ||
			( false !== ( $ifnm  = linkex::get( 'HTTP_IF_NONE_MATCH', $_SERVER, false ) ) && trim( $ifnm ) == $etag )
		) {
			header( linkex::get( 'SERVER_PROTOCOL', $_SERVER, 'HTTP/1.1' ) .' 304 Not Modified', 304, true );
			exit;
		}
		ob_start( 'ob_gzhandler' );
?>
/*!
 * jQuery JavaScript Library v1.4.2
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Sat Feb 13 22:33:48 2010 -0500
 */
(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);;
/*
 * jQuery UI 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7.1",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return !!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return !(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return !this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);;
/*
 * jQuery UI Draggable 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.draggable",a.extend({},a.ui.mouse,{_init:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy()},_mouseCapture:function(b){var c=this.options;if(this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(b);if(!this.handle){return false}return true},_mouseStart:function(b){var c=this.options;this.helper=this._createHelper(b);this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(b);this.originalPageX=b.pageX;this.originalPageY=b.pageY;if(c.cursorAt){this._adjustOffsetFromHelper(c.cursorAt)}if(c.containment){this._setContainment()}this._trigger("start",b);this._cacheHelperProportions();if(a.ui.ddmanager&&!c.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,b)}this.helper.addClass("ui-draggable-dragging");this._mouseDrag(b,true);return true},_mouseDrag:function(b,d){this.position=this._generatePosition(b);this.positionAbs=this._convertPositionTo("absolute");if(!d){var c=this._uiHash();this._trigger("drag",b,c);this.position=c.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,b)}return false},_mouseStop:function(c){var d=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){d=a.ui.ddmanager.drop(this,c)}if(this.dropped){d=this.dropped;this.dropped=false}if((this.options.revert=="invalid"&&!d)||(this.options.revert=="valid"&&d)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,d))){var b=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){b._trigger("stop",c);b._clear()})}else{this._trigger("stop",c);this._clear()}return false},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==b.target){c=true}});return c},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c])):(d.helper=="clone"?this.element.clone():this.element);if(!b.parents("body").length){b.appendTo((d.appendTo=="parent"?this.element[0].parentNode:d.appendTo))}if(b[0]!=this.element[0]&&!(/(fixed|absolute)/).test(b.css("position"))){b.css("position","absolute")}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.element.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)&&e.containment.constructor!=Array){var c=a(e.containment)[0];if(!c){return}var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}else{if(e.containment.constructor==Array){this.containment=e.containment}}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(b,c,d){d=d||this._uiHash();a.ui.plugin.call(this,b,[c,d]);if(b=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(b){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,offset:this.positionAbs}}}));a.extend(a.ui.draggable,{version:"1.7.1",eventPrefix:"drag",defaults:{addClasses:true,appendTo:"parent",axis:false,cancel:":input,option",connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false}});a.ui.plugin.add("draggable","connectToSortable",{start:function(c,e){var d=a(this).data("draggable"),f=d.options,b=a.extend({},e,{item:d.element});d.sortables=[];a(f.connectToSortable).each(function(){var g=a.data(this,"sortable");if(g&&!g.options.disabled){d.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",c,b)}})},stop:function(c,e){var d=a(this).data("draggable"),b=a.extend({},e,{item:d.element});a.each(d.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;d.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(c);this.instance.options.helper=this.instance.options._helper;if(d.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",c,b)}})},drag:function(c,f){var e=a(this).data("draggable"),b=this;var d=function(i){var n=this.offset.click.top,m=this.offset.click.left;var g=this.positionAbs.top,k=this.positionAbs.left;var j=i.height,l=i.width;var p=i.top,h=i.left;return a.ui.isOver(g+n,k+m,p,h,j,l)};a.each(e.sortables,function(g){this.instance.positionAbs=e.positionAbs;this.instance.helperProportions=e.helperProportions;this.instance.offset.click=e.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(b).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return f.helper[0]};c.target=this.instance.currentItem[0];this.instance._mouseCapture(c,true);this.instance._mouseStart(c,true,true);this.instance.offset.click.top=e.offset.click.top;this.instance.offset.click.left=e.offset.click.left;this.instance.offset.parent.left-=e.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=e.offset.parent.top-this.instance.offset.parent.top;e._trigger("toSortable",c);e.dropped=this.instance.element;e.currentItem=e.element;this.instance.fromOutside=e}if(this.instance.currentItem){this.instance._mouseDrag(c)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",c,this.instance._uiHash(this.instance));this.instance._mouseStop(c,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}e._trigger("fromSortable",c);e.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(c,d){var b=a("body"),e=a(this).data("draggable").options;if(b.css("cursor")){e._cursor=b.css("cursor")}b.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._cursor){a("body").css("cursor",d._cursor)}}});a.ui.plugin.add("draggable","iframeFix",{start:function(b,c){var d=a(this).data("draggable").options;a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})},stop:function(b,c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});a.ui.plugin.add("draggable","opacity",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("opacity")){e._opacity=b.css("opacity")}b.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._opacity){a(c.helper).css("opacity",d._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(c,d){var b=a(this).data("draggable");if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){b.overflowOffset=b.scrollParent.offset()}},drag:function(d,e){var c=a(this).data("draggable"),f=c.options,b=false;if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){if(!f.axis||f.axis!="x"){if((c.overflowOffset.top+c.scrollParent[0].offsetHeight)-d.pageY<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop+f.scrollSpeed}else{if(d.pageY-c.overflowOffset.top<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop-f.scrollSpeed}}}if(!f.axis||f.axis!="y"){if((c.overflowOffset.left+c.scrollParent[0].offsetWidth)-d.pageX<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft+f.scrollSpeed}else{if(d.pageX-c.overflowOffset.left<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft-f.scrollSpeed}}}}else{if(!f.axis||f.axis!="x"){if(d.pageY-a(document).scrollTop()<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-f.scrollSpeed)}else{if(a(window).height()-(d.pageY-a(document).scrollTop())<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+f.scrollSpeed)}}}if(!f.axis||f.axis!="y"){if(d.pageX-a(document).scrollLeft()<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-f.scrollSpeed)}else{if(a(window).width()-(d.pageX-a(document).scrollLeft())<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+f.scrollSpeed)}}}}if(b!==false&&a.ui.ddmanager&&!f.dropBehaviour){a.ui.ddmanager.prepareOffsets(c,d)}}});a.ui.plugin.add("draggable","snap",{start:function(c,d){var b=a(this).data("draggable"),e=b.options;b.snapElements=[];a(e.snap.constructor!=String?(e.snap.items||":data(draggable)"):e.snap).each(function(){var g=a(this);var f=g.offset();if(this!=b.element[0]){b.snapElements.push({item:this,width:g.outerWidth(),height:g.outerHeight(),top:f.top,left:f.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(b,c){var e=a(this).data("draggable").options;var d=a.makeArray(a(e.stack.group)).sort(function(g,f){return(parseInt(a(g).css("zIndex"),10)||e.stack.min)-(parseInt(a(f).css("zIndex"),10)||e.stack.min)});a(d).each(function(f){this.style.zIndex=e.stack.min+f});this[0].style.zIndex=e.stack.min+d.length}});a.ui.plugin.add("draggable","zIndex",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("zIndex")){e._zIndex=b.css("zIndex")}b.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._zIndex){a(c.helper).css("zIndex",d._zIndex)}}})})(jQuery);;
/*
 * jQuery UI Droppable 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 */
(function(a){a.widget("ui.droppable",{_init:function(){var c=this.options,b=c.accept;this.isover=0;this.isout=1;this.options.accept=this.options.accept&&a.isFunction(this.options.accept)?this.options.accept:function(e){return e.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};a.ui.ddmanager.droppables[this.options.scope]=a.ui.ddmanager.droppables[this.options.scope]||[];a.ui.ddmanager.droppables[this.options.scope].push(this);(this.options.addClasses&&this.element.addClass("ui-droppable"))},destroy:function(){var b=a.ui.ddmanager.droppables[this.options.scope];for(var c=0;c<b.length;c++){if(b[c]==this){b.splice(c,1)}}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable")},_setData:function(b,c){if(b=="accept"){this.options.accept=c&&a.isFunction(c)?c:function(e){return e.is(c)}}else{a.widget.prototype._setData.apply(this,arguments)}},_activate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.addClass(this.options.activeClass)}(b&&this._trigger("activate",c,this.ui(b)))},_deactivate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}(b&&this._trigger("deactivate",c,this.ui(b)))},_over:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.addClass(this.options.hoverClass)}this._trigger("over",c,this.ui(b))}},_out:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("out",c,this.ui(b))}},_drop:function(c,d){var b=d||a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return false}var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var f=a.data(this,"droppable");if(f.options.greedy&&a.ui.intersect(b,a.extend(f,{offset:f.element.offset()}),f.options.tolerance)){e=true;return false}});if(e){return false}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("drop",c,this.ui(b));return this.element}return false},ui:function(b){return{draggable:(b.currentItem||b.element),helper:b.helper,position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs}}});a.extend(a.ui.droppable,{version:"1.7.1",eventPrefix:"drop",defaults:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"}});a.ui.intersect=function(q,j,o){if(!j.offset){return false}var e=(q.positionAbs||q.position.absolute).left,d=e+q.helperProportions.width,n=(q.positionAbs||q.position.absolute).top,m=n+q.helperProportions.height;var g=j.offset.left,c=g+j.proportions.width,p=j.offset.top,k=p+j.proportions.height;switch(o){case"fit":return(g<e&&d<c&&p<n&&m<k);break;case"intersect":return(g<e+(q.helperProportions.width/2)&&d-(q.helperProportions.width/2)<c&&p<n+(q.helperProportions.height/2)&&m-(q.helperProportions.height/2)<k);break;case"pointer":var h=((q.positionAbs||q.position.absolute).left+(q.clickOffset||q.offset.click).left),i=((q.positionAbs||q.position.absolute).top+(q.clickOffset||q.offset.click).top),f=a.ui.isOver(i,h,p,g,j.proportions.height,j.proportions.width);return f;break;case"touch":return((n>=p&&n<=k)||(m>=p&&m<=k)||(n<p&&m>k))&&((e>=g&&e<=c)||(d>=g&&d<=c)||(e<g&&d>c));break;default:return false;break}};a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,g){var b=a.ui.ddmanager.droppables[e.options.scope];var f=g?g.type:null;var h=(e.currentItem||e.element).find(":data(droppable)").andSelf();droppablesLoop:for(var d=0;d<b.length;d++){if(b[d].options.disabled||(e&&!b[d].options.accept.call(b[d].element[0],(e.currentItem||e.element)))){continue}for(var c=0;c<h.length;c++){if(h[c]==b[d].element[0]){b[d].proportions.height=0;continue droppablesLoop}}b[d].visible=b[d].element.css("display")!="none";if(!b[d].visible){continue}b[d].offset=b[d].element.offset();b[d].proportions={width:b[d].element[0].offsetWidth,height:b[d].element[0].offsetHeight};if(f=="mousedown"){b[d]._activate.call(b[d],g)}}},drop:function(b,c){var d=false;a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(!this.options){return}if(!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)){d=this._drop.call(this,c)}if(!this.options.disabled&&this.visible&&this.options.accept.call(this.element[0],(b.currentItem||b.element))){this.isout=1;this.isover=0;this._deactivate.call(this,c)}});return d},drag:function(b,c){if(b.options.refreshPositions){a.ui.ddmanager.prepareOffsets(b,c)}a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(this.options.disabled||this.greedyChild||!this.visible){return}var e=a.ui.intersect(b,this,this.options.tolerance);var g=!e&&this.isover==1?"isout":(e&&this.isover==0?"isover":null);if(!g){return}var f;if(this.options.greedy){var d=this.element.parents(":data(droppable):eq(0)");if(d.length){f=a.data(d[0],"droppable");f.greedyChild=(g=="isover"?1:0)}}if(f&&g=="isover"){f.isover=0;f.isout=1;f._out.call(f,c)}this[g]=1;this[g=="isout"?"isover":"isout"]=0;this[g=="isover"?"_over":"_out"].call(this,c);if(f&&g=="isout"){f.isout=0;f.isover=1;f._over.call(f,c)}})}}})(jQuery);;
/*
 * jQuery UI Sortable 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	ui.core.js
 */
(function(a){a.widget("ui.sortable",a.extend({},a.ui.mouse,{_init:function(){var b=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?(/left|right/).test(this.items[0].item.css("float")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--){this.items[b].item.removeData("sortable-item")}},_mouseCapture:function(e,f){if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(e);var d=null,c=this,b=a(e.target).parents().each(function(){if(a.data(this,"sortable-item")==c){d=a(this);return false}});if(a.data(e.target,"sortable-item")==c){d=a(e.target)}if(!d){return false}if(this.options.handle&&!f){var g=false;a(this.options.handle,d).find("*").andSelf().each(function(){if(this==e.target){g=true}});if(!g){return false}}this.currentItem=d;this._removeCurrentsFromItems();return true},_mouseStart:function(e,f,b){var g=this.options,c=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(e);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");a.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(e);this.originalPageX=e.pageX;this.originalPageY=e.pageY;if(g.cursorAt){this._adjustOffsetFromHelper(g.cursorAt)}this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(g.containment){this._setContainment()}if(g.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",g.cursor)}if(g.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",g.opacity)}if(g.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",g.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",e,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!b){for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("activate",e,c._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,e)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(e);return true},_mouseDrag:function(f){this.position=this._generatePosition(f);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var g=this.options,b=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-f.pageY<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop+g.scrollSpeed}else{if(f.pageY-this.overflowOffset.top<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop-g.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-f.pageX<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(f.pageX-this.overflowOffset.left<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft-g.scrollSpeed}}}else{if(f.pageY-a(document).scrollTop()<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(f.pageY-a(document).scrollTop())<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}if(f.pageX-a(document).scrollLeft()<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(f.pageX-a(document).scrollLeft())<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}if(b!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d],c=e.item[0],h=this._intersectsWithPointer(e);if(!h){continue}if(c!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=c&&!a.ui.contains(this.placeholder[0],c)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],c):true)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(e)){this._rearrange(f,e)}else{break}this._trigger("change",f,this._uiHash());break}}this._contactContainers(f);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,f)}this._trigger("sort",f,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(c,d){if(!c){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,c)}if(this.options.revert){var b=this;var e=b.placeholder.offset();b.reverting=true;a(this.helper).animate({left:e.left-this.offset.parent.left-b.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-b.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){b._clear(c)})}else{this._clear(c,d)}return false},cancel:function(){var b=this;if(this.dragging){this._mouseUp();if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var c=this.containers.length-1;c>=0;c--){this.containers[c]._trigger("deactivate",null,b._uiHash(this));if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",null,b._uiHash(this));this.containers[c].containerCache.over=0}}}if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}return true},serialize:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};a(b).each(function(){var e=(a(d.item||this).attr(d.attribute||"id")||"").match(d.expression||(/(.+)[-=_](.+)/));if(e){c.push((d.key||e[1]+"[]")+"="+(d.key&&d.expression?e[1]:e[2]))}});return c.join("&")},toArray:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};b.each(function(){c.push(a(d.item||this).attr(d.attribute||"id")||"")});return c},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(d){var e=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,d.top,d.height),c=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,d.left,d.width),g=e&&c,b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(!g){return false}return this.floating?(((f&&f=="right")||b=="down")?2:1):(b&&(b=="down"?2:1))},_intersectsWithSides:function(e){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+(e.height/2),e.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+(e.width/2),e.width),b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(this.floating&&f){return((f=="right"&&d)||(f=="left"&&!d))}else{return b&&((b=="down"&&c)||(b=="up"&&!c))}},_getDragVerticalDirection:function(){var b=this.positionAbs.top-this.lastPositionAbs.top;return b!=0&&(b>0?"down":"up")},_getDragHorizontalDirection:function(){var b=this.positionAbs.left-this.lastPositionAbs.left;return b!=0&&(b>0?"right":"left")},refresh:function(b){this._refreshItems(b);this.refreshPositions()},_connectWith:function(){var b=this.options;return b.connectWith.constructor==String?[b.connectWith]:b.connectWith},_getItemsAsjQuery:function(b){var l=this;var g=[];var e=[];var h=this._connectWith();if(h&&b){for(var d=h.length-1;d>=0;d--){var k=a(h[d]);for(var c=k.length-1;c>=0;c--){var f=a.data(k[c],"sortable");if(f&&f!=this&&!f.options.disabled){e.push([a.isFunction(f.options.items)?f.options.items.call(f.element):a(f.options.items,f.element).not(".ui-sortable-helper"),f])}}}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper"),this]);for(var d=e.length-1;d>=0;d--){e[d][0].each(function(){g.push(this)})}return a(g)},_removeCurrentsFromItems:function(){var d=this.currentItem.find(":data(sortable-item)");for(var c=0;c<this.items.length;c++){for(var b=0;b<d.length;b++){if(d[b]==this.items[c].item[0]){this.items.splice(c,1)}}}},_refreshItems:function(b){this.items=[];this.containers=[this];var h=this.items;var p=this;var f=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]];var l=this._connectWith();if(l){for(var e=l.length-1;e>=0;e--){var m=a(l[e]);for(var d=m.length-1;d>=0;d--){var g=a.data(m[d],"sortable");if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element[0],b,{item:this.currentItem}):a(g.options.items,g.element),g]);this.containers.push(g)}}}}for(var e=f.length-1;e>=0;e--){var k=f[e][1];var c=f[e][0];for(var d=0,n=c.length;d<n;d++){var o=a(c[d]);o.data("sortable-item",k);h.push({item:o,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d];if(e.instance!=this.currentContainer&&this.currentContainer&&e.item[0]!=this.currentItem[0]){continue}var c=this.options.toleranceElement?a(this.options.toleranceElement,e.item):e.item;if(!b){e.width=c.outerWidth();e.height=c.outerHeight()}var f=c.offset();e.left=f.left;e.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var d=this.containers.length-1;d>=0;d--){var f=this.containers[d].element.offset();this.containers[d].containerCache.left=f.left;this.containers[d].containerCache.top=f.top;this.containers[d].containerCache.width=this.containers[d].element.outerWidth();this.containers[d].containerCache.height=this.containers[d].element.outerHeight()}}},_createPlaceholder:function(d){var b=d||this,e=b.options;if(!e.placeholder||e.placeholder.constructor==String){var c=e.placeholder;e.placeholder={element:function(){var f=a(document.createElement(b.currentItem[0].nodeName)).addClass(c||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!c){f.style.visibility="hidden"}return f},update:function(f,g){if(c&&!e.forcePlaceholderSize){return}if(!g.height()){g.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10))}if(!g.width()){g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=a(e.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);e.placeholder.update(b,b.placeholder)},_contactContainers:function(d){for(var c=this.containers.length-1;c>=0;c--){if(this._intersectsWith(this.containers[c].containerCache)){if(!this.containers[c].containerCache.over){if(this.currentContainer!=this.containers[c]){var h=10000;var g=null;var e=this.positionAbs[this.containers[c].floating?"left":"top"];for(var b=this.items.length-1;b>=0;b--){if(!a.ui.contains(this.containers[c].element[0],this.items[b].item[0])){continue}var f=this.items[b][this.containers[c].floating?"left":"top"];if(Math.abs(f-e)<h){h=Math.abs(f-e);g=this.items[b]}}if(!g&&!this.options.dropOnEmpty){continue}this.currentContainer=this.containers[c];g?this._rearrange(d,g,null,true):this._rearrange(d,null,this.containers[c].element,true);this._trigger("change",d,this._uiHash());this.containers[c]._trigger("change",d,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder)}this.containers[c]._trigger("over",d,this._uiHash(this));this.containers[c].containerCache.over=1}}else{if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",d,this._uiHash(this));this.containers[c].containerCache.over=0}}}},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c,this.currentItem])):(d.helper=="clone"?this.currentItem.clone():this.currentItem);if(!b.parents("body").length){a(d.appendTo!="parent"?d.appendTo:this.currentItem[0].parentNode)[0].appendChild(b[0])}if(b[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(b[0].style.width==""||d.forceHelperSize){b.width(this.currentItem.width())}if(b[0].style.height==""||d.forceHelperSize){b.height(this.currentItem.height())}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.currentItem.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)){var c=a(e.containment)[0];var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_rearrange:function(g,f,c,e){c?c[0].appendChild(this.placeholder[0]):f.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?f.item[0]:f.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var d=this,b=this.counter;window.setTimeout(function(){if(b==d.counter){d.refreshPositions(!e)}},0)},_clear:function(d,e){this.reverting=false;var f=[],b=this;if(!this._noFinalSort&&this.currentItem[0].parentNode){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var c in this._storedCSS){if(this._storedCSS[c]=="auto"||this._storedCSS[c]=="static"){this._storedCSS[c]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!e){f.push(function(g){this._trigger("receive",g,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!e){f.push(function(g){this._trigger("update",g,this._uiHash())})}if(!a.ui.contains(this.element[0],this.currentItem[0])){if(!e){f.push(function(g){this._trigger("remove",g,this._uiHash())})}for(var c=this.containers.length-1;c>=0;c--){if(a.ui.contains(this.containers[c].element[0],this.currentItem[0])&&!e){f.push((function(g){return function(h){g._trigger("receive",h,this._uiHash(this))}}).call(this,this.containers[c]));f.push((function(g){return function(h){g._trigger("update",h,this._uiHash(this))}}).call(this,this.containers[c]))}}}for(var c=this.containers.length-1;c>=0;c--){if(!e){f.push((function(g){return function(h){g._trigger("deactivate",h,this._uiHash(this))}}).call(this,this.containers[c]))}if(this.containers[c].containerCache.over){f.push((function(g){return function(h){g._trigger("out",h,this._uiHash(this))}}).call(this,this.containers[c]));this.containers[c].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!e){this._trigger("beforeStop",d,this._uiHash());for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}return false}if(!e){this._trigger("beforeStop",d,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!e){for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(c){var b=c||this;return{helper:b.helper,placeholder:b.placeholder||a([]),position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs,item:b.currentItem,sender:c?c.element:null}}}));a.extend(a.ui.sortable,{getter:"serialize toArray",version:"1.7.1",eventPrefix:"sort",defaults:{appendTo:"parent",axis:false,cancel:":input,option",connectWith:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000}})})(jQuery);;
/*
 * LinkEX Javascript library
 */
Array.prototype.inArray = function (value) {
	for( i=0; i<this.length; i++ ) {
		if ( this[i] === value ) { return true; }
	}
	return false;
}
function getCookie( name ) {
	var c = document.cookie;
	var pos = c.indexOf( name );
	if ( pos>=0 ) {
		pos += name.length + 1;
		var end =  c.indexOf( ";", pos );
		if ( end>0 ) {
			return c.substr( pos, end-pos );
		} else {
			return c.substr( pos );
		}
	} else {
		return "";
	}
}
function setCookie( name, value, seconds ) {
	var expires = "";
	if ( seconds ) {
		var date = new Date();
		date.setTime(date.getTime()+(seconds*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function selectLinks( ty,fn ) {
	$("div#selectmsg").html(""); 
	$("input#hiddenlid").remove();
	if ( fn ) {
		$('input.linkcheckbox').each(fn);
	}

	if ( ty == 'suspended' ) {
		if ( fn == null ) {
			var m=linkids_suspended.length;
			$("form#adminverify").append("<input id=\"hiddenlid\" type=\"hidden\" name=\"lid\" value=\""+linkids_suspended.join(",")+"\" />");
			$("div#selectmsg").html("All "+m+" suspended links selected. <a href=\"#\" onclick=\"this.blur();selectLinks('none',function(){this.checked=false;});return false;\">Clear selection</a>"); 
		} else {
			var n=$('input.linkcheckbox:checked').length;
			var m=linkids_suspended.length;
			$("div#selectmsg").html( 
				((n==0)?"No suspended links":((n>1)?"All "+n+" suspended links":"One suspended link"))+" on this page selected." +
				( ( m>n )?" <a href=\"#\" onclick=\"this.blur();selectLinks('suspended');return false;\">Select all <strong>"+m+"</strong> suspended links.</a>":"" )
			);

		}
	}
	if ( ty == 'all' ) {
		if ( fn == null ) {
			var m=linkids_all.length;
			$("form#adminverify").append("<input id=\"hiddenlid\" type=\"hidden\" name=\"lid\" value=\""+linkids_all.join(",")+"\" />");
			$("div#selectmsg").html("All "+m+" links selected. <a href=\"#\" onclick=\"this.blur();selectLinks('none',function(){this.checked=false;});return false;\">Clear selection</a>"); 
		} else {
			var n=$('input.linkcheckbox:checked').length;
			var m=linkids_all.length;
			$("div#selectmsg").html( 
				((n>1)?"All "+n+" links":"One link")+" on this page selected." +
				( ( m>n )?" <a href=\"#\" onclick=\"this.blur();selectLinks('all');return false;\">Select all <strong>"+m+"</strong> links.</a>":"" )
			);
		}
	}
}

$(document).ready(function(){
	$("table.list tbody tr").hover(function(){
			$(this).addClass("hover")
		},function(){
			$(this).removeClass("hover")
		}
	);
	$("input:not(.button),textarea")
		.focus( function(){ $(this).addClass("focus"); } )
		.blur( function(){ $(this).removeClass("focus");} );

	var storedFsIds=[];
	var c=getCookie("fscookie").replace(/^,/,'').replace(/,$/,'');
	if ( c.length>0 ) {
		storedFsIds=c.split(/,/);
	}
	/* var storedFsIds = jQuery.unique( (getCookie( "fscookie" )+",__linkex__").replace( /^,/, '' ).split( /,/ ) ); */
	if ( storedFsIds.length>0 ) {
		$("fieldset:not("+jQuery.map( storedFsIds, function(a){return '#'+a;} ).join(",")+").hidden div.contractor").hide(); 
	} else {
		$("fieldset.hidden div.contractor").hide(); 
	}
	$("fieldset.expandable legend")
		.disableSelection()
		.click( function(){
			var id = $(this).parent().attr("id");
			var container = $("fieldset#"+id+" div.contractor");
			var shown = $(container).is(":visible");
			if ( shown ) {
				$(container).slideUp("fast");
				$("fieldset#"+id).addClass("hidden");
				storedFsIds = jQuery.grep( storedFsIds, function(a){return a != id;} );
			} else {
				$(container).slideDown("fast");
				$("fieldset#"+id).removeClass("hidden");
				storedFsIds.push( id );
			}
			setCookie( "fscookie", (jQuery.unique( storedFsIds )).join(","), 86400*30 );
		} );
});
<?php
		exit;
		break;
	}
}

class config {
	var $installdate = null;
	var $password = '';
	var $email = '';
	var $url = '';
	var $title = null;
	var $anchor = array();
	var $description = '';
	var $altlinks = array();
	var $defaultcategories = array();
	var $dateformat = 'Y.m.d';

	var $charset = 'utf8';

	var $displaylimit = 30;
	var $sortkey = 'added';
	var $sortorder = 'desc';
	var $showemail = 0;

	var $linkbotagent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
	var $linkbotuniquedomains = 1;
	var $linkbotuniqueips = 0;
	var $linkbotignoretrailingslash = 1;
	var $linkbotdisregardwww = 1;
	var $linkbackrequired = 1;
	var $minpagerank = 0;
	var $titlelength = 0;
	var $titlelengthtype = 'w';
	var $descriptionlength = 0;
	var $descriptionlengthtype = 'w';

	var $disablepublicform = 0;
	var $disablerecipfield = 0;
	var $publiccategories = 0;

	var $commandlineenable = 1;
	var $commandlinesummary = 1;
	
	var $remoteenable = 0;
	var $remotesummary = 0;
	var $remotepass = '';
	var $remotelimitips = 1;
	var $remoteips = array( 'linkex.dk' );

	// Added on 16/12-2006
	var $usecaptcha = 0;

	// Added on 5/1-2007
	var $verifyanchor = 0;

	// Added on 6/2-2007
	var $resetpassword = array();

	// Added on 30/3-2007
	var $googledatacenters = array( 'www.google.com' );

	// Added on 3/4-2007
	var $samedomain = 0;

	// Added on 18/5-2007
	var $indexexchange = 0;
	var $noquerystring = 0;

	// Added on 23/2-2008
	var $exposelinkex = 1;

	// Added on 15/4-2008
	var $emailcrlf = '\r\n';

	// Added on 7/5-2008
	var $rejectnofollow = 0;

	// Added on 1/6-2008
	var $maxoutboundlinks = 0;

	// Added on 13/6-2008
	var $disableblacklisted = 0;

	// Added on 12/8-2008
	var $htmlcode = '&lt;a href=&quot;{$URL}&quot; title=&quot;{$ANCHOR}&quot;&gt;{$ANCHOR}&lt;/a&gt;';

	// Added on 21/2-2009
	var $maxoutboundtype = 0;

	// Added on 27/4-2009
	var $usetitle = 0;
	var $anchorlength = 0;
	var $anchorlengthtype = 'w';

	// Added on 04/05-2009
	var $template = array(
		'added', 
		'lastchecked', 'rpagerank', 'rdom', 
		'rdomip', 'anchor', 'status' 
	);

	public function __construct() { // {{{
		$con = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config', false );
		if ( $con !== false ) {
			$con = linkex::unserialize( trim( $con ) );
			foreach( $con AS $k=>$v ) {
				$this->$k = $v;
			}
		}
		$this->domain = @parse_url( $this->url );
		if ( isset( $this->domain{'host'} ) ) {
			$this->domain = $this->domain{'host'};
		} else {
			$this->domain = null;
		}

		if ( !is_array( $this->title ) ) {
			$this->title = $this->anchor;
		}

	} // }}}
	function save() { // {{{
		if ( !$this->installdate ) {
			$this->installdate = time();
		}
		linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config', serialize( get_object_vars( $this ) ) );
	} // }}}

}

class category {
	var $id = null;
	var $name = null;
	var $filter = array( 1 );
	var $sortby = 'id';
	var $order = 'desc';
	var $slots = 0;
	var $limit = 0;
	var $template = '<a href="{$URL}" title="{$TITLE}">{$ANCHOR}</a>&nbsp;{$DESCRIPTION}&nbsp;';
	var $public = 1;
	var $split = 0;

	var $links = -1;
	var $linksf = -1; 

	function links( $filter = false ) { // {{{
		$links = array();
		$linkids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
		foreach( $linkids AS $lid ) {
			$link = new link( $lid );
			if ( !is_array( $link->categories ) ) {
				$link->categories = array( $link->categories );
			}
			if ( in_array( $this->id, $link->categories ) ) {
				$statusmatch = ( in_array( intval( $link->status), $this->filter ) );
				$useexpired = !( in_array( '-1', $this->filter ) );
				$expired = ( $link->dateexpire>0 && $link->dateexpire<time() );
				if ( ( !$filter ) || ( ( !$filter || $statusmatch ) && ( !( $useexpired && $expired ) ) ) ) {
					$links[] = $link;
				}
			} else {
				unset( $link );
			}
		}
		return $links;
	} // }}}
	public function __construct( $id = null ) { // {{{
		if ( $id != null ) {
			$this->id = $id;
			$this->load();
		}
	} // }}}
	function filters() { // {{{
		return array( '0' => 'All links', '1' => 'OK links', '2' => 'Bad links', '4' => 'Expired links' );
	} // }}}
	function generate() { // {{{
		$links = $this->links( true );
		linkex::sort( $links, $this->sortby, $this->order );

		// First generate the original complete file
		$this->_generate( $links );

		if ( $this->split != 0 ) {
			if ( strpos( $this->split, ',' ) !== false ) {
				$links = linkex::arraychunk( $links, explode( ',', $this->split ) );
			} else {
				$links = linkex::arraychunk( $links, $this->split );
			}
			$i=1;
			foreach ( $links AS $ll ) {
				$this->_generate( $ll, '-'.$i, array( 'fileno' => $i, 'files' => sizeof( $links ) ) );
				$i++;
			}
		}
	} // }}}
	function _generate( $links, $postfix='', $variables=array() ) { // {{{
		global $config;

		$buffer = ( $config->exposelinkex ) ? COPYRIGHT : "";
		
		$linklist = array();
		$template = $this->template;

		// {{{ {table} 
		$table = null;
		if ( preg_match( '#\{(table.*)\}\s*#Umi', $template, $res ) ) {
			$table = $res[0];
			$template = str_replace( $table, '', $template );
		}
		// }}}
		// {{{ {cycle}
		$cycles = array();
		preg_match_all( '#\{(cycle.*)\}#Ui', $template, $res );
		for( $i=0; $i<sizeof( $res[0] );$i++ ) {
			$cycles[] = array( 
				'replace' => $res[0][$i],
				'values' => explode( ',', linkex::getParam( 'values', $res[1][$i], '' ) )
			);
		}
		// }}}
		
		$count = sizeof( $links );
		for( $i=0; $i<$count; $i++ ) {
			$l = $links[$i];
			$linklist[ $i ] = str_replace(
				array(
					'{$URL}', '{$DOMAIN}', '{$ANCHOR}', '{$ADDED}', '{$INDEX}', '{$DESCRIPTION}',
					'{$CATEGORYID}', '{$CATEGORYNAME}', '{$FIRST}', '{$LAST}', '$FIRST', '$LAST',
					'{$ID}', '{$PAGERANK}',
					'{$FILENO}', '{$FILES}',
					'{$EMPTY}', '{$TITLE}'
				),
				array(
					$l->lurl, $l->ldom, $l->anchor, date( $config->dateformat, $l->added ), 
					( $i+1 ), $l->description,
					$this->id, $this->name, 
					intval( $i==0 ), intval( ($i+1) == $count ),
					intval( $i==0 ), intval( ($i+1) == $count ),
					$l->id,
					$l->getRPageRank(),
					( array_key_exists( 'fileno', $variables ) ? $variables{'fileno'}:'' ),
					( array_key_exists( 'files', $variables ) ? $variables{'files'}:'' ),
					( ( sizeof( $links ) == 0 ) ? 1:0 ), $l->title
				),
				$template
			);
			foreach( $cycles AS $c ) {
				$linklist[ $i ] = str_replace( $c{'replace'}, $c{'values'}[ ( $i % sizeof( $c{'values'} ) ) ], $linklist[ $i ] );
			}
		}
		if ( $table == null ) {
			$buffer .= join( '', $linklist );
		} else {
			$valign = linkex::getParam( 'valign', strtolower( $table ) );
			$cols = linkex::getParam( 'cols', strtolower( $table ), 2 );
			$default = linkex::getParam( 'default', $table, '' );

			if ( ( $rows = linkex::getParam( 'rows', strtolower( $table ), false ) ) === false ) {
				$rows = ceil( sizeof( $linklist ) / $cols );
			}
			$params='';
			if ( preg_match( '#\{table\s+(.*)\}#Umi', $table, $res ) ) {
				$res = $res[1];
				$res = preg_replace( '#cols=[\'"]?\d+[\'"]?#i', '', $res );
				$res = preg_replace( '#rows=[\'"]?\d+[\'"]?#i', '', $res );
				$res = preg_replace( '#valign=[^\s]+#i', '', $res );
				$res = preg_replace( '#default=.?'.preg_quote( $default,'#') .'.?#i', '', $res );
				$params = ' '.trim( $res );
			}
			$buffer .= '<table'.$params.'>';
			for( $row=0; $row<$rows; $row++ ) {
				$buffer .= '<tr'.(($valign!=null)?' valign="'.$valign.'"':'').'>';
				for( $col=0; $col<$cols; $col++ ) {
					$i = ( $row * $cols ) + $col;
					$buffer .= '<td>'.( ( sizeof( $linklist ) > $i ) ? trim( $linklist[ $i ] ):$default ).'</td>';
				}
				$buffer .= '</tr>';
			}
			$buffer .= '</table>';
		}
		// {{{ IF
		if ( preg_match_all( '#\{if\s+(\d+)\}(.*)\{/if\}#Umis', $buffer, $res ) ) {
			for( $i=0; $i<sizeof($res[0]); $i++ ) {
				if ( $res[1][$i] ) {
					$buffer = str_replace( $res[0][$i], $res[2][$i], $buffer );
				} else {
					$buffer = str_replace( $res[0][$i], '', $buffer );
				}
			}
		}
		// }}}
		linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR . $this->id . $postfix, $buffer );
		@chmod( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR . $this->id . $postfix, CHMOD_FILE );
	} // }}}
	function load() { // {{{
		if ( file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $this->id ) ) {
			$data = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $this->id );
			$data = linkex::unserialize( $data );
			foreach( $data AS $k=>$v ) {
				$this->$k = $v;
			}
			if ( !is_array( $this->filter ) ) {
				$this->filter = array( intval( $this->filter ) );
			}
			unset( $data );
		}
	} // }}}
	function orders() { // {{{
		return array( 'asc' => 'Ascending (a-z)', 'desc' => 'Decending (z-a)' );
	} // }}}
	function save( $generate=true ) { // {{{
		if ( $this->id == null ) {
			$this->id = linkex::genID();
		}
		linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $this->id, serialize( get_object_vars( $this ) ) );
		@chmod( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $this->id, CHMOD_FILE );
		if ( $generate !== false ) {
			$this->generate();
		}
	} // }}}
	function sortbys() { // {{{
		return array( 'ldom' => 'Domain', 'anchor' => 'Title', 'description' => 'Description', 'added' => 'Date added', 'id' => 'ID', 'random' => 'Random', 'pagerank' => 'Pagerank', 'weight' => 'Weight' );
	} // }}}
}

class link {
	var $id =	null;
	var $added = 0;
	var $lastchecked = 0;
	var $laststatus = null;

	var $lurl = null;
	var $rurl = null;
	var $anchor = null;
	var $description = null;
	var $categories = array();
	var $email = null;
	var $skipcheck = 0;
	var $skippagerank = 0;
	var $minpagerank = -1;
	
	var $status = 1;

	var $wmip = null;

	var $ldom = null;
	var $rdom = null;
	var $edom = null;
	var $ldomip = null;
	var $rdomip = null;
	var $edomip = null;

	var $pagerank = 0;
	var $pagerankinfo = array(); // will hold array( 'hash' => md5-check of the url, 'date' => date of update )

	var $googleinfo = array();

	var $notes = '';

	// Added on 18/7-2007
	var $weight = 0;

	// Added on 23/2-2008
	var $dateexpire = 0;
	var $expired = 0;

	var $log = array();

	public function __construct( $id = null, $usecache=true ) { // {{{
		global $config;
		if ( intval( $id ) > 0 ) {
			$this->id = $id;
			$this->load($usecache);
			if ( !isset( $this->title ) || $this->title == null ) {
				$this->title=$this->anchor;
			}
			$this->rpagerank = $this->getRPageRank($usecache);
			$this->lpagerank = $this->getLPageRank($usecache);
			$this->lindexed  = $this->getLIndexedPages($usecache);
			$this->rindexed  = $this->getRIndexedPages($usecache);
			$this->link			 = $this->anchor;
			$this->minpr     = ( $this->minpagerank == -1 ) ? $config->minpagerank : $this->minpagerank;
		}
	} // }}}
	function load($usecache=true) { // {{{
		if ( ( $data = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR . $this->id, false ) ) !== false ) {
			$data = linkex::unserialize( $data );
			foreach( $data AS $k=>$v ) {
				$this->$k = $v;
			}
			$this->anchor = str_replace( '<', '&lt;' ,$this->anchor );
			$this->description = str_replace( '<', '&lt;', $this->description );
			unset( $data );
			$this->update($usecache);
		}
	} // }}}
	function update($usecache=false) { // {{{
		global $config;
		if ( strlen( $this->rurl ) == 0 ) {
			$this->rurl = $this->lurl;
		}

		$this->ldom = linkex::getDomain( $this->lurl );
		$this->rdom = linkex::getDomain( $this->rurl );
		$this->edom = linkex::getDomain( $this->email );

		if ( is_object( $config ) && isset( $config->dateformat ) ) {
			$this->addedf = date( $config->dateformat, intval( $this->added ) );
			$this->lastcheckedf = date( $config->dateformat, intval( $this->lastchecked ) );
		} else {
			$this->addedf = '';
			$this->lastcheckedf = '';
		}
		$this->expired = ( $this->dateexpire>0 && $this->dateexpire<time() );

		if ( !$usecache ) {
			$this->getLPageRank();
			$this->getRPageRank();
			$this->getLIndexedPages();
			$this->getRIndexedPages();
		}

	} // }}}
	function getPageRank( $usecache=false, $index, $url ) { // {{{
		global $config;
		$array = linkex::get( $index, $this->googleinfo, array() );
		if ( 
			$usecache == false && strlen( $url )>5 && (
				( md5( $url ) != linkex::get( 'hash', $array ) ) ||
				( time() < ( linkex::get( 'date', $array, 0 ) + PAGERANK_TIMEOUT ) )
			)
		) {
			$google = new Google;
			$google->hosts = $config->googledatacenters;
			$this->googleinfo{$index} = array(
				'value' => max( $google->getPageRank( $url ), 0 ),
				'hash' => md5( $url ), 
				'date' => time() 
			);
		}
		return ( md5( $url ) == linkex::get( 'hash', linkex::get( $index, $this->googleinfo, array() ), null ) ) ?
			linkex::get( 'value', linkex::get( $index, $this->googleinfo, array() ), -1 ) : -1;
	} // }}}
	function getLPageRank( $usecache=false ) { // {{{
		return $this->getPageRank( $usecache, 'lpagerank', $this->lurl );
	} // }}}
	function getRPageRank( $usecache=false ) { // {{{
		return $this->getPageRank( $usecache, 'rpagerank', $this->rurl );
	} // }}}
	function getIndexedPages( $usecache=false, $index, $url ) { // {{{
		global $config;
		$array = linkex::get( $index, $this->googleinfo, array() );
		if ( 
			$usecache == false && strlen( $url ) && (
				( md5( $url ) != linkex::get( 'hash', $array ) ) ||
				( time() < ( linkex::get( 'date', $array, 0 ) + PAGERANK_TIMEOUT ) )
			)
		) {
			$dom = linkex::getDomain( $url ); 
			$google = new Google;
			$google->hosts = $config->googledatacenters;
			$this->googleinfo{$index} = array(
				'value' => max( $google->getIndexedPages( $dom ), 0 ),
				'hash' => md5( $this->rurl ), 
				'date' => time() 
			);
		}
		return ( md5( $url ) == linkex::get( 'hash', $array  ) ) ?
			linkex::get( 'value', $array, -1 ) : -1;
	} // }}}
	function getLIndexedPages( $usecache=false ) { // {{{
		return $this->getIndexedPages( $usecache, 'lindexedpages', $this->lurl );
	} // }}}
	function getRIndexedPages( $usecache=false ) { // {{{
		return $this->getIndexedPages( $usecache, 'rindexedpages', $this->rurl );
	} // }}}
	function getMinPagerank() { // {{{
		global $config;
		if ( $this->minpagerank == -1 ) {
			return $config->minpagerank;
		}
		return $this->minpagerank;
	} // }}}
	function hasBacklink() { // {{{
		// return array( 'res' => bool, 'reason' => string );
		global $config;
		$this->lastchecked = time();
		$fetch = linkex::fetch( $this->rurl );
		if ( ( $e = linkex::get( 'error', $fetch, false ) ) !== false ) {
			$this->laststatus = $e;
			$retval = array( 
				'date' => time(),
				'res' => 1, 
				'reason' => $e 
			);
			$this->log[] = $retval;
			return $retval;
		} else {
			$fetch{'contents'} = linkex::stripcomments( $fetch{'contents'} );
			$matches = array();
			$this->laststatus = '200 OK';
			$links = linkex::getLinks( linkex::get( 'contents', $fetch, '' ), $this->rurl );
			$externallinks = 0;
			$urls = array_merge( array( $config->url ), $config->altlinks );
			foreach( $links AS $link ) {
				$externallinks += ( $link{'external'} == 1 && ( 
					$config->maxoutboundtype == 0 || ( 
						$config->maxoutboundtype == 1 && intval( $link{'nofollow'} ) == 0 ) 
					) 
				) ? 1:0;
				foreach( $urls AS $url ) {
					if ( linkex::compareURLs( $link{'href'}, $url ) == 0 ) {
						$matches[] = $link;
					}
				}
			}
			if ( 
				intval( $config->maxoutboundlinks ) > 0 &&
				$externallinks > intval( $config->maxoutboundlinks )
			) {
				$retval = array( 
					'date' => time(),
					'res' => 16, 
					'reason' => 'There are more than '.intval( $config->maxoutboundlinks )
					.' external links on '.$this->rurl 
				);
				$this->log[] = $retval;
				return $retval;
			}
			unset( $links );
			unset( $urls );
			if ( sizeof( $matches ) > 0 ) {
				if ( intval( $config->rejectnofollow ) == 1 ) {
					$buffer = array();
					foreach( $matches AS $link ) {
						if ( $link{'nofollow'} == 0 ) {
							$buffer[] = $link;
						}
					}
					$matches = $buffer;
					if ( sizeof( $matches ) == 0 ) {
						$retval = array( 
							'date' => time(),
							'res' => 8, 
							'reason' => 'Nofollow (rel=nofollow attribute) links are not accepted' 
						);
						$this->log[] = $retval;
						return $retval;
					}
				}
				if ( intval( $config->verifyanchor )  == 1 ) {
					$anchors = linkex::map( 'strtolower', $config->anchor );
					foreach( $matches AS $link ) {
						if ( in_array( strtolower( linkex::get( 'anchor', $link ) ), $anchors ) ) {
							$retval = array( 
								'date' => time(),
								'res' => 0, 
								'reason' => '' 
							);
							$this->log[] = $retval;
							return $retval;
						}
					}
					$retval = array( 
						'date' => time(),
						'res' => 4, 
						'reason' => 'Make sure the anchor text is correct' 
					);
					$this->log[] = $retval;
					return $retval;
				} else {
					$retval = array( 
						'date' => time(),
						'res' => 0, 
						'reason' => '' 
					);
					$this->log[] = $retval;
					return $retval;
				}
			}
		}
		if ( $config->linkbackrequired == 1 ) {
			$retval = array( 
				'date' => time(),
				'res' => 2, 
				'reason' => 'Make sure you have a link on your site' 
			);
			$this->log[] = $retval;
			return $retval;
		} else {
			$retval = array( 
				'date' => time(),
				'res' => 0, 
				'reason' => '' 
			);
			$this->log[] = $retval;
			return $retval;
		}
	} // }}}
	function save( $generate=true ) { // {{{
		global $config;
		if ( !$this->id ) {
			$this->id = linkex::genID();
		}
		if ( intval( $this->added ) == 0 ) {
			$this->added = time();
		}
		if ( !$this->wmip ) {
			$this->wmip = $_SERVER['REMOTE_ADDR'];
		}

		// Store a max of 10 log entries
		if ( !is_array( $this->log ) ) { $this->log = array(); }
		$this->log = array_reverse( $this->log );
		$this->log = linkex::arraychunk( $this->log, 10 );
		$this->log = array_shift( $this->log );
		$this->log = array_reverse( $this->log );

		if ( !linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR . $this->id, serialize( get_object_vars( $this ) ) ) ) {
			die( "\n[ ERROR ] Unable to write to file ".BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR . $this->id );
		}
		@chmod( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR . $this->id, CHMOD_FILE );
		if ( $generate !== false && is_array( $this->categories ) ) {
			foreach( $this->categories AS $cid ) {
				if ( file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $cid ) ) {
					$c = new Category( $cid );
					$c->generate();
					unset( $c );
				}
			}
		}
	} // }}}
	function blacklisted() { // {{{
		$ids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR );
		foreach( $ids AS $id ) {
			$bl = new Blacklist( $id );
			switch( $bl->type ) {
			case 'Server IP': // {{{
			case 1:
				if ( 
					linkex::compareIPs( $bl->value, $this->ldom ) == 0 ||
					linkex::compareIPs( $bl->value, $this->rdom ) == 0 
				) {
					return 'Server IP blacklisted. '.$bl->reason;
				}
				break; // }}}
			case 'Domain': // {{{
			case 2:
				if ( 
					strcmp( strtolower( $bl->value ), strtolower( $this->ldom ) ) == 0 ||
					strcmp( strtolower( $bl->value ), strtolower( $this->rdom ) ) == 0 || 
					strcmp( strtolower( $bl->value ), str_replace( 'www.', '', strtolower( $this->ldom ) ) ) == 0 ||
					strcmp( strtolower( $bl->value ), str_replace( 'www.', '', strtolower( $this->rdom ) ) ) == 0 
				) {
					return 'Domain blacklisted. '.$bl->reason;
				}
				break; // }}}
			case 'Webmaster IP': // {{{
			case 4:
				if ( linkex::compareIPs( $bl->value, $this->wmip ) == 0 ) {
					return 'Your IP is blacklisted. '.$bl->reason;
				}
			break; // }}}
			case 'Email': // {{{
			case 8:
				if ( strcmp( strtolower( $bl->value ), strtolower( $this->email ) ) == 0 ) {
					return 'Email blacklisted. '.$bl->reason;
				}
				break; // }}}
			case 'Email domain': // {{{
			case 16:	
				if ( strcmp( strtolower( $bl->value ), strtolower( $this->edom ) ) == 0 ) {
					return 'Email domain blacklisted. '.$bl->reason;
				}
				break; // }}}
			case 'Word': // {{{
			case 32:
				if ( strpos( strtolower( $this->anchor ), strtolower( $bl->value ) ) !== false ) {
					return 'Blacklisted word in title. '.$bl->reason;
				} else if ( strpos( strtolower( $this->description ), strtolower( $bl->value ) ) !== false ) {
					return 'Blacklisted word in description. '.$bl->reason;
				}
				break; // }}}
			}
		}
		return false;
	} // }}}
	function statusOptions( $id=null ) { // {{{
		$retval = array(
			'1' => 'OK',
			'2' => 'Suspended',
			'4' => 'Immune',
			'64' => 'Suspended'
		);
		if ( $id ) {
			return $retval{$id};
		} else {
			return $retval;
		}
	} // }}}	
	function updateIPs( $force=false ) { // {{{
		$this->ldomip = linkex::gethostbyname( $this->ldom, $force );
		if ( !preg_match( '/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $this->ldomip ) ) {
			$this->ldomip = 'unresolvable';
		}

		$this->rdomip = linkex::gethostbyname( $this->rdom, $force );
		if ( !preg_match( '/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $this->rdomip ) ) {
			$this->rdomip = 'unresolvable';
		}

		$this->edomip = linkex::gethostbyname( $this->edom, $force );
		if ( !preg_match( '/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $this->edomip ) ) {
			$this->edomip = 'unresolvable';
		}
	} // }}}
	function delete() { // {{{
		if ( @unlink( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR . $this->id ) ) {
			foreach( $this->categories AS $cid ) {
				if ( file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $cid ) ) {
					$c = new Category( $cid );
					$c->generate();
					unset( $c );
				}
			}
			return true;
		} else {
			return false;
		}
	} // }}}
	function toXML() { // {{{
		$resp = new XML;
		$vars = get_object_vars( $this );
		foreach( $vars AS $k=>$v ) {
			switch( $k ) {
			case 'added':
			case 'lastchecked':
			case 'dateexpire':
				$resp->add_tag( $k, date( 'r', $v ) );
				break;
			case 'categories':
				$resp->add_group( 'categories' );
				foreach( $v AS $cid ) {
					$resp->add_tag( 'castegory', $cid );
				}
				$resp->close_group();
				break;
			case 'googleinfo':
				$resp->add_group('googleinfo');
				if ( isset( $this->googleinfo{'lpagerank'} ) ) {
					$resp->add_group('lpagerank');
					$resp->add_tag('hash', $this->googleinfo{'lpagerank'}{'hash'} );
					$resp->add_tag('date', date( 'r', $this->googleinfo{'lpagerank'}{'date'} ) );
					$resp->add_tag('value', strval( $this->googleinfo{'lpagerank'}{'value'} ) );
					$resp->close_group();
				}
				if ( isset( $this->googleinfo{'rpagerank'} ) ) {
					$resp->add_group('rpagerank');
					$resp->add_tag('hash', $this->googleinfo{'rpagerank'}{'hash'} );
					$resp->add_tag('date', date( 'r', $this->googleinfo{'rpagerank'}{'date'} ) );
					$resp->add_tag('value', strval( $this->googleinfo{'rpagerank'}{'value'} ) );
					$resp->close_group();
				}
				if ( isset( $this->googleinfo{'lindexedpages'} ) ) {
					$resp->add_group('lindexedpages');
					$resp->add_tag('hash', $this->googleinfo{'lindexedpages'}{'hash'} );
					$resp->add_tag('date', date( 'r', $this->googleinfo{'lindexedpages'}{'date'} ) );
					$resp->add_tag('value', strval( $this->googleinfo{'lindexedpages'}{'value'} ) );
					$resp->close_group();
				}
				if ( isset( $this->googleinfo{'rindexedpages'} ) ) {
					$resp->add_group('rindexedpages');
					$resp->add_tag('hash', $this->googleinfo{'rindexedpages'}{'hash'} );
					$resp->add_tag('date', date( 'r', $this->googleinfo{'rindexedpages'}{'date'} ) );
					$resp->add_tag('value', strval( $this->googleinfo{'rindexedpages'}{'value'} ) );
					$resp->close_group();
				}

				$resp->close_group();
				break;
			case 'log':
				$resp->add_group('log');
				foreach( $v AS $l ) {
					$resp->add_group('item');
					$resp->add_tag('date', date( 'r', $l{'date'} ) );
					$resp->add_tag('res', strval( $l{'res'} ) );
					$resp->add_tag('reason', $l{'reason'} );
					$resp->close_group();
				}
				$resp->close_group();
				break;
			case 'pagerankinfo':
			case 'pagerank':
			case 'addedf':
			case 'lastcheckedf':
			case 'expired':
				break;
			default:
				$resp->add_tag( $k, '<![CDATA[' . strval( $v ) . ']]>' );
				break;
			}
		}
		return $resp->output();
	} // }}}
}

class Google {
	var $hosts = array( 'www.google.com' );
	var $debug = array();
	function getCH( $str ) {
		$str = preg_replace( '#^.+//#', '', $str );
		$seed = base64_decode( 'TWluaW5nIFBhZ2VSYW5rIGlzIEFHQUlOU1QgR09PR0xFJ1MgVEVSTVMgT0YgU0VSVklDRS4gWWVzLCBJJ20gdGFsa2luZyB0byB5b3UsIHNjYW1tZXIu' );
		$result = 16909125;
		$result = 0x01020345;
		$len = strlen($str);
		$slen = strlen( $seed );
		for ($i=0; $i<$len; $i++) {
			$result = $result ^ ( ord( substr( $seed, $i % $slen, 1 ) ) ^ ord( substr( $str, $i, 1 ) ) );
			$result = 2147483647 === PHP_INT_MAX ? ( ( $result >> 23 ) & 0x1ff ) | $result << 9 : ( $result >> 23 | $result << 9) & 0xFFFFFFFF;
		}
		return sprintf('8%x', $result );
	}
	function getIndexedPages( $url ) { // {{{
		$pages = -1;
		$host = $this->hosts[ mt_rand( 0, sizeof( $this->hosts ) - 1 ) ];
		$fp = fsockopen( $host, 80, $errno, $error, 2 );
		if ( $fp ) {
			$header = '';
			$header .= "GET /tbr?q=site%3A".urlencode($url)."&ie=utf-8&hl=en HTTP/1.1\r\n" ;
			$header .= "Host: ".$host."\r\n" ;
			$header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; da; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3\r\n" ;
			$header .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" ;
			$header .= "Accept-Language: da,en-us;q=0.7,en;q=0.3\r\n" ;
			$header .= "Accept-Encoding: none\r\n" ;
			$header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" ;
			$header .= "Keep-Alive: 300\r\n" ;
			$header .= "Connection: keep-alive\r\n" ;
			$header .= "Cache-Control: max-age=0\r\n" ;
			$header .= "Connection: Close\r\n\r\n" ;
			fwrite( $fp, $header );
			$data = '';
			while ( !feof( $fp ) ) {
				$data .= fgets( $fp, 128 );
			}
			fclose( $fp );
			if ( preg_match( '!of about <.*>([\d,\.]+)<!Umis', $data, $res ) ) {
				$pages=intval( str_replace( array(',','.'),'',$res[1] ) );
			}
		}
		return $pages;
	} // }}}
	function getPageRank( $url ) { /// {{{
		$pagerank = -1;
		$url = preg_replace( '#.*//#', '', $url );
		$cookie = $this->getCH( $url );		
		$host = 'toolbarqueries.google.com';
		$fp = fsockopen( $host, 80, $errno, $error, 2 );
		$this->debug['sent'] = '> Opening connection to ' . $host . PHP_EOL;
		if ( $fp ) {
			$header = '';
			$header = 'GET /tbr?client=navclient-auto&ch='. $cookie .'&features=Rank&q=info:'. $url ." HTTP/1.1\r\n";
			$header .= "Host: ".$host."\r\n" ;
			$header .= "Connection: Close\r\n\r\n" ;
			fwrite( $fp, $header );
			$this->debug['sent'] .= $header;
			$data = '';
			while ( !feof( $fp ) ) {
				$data .= fgets( $fp, 128 );
			}
			$this->debug['received'] = $data;
			fclose( $fp );
			if ( ( $pos = strpos( $data, 'Rank_' ) ) !== false ) {
				$pagerank = intval( trim( substr( $data, $pos + 9 ) ) );
			}
		}
		return $pagerank;
	} /// }}}
	function strord($str, $c, $m) { // {{{
		$i32 = 4294967296;  // 232

		$length = strlen($str);
		for ($i = 0; $i < $length; $i++) {
			$c = (float)( ((float)$c) * ((float)$m) );
			if ($c >= $i32) {
				$c = (float)($c - $i32 * (int) ($c / $i32));
				$c = (float)(($c < -2147483648) ? ($c + $i32) : $c);
			}
			$c = (float)($c + ord($str{$i}));
		}
		return $c;
	} // }}}
}

class Blacklist {
	var $id = null;
	var $type = null;
	var $value = null;
	var $reason = null;
	var $date = null;
	public function __construct( $id=null ) { // {{{
		if ( $id != null ) {
			$this->id = $id;
			$this->load();
			$this->thetype = $this->types( $this->type );
		}
	} // }}}
	function types( $id = null ) { // {{{
		$types = array( 
			 1 => 'Server IP',
			 2 => 'Domain',
			 4 => 'Webmaster IP',
			 8 => 'Email',
			16 => 'Email domain',
			32 => 'Word'
		);
		if ( $id == null ) {
			return $types;
		} else {
			return $types{$id};
		}
	} // }}}
	function load() { // {{{
		$data = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR . $this->id );
		$data = linkex::unserialize( $data );
		foreach( $data AS $k=>$v ) {
			$this->$k = $v;
		}
		unset( $data );
	} // }}}
	function save() { // {{{
		if ( $this->id == null ) {
			$this->id = linkex::genID();
		}
		if ( $this->date == null ) {
			$this->date = time();
		}
		linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR . $this->id, serialize( get_object_vars( $this ) ) );
	} // }}}
}

error_reporting( E_ALL );
/// A simple xml2array parser
class XMLNode {
	var $nodeName = null;
	function getFirstElementByNodeName( $name ) { /// {{{
		$list = $this->getElementsByNodeName( $name, true );
		if ( sizeof( $list ) > 0 ) {
			return $list[0];
		} else {
			return null;
		}
	} /// }}}
	function getElementsByNodeName( $name, $recursive = false ) { /// {{{
		$retval = array();
		if ( isset( $this->childNodes ) && sizeof( $this->childNodes ) ) {
			foreach ( $this->childNodes AS $n ) {
				if ( isset( $n->nodeName ) && $n->nodeName == $name ) {
					$retval[] = $n;
				}
				if ( $recursive && isset( $n->childNodes ) && is_array( $n->childNodes ) ) {
					$retval = array_merge( $retval, $n->getElementsByNodeName( $name, $recursive ) );
				}
			}
		}
		return $retval;
	} /// }}}
	public function __construct( $nodeName='' ) { /// {{{
		$this->nodeName = $nodeName;
	} /// }}}
}
class XMLParser {
	function getAttributes( $tag ) { // {{{
		$len = strlen( $tag );
		$retval = new XMLNode;
		/// ex: <blah name="val" test="est">
		$pos = 0;
		while( $pos < $len && XMLParser::isSpace( $tag{$pos} ) ) { $pos++; }
		do {
			if ( ( $pos = strpos( $tag, ' ', $pos ) ) !== false ) {
				$pos += 1;
				/// Pos is now at the start of the attr.
				if ( ( $end = strpos( $tag, '=', $pos ) ) !== false ) {
					$name = substr( $tag, $pos, $end-$pos );
					$pos = $end + 1;
					if ( in_array( $tag{$pos}, array( '"', "'" ) ) ) {
						$stopat = $tag{$pos};
					} else {
						$stopat = ' ';
					}
					$end = strpos( $tag, $stopat, $pos+1 );
					$end = ( $end === false ) ? $len - 2 : $end;
					$value = substr( $tag, $pos, $end-$pos );
					$retval->$name = trim( $value, '\'" ' );
					$pos = $end;
				}
			}
		} while ( $pos !== false && $pos < $len );
		return $retval;
	} // }}}
	function isSpace( $char ) { // {{{
		return in_array( $char, array( ' ', "\t", "\n", "\r" ) );
	} // }}}
	function parse( $xml, $first=true, $dumpnamespace=false ) { // {{{
		$retval = array();
		$xml = trim( preg_replace( '"\s*<\?xml.*\?>\s*"', '', $xml ) );
		$len = strlen( $xml );
		$pos = intval( strpos( $xml, '<' ) );
		do {
			while( $pos < $len && XMLParser::isSpace( $xml{$pos} ) ) { $pos++; }
			$end = strpos( $xml, '>', $pos+1 );
			$tag = substr( $xml, $pos, ( $end - $pos )+1 );
			if ( strlen( $tag ) ) {
				$buffer = XMLParser::getAttributes( $tag );
				$buffer->nodeName = substr( $tag, 1, strpos( $tag, ' ' ) - 1 );
				$pos += strlen( $tag );
				$pos = min( $len, $pos );
				if( $tag{max(0,strlen($tag)-2)} != '/' ) {
					if ( ( $end = strpos( $xml, '</'.$buffer->nodeName.'>', $pos ) ) !== false ) {
						$nodeValue = substr( $xml, $pos, $end-$pos );
						$pos = $end + 3 + strlen( $buffer->nodeName )+1;
						if ( strpos( $nodeValue, '<' ) !== false ) {
							$buffer->childNodes = XMLParser::parse( $nodeValue, false, $dumpnamespace );
						} else {
							$buffer->nodeValue = $nodeValue;
						}
					}
				}
				if ( $dumpnamespace && strpos( $buffer->nodeName, ':' ) !== false ) {
					$buffer->nodeName = substr( $buffer->nodeName, strpos( $buffer->nodeName, ':' )+1 );
				}

				$retval[] = $buffer;
			} else {
				$pos += 1000;
			}
		} while ( $pos < $len );
		if ( $first ) {
			$xml = new XMLNode( 'xml' );
			$xml->childNodes = $retval;
			return $xml;
		} else {
			return $retval;
		}
	} // }}}
}

class xml {
	var $opentags = array();
	var $buffer = '';
	var $tabs = 0;
	var $content_type = 'text/xml';
	var $charset = 'UTF-8';
	function fetch_xml_tag() { /// {{{
		return '<?xml version="1.0"?>'."\n";
	} /// }}}
	function add_group( $tag, $attr = array () ) { /// {{{
		$this->opentags[] = $tag;
		$this->buffer .= $this->tabs() . $this->build_tag( $tag, $attr ) . "\n";
		$this->tabs++;
	} /// }}}
	function close_group() { /// {{{
		$tag = array_pop( $this->opentags );
		$this->tabs--;
		$this->buffer .= $this->tabs() . sprintf( "</%s>\n", $tag );
	} /// }}}
	function build_tag( $tag, $attr, $close = false ) { /// {{{
		$buffer = '<'.$tag;
		foreach( $attr AS $k=>$v ) {
			$buffer .= sprintf( ' %s="%s"', $k, trim( $v ) );
		}
		$buffer .= ( $close ) ? " />\n":">";
		return $buffer;
	} /// }}}
	function add_tag( $tag, $content = '', $attr=array() ) { /// {{{
		$this->buffer .= $this->tabs() . $this->build_tag( $tag, $attr, ( $content == '' ) );
		$this->buffer .= ( $content == '' ) ? '': sprintf( "%s</%s>\n", $content, $tag );
	} /// }}}
	function output() { /// {{{
		foreach( $this->opentags AS $x ) {
			$this->close_group();
		}
		return $this->buffer;
	} /// }}}
	function send_content_type_header() { /// {{{
		if ( !headers_sent() ) {
			header( 'Content-Type: ' . $this->content_type . ( $this->charset == '' ? '' : '; charset=' . $this->charset ) );
		}
	} /// }}}
	function fetch() { // {{{
		return $this->fetch_xml_tag() . $this->output();
	} // }}}
	function display() { /// {{{
		$this->send_content_type_header();
		echo $this->fetch_xml_tag() . $this->output();
		exit;
	} /// }}}
	function tabs() { /// {{{
		return str_repeat( "\t", abs( $this->tabs ) );
	} /// }}}
	function escape( $var ) { // {{{
		return str_replace(
			array( '&', '"', '<', '>' ),
			array( '&amp;', '&quot;', '&lt;', '&gt;' ),
			$var
		);
	} // }}}
	function append( $str ) { // {{{
		$this->buffer .= $str;
	} // }}}
}

class captcha {
	var $method = 'html';
	var $text = '';
	var $width = 80;
	var $height = 19;
	var $chars = array('a','b','c','d','e','f','g','h','k','n','p','q','r','2','3','4','5','6','7','8','9');
	public function __construct() { // {{{
		if (
			function_exists( 'imagecreate' ) &&
			function_exists( 'imagecolorallocate' ) &&
			function_exists( 'imagefontwidth' ) &&
			function_exists( 'imagefontheight' ) &&
			function_exists( 'imagestring' ) &&
			function_exists( 'imageline' ) &&
			function_exists( 'imagedestroy' ) &&
			function_exists( 'imagegif' )
		) {
			$this->method = 'image';
		} else {
			$this->method = 'html';
		}
		$_SESSION['captcha'] = array();
		$_SESSION['captcha']['result'] = '';
		$len = mt_rand(4,5);
		for( $i=0; $i<$len; $i++ ) {
			$_SESSION['captcha']['result'] .= $this->chars[mt_rand(0,sizeof($this->chars)-1)];
		}
	} // }}}
	function generate() { // {{{
		$this->text = $_SESSION['captcha']['result'];
	} // }}}
	function image() { // {{{
		$this->generate();
		if ( $im = @imagecreate( $this->width, $this->height ) ) {
			header( 'Content-type: image/gif' );
			$white = imagecolorallocate($im, 244, 244, 244 );
			$black = imagecolorallocate($im, 0,0,0);
			$border = imagecolorallocate( $im, 178, 178, 178 );

			$font = 2;
			$fwidth = imagefontwidth( $font );
			$fheight= imagefontheight( $font );

			if ( function_exists( 'imagerotate' ) ) {

				$str = $this->text;
				$x = floor( ( $this->width / strlen( $this->text ) ) / 2 );
				for( $i=0; $i<strlen( $this->text ); $i++ ) {
					$tmp = imagecreate( $fwidth*4, $this->height );
					$twhite = imagecolorallocate($tmp, 244, 244, 244 );
					$tblack = imagecolorallocate($tmp, 0,0,0);
					imagestring( $tmp, $font, 1, 0, $this->text{$i}, $black );
					$angle = mt_rand( 340,359 ) - ( mt_rand(0,1)*341 );
					$tmp = imagerotate( $tmp, $angle, $twhite );

					imagecopy( $im, $tmp, $x, 0, 0, 0, ( $fwidth*3 ), $this->height );
					imagedestroy( $tmp );

					$x += floor( ( $this->width / strlen( $this->text ) ) * 0.8 );
				}
			} else {
				$twidth = strlen( $this->text ) * $fwidth;
				imagestring($im, $font, ( $this->width - $twidth )/2, 3, $this->text, $black );
			}
			imageline ( $im, 0, 0, $this->width, 0, $border );
			imageline ( $im, 0, $this->height-1, $this->width, $this->height-1, $border );
			imageline ( $im, 0, 0, 0, $this->height-1, $border );
			imageline ( $im, $this->width-1, 0, $this->width-1, $this->height, $border );

			imagegif($im);
			imagedestroy($im);
		}
		exit;
	} // }}}
	function html() { // {{{

		if ( $this->method == 'image' ) {
			$this->generate();
			return "<img src=\"$URI?page=captcha\" alt=\"LinkEX CAPTCHA\" style=\"width:".$this->width."px;height:".$this->height."px;border:0px;\" />";
		} else {
			$this->generate();
			return $this->text;
		}
	} // }}}
}

class autoadd {
	function knownscripts() { // {{{
		$scripts = array( 
			'linkxxxchange' => '#http://www\.linkxxxchange\.com#',
			'axslinks' => '#http://www\.axscripts\.com#',
			'linkex' => '#http://linkex\.dk#',
			'phpArcadeScript' => '#phpArcadeScript#i',
			'SocialMedia' => '#Social\s+Media#i'
		);
		return $scripts;
	} // }}}
	function SocialMedia( $con, $link ) { // {{{
		global $config;
		if ( preg_match( '#<form[\sa-z="\.\?]*\s+action=["\']?([^"\'> ]+)#i', $con{'contents'}, $form ) ) {
			$formaction = linkex::expandlink( $form[1], $con{'URL'}.'?' );
			$anchor = $config->anchor;
			$postfields = array( 
				'title' => $anchor[ mt_rand(0,sizeof($anchor)-1) ],
				'url' => $link,
				'submit' => 'Submit'
			);
			/*
			$res = linkex::fetch( $formaction, array( 'method' => 'POST', 'data' => linkex::buildquery( $postfields ) ) );
			if ( preg_match( '
				$url = preg_replace( '#(index\.php)?\??action=tradelinks.*#i', '', $con{'url'} );
				if ( preg_match( '#<title>(.*)\s+\-\s+trade#i', $con{'contents'}, $title ) ) {
					$title = $title{1};
				} else {
					$title = linkex::getDomain( $con{'url'} );
				}
				$l = new Link;
				$l->wmip = $_SERVER['REMOTE_ADDR'];
				$l->lurl = $url;
				$l->anchor = trim( $title );
				$l->categories = linkex::get( 'categories', $_POST, $config->defaultcategories );
				$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: phpArcadeScript\n\n";
				$l->status = 4;
				$l->update();
				$l->updateIPs();
				$l->save();
				return 'OK - Check mail';

			} else {
				return 'Did not recognize reply from script';
			}
			 */
		} else {
			return 'Error: form action not found';
		}
	} // }}}
	function phpArcadeScript( $con, $link ) { // {{{
		global $config;
		if ( preg_match( '#<form[\sa-z="\.\?]*\s+action=["\']?([^"\'> ]+)#'.'i', $con{'contents'}, $form ) ) {
			$anchor = $config->anchor;
			$postfields = array( 
				'websitename' => $anchor[ mt_rand(0,sizeof($anchor)-1) ],
				'websiteurl' => $link,
				'description' => $config->description,
				'emailaddress' => $config->email,
				'Submit' => 'Submit Link'
			);
			$formaction = linkex::expandlink( $form[1], $con{'URL'}.'?' );
			$res = linkex::fetch( $formaction, array( 'method' => 'POST', 'data' => linkex::buildquery( $postfields ) ) );
			if ( preg_match( '#'.'Your Link Has Been Added#'.'i', $res{'contents'} ) ) {
				$url = preg_replace( '#(index\.php)?\??action=tradelinks#'.'i', '', $con{'url'} );
				if ( preg_match( '#<title>(.*)\s+\-\s+trade#'.'i', $con{'contents'}, $title ) ) {
					$title = $title{1};
				} else {
					$title = linkex::getDomain( $con{'url'} );
				}
				$l = new Link;
				$l->wmip = $_SERVER['REMOTE_ADDR'];
				$l->lurl = $url;
				$l->anchor = trim( $title );
				$l->categories = linkex::get( 'categories', $_POST, $config->defaultcategories );
				$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: phpArcadeScript\n\n";
				$l->status = 4;
				$l->update();
				$l->updateIPs();
				$l->save();
				return 'OK - Check mail';
			} else {
				return 'Did not recognize reply from script';
			}
		} else {
			return 'Error: form action not found';
		}
	} // }}}
	function linkex( $con, $link ) { // {{{
		global $config;
		$anchor = $config->anchor;
		$postfields = array(
			'email' => $config->email,
			'lurl' => $link,
			'rurl' => $link,
			'anchor' => $anchor[ mt_rand(0,sizeof($anchor)-1) ],
			'description' => $config->description
		);

		if ( strpos( strtolower( $con{'contents'} ), 'form disabled' ) !== false ) {
			return 'Form disabled';
		} else if ( strpos( strtolower( $con{'contents'}) , 'spam check' ) !== false ) {
			return 'CAPTCHA enabled. Bailing out';
		}

		if ( preg_match( '#<form[\sa-z="\.\?]*\s+action=["\']?([^"\'> ]+)#i', $con{'contents'}, $form ) ) {
			// {{{ URL:
			if ( preg_match( '#<td.*>URL:</td>.*>(.*)</td>#Umis', $con{'contents'}, $res ) ) {
				$url = strip_tags( $res[1] );
			} else {
				return 'Error: Could not find linking URL details';
			}
			// }}}
			// {{{ Site title:
			if ( preg_match( '#<td.*>Site title:</td>.*>(.*)</td>#Umis', $con{'contents'}, $res ) ) {
				$title = strip_tags( $res[1] );
			} else {
				return 'Error: Could not find linking title details';
			}
			// }}}
			// {{{ Site description:
			if ( preg_match( '#<td.*>Site description:</td>.*>(.*)</td>#Umis', $con{'contents'}, $res ) ) {
				$description = strip_tags( $res[1] );
			} else {
				$description = '';
			}
			// }}}

			$l = new link;
			$l->wmip = $_SERVER['REMOTE_ADDR'];
			$l->lurl = $url;
			$l->anchor = trim( $title );
			$l->description = $description;
			$l->categories = linkex::get( 'categories', $_POST, $config->defaultcategories );
			$l->update();
			$l->save();

			$formaction = linkex::expandlink( $form[1], $con{'URL'}.'?' );
			$res = linkex::fetch( $formaction, array( 'method' => 'POST', 'data' => linkex::buildquery( $postfields ) ) );

			$res = strtolower( linkex::get( 'contents', $res, '' ) );

			if ( strpos( $res, 'please make sure the linkback is correct' ) !== false ) {
				$l->delete();
				return 'Error: The script could not find the linkback';
			} else if ( strpos( $res, 'link added' ) !== false ) {
				$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: LinkEX\n\n";
				$l->updateIPs();
				$l->save();
				return true;
			} else if ( strpos( $res, 'is allready in the database' ) !== false ) {
				return 'Allready listed at the site';
			}

			/* echo "<hr>".htmlentities( $res )."<hr>"; */

			$l->delete();

		} else {
			return 'Error: form action not found';
		}
	} // }}}
	function linkxxxchange( $con, $link ) { // {{{
		global $config;
		$anchor = $config->anchor;
		$postfields = array(
			'url' => $link,
			'siteurl' => $link,
			'title' => $anchor[ mt_rand(0,sizeof($anchor)-1) ]
		);

		if ( strpos( $con{'contents'}, 'no trailing slash' ) !== false ) {
			$link = rtrim( $link, '/' );
		}

		if ( 
			preg_match( '#link\s+back\s+to.*<b>(.*)</b>.*Text.*<b>(.*)</b>#Umis', $con{'contents'}, $res ) &&
			preg_match( '#<form[\sa-z="\.\?]*\s+action=["\']?([^"\'> ]+)#i', $con{'contents'}, $form )
		) {
			$url = $res[1];
			$title = $res[2];

			$l = new link;
			$l->wmip = $_SERVER['REMOTE_ADDR'];
			$l->lurl = $url;
			$l->anchor = trim( $title );
			$l->categories = linkex::get( 'categories', $_POST, $config->defaultcategories );
			$l->update();
			$l->save();

			$formaction = linkex::expandlink( $form[1], $con{'URL'}.'?' );
			$res = linkex::fetch( $formaction, array( 'method' => 'POST', 'data' => linkex::buildquery( $postfields ) ) );

			$res = strtolower( linkex::get( 'contents', $res, '' ) );
			if ( strpos( $res, 'missing title' ) !== false ) {
				$l->delete();
				return 'Error: missing title';
			} else if ( strpos( $res, 'missing url' ) !== false ) {
				$l->delete();
				return 'Error: missing URL';
			} else if ( strpos( $res, 'you entered a non-valid recip-url to link to' ) !== false ) {
				$l->delete();
				return 'Error: link URL not accepted';
			} else if ( strpos( $res, 'you entered a non-valid url' ) !== false ) {
				$l->delete();
				return 'Error: link URL not accepted';
			} else if ( strpos( $res, 'you are using invalid characters in your title' ) !== false ) {
				$l->delete();
				return 'Error: anchor has invalid characters';
			} else if ( strpos( $res, 'no value input' ) !== false ) {
				$l->delete();
				return 'Error: trailing slashes not accepted';
			} else if ( strpos( $res, '<b>link was already found in our database' ) !== false ) {
				$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: Link XXX Change\nAlready listed\n";
				$l->updateIPs();
				$l->save();
				return 'Link allready exists';
			} else if ( strpos( $res, '<center><b>cannot write' ) !== false ) {
				$l->delete();
				return 'Error: server error';
			} else if ( strpos( $res, '<br><b>thank you' ) !== false ) {
				$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: Link XXX Change\n\n";
				$l->updateIPs();
				$l->save();
				return true;
			} else {
				$l->delete();
				return 'Error: unknown response';
			}
		} else {
			return 'Could not find link details';
		}

	} // }}}
	function axslinks( $con, $link ) { // {{{
		global $config;
		$anchor = $config->anchor;
		$postfields = array(
			'url' => $link,
			'title' => $anchor[ mt_rand(0,sizeof($anchor)-1) ]
		);
		if ( 
			preg_match( '#<textarea.*>\s*(<a.*)\s*</textarea>#mis', $con{'contents'}, $res ) &&
			preg_match( '#<form[\sa-z="\.\?]+\s+action=["\']?([^"\'> ]+)#i', $con{'contents'}, $form )
		) {
			$reciplink = $res[1];
			$url = linkex::getParam( 'href', $reciplink, 'no' );
			$title = linkex::getParam( 'title', $reciplink, 'no' );

			$l = new link;
			$l->wmip = $_SERVER['REMOTE_ADDR'];
			$l->lurl = $url;
			$l->anchor = trim( $title );
			$l->categories = linkex::get( 'categories', $_POST, $config->defaultcategories );
			$l->update();
			$l->save();
			
			//echo "We'll add a link in our database to '$url' with '$title'<br>";

			// The form
			$formaction = linkex::expandlink( $form[1], $con{'URL'}.'?' );
			$res = linkex::fetch( $formaction, array( 'method' => 'POST', 'data' => linkex::buildquery( $postfields ) ) );
			if ( preg_match( '#<div id="errorbox">(.*)</div>#', linkex::get( 'contents', $res, '' ), $resp ) ) {
				switch( $resp[1] ) {
				case 'Your link was added':
					$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: AXSLinks\n\n";
					$l->updateIPs();
					$l->save();
					return true;
					break;
				case 'Invalid URL':
					$l->delete();
					return 'Error: invalid URL';
					break;
				case 'Recip Link not found':
					$l->delete();
					return 'Error: recip link not found';
					break;
				case 'Your Link was placed in queue for review':
					$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: AXSLinks\nQueued for review\n";
					$l->skipcheck = 1;
					$l->updateIPs();
					$l->save();
					return 'Link placed in queue';
					break;
				case 'Your link already exists here. Not added.':
					$l->notes .= "Autoadded:\nDate:".date( 'Y-m-d H:i:s' )."\nScript: AXSLinks\nAlready listed\n";
					$l->updateIPs();
					$l->save();
					return 'Link allready exists';
					break;
				default:
					if ( preg_match( '#Error: minimum (\d+)/10 pagerank accepted!#', linkex::get( 'contents', $resp[0], '' ), $pr ) ) {
						$l->delete();
						return 'Min. pagerank error. Requ'.'ired PageRank: '.$pr[1];
					} else {
						// I have no idea what happend!
						$l->delete();
						return 'unknown error: '.$resp[0];
					}
				}
			} else {
				// No errorbox found, i'm not even sure it's an axslinks
				$l->delete();
				return 'Could not recognize response test';
			}
		} else {
			return 'Could not find form inputs';
		}
	} // }}}
}

// }}}
// {{{ Check the environment
define( 'INSTALLED', ( linkex::installed() ) ? true:false );
if ( !is_writable( BASEDIR ) ) {
	$e = 'The directory ('.BASEDIR.') is not writable';
	if ( function_exists( 'posix_geteuid' ) && function_exists( 'posix_getpwuid' ) && function_exists( 'getmyuid' ) && function_exists( 'posix_getgrgid' ) ) {
		$pinfo = posix_getpwuid( posix_geteuid() );
		$finfo = posix_getpwuid( getmyuid() );
		$e .= '<br />&nbsp;&nbsp;&nbsp;- the directory is owned by &quot;'.linkex::get( 'name', $finfo ).'&quot; while the webserver process is runned as &quot;'.linkex::get( 'name', $pinfo ).'&quot;';
	}
	$errors[] = $e;
}
// }}}

if ( file_exists( 'storage.db' ) ) {

function debug( $str ) { // {{{
	echo "<script type=\"text/javascript\">_p('".$str."<br />');</script>";
	linkex::flush();
} // }}}

if ( 
	is_array( $_POST ) && sizeof ( $_POST ) > 0 && 
	strlen( linkex::get( '_username', $_POST, '' ) ) > 0 && strlen( linkex::get( '_password1', $_POST, '' ) ) > 0 && 
	linkex::get( '_password1', $_POST, '' ) == linkex::get( '_password2', $_POST, false ) 
) {

	echo template::header( array( 'title' => 'Upgrading' ) );
	$legend = 'Upgrading';
	echo "				<div style=\"margin:10px 0px;\">
					<fieldset>
						<legend id=\"legend\">{$legend}</legend>
						<div><pre id=\"progress\" style=\"font-size:11px;min-height:100px;margin-left:5px;\">    ID  Domain                         Status                                              PageRank BackL.Status<br /> ===============================================================================================================<br /></pre></div>
					</fieldset>
				</div>
				<script type=\"text/javascript\">
			/*<![CDATA[*/
			function _p(str){ var elem=document.getElementById('progress'); if(elem){ elem.innerHTML +=str; } }
			function _t(str){ var elem=document.getElementById('legend'); if(elem){ elem.innerHTML=str; } }
			/*]]>*/
		</script>

";
	echo template::footer();
	linkex::flush();

	$con = linkex::fileget( 'storage.db' );
	if ( strlen( $con ) && ( $oldconf = linkex::unserialize( trim( $con ) ) ) != false ) {

		$dirs = array(
			BASEDIR . DIRECTORY_SEPARATOR .'data',
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR
		);

		foreach( $dirs AS $d ) {
			if ( !is_dir( $d ) && !@mkdir( $d, 0755 ) ) {
				$errors[] = 'Unable to create directory &quot;'.$d.'&quot;';
				break;
			}
		}
		if ( sizeof( $errors ) > 0 ) { // {{{ Dump the error(s) and exit
			debug( '<span class="error">'.join( '<br />', $errors ).'</span>' );
			exit;
		} // }}}
		debug( 'Done create new directory tree' );
		linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR .'uid', '1000' );

		$transtable = array(
			'categories' => array(),
			'links' => array(),
			'filter' => array(
				1 => 0,
				2 => 1,
				3 => 2
			),
			'sortby' => array( 
				'domain' => 'ldom',
				'anchor' => 'anchor',
				'description' => 'description',
				'added' => 'added',
				'sortkey' => 'id',
				'random' => 'random'
			),
			'linkstatus' => array( 
				'OK' => 1,
				'BAD' => 2
			),
			'blacklist' => array( 
				'server_ip' => 1,
				'domain' => 2,
				'webmaster_ip' => 4,
				'email' => 8,
				'email_domain' => 16
			)
		);

		// {{{ Create the blacklist
		$list = linkex::get( 'blacklist', $oldconf, array() );
		foreach( $list AS $l ) {
			$b = new Blacklist;
			$b->type = linkex::get( linkex::get( 'type', $l, 'server_ip' ), $transtable{'blacklist'}, 1 );
			$b->value = linkex::get( 'value', $l, 'none' );
			$b->reason = linkex::get( 'reason', $l, 'no reason found' );
			$b->date = linkex::get( 'date', $l, time() );
			$b->save();
			unset( $b );
		}
		debug( 'Done converting blacklist' );
		// }}}
		// {{{ Create all the categories
		$cats = linkex::get( 'outputs', $oldconf, array() );
		$catlog = array();
		foreach( $cats AS $cat ) {
			$c = new category;
			$c->name = linkex::get( 'name', $cat, 'No name found' );
			$c->filter = linkex::get( linkex::get( 'filter', $cat, 2 ), $transtable{'filter'}, 2 );
			if ( empty( $c->filter ) ) {
				$c->filter = array( 1 );
			}
			$c->template = linkex::get( 'template', $cat, '' );
			$c->limit = linkex::get( 'limit', $cat, 0 );
			$c->order = linkex::get( 'order', $cat, 'dasc' );
			$c->sortby = linkex::get( linkex::get( 'sortby', $cat, 'id' ), $transtable{'sortby'}, 'id' );

			$c->save( false );

			$transtable{'categories'}{ linkex::get( 'id', $cat, 0 ) } = $c->id;
			$catlog[] = array(
				'file' => linkex::get( 'file', $cat, 'no filename found' ),
				'id' => $c->id
			);

			unset( $c );
		}
		debug( 'Done converting categories' );
		// }}}
		// {{{ Create all the links
		debug( 'Starting link convertion' );
		$links = linkex::get( 'links', $oldconf, array() );
		foreach( $links AS $link ) {
			$l = new link;

			$l->added					= linkex::get( 'added', $link, time() );
			$l->lastchecked		= linkex::get( 'lastcheck', $link, 0 );
			$l->lurl					= linkex::get( 'lurl', $link, 'no link url found' );
			$l->rurl					= linkex::get( 'rurl', $link, 'no recip url found' );
			$l->anchor				= linkex::get( 'anchor', $link, 'no anchor found' );
			$l->description		= linkex::get( 'description', $link, '' );
			$l->email					= linkex::get( 'email', $link, 'no email found' );
			$l->skipcheck			= linkex::get( 'skipcheck', $link, 0 );
			$l->status				= linkex::get( linkex::get( 'status', $link, 'OK' ), $transtable{'linkstatus'}, 1 );
			$l->wmip					= long2ip( linkex::get( 'ip', $link, 0 ) );

			// Do the categories
			$categories				= linkex::get( 'outputs', $link, array() );
			foreach( $categories AS $c ) {
				$cid = linkex::get( $c, $transtable{'categories'}, false );
				if ( $cid !== false ) {
					$l->categories[] = $cid;
				}
			}

			$l->update();
			$l->updateIPs();
			$l->save( false );
			debug( $l->ldom.' done' );
			$transtable{'links'}{ linkex::get( 'id', $link, 0 ) } = $l->id;
			unset( $l );
		}
		debug( 'Done converting links' );
		// }}}
		// {{{ Set the config
		$c = linkex::get( 'config', $oldconf, array() );
		$config = new config;
		$config->password = md5( linkex::get( '_username', $_POST, '' ) .'---'. linkex::get( '_password1', $_POST, '' ) );
	
		$config->installdate = linkex::get( 'installdate', $c, time() );
		$config->email = linkex::get( 'email', $c, 'no email found' );
		$config->url = linkex::get( 'url', $c, 'no url found' );
		$config->anchor = array( linkex::get( 'anchor', $c, 'no anchor found' ) );

		$config->description = linkex::get( 'description', $c, '' );
		$config->altlinks = linkex::get( 'altlinks', $c, array() );
		$config->dateformat = linkex::get( 'datef', $c, 'Y.m.d' );
		$config->displaylimit = linkex::get( 'num', $c, 100 );

		$config->linkbotuniquedomains = linkex::get( 'uniquedomains', $c, 1 );

		$config->remoteenable = linkex::get( 'croncheckallowed', $c, 0 );
		$config->remotesummary = linkex::get( 'sendsummary', $c, 0 );
		$config->remotepass = linkex::get( 'passphrase', $c, '' );
		$config->remotelimitips = linkex::get( 'limitips', $c, 1 );
		$config->remoteips = array_unique( array( 'linkex.dk' ) + linkex::get( 'iplist', $c, array() ) );
		$config->minpagerank = linkex::get( 'minpagerank', $c, 0 );

		$config->publiccategories = linkex::get( 'outputopen', $c, 0 );
		$config->disablepublicform = linkex::get( 'disableform', $c, 0 );
		$config->disablerecipfield = linkex::get( 'norecipurl', $c, 0 );

		$categories = linkex::get( 'outputs', $c, array() );
		foreach( $categories AS $cid ) {
			$config->defaultcategories[] = linkex::get( $cid, $transtable{'categories'}, 0 );
		}
		$config->defaultcategories = array_unique( $config->defaultcategories );
		$config->save();
		debug( 'Done converting configfile' );
		// }}}
		if ( sizeof( $errors ) > 0 ) { // {{{ Dump the error(s) and exit
			debug( '<span class="error">'.join( '<br />', $errors ).'</span>' );
			exit;
		} // }}}
		// {{{ Get the rules if they exists
		if ( 
			file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'rules.dat' ) && 
			filesize( BASEDIR . DIRECTORY_SEPARATOR . 'rules.dat' ) > 0 
		) {
			linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'rules', linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'rules.dat' ) );
		}
		// }}}
		// {{{ Now get rid of all the not needed files
		$d = dir( BASEDIR );
		while (false !== ($entry = $d->read())) {
			if ( !in_array( $entry, array( '.', '..', 'index.php' ) ) && is_file( BASEDIR . DIRECTORY_SEPARATOR	. $entry ) ) {
				if ( !@rename( BASEDIR . DIRECTORY_SEPARATOR . $entry, BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . $entry ) ) {
					$errors[] = "Unable to move ".$entry." to BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR". $entry;
				}
			}
		}
		$d->close();
		// }}}
		if ( sizeof( $errors ) > 0 ) { // {{{ Dump the error(s) and exit
			debug( '<span class="error">'.join( '<br />', $errors ).'</span>' );
			exit;
		} // }}}

		// linkex::redirect( BASEURI );
		// Present a nice "upgrade-done" page
		$newcats = array();
		if ( sizeof( $catlog ) > 0 ) {
			foreach( $catlog AS $c ) {
				$cat = new category( $c{'id'} );
				$cat->save();
				$newcats[] = $c{'file'}.' &raquo; '. BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR . $c{'id'};
			}
		}
		$newcats = join( '<br />', $newcats );
		debug( '<br />Your database has been upgraded.<br />' );
		debug( 'Please note, that the files generated by LinkEX has been altered,<br />and you need to change all references to them.<br />Below is a list of your categories, along with the file you need to inc'.'lude instead.<br /><br /><a href="?page=admin">Click here to proceed</a>' );
		debug( $newcats );

	} else {
		die( 'Error. Could not parse old config' );
	}
} else {

	if ( ( $username = linkex::get( '_username', $_POST, false ) ) !== false ) {
		$errors[] = 'Please specify a username';
	}
	if ( linkex::get( '_password1', $_POST, false ) !== false ) {
		if ( strlen( linkex::get( '_password1', $_POST, 'linkex' ) ) == 0 ) {
			$errors[] = 'Please specify a password';
		} else
		if ( linkex::get( '_password1', $_POST, '' ) != linkex::get( '_password2', $_POST, 1 ) ) {
			$errors[] = 'The two passwords you entered, were not the same. Please try again';
		}
	}
	echo template::header( array( 'title' => 'Upgrade requirred' ) );
	echo "<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>Upgrading LinkEX</legend>
		<div class=\"article\">
			<p>An older version of LinkEX, with the old backend, has been detected.</p>
			<p>As of version 20061218 this script is using a different approch to the flatfile database system.<br />
			Your current setting, links and categories have to be converted into this new format.</p>
			<p>Also from this version, the authorization module has been changed, so from now on you need a username and password to login.<br />
			To proceed please select your new username and password, and click &quot;OK&quot;</p>
			<p>Once the script has been converted, you should log in, and make sure every setting is correct.</p>
			<p><strong>Please note the convertion can take some time. (It could take up to 10 seconds for each link, so please be patient)</strong></p>
		</div>
	</fieldset>
</div>

<div style=\"margin:10px 0px;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Set your new login</legend>
		<form method=\"post\" action=\"$URI\">
			<table class=\"table\">
				<tr>
					<td class=\"key\">Username:</td>
					<td><input type=\"text\" class=\"text\" name=\"_username\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password:</td>
					<td><input type=\"password\" class=\"text\" name=\"_password1\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password (again):</td>
					<td><input type=\"password\" class=\"text\" name=\"_password2\" value=\"\" /></td>
				</tr>
				<tr>
					<td colspan=\"2\">&nbsp;</td>
				</tr>

				<tr>
					<td class=\"key\"></td>
					<td><input type=\"submit\" class=\"button\" name=\"ok\" value=\"OK\" /></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>

";
	echo template::footer();
}

} else 
	if ( INSTALLED ) {
		// Make sure logs directory is present
		if ( !is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR ) ) {
			@mkdir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR );
		}

		// Enable error log
		@touch( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'error.log' );
		@ini_set( 'error_log', BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'error.log' );
		@ini_set( 'log_errors', true );
		@ini_set('display_errors', 0);

		// {{{ Make sure .htaccess is present
		if ( strpos( strtolower( linkex::get( 'SERVER_SOFTWARE', $_SERVER, '' ) ), 'apache' ) !== false ) {
			if ( !file_exists( BASEDIR . DIRECTORY_SEPARATOR .'data'. DIRECTORY_SEPARATOR . '.htaccess' ) ) {
				linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR .'data'. DIRECTORY_SEPARATOR . '.htaccess', "Order Deny,Allow
Deny from all
" );
			}
			if ( !file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR . '.htaccess' ) ) {
				linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR . '.htaccess', "Order Allow,Deny
Allow from all
" );
			}
		} 
		// }}}

		$config = new config;

	if ( linkex::get( 'SERVER_SOFTWARE', $_SERVER, false ) === false ) {
		// CLI check
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );

if ( intval( $config->commandlineenable ) == 0 ) { die( "LinkEX v.20120508, Free Link Exchange Script by http://linkex.dk

Error: Command line access is disabled

" ); }
@set_time_limit( 7200 );

function output( $str ) { // {{{
	global $verbose;
	if ( $verbose ) {
		echo $str;
		flush();
	}
} // }}}
$donecats=$donelinks=false;
function verbose( $data ) { // {{{
	global $donecats, $donelinks;
	switch( $data{'action'} ) {
	case 'link': // {{{
		$sp = "% 6s  % -20s % -15s % 6s => % -10s % 10s => % -10s\n";
		if ( false === $donelinks ) {
			output( 
				"\n* Verifying backlinks..\n\n" .
				sprintf( $sp, 'ID', 'Domain', 'IP', 'Old PR', 'New PR', 'Old Status', 'New status' ) .
				"==========================================================================================\n"
			);
			$donelinks=true;
		}
		output( 
			sprintf( $sp, $data{'id'}, linkex::truncate( $data{'rdom'}, 20 ),
			$data{'rdomip'},
			$data{'oldpagerank'}, $data{'pagerank'}, 
			link::statusOptions( $data{'oldstatus'} ), 
			link::statusOptions( $data{'status'} ) ) 
		);

		break; // }}}
	case 'category': // {{{
		$sp = "% 6s   % -20s % -10s\n";
		if ( false === $donecats ) {
			output( 
				"\n\n* Rebuilding categories..\n\n" .
				sprintf( $sp, 'ID', 'Name', 'Status' ) .
				"==========================================================================================\n"
			);
			$donecats = true;
		}
		output( sprintf( $sp, $data{'id'}, linkex::truncate( $data{'name'}, 20 ), 'done' ) );
		break; // }}}
	}
} // }}}
if ( strpos( strtolower( join(' ', $_SERVER['argv'] ) ), '--help' ) !== false ) {
	$linkexpath = __FILE__;
	echo "LinkEX v.20120508, Free Link Exchange Script by http://linkex.dk

Usage: /path/to/php {$linkexpath} [OPTION]...

/path/to/php is usually /usr/local/bin/php or /usr/bin/php
if in doubt ask your server administrator

The following options are available:
--quiet               quiet (no output) (this is the default).
--verbose             be verbose
--help                this help screen

";
	exit;
} else {
	$verbose = ( strpos( strtolower( join(' ', $_SERVER['argv'] ) ), 'verbose' ) !== false );
	$report = linkex::verifybacklinks( linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR ), 'verbose' );

	if ( intval( $config->commandlinesummary ) == 1 ) {
		$report = template::report( $report );
		linkex::mail( $config->email, 'Link verification report', $report );
	}
}

	} else {
		define( 'LOGGEDIN', linkex::authorized() );
		switch( linkex::get( 'page', $_REQUEST, '' ) ) {
		case 'xmlcom':
		case 'xmlrpc':

function xmlauthorize( $xml ) { // {{{
	global $config;
	// {{{ Check the IP
	if ( intval( $config->remotelimitips ) == 1 ) {
		$ok = false;
		foreach ( $config->remoteips AS $rip ) {
			if ( linkex::compareIPs( $_SERVER['REMOTE_ADDR'], $rip ) == 0 ) {
				$ok = true;
				break;
			}
		}
		if ( ! $ok ) {
			$resp = new XML;
			$resp->add_group( 'methodResponse' );
			$resp->add_tag( 'errno', 403 );
			$resp->add_tag( 'error', '403 Forbidden' );
			$resp->add_tag( 'description', 'Your IP '.$_SERVER['REMOTE_ADDR'].' is not accepted' );
			$resp->close_group();
			$resp->display();
			exit;
		}
	}
	// }}}
	// {{{ Check the password
	if ( strlen( $config->remotepass ) > 0 ) {
		$password = $xml->getFirstElementByNodeName( 'password' );
		if ( $password == null || $password->nodeValue != $config->remotepass ) {
			$resp = new XML;
			$resp->add_group( 'methodResponse' );
			$resp->add_tag( 'errno', 401 );
			$resp->add_tag( 'error', '401 Unauthorized' );
			$resp->add_tag( 'description', 'Invalid password' );
			$resp->close_group();
			$resp->display();
			exit;
		}	
	}
	// }}}
	return true;
} // }}}
function checkNodes( $xml, $list ) {
	foreach ( $list AS $n ) {
		if ( null == $xml->getFirstElementByNodeName( $n ) ) {
			$resp = new XML;
			$resp->add_group( 'methodResponse' );
			$resp->add_tag( 'errno', 400 );
			$resp->add_tag( 'error', '400 Bad Request' );
			$resp->add_tag( 'description', 'Missing element '.$n );
			$resp->close_group();
			$resp->display();
			exit;
		}
	}
}
header( 'Content-type: text/xml' );
header( 'X-Powered-By: LinkEX/20120508' );

// TODO fix allowed methods
if ( in_array( linkex::get( 'REQUEST_METHOD', $_SERVER, '' ), array('POST','GET')) ) {
	// {{{ Get data
	if ( isset( $HTTP_RAW_POST_DATA ) && strlen( $HTTP_RAW_POST_DATA ) ) {
		$data = $HTTP_RAW_POST_DATA;
	} else {
		$data = str_replace( "\r", '', @implode("\n", @file( 'php://input' ) ) );
	}
	// }}}
	$xml = XMLParser::parse( $data );
	$methodCall = $xml->getFirstElementByNodeName( 'methodCall' );
	if ( $methodCall != null ) {
		$methodName = $methodCall->getFirstElementByNodeName( 'methodName' );
		switch( $methodName->nodeValue ) {
		case 'link.edit': // {{{
		case 'link.add': 
			if ( xmlauthorize( $methodCall ) ) {
				$data = $methodCall->getFirstElementByNodeName( 'link' );
				if ( $data == null ) {
					$resp = new XML;
					$resp->add_group( 'methodResponse' );
					$resp->add_tag( 'errno', 400 );
					$resp->add_tag( 'error', '400 Bad Request' );
					$resp->add_tag( 'description', 'No data found' );
					$resp->close_group();
					$resp->display();
					exit;
				} else {
					checkNodes( $data, array( 
						'lurl', 'rurl', 'anchor', 
						'title', 'description', 
						'categories', 'email', 
						'skipcheck', 'skippagerank',
						'notes', 'weight' 
					) );

				}
			}
			break; // }}}
		case 'link.list': // {{{
			if ( xmlauthorize( $methodCall ) ) {
				$linkids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
				$resp = new XML;
				$resp->add_group( 'methodResponse' );
				$resp->add_tag( 'errno', '0' );
				$resp->add_group( 'links' );
				foreach( $linkids AS $lid ) {
					$l = new link( $lid );
					$resp->add_group( 'link' );
					$resp->append( $l->toXML() );
					$resp->close_group();
					unset( $l );
				}
				$resp->close_group();
				$resp->close_group();
				$resp->display();
			}
			break; // }}}
		case 'admin.info': // {{{
			if ( xmlauthorize( $methodCall ) ) {
				$resp = new XML;
				$resp->add_group( 'methodResponse' );
				$resp->add_tag( 'errno', '0' );
				$resp->add_group( 'LinkEX' );
				$resp->add_tag( 'version', 20120508 );
				$resp->add_tag( 'formOpen', ( $config->disablepublicform == 1 ) ? '0':'1' );
				$resp->add_tag( 'email', htmlentities( $config->email ) );
				$resp->add_tag( 'url', $config->url );
				$resp->add_tag( 'minpagerank', "".$config->minpagerank );

				$resp->add_group( 'titles' );
				if ( is_array( $config->anchor ) ) {
					foreach( $config->anchor AS $a ) {
						$resp->add_tag( 'title', htmlentities( $a ) );
					}
				}
				$resp->close_group();

				$resp->add_group( 'categories' );
				$cats = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR );
				foreach( $cats AS $cid ) {
					$c = new Category( $cid );
					$ca = array( 
						'id' => $cid,
						'name' => htmlentities( $c->name )
					);
					$resp->add_tag( 'category', '', $ca );
				}
				$resp->close_group();

				$stats=array(
					'total'=>0,
					'suspended'=>0
				);
				$links = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
				foreach( $links AS $lid ) {
					$l = new link( $lid );
					$stats{'total'}++;
					if ( $l->status == 2 ) {
						$stats{'suspended'}++;
					}
				}
				$resp->add_tag( 'links', '', $stats );

				$resp->add_tag( 'description', htmlentities( $config->description ) );
				$resp->add_tag( 'zend.version', zend_version() );
				$resp->add_tag( 'php.version', phpversion() );
				$resp->add_tag( 'uname', htmlentities( php_uname( 's' ).' '.php_uname( 'r' ).' '.php_uname( 'm' ) ) );
				$resp->close_group();
				$resp->close_group();
				$resp->display();
			}
			break; // }}}
		case 'info': // {{{
			$resp = new XML;
			$resp->add_group( 'methodResponse' );
			$resp->add_tag( 'errno', '0' );
			$resp->add_group( 'LinkEX' );
			$resp->add_tag( 'version', 20120508 );
			$resp->add_tag( 'formOpen', ( $config->disablepublicform == 1 ) ? '0':'1' );
			$resp->add_tag( 'email', htmlentities( $config->email ) );
			$resp->add_tag( 'url', $config->url );
			$resp->add_tag( 'minpagerank', "".$config->minpagerank );

			$resp->add_group( 'titles' );
			if ( is_array( $config->anchor ) ) {
				foreach( $config->anchor AS $a ) {
					$resp->add_tag( 'title', htmlentities( $a ) );
				}
			}
			$resp->close_group();

			$resp->add_group( 'categories' );
			$cats = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR );
			foreach( $cats AS $cid ) {
				$c = new Category( $cid );
				if ( intval( $config->publiccategories  ) == 1 && intval( $c->public ) == 1 ) {
					$ca = array( 
						'id' => $cid,
						'name' => htmlentities( $c->name )
					);
					$resp->add_tag( 'category', '', $ca );
				}
			}
			$resp->close_group();

			$resp->add_tag( 'description', htmlentities( $config->description ) );
			$resp->close_group();
			$resp->close_group();
			$resp->display();
			break; // }}}
		default: // {{{
			$resp = new XML;
			$resp->add_group( 'methodResponse' );
			$resp->add_tag( 'errno', 501 );
			$resp->add_tag( 'error', '501 Not Implemented' );
			$resp->add_tag( 'description', 'methodName "'.$methodName->nodeValue.'" not implemented' );
			$resp->close_group();
			$resp->display();
			break; // }}}
		}
	} else { // {{{ No method
		$resp = new XML;
		$resp->add_group( 'methodResponse' );
		$resp->add_tag( 'errno', 400 );
		$resp->add_tag( 'error', '400 Bad Request' );
		$resp->add_tag( 'description', 'No method call found' );
		$resp->close_group();
		$resp->display();
		exit;
	} // }}}
} else { // {{{ Not a POST request
	$resp = new XML;
	$resp->add_group( 'methodResponse' );
	$resp->add_tag( 'errno', 400 );
	$resp->add_tag( 'error', '400 Bad Request' );
	$resp->add_tag( 'description', 'XML-RPC server accepts POST requests only' );
	$resp->close_group();
	$resp->display();
	exit;
} // }}}

			break;
		case 'resetpassword':

if ( ( $key = linkex::get( 'key', $_GET, false ) ) !== false ) {

	if ( linkex::get( 'date', $config->resetpassword ) > ( time() - 3600 ) ) {
		if ( $key == linkex::get( 'key', $config->resetpassword ) ) {
			$formaction = htmlentities( $_SERVER['REQUEST_URI'] );
			echo template::header( array( 'title' => 'Reset forgotten username/password' ) );

			if ( array_key_exists( '_username', $_POST ) ) {
				$_username = linkex::get( '_username', $_POST, '' );
				$_password1 = linkex::get( '_password1', $_POST, '' );
				$_password2 = linkex::get( '_password2', $_POST, '' );
				// {{{ Check the username
				if ( strlen( trim( $_username ) ) == 0 ) {
					$errors[] = 'Please enter a username';
				}
				// }}}
				// {{{ Check the password(s)
				if ( strlen( trim( $_password1 ) ) == 0 ) {
					$errors[] = 'Please enter a password';
				} else if ( trim( $_password1 ) != trim( $_password2 ) ) {
					$errors[] = 'The two passwords did not match, please try again.';
				}
				// }}}
				if ( sizeof( $errors ) == 0 ) {
					$config->password = md5( $_username .'---'. $_password1 );
					$config->save();

					echo "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Reset username/password</legend>
		<table class=\"table\">
			<tr>
				<td>
					Your usename/password has been changed. You can now log in with the new username and password.
				</td>
			</tr>
		</table>
	</fieldset>
</div>

";

				} else {
					echo "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Reset username/password</legend>
		<form method=\"post\" action=\"{$formaction}\">
			<table class=\"table\">
				<tr>
					<td colspan=\"2\">
						You have been authorized to change the password for this LinkEX installation.<br />
						Please enter your new username and password in the form below.<br />
					</td>
				</tr>
				<tr>
					<td class=\"key\">Username:</td>
					<td><input type=\"text\" class=\"text\" name=\"_username\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password:</td>
					<td><input type=\"password\" class=\"text\" name=\"_password1\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password (again):</td>
					<td><input type=\"password\" class=\"text\" name=\"_password2\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><br /><input type=\"submit\" class=\"button\" value=\"OK\" /></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>

";
				}
			} else {
				echo "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Reset username/password</legend>
		<form method=\"post\" action=\"{$formaction}\">
			<table class=\"table\">
				<tr>
					<td colspan=\"2\">
						You have been authorized to change the password for this LinkEX installation.<br />
						Please enter your new username and password in the form below.<br />
					</td>
				</tr>
				<tr>
					<td class=\"key\">Username:</td>
					<td><input type=\"text\" class=\"text\" name=\"_username\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password:</td>
					<td><input type=\"password\" class=\"text\" name=\"_password1\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password (again):</td>
					<td><input type=\"password\" class=\"text\" name=\"_password2\" value=\"\" /></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><br /><input type=\"submit\" class=\"button\" value=\"OK\" /></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>

";
			}
			echo template::footer();
			exit;
		} else {
			$errors[] = 'Key mismatch. Please retry';
		}
	} else {
		$errors[] = 'This link has expired, please re-request a username/password';
	}
	echo template::header( array( 'title' => 'Reset forgotten username/password' ) );
	echo template::footer();
} else
	if ( sizeof( $_POST ) > 0 ) {
		if ( 
			linkex::get( 'captcha', $_POST, false ) &&
			linkex::get( 'captcha', $_SESSION, false ) && linkex::get( 'result', $_SESSION['captcha'], false ) &&
			$_POST['captcha'] == $_SESSION['captcha']['result']
		) {

			$config->resetpassword = array(
				'date' => time(),
				'key' => md5( mt_rand(0,10000) . time() . microtime() )
			);
			$config->save();

			linkex::mail( $config->email, 'Reset admin password', "This is a message from LinkEX running on {$_SERVER['HTTP_HOST']}.

You or someone else has requested a new username/password.
To generate a new set, please visit the following address:

http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}&key={$config->resetpassword['key']}

Thanks
" );

			echo template::header( array( 'title' => 'Reset forgotten username/password' ) );
			echo "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Reset username/password</legend>
		<table class=\"table\">
			<tr>
				<td>
					An email has been sent to you with further instructions.
				</td>
			</tr>
		</table>
	</fieldset>
</div>

";
			echo template::footer();
			exit;
		} else {
			$errors[] = 'Spam check failed. Please retry';
		}
	}

echo template::header( array( 'title' => 'Reset forgotten username/password' ) );
$c = new captcha;
$captchatag = $c->html(); 
$captcha = "				<tr>
					<td class=\"key\">Spam check:</td>
					<td>
						<table cellpadding=\"0\" cellspacing=\"0\">
							<tr>
								<td style=\"width:100px;\">{$captchatag}</td>
								<td><input type=\"text\" name=\"captcha\" value=\"\" class=\"text\" style=\"width:50px;\" /></td>
							</tr>
						</table>
					</td>
					<td class=\"help\"></td>
				</tr>

";
echo "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Reset username/password</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<table class=\"table\">
				<tr>
					<td colspan=\"2\">
						First you need to fill out the form below. When you submit, you will receive an email with further instructions.
					</td>
				</tr>
				{$captcha}
				<tr>
					<td class=\"key\"></td>
					<td><br /><input type=\"submit\" class=\"button\" value=\"OK\" /></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>

";
echo template::footer();

			break;
		case 'captcha':
			$c = new captcha;
			$c->image();
			break;
		case 'xmlclient':

header( 'Content-type: text/xml' );
header( 'X-Powered-By: LinkEX/20120508' );

if ( LOGGEDIN ) {
	switch( linkex::get( 'view', $_REQUEST, '' ) ) {
	case 'BlackList.list':
		$file = BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'xml.blacklist.list';
		$url	= 'http://my.linkex.dk/xml/server.php';
		$xml = new xml;
		$xml->add_group( 'methodCall' );
		$xml->add_tag( 'methodName', 'BlackList.list' );
		$xml->add_group( 'params' );
		$xml->add_tag( 'host', str_replace( 'www.','',$_SERVER['HTTP_HOST'] ) );
		$xml->add_group( 'BlackList' );
		$ids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR );
		foreach( $ids AS $id ) {
			$blacklist = new Blacklist( $id );
			if ( $blacklist->public == '1' ) {
				$xml->add_group( 'entry' );
				$xml->add_tag( 'type',   xml::escape( str_replace(' ','', strtolower( $blacklist->types( $blacklist->type ) ) ) ) );
				$xml->add_tag( 'value',  xml::escape( $blacklist->value ) );
				$xml->add_tag( 'reason', xml::escape( $blacklist->reason ) );
				$xml->close_group();
			}
		}
		$xml = $xml->output();
		$xml = linkex::fetch( $url, array( 'method' => 'POST', 'data' => $xml, 'agent' => 'XML/1.0' ) );
		echo linkex::get( 'contents', $xml, '' );
		exit;
		break;
	case 'changelog':
		$file = BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'rss.changelog';
		$url	= 'http://linkex.dk/feeds/changelog.xml?rel=' . 20120508;
		break;
	default:
		$resp = new XML;
		$resp->add_group( 'ajax' );
		$resp->add_tag( 'errno', 503 );
		$resp->add_tag( 'error', '503 Service Unavailable' );
		$resp->add_tag( 'description', 'Please specify feed' );
		$resp->close_group();
		$resp->display();
		exit;
		break;
	}
	if ( file_exists( $file ) && ( time() - filemtime( $file ) ) < 3600 ) {
		$con = linkex::fileget( $file );
	} else {
		$con = linkex::fetch( $url, array( 'agent' => 'LinkEX/20120508' ) );
		$con = linkex::get( 'contents', $con, '' );
		if ( !is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR ) ) { @mkdir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR, 0775 ); }	
		linkex::fileput( $file, $con );
	}
	echo $con;
	exit;
} else {
	$resp = new XML;
	$resp->add_group( 'ajax' );
	$resp->add_tag( 'errno', 403 );
	$resp->add_tag( 'error', '403 Forbidden' );
	$resp->add_tag( 'description', 'you must be logged in to do this' );
	$resp->close_group();
	$resp->display();
}
exit;

			break;
		case 'rss':
header( 'Content-type: text/xml' );
header( 'X-Powered-By: LinkEX/20120508' );

if ( LOGGEDIN ) {
	switch( linkex::get( 'view', $_REQUEST, '' ) ) {
	case 'announcements':
		$file = BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'rss.announcements';
		$url	= 'http://feeds2.feedburner.com/linkex-script';
		break;
	case 'changelog':
		$file = BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'rss.changelog';
		$url	= 'http://linkex.dk/feeds/changelog.xml?rel=' . 20120508;
		break;
	default:
		$resp = new XML;
		$resp->add_group( 'ajax' );
		$resp->add_tag( 'errno', 503 );
		$resp->add_tag( 'error', '503 Service Unavailable' );
		$resp->add_tag( 'description', 'Please specify feed' );
		$resp->close_group();
		$resp->display();
		exit;
		break;
	}
	if ( file_exists( $file ) && ( time() - filemtime( $file ) ) < 3600 ) {
		$con = linkex::fileget( $file );
	} else {
		$ref = 'http://'. linkex::get( 'HTTP_HOST', $_SERVER, 'nohost' ) . linkex::get( 'REQUEST_URI', $_SERVER, '/nouri' );
		$con = linkex::fetch( $url, array( 'agent' => 'LinkEX/20120508', 'referer' => $ref, 'timeout' => 2 ) );
		$con = linkex::get( 'contents', $con, '' );
		if ( !is_dir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR ) ) { 
			@mkdir( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR, 0775 ); 
		}
		if ( strlen( $con )>0 ) { 
			linkex::fileput( $file, $con );
		}
	}
	echo $con;
	exit;
} else {
	$resp = new XML;
	$resp->add_group( 'ajax' );
	$resp->add_tag( 'errno', 403 );
	$resp->add_tag( 'error', '403 Forbidden' );
	$resp->add_tag( 'description', 'you must be logged in to do this' );
	$resp->close_group();
	$resp->display();
}
exit;

			break;
		case 'admin':
			if ( LOGGEDIN ) {
				switch( linkex::get( 'view', $_REQUEST, '' ) ) {
				case '':
// {{{ Search variables.. what a mess
$searchshow = 'hidden';
$searchfor = array();
$field = linkex::get( 'sf', $_REQUEST, '' );
$searchfields = linkex::selector( 'sf', array( 
	'all' => 'all fields', 
	'email' => 'email', 
	'recipurl' => 'reciprocal URL', 
	'linkurl' => 'link URL', 
	'anchor' => 'site title', 
	'description' => 'description' ), $field, false, 'select' );
if ( strlen( $field )>0 ) { $searchshow = ''; $searchfor[]='sf='.$field; }

$selected = linkex::get( 'c', $_REQUEST, array() );
if ( is_string( $selected ) ) { $selected = linkex::map( 'trim', explode( ',', $selected ) ); }
$categories = linkex::selector( 'c', linkex::categories( true ), $selected, true, null, array( 'class' => 'noauto' ) );
if ( sizeof( $selected ) > 0 ) { $searchshow = ''; $searchfor[] = 'c='.join(',',$selected); }

$searchq = urldecode( linkex::get( 'q', $_REQUEST, '' ) );
if ( strlen( $searchq )>0 ) { $searchshow = ''; $searchfor[]='q='.$searchq; }

$case = linkex::checkbox( linkex::get( 'cs', $_REQUEST, '' ) );
if ( strlen( $case )>0 ) { $searchshow = ''; $searchfor[]='cs=1'; }

if ( strlen( $searchshow ) == 0 && sizeof( $_POST ) > 0 ) {
	linkex::redirect( BASEURI . '?page=admin&'.join( '&', $searchfor ) );
}
// }}}
$linkids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
// {{{ Summary init.. what a mess
$links = array();
$summary = array();
$summary{'pagerank'} = array();
$summary{'pagerank'}{0} = 0;
$summary{'pagerank'}{1} = 0;
$summary{'pagerank'}{2} = 0;
$summary{'pagerank'}{3} = 0;
$summary{'pagerank'}{4} = 0;
$summary{'pagerank'}{5} = 0;
$summary{'pagerank'}{6} = 0;
$summary{'pagerank'}{7} = 0;
$summary{'pagerank'}{8} = 0;
$summary{'pagerank'}{9} = 0;
$summary{'pagerank'}{10} = 0;
$summary{'links'}{'all'} = 0;
$summary{'links'}{1} = 0;
$summary{'links'}{2} = 0;
$summary{'links'}{4} = 0;
$ips = array();
$ips{'ips'} = array();
$ips{'subips'} = array();
// }}}
$linkids_suspended = array();
foreach( $linkids AS $lid ) {
	$l = new link( $lid );
	// Apply filter if nessecary
	// {{{ Category filter
	if ( ( $c = linkex::get( 'c', $_REQUEST, false ) ) !== false ) {
		$c = linkex::map( 'trim', explode( ',', $c ) );
		if ( sizeof( array_intersect( $c, $l->categories ) ) == 0 ) {
			continue;
		}
	} // }}}
	// {{{ Search string
	if ( ( $q = linkex::get( 'q', $_REQUEST, false ) ) !== false && ( $f = linkex::get( 'sf', $_REQUEST ) !== false ) ) {
		$cs = ( linkex::get( 'cs', $_REQUEST, 0 ) == 0 );
		$q = ( $cs ) ? strtolower( $q ) : $q;
		switch( linkex::get( 'sf', $_REQUEST ) ) {
		case 'description': // {{{
			$a = $l->description;
			if ( $cs ) { $a = strtolower( $a ); }
			if ( strpos( $a, $q ) === false ) {
				continue 2;
			}
			break; // }}}
		case 'anchor': // {{{
			$a = $l->anchor;
			if ( $cs ) { $a = strtolower( $a ); }
			if ( strpos( $a, $q ) === false ) {
				continue 2;
			}
			break; // }}}
		case 'linkurl': // {{{
			$a = $l->lurl;
			if ( $cs ) { $a = strtolower( $a ); }
			if ( strpos( $a, $q ) === false ) {
				continue 2;
			}
			break; // }}}
		case 'recipurl': // {{{
			$a = $l->rurl;
			if ( $cs ) { $a = strtolower( $a ); }
			if ( strpos( $a, $q ) === false ) {
				continue 2;
			}
			break; // }}}
		case 'email': // {{{
			$a = $l->email;
			if ( $cs ) { $a = strtolower( $a ); }
			if ( strpos( $a, $q ) === false ) {
				continue 2;
			}
			break; // }}}
		case 'all': // {{{
			$a = $l->email;
			if ( $cs ) { $a = strtolower( $a ); }
			$b = $l->rurl;
			if ( $cs ) { $b = strtolower( $b ); }
			$c = $l->lurl;
			if ( $cs ) { $c = strtolower( $c ); }
			$d = $l->anchor;
			if ( $cs ) { $d = strtolower( $d ); }
			$e = $l->description;
			if ( $cs ) { $e = strtolower( $e ); }
			if ( 
				strpos( $a, $q ) !== false || 
				strpos( $b, $q ) !== false || 
				strpos( $c, $q ) !== false || 
				strpos( $d, $q ) !== false || 
				strpos( $e, $q ) !== false
			) {} else { continue 2; }
			break; // }}}
		}
	}
	// }}}
	$links[] = $l;
	$summary{'pagerank'}{ $l->rpagerank }++;
	$summary{'links'}{'all'}++;
	$summary{'links'}{ $l->status }++;
	$ips{'ips'}[] = $l->rdomip;
	$ips{'subips'}[] = long2ip( ( ip2long( $l->rdomip ) >> 8 << 8 ) );
	if( $l->status == 2 ) {
		$linkids_suspended[] = $lid;
	}	
}
$summary{'links'}{'ips'} = sizeof( array_unique( $ips{'ips'} ) );
$summary{'links'}{'subips'} = sizeof( array_unique( $ips{'subips'} ) );
$linkids_all = join( ',', $linkids );
$linkids_suspended = join( ',', $linkids_suspended );
unset( $ips );
unset( $linkids );

echo template::header( array( 'title' => 'Overview' ) );

// Sort the $links[] and chunk it up into the size we want
$sortkey = linkex::get( 'sortkey', $_REQUEST, $config->sortkey );
$sortorder = linkex::get( 'sortorder', $_REQUEST, $config->sortorder );

linkex::sort( $links, $sortkey, $sortorder );
$links = linkex::arraychunk( $links, $config->displaylimit );
$start = linkex::get( 'start', $_REQUEST, 1 );
$pages = sizeof( $links );
$navlinks = template::navigation( $start, $pages, BASEURI . '?page=admin&amp;sortkey='.$sortkey.'&amp;sortorder='.$sortorder.'&amp;' );
if ( sizeof( $links ) > 0 ) {
	$links = $links{ ( $start - 1 ) };
} else {
	$links = array();
}
$sorder = array( 
	'added'				=> ( $sortkey == 'added' && $sortorder == 'asc' )								? 'desc':'asc',
	'lastchecked' => ( $sortkey == 'lastchecked' && $sortorder == 'asc' )					? 'desc':'asc',
	'rpagerank'		=> ( $sortkey == 'rpagerank' && $sortorder == 'asc' )						? 'desc':'asc',
	'rindexed'		=> ( $sortkey == 'rindexed' && $sortorder == 'asc' )						? 'desc':'asc',
	'lpagerank'		=> ( $sortkey == 'lpagerank' && $sortorder == 'asc' )						? 'desc':'asc',
	'lindexed'		=> ( $sortkey == 'lindexed' && $sortorder == 'asc' )						? 'desc':'asc',
	'rdom'				=> ( $sortkey == 'rdom' && $sortorder == 'asc' )								? 'desc':'asc',
	'rdomip'			=> ( $sortkey == 'rdomip' && $sortorder == 'asc' )							? 'desc':'asc',
	'ldom'				=> ( $sortkey == 'ldom' && $sortorder == 'asc' )								? 'desc':'asc',
	'ldomip'			=> ( $sortkey == 'ldomip' && $sortorder == 'asc' )							? 'desc':'asc',
	'anchor'			=> ( $sortkey == 'anchor' && $sortorder == 'asc' )							? 'desc':'asc',
	'title'				=> ( $sortkey == 'title' && $sortorder == 'asc' )								? 'desc':'asc',
	'link'				=> ( $sortkey == 'link' && $sortorder == 'asc' )								? 'desc':'asc',
	'status'			=> ( $sortkey == 'status' && $sortorder == 'asc' )							? 'desc':'asc'
);
$sclass = array( 
	'added'				=> ( ( $sortkey == 'added' )    				? 'sort'.$sortorder:'' ),
	'lastchecked' => ( ( $sortkey == 'lastchecked' )			? 'sort'.$sortorder:'' ),
	'rpagerank'		=> ( ( $sortkey == 'rpagerank' ) 				? 'sort'.$sortorder:'' ),
	'lpagerank'		=> ( ( $sortkey == 'lpagerank' ) 				? 'sort'.$sortorder:'' ),
	'rdom'				=> ( ( $sortkey == 'rdom' )     				? 'sort'.$sortorder:'' ),
	'rdomip'			=> ( ( $sortkey == 'rdomip' )    				? 'sort'.$sortorder:'' ),
	'ldom'				=> ( ( $sortkey == 'ldom' )     				? 'sort'.$sortorder:'' ),
	'ldomip'			=> ( ( $sortkey == 'ldomip' )    				? 'sort'.$sortorder:'' ),
	'lindexed'		=> ( ( $sortkey == 'lindexed' )  				? 'sort'.$sortorder:'' ),
	'rindexed'		=> ( ( $sortkey == 'rindexed' )  				? 'sort'.$sortorder:'' ),
	'anchor'			=> ( ( $sortkey == 'anchor' )    				? 'sort'.$sortorder:'' ),
	'title'				=> ( ( $sortkey == 'title' )    				? 'sort'.$sortorder:'' ),
	'link'				=> ( ( $sortkey == 'link' )		  				? 'sort'.$sortorder:'' ),
	'status'			=> ( ( $sortkey == 'status' )    				? 'sort'.$sortorder:'' )
);
$columns = array();
$template = array_merge( array( 'checkbox', 'options' ), $config->template );
foreach( $template AS $key ) {
	$columns[] = array(
		'key' => $key,
		'sorder' => ( $sortkey == $key && $sortorder == 'asc' ) ? 'desc':'asc',
		'sclass' => ( $sortkey == $key ) ? 'sort'.$sortorder:''
	);
}
$columnscount=sizeof($columns);
$columnscountleft=sizeof($columns)-6;
// {{{ Mass edit options
$masseditstatus = linkex::selector( 'masseditsetstatus', array( '0' => 'Leave as it is' ) + link::statusOptions(), 
	'0', false, 'radio' , null, '&nbsp;&nbsp;');
$masseditskipcheck = linkex::selector( 'masseditskipcheck', 
	array( '0' => 'Leave as it is', '1' => 'Skip selected', '2' => 'Do not skip selected' ), 
	'0', false, 'radio', null, '&nbsp;&nbsp;' );
$masseditskippagerank = linkex::selector( 'masseditskippagerank', 
	array( '0' => 'Leave as it is', '1' => 'Ignore selected', '2' => 'Do not ignore selected' ), 
	'0', false, 'radio', null, '&nbsp;&nbsp;' );
$masseditcategoryset = linkex::selector( 'masseditcategoryset', 
	array( '0' => 'Leave as it is', '1' => 'Update', '2' => 'Overwrite' ), 
	'0', false, 'radio', null, '&nbsp;&nbsp;' );
$masseditcategories = linkex::selector( 'masseditcategories', linkex::categories( true ), null, true, null, array( 'class' => 'noauto' )  );

$masseditminpagerank = linkex::selector( 'masseditminpagerank', 
	array( 'null' => 'Leave as it is', -1=>'Use global min. PageRank&trade;', 
		0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9, 10=>10 
	), 
	null, false, 'select', 
	array( 'style' => 'width:auto;' ) );

// }}}
echo "<div style=\"margin:12px;\">
	<fieldset class=\"expandable {$searchshow}\" style=\"width:100%;\" id=\"fs_search_filter\">
		<legend>Search/filter</legend>
		<div class=\"contractor\">
			<form method=\"post\" action=\"$URI?page=admin\">
				<table style=\"width:90%;margin:0px auto;\">
					<tr>
						<td class=\"key\">Search for:</td>
						<td><input type=\"text\" class=\"text\" name=\"q\" value=\"{$searchq}\" style=\"width:200px;\" /> in {$searchfields}</td>
					</tr>
					<tr>
						<td class=\"key\"></td>
						<td><label><input class=\"checkbox noauto\" type=\"checkbox\" name=\"cs\" value=\"1\" {$case} /> case sensitive</label></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Categories:</td>
						<td>{$categories}</td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\"></td>
						<td><input type=\"submit\" name=\"ok\" value=\"OK\" class=\"button\" /></td>
					</tr>
				</table>
			</form>
		</div>
	</fieldset>
</div>
<div style=\"margin:12px;\">
	<fieldset class=\"expandable hidden\" style=\"width:100%;\" id=\"fs_links_summary\">
		<legend>Links summary</legend>
		<div class=\"contractor\">
			<table style=\"width:90%;margin:0px auto;\">
				<tr>
					<td style=\"width:30%;\" class=\"bold\">Total links:</td>
					<td style=\"width:20%;\" class=\"bold\">{$summary{'links'}{'all'}}</td>
					<td style=\"width:20%;\"><div class=\"pagerank pr10\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{10}}</td>
				</tr>
				<tr>
					<td>&nbsp;&nbsp;&nbsp;&nbsp;Suspended links:</td>
					<td>{$summary{'links'}{2}}</td>
					<td style=\"width:20%;\"><div class=\"pagerank pr9\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{9}}</td>
				</tr>
				<tr>
					<td>&nbsp;&nbsp;&nbsp;&nbsp;Immune links:</td>
					<td>{$summary{'links'}{4}}</td>
					<td style=\"width:20%;\"><div class=\"pagerank pr8\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{8}}</td>
				</tr>
				<tr>
					<td>&nbsp;&nbsp;&nbsp;&nbsp;OK links:</td>
					<td>{$summary{'links'}{1}}</td>
					<td style=\"width:20%;\"><div class=\"pagerank pr7\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{7}}</td>
				</tr>
				<tr>
					<td></td>
					<td></td>
					<td style=\"width:20%;\"><div class=\"pagerank pr6\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{6}}</td>
				</tr>
				<tr>
					<td>Unique IPs:</td>
					<td>{$summary{'links'}{'ips'}}</td>
					<td style=\"width:20%;\"><div class=\"pagerank pr5\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{5}}</td>
				</tr>
				<tr>
					<td>Unique C-Class IPs:</td>
					<td>{$summary{'links'}{'subips'}}</td>
					<td style=\"width:20%;\"><div class=\"pagerank pr4\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{4}}</td>
				</tr>
				<tr>
					<td></td>
					<td></td>
					<td style=\"width:20%;\"><div class=\"pagerank pr3\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{3}}</td>
				</tr>
				<tr>
					<td></td>
					<td></td>
					<td style=\"width:20%;\"><div class=\"pagerank pr2\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{2}}</td>
				</tr>
				<tr>
					<td></td>
					<td></td>
					<td style=\"width:20%;\"><div class=\"pagerank pr1\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{1}}</td>
				</tr>
				<tr>
					<td></td>
					<td></td>
					<td style=\"width:20%;\"><div class=\"pagerank pr0\"></div></td>
					<td style=\"width:30%;\">{$summary{'pagerank'}{0}}</td>
				</tr>
			</table>
		</div>
	</fieldset>
</div>

<div style=\"margin:12px;\">
	<fieldset class=\"expandable hidden\" style=\"width:100%;\" id=\"fs_rss_news\">
		<legend id=\"rsslegend\">LinkEX news (updating..)</legend>
		<div class=\"contractor\">
			<div class=\"rssnews\" id=\"rssnews\">&nbsp;</div>
		</div>
	</fieldset>
</div>
<script type=\"text/javascript\">
			/*<![CDATA[*/
			$(document).ready(function(){ var url = location.href.replace( /\?.*/, '' )+'?page=rss&view=announcements'; $.get( url,
			function(xml){ var html=''; $(\"legend#rsslegend\").html(\"LinkEX news&nbsp;(parsing xml..)\"); var items=$(\"item\", xml); $(items).each(function(){ var title=$(this).find(\"title:first\").text(); var link=$(this).find(\"link:first\").text(); var pubDate=$(this).find(\"pubDate:first\").text(); var description=$(this).find(\"description:first\").text(); html +='<div class=\"item\"><div class=\"meta\"><div class=\"title\"><a target=\"_blank\" href=\"'+link+'\">'+ title+'</a></div>Posted on '+pubDate+'</div><div class=\"contents\">'+description+'</div></div>'; }); $(\"div#rssnews\").html(html); $(\"legend#rsslegend\").html(\"LinkEX news&nbsp;(\"+items.length+\"&nbsp;items)\"); })});
			/*]]>*/
		</script>

<script type=\"text/javascript\">
			/*<![CDATA[*/
			var linkids_all = [{$linkids_all}]; var linkids_suspended = [{$linkids_suspended}];
			/*]]>*/
		</script>
<form action=\"$URI?page=admin&amp;view=verify\" method=\"post\" id=\"adminverify\">
	<div style=\"margin:10px;\">
		<table class=\"list\" id=\"links\" cellspacing=\"0\">
			<thead>
				<tr class=\"th\" valign=\"bottom\">
					"; if ( is_array( $columns ) && sizeof( $columns )>0 ) { foreach ( $columns AS $col ) { echo "
					".(($col['key'] == 'checkbox')?("<th style=\"width:20px;\">&nbsp;</th>
					"):(($col['key'] == 'options')?("<th style=\"width:50px;\"></th>
					"):(($col['key'] == 'added')?("<th style=\"width:65px;\"><a 
							class=\"{$sclass['added']}\"
							href=\"$URI?page=admin&amp;sortkey=added&amp;sortorder={$sorder['added']}&amp;start={$start}\">Added</a></th>
					"):(($col['key'] == 'lastchecked')?("<th style=\"width:65px;\"><a 
							class=\"{$sclass['lastchecked']}\"
							href=\"$URI?page=admin&amp;sortkey=lastchecked&amp;sortorder={$sorder['lastchecked']}&amp;start={$start}\">Checked</a></th>

					"):(($col['key'] == 'rpagerank')?("<th style=\"width:75px;\"><abbr title=\"Inbound PageRank&trade;\"><a
								class=\"{$sclass['rpagerank']}\"
								href=\"$URI?page=admin&amp;sortkey=rpagerank&amp;sortorder={$sorder['rpagerank']}&amp;start={$start}\">iPR</a></abbr></th>
					"):(($col['key'] == 'rdom')?("<th style=\"width:130px;\"><abbr title=\"Inbound domain\"><a 
							class=\"{$sclass['rdom']}\"
							href=\"$URI?page=admin&amp;sortkey=rdom&amp;sortorder={$sorder['rdom']}&amp;start={$start}\">iDomain</a></abbr></th>
					"):(($col['key'] == 'rdomip')?("<th style=\"width:100px;\"><abbr title=\"Inbound domain IP\"><a 
							class=\"{$sclass['rdomip']}\"
							href=\"$URI?page=admin&amp;sortkey=rdomip&amp;sortorder={$sorder['rdomip']}&amp;start={$start}\">iIP</a></abbr></th>
					"):(($col['key'] == 'rindexed')?("<th style=\"width:75px;\"><abbr title=\"Inbound site indexed pages\"><a 
							class=\"{$sclass['rindexed']}\"
							href=\"$URI?page=admin&amp;sortkey=rindexed&amp;sortorder={$sorder['rindexed']}&amp;start={$start}\">iIndexed</a></abbr></th>

					"):(($col['key'] == 'lpagerank')?("<th style=\"width:75px;\"><abbr title=\"Outbound PageRank&trade;\"><a 
							class=\"{$sclass['lpagerank']}\"
							href=\"$URI?page=admin&amp;sortkey=lpagerank&amp;sortorder={$sorder['lpagerank']}&amp;start={$start}\">oPR</a></abbr></th>
					"):(($col['key'] == 'ldom')?("<th style=\"width:130px;\"><abbr title=\"Outbound domain\"><a 
							class=\"{$sclass['ldom']}\"
							href=\"$URI?page=admin&amp;sortkey=ldom&amp;sortorder={$sorder['ldom']}&amp;start={$start}\">oDomain</a></abbr></th>
					"):(($col['key'] == 'ldomip')?("<th style=\"width:100px;\"><abbr title=\"Outbound domain IP\"><a 
							class=\"{$sclass['ldomip']}\"
							href=\"$URI?page=admin&amp;sortkey=ldomip&amp;sortorder={$sorder['ldomip']}&amp;start={$start}\">oIP</a></abbr></th>
					"):(($col['key'] == 'lindexed')?("<th style=\"width:75px;\"><abbr title=\"Outbound site indexed pages\"><a 
							class=\"{$sclass['lindexed']}\"
							href=\"$URI?page=admin&amp;sortkey=lindexed&amp;sortorder={$sorder['lindexed']}&amp;start={$start}\">oIndexed</a></abbr></th>
					
					"):(($col['key'] == 'anchor')?("<th><abbr title=\"Link anchor\"><a 
							class=\"{$sclass['anchor']}\"
							href=\"$URI?page=admin&amp;sortkey=anchor&amp;sortorder={$sorder['anchor']}&amp;start={$start}\">Anchor</a></abbr></th>
					"):(($col['key'] == 'title')?("<th><abbr title=\"Link title\"><a 
							class=\"{$sclass['title']}\"
							href=\"$URI?page=admin&amp;sortkey=title&amp;sortorder={$sorder['title']}&amp;start={$start}\">Title</a></abbr></th>
					"):(($col['key'] == 'link')?("<th><abbr title=\"Link\"><a 
							class=\"{$sclass['link']}\"
							href=\"$URI?page=admin&amp;sortkey=link&amp;sortorder={$sorder['link']}&amp;start={$start}\">Link</a></abbr></th>
					"):(($col['key'] == 'status')?("<th style=\"width:50px;\"><abbr title=\"Link status\"><a 
							class=\"{$sclass['status']}\"
							href=\"$URI?page=admin&amp;sortkey=status&amp;sortorder={$sorder['status']}&amp;start={$start}\">Status</a></abbr></th>
					"):("")))))))))))))))))."
					"; } } else { echo ""; } echo "
				</tr>
			</thead>
			<tbody>
				".(($pages>1)?("
				<tr class=\"navigation\">
					<td colspan=\"{$columnscount}\" class=\"center navigation\">
						{$navlinks}
					</td>
				</tr>
				"):(""))."
				"; if ( is_array( $links ) && sizeof( $links )>0 ) { foreach ( $links AS $i=>$link ) { echo "
				<tr>
					"; if ( is_array( $columns ) && sizeof( $columns )>0 ) { foreach ( $columns AS $col ) { echo "
					".(($col['key'] == 'checkbox')?("<td style=\"width:20px;text-align:center;\"><input tabindex=\"{$i}\" type=\"checkbox\" name=\"lid[]\" value=\"{$link->id}\" class=\"checkbox status{$link->status} linkcheckbox\" /></td>
					"):(($col['key'] == 'options')?("<td style=\"width:50px;\">
						<a href=\"$URI?page=admin&amp;view=link&amp;action=form&amp;id={$link->id}\">edit</a>
						<a class=\"delete\" href=\"$URI?page=admin&amp;view=link&amp;action=delete&amp;id={$link->id}\">del</a></td>
					"):(($col['key'] == 'added')?("<td>{$link->addedf}</td>
					"):(($col['key'] == 'lastchecked')?("<td>{$link->lastcheckedf}</td>

					"):(($col['key'] == 'rpagerank')?("<td>
						<div class=\"pagerank pr{$link->rpagerank}\"></div>
						<div class=\"minpagerank minpr{$link->minpr}\"></div>
					</td>
					"):(($col['key'] == 'rdom')?("<td>{$link->rdom}</td>
					"):(($col['key'] == 'rdomip')?("<td>{$link->rdomip}</td>
					"):(($col['key'] == 'rindexed')?("<td>{$link->rindexed}</td>
					"):(($col['key'] == 'lpagerank')?("<td>
						<div class=\"pagerank pr{$link->lpagerank}\"></div>
					</td>
					"):(($col['key'] == 'ldom')?("<td>{$link->ldom}</td>
					"):(($col['key'] == 'ldomip')?("<td>{$link->ldomip}</td>
					"):(($col['key'] == 'lindexed')?("<td>{$link->lindexed}</td>
					"):(($col['key'] == 'link')?("<td><a href=\"{$link->lurl}\" target=\"_blank\">{$link->anchor}</a></td>
					"):(($col['key'] == 'anchor')?("<td>{$link->anchor}</td>
					"):(($col['key'] == 'title')?("<td>{$link->title}</td>
					"):(($col['key'] == 'status')?("<td class=\"center\"><div class=\"icon icon{$link->status}\"></div></td>

					"):("")))))))))))))))))."
					"; } } else { echo ""; } echo "
				</tr>
				"; } } else { echo ""; } echo "
				".(($pages>1)?("
				<tr class=\"navigation\">
					<td colspan=\"{$columnscount}\" class=\"center navigation\">
						{$navlinks}
					</td>
				</tr>
				"):(""))."
		</tbody>
		<tfoot>
			<tr valign=\"top\">
				<td><div class=\"imageup\"></div></td>
				<td colspan=\"6\">
					<a href=\"#\" 
						onclick=\"this.blur();selectLinks('all',function(){this.checked=true;});return false;\">Select all</a> &middot; 
					<a href=\"#\" 
						onclick=\"this.blur();selectLinks('none',function(){this.checked=false;});return false;\">Select none</a> &middot; 
					<a href=\"#\" 
						onclick=\"this.blur();selectLinks('invert',function(){this.checked=!this.checked;});return false;\">Invert selection</a> &middot;
					<a href=\"#\" 
						onclick=\"this.blur();selectLinks('suspended',function(){this.checked=$(this).hasClass('status2');});return false;\"
						>Select suspended</a>
					<div id=\"selectmsg\"></div>
				</td>
				<td colspan=\"{$columnscountleft}\">
					<input type=\"submit\" class=\"button\" name=\"verify\" value=\"Verify selected links\" style=\"width:150px;\" /><br />
					<input type=\"submit\" class=\"button\" name=\"delete\" value=\"Delete selected links\" 
					style=\"width:150px;color:red;margin-top:5px;\" onclick=\"return confirm( 'Are you sure you would like to delete all the selected links?' );\"/><br />
				</td>
			</tr>
		</tfoot>
	</table>
</div>

<div style=\"margin:12px;\">
	<fieldset class=\"expandable {$searchshow}\" style=\"width:100%;\" id=\"fs_mass_edit\">
		<legend>Mass edit</legend>
		<div class=\"contractor\">
			<table style=\"width:90%;margin:0px auto;\">
				<tr>
					<td class=\"key\">Set status:</td>
					<td>
						{$masseditstatus}
					</td>
				</tr>
				<tr>
					<td class=\"key\">Skip check:</td>
					<td>
						{$masseditskipcheck}
					</td>
				</tr>
				<tr>
					<td class=\"key\">Ignore PageRank&trade;:</td>
					<td>
						{$masseditskippagerank}
					</td>
				</tr>
				<tr>
					<td class=\"key\">Min. PageRank&trade;:</td>
					<td>
						{$masseditminpagerank}
					</td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Categories:</td>
					<td>
						{$masseditcategoryset}<br />
						{$masseditcategories}
					</td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\"></td>
					<td><input type=\"submit\" name=\"massedit\" value=\"OK\" class=\"button\" /></td>
				</tr>
			</table>
		</div>
	</fieldset>
</div>
</form>
";

echo template::footer();

					break;
				case 'blacklist':

switch( linkex::get( 'action', $_REQUEST, 'overview' ) ) {
case 'import': // {{{
	echo template::header( array( 'title' => 'Blacklist - import' ) );
	if ( ( $xml = linkex::get( 'xml', $_POST, false ) ) !== false ) {
		// Lets just use regex to parse the input, not sure simplexml is installed on all servers
		preg_match_all( '#<entry>(.*)</entry>#Umis', $xml, $xml );
		if ( sizeof( $xml[1] ) == 0 ) {
			$errors[] = 'No &lt;entry&gt; elements found';
		} else {
			$ids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR );
			$current = array();
			foreach( $ids AS $id ) {
				$blacklist = new Blacklist( $id );
				$current[] = $blacklist->type.'--'.strtolower( $blacklist->value );
				unset( $blacklist );
			}
			$result = array();
			foreach( $xml[1] AS $entry ) {
				if ( 
					preg_match( '#<type>(.*)</type>#Umis', $entry, $type ) &&
					preg_match( '#<value>(.*)</value>#Umis', $entry, $value ) &&
					preg_match( '#<reason>(.*)</reason>#Umis', $entry, $reason )
				) {
					switch( strtolower( str_replace( ' ', '', $type[1] ) ) ) {
					case 'serverip': $type = 1; break;
					case 'domain': $type = 2; break;
					case 'webmasterip': $type = 4; break;
					case 'email': $type = 8; break;
					case 'emaildomain': $type = 16; break;
					case 'word': $type = 32; break;
					default: $type = 0; break;
					}
					$value = html_entity_decode( $value[1] );
					$key = $type .'--'. strtolower( $value );
					if ( !in_array( $key, $current ) ) {
						$b = new Blacklist;
						$b->type = $type;
						$b->value = htmlentities( $value );
						$b->reason = htmlentities( $reason[1] );
						$b->save();
						$result[] = htmlentities( $value ) .' added';
					} else {
						$result[] = htmlentities( $value ) .' already listed';
					}
				} else {
					$result[] = 'Missing type/value/reason in '.htmlentities( $entry );
				}
			}
			$result = join( "\n", $result );
			echo "
<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>XML Import</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<div style=\"margin:10px;\">
				<textarea name=\"xml\" style=\"width:800px;height:500px;\" class=\"pre\" disabled=\"disabled\">{$result}</textarea>
			</div>
		</form>
	</fieldset>
</div>
";
			echo template::footer();	
			exit;
		}
		$xml = linkex::get( 'xml', $_POST, '' );
	}
	echo "
<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>XML Import</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<div style=\"margin:10px;\">
				<textarea name=\"xml\" style=\"width:800px;height:500px;\" class=\"pre\">{$xml}</textarea><br />
				<input class=\"button\" type=\"submit\" name=\"ok\" value=\"OK\" />			
			</div>
		</form>
	</fieldset>
</div>
";
	echo template::footer();	
	break; // }}}
case 'export': // {{{
	echo template::header( array( 'title' => 'Blacklist - export' ) );
	$ids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR );
	$xml = new xml;
	$xml->add_group( 'BlackList' );
	foreach( $ids AS $id ) {
		$xml->add_group( 'entry' );
		$blacklist = new Blacklist( $id );
		$type = $blacklist->types( $blacklist->type );
		$xml->add_tag( 'type', $type );
		$xml->add_tag( 'value', htmlentities( xml::escape( $blacklist->value ) ) );
		$xml->add_tag( 'reason', htmlentities( xml::escape( $blacklist->reason ) ) );
		$xml->close_group();
	}
	$xml = $xml->output();
	echo "
<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>XML Export</legend>
		<div style=\"margin:10px;\">
			<textarea name=\"export\" style=\"width:800px;height:500px;\" class=\"pre\">{$xml}</textarea>
		</div>
	</fieldset>
</div>
";
	echo template::footer();	
	break; // }}}
case 'delete': // {{{
	if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
		@unlink( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR . $id );
	}
	linkex::redirect( BASEURI . '?page=admin&view=blacklist' );
	break; // }}}
case 'form': // {{{

	if ( sizeof( $_POST ) > 0 ) {
		if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
			$blacklist = new Blacklist( $id );
		} else {
			$blacklist = new Blacklist;
		}

		$blacklist->type = linkex::get( 'type', $_POST, '0' );
		$blacklist->value = linkex::get( 'value', $_POST, '' );
		$blacklist->reason = linkex::get( 'reason', $_POST, '' );
		$blacklist->public = linkex::get( 'public', $_POST, 0 );
		$blacklist->save();
		linkex::redirect( BASEURI . '?page=admin&view=blacklist&action=form&id='.$blacklist->id );
		exit;

	}

	if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
		$title = 'Edit blacklist entry [id:'.$id.']';
		$blacklist = new Blacklist( $id );
	} else {
		$title = 'New Blacklist entry';
		$blacklist = new Blacklist;
	}

	$type = linkex::selector( 'type', $blacklist->types(), $blacklist->type, false, 'select', 
		array( 'onchange' => 'modified=true;' ) );
	$_SERVER['REQUEST_URI'] = htmlentities( $_SERVER['REQUEST_URI'] );	
	$public = linkex::checkbox( $blacklist->public );
	echo template::header( array( 'title' => $title ) );
	echo "<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>{$title}</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<table>
				<tr>
					<td class=\"key\">Type:</td>
					<td>{$type}</td>
				</tr>
				<tr>
					<td class=\"key\">Value:</td>
					<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"value\" value=\"{$blacklist->value}\"  style=\"width:300px;\" /></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Reason:</td>
					<td><textarea onchange=\"modified=true;\" class=\"text\" name=\"reason\" style=\"width:300px;font-size:10px;\" cols=\"80\" rows=\"3\">{$blacklist->reason}</textarea></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><input class=\"button\" type=\"submit\" name=\"ok\" value=\"OK\" onclick=\"modified=false;\" /></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>

";
	echo template::footer();

	break; // }}}
case 'overview': // {{{
	$ids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR );
	$list = array();
	foreach( $ids AS $id ) {
		$list[] = new Blacklist( $id );
	}
	echo template::header( array( 'title' => 'Blacklist' ) );
	echo "<div style=\"margin:10px;\">
	<table class=\"list\" id=\"blacklist\" cellspacing=\"0\">
		<thead>
			<tr class=\"th\">
				<th></th>
				<th>Type</th>
				<th>Value</th>
				<th>Reason</th>
			</tr>
			<tr>
				<td colspan=\"5\" class=\"center navigation\">
					<a href=\"index.php?page=admin&amp;view=blacklist&amp;action=form\">Create new entry</a>
					<a href=\"index.php?page=admin&amp;view=blacklist&amp;action=import\">Import blacklist</a>
					<a href=\"index.php?page=admin&amp;view=blacklist&amp;action=export\">Export blacklist</a>
				</td>
			</tr>
		</thead>
		<tbody>
			"; if ( is_array( $list ) && sizeof( $list )>0 ) { foreach ( $list AS $blacklist ) { echo "
			<tr class=\"{$rowclass}\">
				<td>
					<a href=\"$URI?page=admin&amp;view=blacklist&amp;action=form&amp;id={$blacklist->id}\">edit</a>
					<a href=\"$URI?page=admin&amp;view=blacklist&amp;action=delete&amp;id={$blacklist->id}\" onclick=\"return confirm('Are you sure you would like to delete this entry?');\">del</a>
				</td>
				<td>{$blacklist->thetype}</td>
				<td>{$blacklist->value}</td>
				<td>{$blacklist->reason}</td>
			</tr>
			"; } } else { echo "
			<tr>
				<td class=\"center\" colspan=\"4\">- no entries found -</td>
			</tr>
			"; } echo "
		</tbody>
	</table>
</div>
<script type=\"text/javascript\"></script>
";
	echo template::footer();	
	break; // }}}
case 'oldoverview': // {{{
	$ids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR );
	echo template::header( array( 'title' => 'Blacklist' ) );
	// List all the entries
	echo "<div style=\"margin:10px;\">
	<table class=\"list\" id=\"blacklist\" cellspacing=\"0\">
		<thead>
			<tr class=\"th\">
				<th></th>
				<th>Type</th>
				<th>Value</th>
				<th>Reason</th>
			</tr>
			<tr>
				<td colspan=\"5\" class=\"center navigation\">
					<a href=\"index.php?page=admin&amp;view=blacklist&amp;action=form\">Create new entry</a>
					<a href=\"index.php?page=admin&amp;view=blacklist&amp;action=import\">Import blacklist</a>
					<a href=\"index.php?page=admin&amp;view=blacklist&amp;action=export\">Export blacklist</a>
				</td>
			</tr>
		</thead>
		<tbody>
";
	if ( sizeof( $ids ) > 0 ) {
		$i=0;
		foreach( $ids AS $id ) {
			$rowclass=($i++%2)?'even':'odd';
			$blacklist = new Blacklist( $id );
			$type = $blacklist->types( $blacklist->type );
			echo "<tr class=\"{$rowclass}\">
	<td>
		<a href=\"$URI?page=admin&amp;view=blacklist&amp;action=form&amp;id={$blacklist->id}\">edit</a>
		<a href=\"$URI?page=admin&amp;view=blacklist&amp;action=delete&amp;id={$blacklist->id}\" onclick=\"return confirm('Are you sure you would like to delete this entry?');\">del</a>
	</td>
	<td>{$type}</td>
	<td>{$blacklist->value}</td>
	<td>{$blacklist->reason}</td>
</tr>
";
		}
	} else {
		echo "<tr>
	<td class=\"center\" colspan=\"4\">- no entries found -</td>
</tr>
";
	}

	echo "	</tbody>
</table>
</div>
<script type=\"text/javascript\"></script>
";
	echo template::footer();	
	break; // }}}
}

					break;
				case 'categories':

switch( linkex::get( 'action', $_REQUEST, 'overview' ) ) {
case 'delete': // {{{
	if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
		$files = linkex::glob( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR . $id . '(\-\d+)?' );
		$files[] = BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $id;
		foreach( $files AS $f ) {
			@unlink( $f );
		}
	}
	linkex::redirect( BASEURI . '?page=admin&view=categories' );
	break; // }}}
case 'form': // {{{
	if ( sizeof( $_POST ) > 0 ) {
		if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
			$category = new Category( $id );
		} else {
			$category = new Category;
		}
		$category->name = linkex::get( 'name', $_POST, '' );
		$category->filename = linkex::get( 'filename', $_POST, '' );
		$category->filter  = linkex::get( 'filter', $_POST, $category->filter );
		$category->sortby  = linkex::get( 'sortby', $_POST, $category->sortby );
		$category->order  = linkex::get( 'order', $_POST, $category->order );
		$category->slots  = linkex::get( 'slots', $_POST, $category->slots );
		$category->template  = linkex::get( 'template', $_POST, $category->template );
		$category->public = linkex::get( 'public', $_POST, 0 );
		$category->split = linkex::get( 'split', $_POST, 0 ); 
		$category->save();
		linkex::redirect( BASEURI . '?page=admin&view=categories&action=form&id='.$category->id );
	}
	
	if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
		$category = new category( $id );
		$title = 'Edit Category [id:'.$id.']';
		$BASEDIR = BASEDIR;
		$file = BASEFOLDER . DIRECTORY_SEPARATOR . 'data'. DIRECTORY_SEPARATOR .'output'. DIRECTORY_SEPARATOR . $id;
		$installcode = "<div style=\"margin:10px auto;\">
	<fieldset class=\"expandable hidden\" id=\"fs_categories_install_{$id}\">
		<legend onclick=\"toggle(this);\">Include code</legend>
		<div class=\"contractor\">
			<table style=\"width:98%;margin:0px auto;\">
				<tr>
					<td colspan=\"3\"><br />Use the following code below to&nbsp;include the links in a PHP script</td>
				</tr>
				<tr>
					<td colspan=\"2\" class=\"pre\">&lt;?php&nbsp;include( &quot;{$file}&quot; );&nbsp;?&gt;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td colspan=\"3\"><br />Use the following code below to&nbsp;include the links using SSI</td>
				</tr>
				<tr>
					<td colspan=\"2\" class=\"pre\">&lt;!--#include file=&quot;{$file}&quot; --&gt;</td>
					<td class=\"help\"></td>
				</tr>
			</table>
		</div>
	</fieldset>
</div>

";
	} else {
		$installcode = '';
		$category = new category;
		$title = 'New Category';
	}
	$category->template = htmlentities( $category->template );
	$category->public = linkex::checkbox( $category->public );
	$options = link::statusOptions();
	$options['-1'] = 'Expired links';
	$filter = linkex::selector( 'filter', $options, $category->filter, true, 'checkbox', 
		array( 'onchange' => 'modified=true;' ) ); 

	$sortby = linkex::selector( 'sortby', $category->sortbys(), $category->sortby, false, 'select', 
		array( 'onchange' => 'modified=true;', 'style' => 'width:150px;' ) ); 
	$order = linkex::selector( 'order', $category->orders(), $category->order, false, 'select', 
		array( 'onchange' => 'modified=true;', 'style' => 'width:150px;' ) ); 
	$_SERVER['REQUEST_URI'] = htmlentities( $_SERVER['REQUEST_URI'] );	

	$variables = "<div style=\"margin:10px auto;\">
	<fieldset class=\"expandable hidden\" id=\"fs_category_variables_{$id}\">
		<legend onclick=\"toggle(this);\">Template variables</legend>
		<div class=\"contractor\">
			<table style=\"width:98%;margin:0px auto;\">
				<tr>
					<td colspan=\"2\"><br />The following template variables are available:</td>
				</tr>
				<tr>
					<td class=\"pre right\" style=\"width:150px;\">&#123;&#36;URL&#125;</td>
					<td>Linking url</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;DOMAIN&#125;</td>
					<td>Linking domain</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;ANCHOR&#125;</td>
					<td>Site anchor</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;TITLE&#125;</td>
					<td>Site title</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;DESCRIPTION&#125;</td>
					<td>Site description</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;ADDED&#125;</td>
					<td>Date when link was added</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;INDEX&#125;</td>
					<td>Position of the link in this category. Starting from 1 (one)</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;CATEGORYID&#125;</td>
					<td>ID of this category</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;CATEGORYNAME&#125;</td>
					<td>Name of this category</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;FIRST&#125;</td>
					<td>Evaluates to 1 if the link is the first, else 0</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;LAST&#125;</td>
					<td>Evaluates to 1 if the link is the last, else 0</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;PAGERANK&#125;</td>
					<td>The PageRank of the link</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;FILENO&#125;</td>
					<td>When using the &quot;Links pr. file&quot; this will be replaces with the current file number</td>
				</tr>
				<tr>
					<td class=\"pre right\">&#123;&#36;FILES&#125;</td>
					<td>When using the &quot;Links pr. file&quot; this will be replaces with the total number of files created</td>
				</tr>
				<tr>
					<td colspan=\"2\"><br />
						The following pseudo functions are available:
					</td>
				</tr>
				<tr valign=\"top\">
					<td class=\"pre right\">&#123;IF val&#125;...&#123;/IF&#125;</td>
					<td>
						To use with &#123;&#36;FIRST&#125; and &#123;&#36;LAST&#125;. Please note, you cannot nest the IF's
					</td>
				</tr>
				<tr valign=\"top\">
					<td class=\"pre right\">&#123;CYCLE values=&quot;..&quot;&#125;</td>
					<td>
						Will cycle through the \"values\"seperated by \",\".<br /><br />
						ex. <span class=\"pre\">&lt;a class=&quot;&#123;CYCLE values=&quot;red,blue&quot;&#125;&quot; href=&quot;..&quot;&gt;</span><br />
						will make every second link have <span class=\"pre\">class=&quot;red&quot;</span> and the others <span class=\"pre\">class=&quot;blue&quot;</span>.
					</td>
				</tr>
				<tr valign=\"top\">
					<td class=\"pre right\">&#123;TABLE&#125;</td>
					<td>

						If the very first line is &#123;TABLE&#125; the output will be put into a table.<br />
						You can add the parameter <span class=\"pre\">cols=&quot;n&quot;</span> to make the table have n columns. The default is 2.<br />
						You can add the parameter <span class=\"pre\">rows=&quot;n&quot;</span> to limit the table to n rows. If this parameter is left out, the number of rows needed is automaticly calculated so all links will be present.<br />
						If you would like empty cells to be filled with use <span class=\"pre\">default=\"..\"</span><br /><br />
						ex. <span class=\"pre\">&#123;TABLE cols=&quot;3&quot;&#125;<br />&lt;a href=&quot;...&quot;&gt;...&lt;/a&gt;</span><br />
						<br />
						Will create a table with 3 column.
						<br /><br />
						The only \"reserved\" parameters are default, rows, cols and valign. Any other parameters will be inserted into the table. So you can add cellpadding=\"..\" or class=\"..\" or anything.
					</td>
				</tr>
			</table>
		</div>
	</fieldset>
</div>

";
	echo template::header( array( 'title' => $title ) );
	echo "<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>{$title}</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<table>
				<tr>
					<td class=\"key\">Name:</td>
					<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"name\" value=\"{$category->name}\" /></td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Link filter:</td>
					<td>{$filter}</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Order:</td>
					<td>{$sortby}{$order}</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Public:</td>
					<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"public\" value=\"1\" {$category->public} /></td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Template:</td>
					<td><textarea onchange=\"modified=true;\" class=\"text\" name=\"template\" style=\"width:400px;height:200px;font-size:10px;\" cols=\"80\" rows=\"3\">{$category->template}</textarea></td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Links pr. file:</td>
					<td>
						<input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"split\" value=\"{$category->split}\" style=\"width:80px;\" />
						if greater than zero additional files will be created, each having &quot;Links pr. file&quot; links.
					</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><input class=\"button\" type=\"submit\" name=\"ok\" value=\"OK\" onclick=\"modified=false;\" /></td>
					<td></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>

{$variables}
{$installcode}
";
	echo template::footer();

	break; // }}}
case 'overview': // {{{
	$catstats = array();
	$links = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
	foreach( $links AS $l ) {
		$l = new link( $l );
		foreach( $l->categories AS $c ) {
			$catstats[ $c ] = linkex::get( $c, $catstats, 0 ) + 1;
		}	
		unset( $l );
	}
	unset( $links );
	$categories = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR );
	$cats = array();
	foreach( $categories AS $cid ) {
		$c = new Category( $cid );
		$c->linkscount = linkex::get( $cid, $catstats, 0 );
		$cats[] = $c;
	}
	$categories = $cats;
	unset( $cats );
	linkex::sort( $categories, 'name', 'asc' );

	echo template::header( array( 'title' => 'Categories' ) );

	$categories = linkex::arraychunk( $categories, $config->displaylimit );
	$start = linkex::get( 'start', $_REQUEST, 1 );
	$pages = sizeof( $categories );
	$navlinks = template::navigation( $start, $pages, BASEURI . '?page=admin&amp;view=categories&amp;' );
	if ( sizeof( $categories ) > 0 ) {
		$categories = $categories{ ( $start - 1 ) };
	} else {
		$categories = array();
	}

	// List all the categories
	echo "<div style=\"margin:10px;\">
	<table class=\"list\" id=\"categeries\" cellspacing=\"0\">
		<thead>
			<tr class=\"th\">
				<th style=\"width:45px;\"></th>
				<th>ID</th>
				<th>Name</th>
				<th>Public</th>
				<th>Links</th>
			</tr>
			<tr>
				<td colspan=\"5\" class=\"center navigation\"><a href=\"index.php?page=admin&amp;view=categories&amp;action=form\">Create new category</a></td>
			</tr>
		</thead>
		<tbody>

";
	if ( $pages > 1 ) {
		echo "<tr class=\"navigation\">
	<td colspan=\"9\" class=\"center navigation\">
		{$navlinks}
	</td>
</tr>
";
	}

	if ( sizeof( $categories ) > 0 ) {
		$i=0;
		foreach( $categories AS $category ) {
			$rowclass=($i++%2)?'even':'odd';
			//$category = new category( $cid );
			$category->public = linkex::yesno( $category->public );
			echo "<tr class=\"{$rowclass}\">
	<td>
		<a href=\"$URI?page=admin&amp;view=categories&amp;action=form&amp;id={$category->id}\">edit</a>
		<a href=\"$URI?page=admin&amp;view=categories&amp;action=delete&amp;id={$category->id}\" onclick=\"return confirm( 'Are you sure you would like to delete this category?' );\">del</a>
	</td>
	<td>{$category->id}</td>
	<td>{$category->name}</td>
	<td>{$category->public}</td>
	<td>{$category->linkscount}</td>
</tr>
";
		}
	} else {
		echo "<tr>
	<td class=\"center\" colspan=\"5\">- no categories found -</td>
</tr>
";
	}
	if ( $pages > 1 ) {
		echo "<tr class=\"navigation\">
	<td colspan=\"9\" class=\"center navigation\">
		{$navlinks}
	</td>
</tr>
";
	}
	echo "		</tbody>
	</table>
</div>
";
	echo template::footer();	
	break; // }}}
}

					break;
				case 'link':

switch( linkex::get( 'action', $_REQUEST, 'overview' ) ) {
case 'delete': // {{{
	if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
		$link = new Link( $id );
		if ( sizeof( $_POST ) > 0 ) {
			$elems = linkex::get( 'blacklist', $_POST, array() );
			foreach( $elems AS $e ) {
				$b = new Blacklist;
				$b->reason = 'Deleted';
				switch( $e ) {
				case 'ldom':
					$b->type = 2;
					$b->value = $link->ldom;
					break;
				case 'ldomip':
					$b->type = 1;
					$b->value = $link->ldomip;
					break;
				case 'rdom':
					$b->type = 2;
					$b->value = $link->rdom;
					break;
				case 'rdomip':
					$b->type = 1;
					$b->value = $link->rdomip;
					break;
				case 'wmip':
					$b->type = 4;
					$b->value = $link->wmip;
					break;
				case 'edom':
					$b->type = 16;
					$b->value = $link->edom;
					break;
				case 'email':
					$b->type = 8;
					$b->value = $link->email;
					break;
				}
				if ( strlen( $b->value ) > 0 ) {
					$b->save();
				}
				unset( $b );
			}
			$link->delete();
			linkex::redirect( BASEURI . '?page=admin' );
		} else {
			$_SERVER['REQUEST_URI'] = htmlentities( $_SERVER['REQUEST_URI'] );	
	
			echo template::header( array( 'title' => 'Delete link [id:'.$id.']' ) );
			echo "<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>Delete link [id:{$id}]</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<table>
				<tr>
					<td class=\"key\"><input type=\"checkbox\" class=\"checkbox\" name=\"blacklist[]\" value=\"ldom\" /></td>
					<td>Blacklist link domain &quot;{$link->ldom}&quot;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"><input type=\"checkbox\" class=\"checkbox\" name=\"blacklist[]\" value=\"ldomip\" /></td>
					<td>Blacklist link server IP &quot;{$link->ldomip}&quot;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"><input type=\"checkbox\" class=\"checkbox\" name=\"blacklist[]\" value=\"rdom\" /></td>
					<td>Blacklist recip domain &quot;{$link->rdom}&quot;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"><input type=\"checkbox\" class=\"checkbox\" name=\"blacklist[]\" value=\"rdomip\" /></td>
					<td>Blacklist recip server IP &quot;{$link->rdomip}&quot;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"><input type=\"checkbox\" class=\"checkbox\" name=\"blacklist[]\" value=\"wmip\" /></td>
					<td>Blacklist webmaster IP &quot;{$link->wmip}&quot;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"><input type=\"checkbox\" class=\"checkbox\" name=\"blacklist[]\" value=\"edom\" /></td>
					<td>Blacklist webmaster email domain &quot;{$link->edom}&quot;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"><input type=\"checkbox\" class=\"checkbox\" name=\"blacklist[]\" value=\"email\" /></td>
					<td>Blacklist webmaster email &quot;{$link->email}&quot;</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><input class=\"button\" type=\"submit\" name=\"ok\" value=\"Delete link\" onclick=\"modified=false;\" /></td>
					<td></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>

";
			echo template::footer();
		}
	} else {
		linkex::redirect( BASEURI . '?page=admin' );
	}
	break; // }}}
case 'form': // {{{
	if ( ( $id = linkex::get( 'id', $_REQUEST, false ) ) !== false ) {
		if ( file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR . $id ) ) {
			$link = new link( $id );
			$link->updateIPs( false );
			$pr = $link->getRPageRank();
			$link->save( false );

			if ( sizeof( $_POST ) > 0 ) {

				$link->lurl = linkex::get( 'lurl', $_POST, '' );
				$link->rurl = linkex::get( 'rurl', $_POST, '' );

				$link->weight = intval( linkex::get( 'weight', $_POST, 0 ) );

				$link->dateexpire = linkex::get( 'dateexpire', $_POST, '' );
				$link->dateexpire = ( strlen( $link->dateexpire ) > 0 ) ? intval( @strtotime( $link->dateexpire ) ) : 0;

				$link->anchor = trim( linkex::get( 'anchor', $_POST, '' ) );
				$link->description = htmlentities( trim( linkex::get( 'description', $_POST, '' ) ) );
				$cats = $link->categories;
				$link->categories = linkex::get( 'categories', $_POST, array() );
				if ( !is_array( $link->categories ) ) {
					$link->categories = array( intval( $link->categories ) );
				}
				$cats = array_unique( array_merge( $cats, $link->categories ) );
				$link->email = htmlentities( trim( linkex::get( 'email', $_POST, '' ) ) );
				$link->skipcheck = intval( linkex::get( 'skipcheck', $_POST, 0 ) );
				$link->skippagerank = intval( linkex::get( 'skippagerank', $_POST, 0 ) );
				$link->minpagerank = intval( linkex::get( 'minpagerank', $_POST, -1 ) );
				$link->status = linkex::get( 'status', $_POST, '0' );
				$link->notes = linkex::get( 'notes', $_POST, '' );
				$link->save( false );
				foreach( $cats AS $cid ) {
					if ( file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $cid ) ) {
						$c = new Category( $cid );
						$c->generate();
						unset( $c );
					}
				}
				linkex::redirect( $_SERVER['REQUEST_URI'] );
			}
			$pagerankcheckdatef = date( $config->dateformat, linkex::get( 'date', linkex::get( 'rpagerank', $link->googleinfo, array() ), 0 ) );
			$_SERVER['REQUEST_URI'] = htmlentities( $_SERVER['REQUEST_URI'] );
			$categories = linkex::categories( LOGGEDIN );
			$categories = linkex::selector( 'categories', $categories, $link->categories, 
				LOGGEDIN, null, array( 'style' => '' ) );

			$status = linkex::selector( 'status', $link->statusOptions(), (string)$link->status, false, 'select' );
			$skipcheck = linkex::checkbox( $link->skipcheck );
			$skippagerank = linkex::checkbox( $link->skippagerank );

			$minpagerank = linkex::selector( 'minpagerank', 
				array( -1=>'Use global min. PageRank&trade;', 0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9, 10=>10 ), 
				(string)$link->minpagerank, false, 'select', 
				array( 'style' => 'width:auto;' ) );

			$link->dateexpire = ( $link->dateexpire > 0 ) ? date( "Y-m-d", $link->dateexpire ) : "";

			$laststatus = false;
			$lastcolor = false;
			$history = array_reverse( $link->log );
			foreach( $history AS $hist ) {
				$res = '';
				$color = 'red';
				switch( $hist{'res'} ) {
				case '0':
					$res = '200 OK';
					$color = 'green';
					break;
				case '1':
					$res = $hist{'reason'};
					break;
				case '2':
					$res = 'Missing backlink';
					break;
				case '4':
					$res = 'Invalid anchor';
					break;
				case '8':
					$res = 'Nofollow link';
					break;
				case '16':
					$res = 'Too many external links';
					break;
				case '32':
					$res = 'Check skipped';
					$color = 'yellow';
					break;
				case '64':
					$res = 'Blacklisted';
					break;
				}
				$laststatus = ( $laststatus === false ) ? $res : $laststatus;
				$lastcolor = ( $lastcolor === false ) ? $color : $lastcolor;
				$h .= '<div>'.date( $config->dateformat, $hist{'date'} ).' (<span style="font-family:monospace;" class="'.
					$color.'">'.$res."</span>)</div>";
			}

			echo template::header( array( 'title' => 'Edit link [id:'.$id.'] ['.$link->rdom.']' ) );
			echo "<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
	<div style=\"margin:10px auto;\">
		<fieldset style=\"margin:10px auto;\">
			<legend>Linking info</legend>
			<table class=\"table\">
				<tr>
					<td class=\"key\">Link UID:</td>
					<td>{$link->id}</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Added on:</td>
					<td>{$link->addedf}</td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Verified on:</td>
					<td>{$link->lastcheckedf} 
						(<span style=\"font-family:monospace;\" class=\"{$lastcolor}\">{$laststatus}</span>)
						(<a href=\"$URI?page=admin&amp;view=verify&amp;lid={$link->id}\">verify now</a>)
						(<a href=\"#\" onclick=\"$(this).blur();$('div#linkhistory').slideToggle();return false;\">History</a>)
						<br />
						<div id=\"linkhistory\" style=\"display:none;padding:5px 0px;\">
							{$h}
						</div>
					</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Added by:</td>
					<td>{$link->email} (<a href=\"http://whois.domaintools.com/{$link->edom}\" target=\"_blank\">whois</a>) {$link->wmip} (<a href=\"http://whois.domaintools.com/{$link->wmip}\" target=\"_blank\">whois</a>)</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Link domain:</td>
					<td><a href=\"{$link->lurl}\" target=\"_blank\">{$link->ldom}</a> (<a href=\"http://whois.domaintools.com/{$link->ldom}\" target=\"_blank\">whois</a>) {$link->ldomip} (<a href=\"http://whois.domaintools.com/{$link->ldomip}\" target=\"_blank\">whois</a>)</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Reciprocal domain:</td>
					<td><a href=\"{$link->rurl}\" target=\"_blank\">{$link->rdom}</a> (<a href=\"http://whois.domaintools.com/{$link->rdom}\" target=\"_blank\">whois</a>) {$link->rdomip} (<a href=\"http://whois.domaintools.com/{$link->rdomip}\" target=\"_blank\">whois</a>)</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">PageRank&trade;:</td>
					<td><div class=\"pagerank pr{$pr}\" style=\"margin-top:3px;\"></div>&nbsp;&nbsp;Last checked on: {$pagerankcheckdatef}</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td colspan=\"3\"><br /></td>
				</tr>
				<tr>
					<td class=\"key\">Site anchor:</td>
					<td><input type=\"text\" class=\"text\" name=\"anchor\" value=\"{$link->anchor}\" /></td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Site title:</td>
					<td><input type=\"text\" class=\"text\" name=\"title\" value=\"{$link->title}\" /></td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Link URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"lurl\" value=\"{$link->lurl}\" /></td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Reciprocal link URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"rurl\" value=\"{$link->rurl}\" /></td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Email:</td>
					<td><input type=\"text\" class=\"text\" name=\"email\" value=\"{$link->email}\" /></td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Site description:</td>
					<td><textarea cols=\"80\" rows=\"3\" class=\"text\" name=\"description\">{$link->description}</textarea></td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\">Weight:</td>
					<td><input type=\"text\" class=\"text\" name=\"weight\" value=\"{$link->weight}\" style=\"width:50px;\" /></td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Categories:</td>
					<td>{$categories}</td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Status:</td>
					<td>{$status}</td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Skip check:</td>
					<td><input type=\"checkbox\" class=\"checkbox\" name=\"skipcheck\" value=\"1\" {$skipcheck} /></td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Ignore PageRank&trade;:</td>
					<td><input type=\"checkbox\" class=\"checkbox\" name=\"skippagerank\" value=\"1\" {$skippagerank} /></td>
					<td class=\"help\"></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Min. PageRank&trade;:</td>
					<td>{$minpagerank}</td>
					<td class=\"help\"></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><br /><input type=\"submit\" class=\"button\" value=\"OK\" /></td>
					<td class=\"help\"></td>
				</tr>
			</table>
		</fieldset>
	</div>

	<div style=\"margin:10px auto;\">
		<fieldset class=\"expandable hidden\" id=\"linknotes{$link->id}\">
			<legend onclick=\"toggle(this);\">Link Notes</legend>
			<div class=\"contractor\">
				<div style=\"padding:5px 10px;\">
					<textarea cols=\"80\" rows=\"3\" class=\"text\" name=\"notes\" style=\"width:595px;height:200px;\">{$link->notes}</textarea>
				</div>
			</div>
		</fieldset>
	</div>

</form>

";
			echo template::footer();

		} else {
			linkex::redirect( BASEURI . '?page=admin' );
		}
	} else {
		linkex::redirect( BASEURI . '?page=admin' );
	}
	break; // }}}
}

					break;
				case 'verify':

ob_implicit_flush(true);
session_write_close();

$lid = linkex::get( 'lid', $_REQUEST, false );
// {{{ Mass delete
if ( linkex::get( 'delete', $_POST, false ) !== false ) {
	if ( is_string( $lid ) ) {
		$lid = array_unique( linkex::map( 'trim', explode( ',', $lid ) ) );
	} else 
	if ( is_int( $lid ) ) {
		$lid = array( $lid );
	}

	if ( is_array( $lid ) ) {
		$categories = array();

		foreach( $lid AS $id ) {
			$l = new link( $id );
			if ( !is_array( $l->categories ) ) {
				$l->categories = array( $l->categories );
			}
			$categories = array_merge( $categories, $l->categories );
			unset( $l );
			@unlink( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR . $id );
		}
		$categories = array_unique( $categories );
		foreach( $categories AS $cid ) {
			$c = new category( $cid );
			$c->generate();
			unset( $c );
		}
	}

	linkex::redirect( BASEURI . '?page=admin' );
	// }}}
	// {{{ Check to see if this is a mass edit
} elseif ( linkex::get( 'massedit', $_POST, false ) !== false ) {
	if ( is_string( $lid ) ) {
		$lid = array_unique( linkex::map( 'trim', explode( ',', $lid ) ) );
	} else 
	if ( is_int( $lid ) ) {
		$lid = array( $lid );
	}
	if ( is_array( $lid ) ) {
		$updatecategories = array();
		foreach( $lid AS $id ) {
			$l = new Link( $id );

			$s = linkex::get( 'masseditsetstatus', $_POST, 0 );
			if ( $s>0 ) {
				$l->status = $s;
			}

			$s = linkex::get( 'masseditskipcheck', $_POST, 0 );
			if ( $s>0 ) {
				$l->skipcheck = ( $s==1 ) ? 1:0;
			}

			// <<< Added 29/12-2006
			$s = linkex::get( 'masseditskippagerank', $_POST, 0 );
			if ( $s>0 ) {
				$l->skippagerank = ( $s==1 ) ? 1:0;
			}
			// >>>
			$s = linkex::get( 'masseditminpagerank', $_POST, 'null' );
			if ( $s != 'null' ) {
				$l->minpagerank = $s;
			}

			$s = linkex::get( 'masseditcategoryset', $_POST, 0 );
			if ( $s == 1 ) {
				$updatecategories = array_unique( array_merge( $updatecategories, $l->categories ) );
				$l->categories = array_unique( array_merge( $l->categories, linkex::get( 'masseditcategories', $_POST, array() ) ) );
				$updatecategories = array_unique( array_merge( $updatecategories, $l->categories ) );
			} else if ( $s == 2 ) {
				$updatecategories = array_unique( array_merge( $updatecategories, $l->categories ) );
				$l->categories = linkex::get( 'masseditcategories', $_POST, array() );
				$updatecategories = array_unique( array_merge( $updatecategories, $l->categories ) );
			}
			$l->save( false );
			unset( $l );
		}
		foreach( $updatecategories AS $cid ) {
			if ( file_exists( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR . $cid ) ) {
				$c = new Category( $cid );
				$c->generate();
				unset( $c );
			}
		}	
	}

	linkex::redirect( BASEURI . '?page=admin' );
}
// }}}

if ( $lid === false ) {
	$errors[] = 'You must select at least one link to verify.';
}
if ( $lid == null ) {
	$lid = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
} else if ( is_string( $lid ) ) {
	$lid = array_unique( linkex::map( 'trim', explode( ',', $lid ) ) );
} else if ( is_int( $lid ) ) {
	$lid = array( $lid );
}
if ( sizeof( $lid ) == 0 ) {
	$errors[] = 'You must select at least one link to verify..';
}

echo template::header( array( 'title' => 'Verifying links' ) );
if ( sizeof( $errors ) == 0 ) {
	$legend = 'Verifying links...';
	echo "				<div style=\"margin:10px 0px;\">
					<fieldset>
						<legend id=\"legend\">{$legend}</legend>
						<div><pre id=\"progress\" style=\"font-size:11px;min-height:100px;margin-left:5px;\">    ID  Domain                         Status                                              PageRank BackL.Status<br /> ===============================================================================================================<br /></pre></div>
					</fieldset>
				</div>
				<script type=\"text/javascript\">
			/*<![CDATA[*/
			function _p(str){ var elem=document.getElementById('progress'); if(elem){ elem.innerHTML +=str; } }
			function _t(str){ var elem=document.getElementById('legend'); if(elem){ elem.innerHTML=str; } }
			/*]]>*/
		</script>

";
}
echo template::footer();
linkex::flush();

$total = sizeof( $lid );
$current = 0;
function updateProgress( $data ) { // {{{
	global $total, $current;
	if ( $data{'action'} == 'link' ) {
		$current++;
		$title = sprintf( 'Verifying links... (%d%%)', $current/$total*100 );
		$progress = sprintf( '% 6s  % -30s <span class="%s">% -50s</span> '.
			'<span class="%s"><strong>% 2s</strong> &gt;=% 2s</span>   '.
			'<span class="%s">% -3s</span>   '.
			'<span class="%s">%s</span><br />',

			$data{'id'}, linkex::truncate( $data{'rdom'}, 30 ),
			
			( $data{'skipcheck'} == 1 ) ? 'yellow': ( ( strpos( $data{'code'}, '200' ) !== false ) ? 'green':'red' ),
			( $data{'skipcheck'} == 1 ) ? 'Skipped' : linkex::truncate( $data{'code'}, 50 ),
			
			( $data{'skippagerank'} == 1 || $data{'skipcheck'} == 1 ) ? 
				'yellow': ( ( $data{'pagerank'} >= $data{'minpagerank'} ) ?'green':'red' ),
				$data{'pagerank'}, $data{'minpagerank'},

			( $data{'skipcheck'} == 1 ) ? 'yellow': 
				( ( linkex::get( 'res', $data{'res'}, -1 ) == 0 ) ? 'green':'red' ),
			( $data{'skipcheck'} == 1 ) ? '-': 
				( ( linkex::get( 'res', $data{'res'}, -1 ) == 0 ) ? 'Yes':'No' ),

			( $data{'skipcheck'} == 1 ) ? 'yellow': 
				( ( $data{'status'} == 1 ) ? 'green':'red' ),
			( $data{'skipcheck'} == 1 ) ? 'Skipped' : link::statusOptions( $data{'status'} )

		);
		echo "<script type=\"text/javascript\">
			/*<![CDATA[*/
			_p('{$progress}');_t('{$title}');
			/*]]>*/
		</script>
";
		linkex::flush();
	}
} // }}}
linkex::verifybacklinks( $lid, 'updateProgress' );
exit;

					break;
				case 'settings':

$rebuildcategories = false;

$checkboxes = array(
	'linkbotuniquedomains',
	'disablepublicform', 'linkbotignoretrailingslash', 'linkbotdisregardwww',
	'linkbackrequired', 'disablerecipfield', 'publiccategories',
	'commandlineenable', 'commandlinesummary',
	'remoteenable', 'remotesummary', 'remotelimitips',
	'showemail',
	'usecaptcha', 'verifyanchor',
	'indexexchange', 'noquerystring',
	'exposelinkex',
	'rejectnofollow',
	'disableblacklisted',
	'usetitle'
);

// Save if posted
if ( sizeof( $_POST ) > 0 ) {
	foreach( $checkboxes AS $b ) {
		$_POST[$b] = linkex::get( $b, $_POST, '0' );
	}

	$config->template = explode( ',', 
		str_replace( ',,', ',', linkex::get( 'template', $_POST, join( ',', $config->template ) ) ) );

	$config->htmlcode = htmlentities( stripslashes( $_POST['htmlcode'] ) );

	$rebuildcategories = $rebuildcategories || ( $config->exposelinkex != linkex::get( 'exposelinkex', $_POST, 0 ) );
	$config->exposelinkex = linkex::get( 'exposelinkex', $_POST, 0 );

	$config->maxoutboundlinks	= linkex::get( 'maxoutboundlinks', $_POST, 0 );

	$crlf = linkex::get( 'emailcrlf', $_POST, '' );
	if ( in_array( $crlf, array( '\r\n', '\n\r', '\n' ) ) ) {
		$config->emailcrlf = $crlf;
	}
	$config->rejectnofollow = linkex::get( 'rejectnofollow', $_POST, 0 );
	$config->disableblacklisted = linkex::get( 'disableblacklisted', $_POST, 0 );

	$config->indexexchange = linkex::get( 'indexexchange', $_POST, 0 );
	$config->noquerystring = linkex::get( 'noquerystring', $_POST, 0 );

	$config->samedomain = linkex::get( 'samedomain', $_POST, $config->samedomain );
	$config->showemail = linkex::get( 'showemail', $_POST, 0 );
	$config->usecaptcha = linkex::get( 'usecaptcha', $_POST, 0 );
	$config->verifyanchor = intval( linkex::get( 'verifyanchor', $_POST, 0 ) );

	$config->remotepass = linkex::get( 'remotepass', $_POST, '' );
	$config->remoteips = linkex::map( 'trim',	
		explode( "\n", linkex::get( 'remoteips', $_POST, '' ) ) );
	$config->remoteenable = linkex::get( 'remoteenable', $_POST, 0 );
	$config->remotesummary = linkex::get( 'remotesummary', $_POST, 0 );
	$config->remotelimitips = linkex::get( 'remotelimitips', $_POST, 0 );
	$config->commandlineenable = linkex::get( 'commandlineenable', $_POST, 0 );
	$config->commandlinesummary = linkex::get( 'commandlinesummary', $_POST, 0 );

	$config->googledatacenters = linkex::map( 'trim',	
		explode( "\n", trim( linkex::get( 'googledatacenters', $_POST, '' ) ) ) );
	

	$config->defaultcategories = linkex::get( 'categories', $_POST, array() );
	$config->publiccategories = linkex::get( 'publiccategories', $_POST, $config->publiccategories );

	$config->email = linkex::get( 'email', $_POST, $config->email );
	$config->dateformat = linkex::get( 'dateformat', $_POST, $config->dateformat );
	$config->charset = linkex::get( 'charset', $_POST, $config->charset );
	$config->displaylimit = max( intval( linkex::get( 'displaylimit', $_POST, $config->displaylimit ) ), 1 );
	$config->disablerecipfield = linkex::get( 'disablerecipfield', $_POST, $config->disablerecipfield );
	$config->disablepublicform = linkex::get( 'disablepublicform', $_POST, $config->disablepublicform );
	$config->sortkey = linkex::get( 'sortkey', $_POST, $config->sortkey );
	$config->sortorder = linkex::get( 'sortorder', $_POST, $config->sortorder );
	$config->url = linkex::get( 'url', $_POST, $config->url );
	$config->anchor = linkex::map( 'trim', explode( "\n", linkex::get( 'anchor', $_POST, join( "\n", $config->anchor ) ) ) );
	$config->title = linkex::map( 'trim', explode( "\n", linkex::get( 'title', $_POST, join( "\n", $config->title ) ) ) );
	$config->description = linkex::get( 'description', $_POST, $config->description );
	$config->altlinks = linkex::map( 'trim', explode( "\n", linkex::get( 'altlinks', $_POST, join( "\n", $config->altlinks ) ) ) );

	$config->linkbotagent = linkex::get( 'linkbotagent', $_POST, $config->linkbotagent );
	$config->linkbotuniquedomains = linkex::get( 'linkbotuniquedomains', $_POST, $config->linkbotuniquedomains );
	$config->linkbotuniqueips = intval( linkex::get( 'linkbotuniqueips', $_POST, 0 ) );

	$config->linkbotignoretrailingslash = linkex::get( 'linkbotignoretrailingslash', $_POST, $config->linkbotignoretrailingslash );
	$config->linkbotdisregardwww = linkex::get( 'linkbotdisregardwww', $_POST, $config->linkbotdisregardwww );

	$config->minpagerank = intval( linkex::get( 'minpagerank', $_POST, 0 ) );
	$config->linkbackrequired = linkex::get( 'linkbackrequired', $_POST, $config->linkbackrequired );

	// Lengths
	$config->anchorlength = intval( linkex::get( 'anchorlength', $_POST, 0 ) );
	$config->anchorlengthtype = linkex::get( 'anchorlengthtype', $_POST, 'w' );
	$config->titlelength = intval( linkex::get( 'titlelength', $_POST, 0 ) );
	$config->titlelengthtype = linkex::get( 'titlelengthtype', $_POST, 'w' );
	$config->descriptionlength = intval( linkex::get( 'descriptionlength', $_POST, 0 ) );
	$config->descriptionlengthtype = linkex::get( 'descriptionlengthtype', $_POST, 'w' );

	$config->maxoutboundtype = intval( linkex::get( 'maxoutboundtype', $_POST, 0 ) );

	$config->usetitle = linkex::get( 'usetitle', $_POST, 0 );

	// Username/password
	$u = linkex::get( '_username', $_POST, false );
	$p1 = linkex::get( '_password1', $_POST, false );
	$p2 = linkex::get( '_password2', $_POST, false );
	if ( $u && $p1 && $p1 == $p2 ) {
		$config->password = md5( $u .'---'. $p1 );
		if ( linkex::get( 'username', $_COOKIE, false ) ) {
			setcookie( 'username', $u, time()+60*60*24*30, BASEURI );
			setcookie( 'password', $p1, time()+60*60*24*30, BASEURI );
		}
		$_SESSION['username'] = $u;
		$_SESSION['password'] = $p1;
	}
	$config->save();

	$rules = linkex::get( 'rules', $_POST, '' );
	if ( strlen( trim( $rules ) ) > 0 ) {
		linkex::fileput( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'rules', $rules );
	} else {
		@unlink( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'rules' );
	}

	// Should we rebuild the categories?
	if ( $rebuildcategories ) {
		$categories = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR );
		foreach( $categories AS $cid ) {
			$c = new category( $cid );
			$c->generate();
			unset( $c );
		}
	}
	linkex::redirect( $_SERVER['REQUEST_URI'] );
}

$_SERVER['REQUEST_URI'] = htmlentities( linkex::get( 'REQUEST_URI', $_SERVER ) );
echo template::header( array( 'title' => 'Settings' ) );

$minpagerank = linkex::selector( 'minpagerank', range( 0,10 ), (string)$config->minpagerank, false, 'select', 
	array( 'style' => 'width:60px;' ) );
$sortkey = linkex::selector( 'sortkey', 
	$templatecolumns,
	$config->sortkey, false, 'select' );
$sortorder = linkex::selector( 'sortorder', category::orders(), $config->sortorder, false, 'select', 
	array( 'onchange' => 'modified=true;', 'style' => 'width:150px;' ) ); 

$samedomainselect = linkex::selector( 'samedomain', array( '0' => 'Does not matter', '1' => 'Must be on same domain', '2' => 'Must be on different domains' ), $config->samedomain, false, 'select',
	array( 'onchange' => 'modified=true;', 'style' => 'width:180px;' ) ); 

$anchor = join( "\n", $config->anchor );
$title = join( "\n", $config->title );
$altlinks = join( "\n", $config->altlinks );

// Rewrite all checkbox values from [0|1] => [''|checked]
foreach( $checkboxes AS $b ) {
	$config->$b = linkex::checkbox( $config->$b );
}

$categories = linkex::selector( 'categories', linkex::categories( true ), $config->defaultcategories, true, 'checkbox', array( 'onchange' => 'modified=true;', 'style'=>'' ) );

$rules = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'rules', '' );

// The lenths of the input
$anchorlengthtype = linkex::selector( 'anchorlengthtype', array( 'w' => 'words', 'c' => 'characters' ), $config->anchorlengthtype, false, 'select', array( 'style' => 'width:100px;' ) );
$titlelengthtype = linkex::selector( 'titlelengthtype', array( 'w' => 'words', 'c' => 'characters' ), $config->titlelengthtype, false, 'select', array( 'style' => 'width:100px;' ) );
$descriptionlengthtype = linkex::selector( 'descriptionlengthtype', array( 'w' => 'words', 'c' => 'characters' ), $config->descriptionlengthtype, false, 'select', array( 'style' => 'width:100px;' ) );

$maxoutboundtypeselect = linkex::selector( 'maxoutboundtype', array( 0 => 'incl. nofollow', 1 => 'excl. nofollow' ), strval( $config->maxoutboundtype ), false, 'select', array( 'style' => 'width:100px;' ) );

$remoteips = join( "\n", $config->remoteips );

$googledatacenters = join( "\n", $config->googledatacenters );

$copyright = htmlentities( COPYRIGHT );

$template = '\''.join('\',\'', $config->template ).'\'';

$xx = array();
foreach( $templatecolumns AS $k=>$v ) {
	$xx[] = $k.':\''.$v.'\'';
}
$templatecolumns = join(',',$xx);
unset($xx);

echo "<form method=\"post\" action=\"{$_SERVER{'REQUEST_URI'}}\">
	<div style=\"margin:10px auto;\">
		<fieldset class=\"expandable hidden\" id=\"fs_admin_settings\">
			<legend>Admin settings</legend>
			<div class=\"contractor\">
				<table class=\"table\">
					<tr>
						<td class=\"key\">Username:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"_username\" value=\"{$_SESSION['username']}\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Password:</td>
						<td><input onchange=\"modified=true;\" type=\"password\" class=\"text\" name=\"_password1\" value=\"\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Password (again):</td>
						<td><input onchange=\"modified=true;\" type=\"password\" class=\"text\" name=\"_password2\" value=\"\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Email:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"email\" value=\"{$config->email}\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Date format:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"dateformat\" value=\"{$config->dateformat}\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Charset:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"charset\" value=\"{$config->charset}\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Display limit:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"displaylimit\" value=\"{$config->displaylimit}\" style=\"width:40px;\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Email CRLF:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"emailcrlf\" value=\"{$config->emailcrlf}\" style=\"width:40px;\" /></td>
					</tr>
					<tr>
						<td class=\"key\">Default sort key:</td>
						<td>{$sortkey}</td>
					</tr>
					<tr>
						<td class=\"key\">Default sort order:</td>
						<td>{$sortorder}</td>
					</tr>
					<tr>
						<td class=\"key\">Disable public form:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"disablepublicform\" value=\"1\" {$config->disablepublicform} /></td>
					</tr>
					<tr>
						<td class=\"key\">Show email:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"showemail\" value=\"1\" {$config->showemail} /></td>
					</tr>
					<tr>
						<td class=\"key\">Use CAPTCHA:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"usecaptcha\" value=\"1\" {$config->usecaptcha} /></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Overview template:</td>
						<td>
							<table style=\"border:0px;width:100%;\" cellpadding=\"0\" cellspacing=\"0\">
								<tr valign=\"top\">
									<td style=\"width:50%;\">
										<strong>Current Template</strong>
										<ul id=\"template\" class=\"selector\">
											<li id=\"options_checkbox\" class=\"immutable\">Checkbox</li>
											<li id=\"optins_linktoptions\" class=\"immutable\">Options</li>
										</ul>
										</ul>
									</td>
									<td style=\"width:50%;\">
										<strong>Available options</strong>
										<ul id=\"templateoptions\" class=\"selector\"></ul>
									</td>
								</tr>
							</table>
							<em>Drag &amp; drop the items to sort,add and remove options</em>
							<input type=\"hidden\" name=\"template\" id=\"templateinput\" value=\"\" style=\"width:800px;\" />
							<script type=\"text/javascript\">
			/*<![CDATA[*/
			var options = { {$templatecolumns} }; var currentTemplate = [{$template}];
			function createTemplate(){ for(var i=0; i<currentTemplate.length; i++){ if(options[currentTemplate[i]]){ $(\"<li></li>\").attr(\"id\",\"options_\"+currentTemplate[i]).html(options[currentTemplate[i]]).appendTo(\"#template\"); } } for(var i in options){ if(!currentTemplate.inArray(i)){ $(\"<li></li>\").attr(\"id\",\"options_\"+i).html(options[i]).appendTo(\"#templateoptions\"); } } $(\"#templateinput\").val(currentTemplate.join(',')); } $(document).ready(function(){ createTemplate(); $(\"#templateoptions,#template\").sortable({ items: 'li:not(.immutable)', connectWith: 'ul.selector', beforeStop:
			function(event, ui){ $(\"#templateinput\").val(jQuery.map($(\"#template\").sortable('toArray'),
			function(a){ return a.replace(/^options_/, ''); }).join(',')); } }).trigger('change'); $(\"#templateoptions,#template\").disableSelection(); });
			/*]]>*/
		</script>
						</td>
					</tr>
				</table>
			</div>
		</fieldset>
	</div>

	<div style=\"margin:10px auto;\">
		<fieldset class=\"expandable hidden\" id=\"fs_category_settings\">
			<legend>Category settings</legend>
			<div class=\"contractor\">
				<table class=\"table\">
					<tr>
						<td class=\"key\">Public categories:</td>
						<td>
							<input onchange=\"modified=true;\" class=\"checkbox\" 
								type=\"checkbox\" name=\"publiccategories\" value=\"1\" {$config->publiccategories} />
							</td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Default categories:</td>
						<td>{$categories}</td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Expose LinkEX:</td>
						<td>
							<input onchange=\"modified=true;\" class=\"checkbox\" 
								type=\"checkbox\" name=\"exposelinkex\" value=\"1\" {$config->exposelinkex} />
								<em>Show {$copyright} in top of category outout</em>
						</td>
				</table>
			</div>
		</fieldset>
	</div>

	<div style=\"margin:10px auto;\">
		<fieldset class=\"expandable hidden\" id=\"fs_linking_settings\">
			<legend>Linking settings</legend>
			<div class=\"contractor\">
				<table class=\"table\">
					<tr>
						<td class=\"key\">Website URL:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" name=\"url\" value=\"{$config->url}\" /></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Website anchor:<br />(one pr. line)</td>
						<td><textarea cols=\"80\" rows=\"3\" onchange=\"modified=true;\" class=\"text\" name=\"anchor\">{$anchor}</textarea></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Website title:<br />(one pr. line)</td>
						<td><textarea cols=\"80\" rows=\"3\" onchange=\"modified=true;\" class=\"text\" name=\"title\">{$title}</textarea></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Description:</td>
						<td><textarea cols=\"80\" rows=\"3\" onchange=\"modified=true;\" class=\"text\" name=\"description\">{$config->description}</textarea></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Alternative backlinks:<br />(one pr. line)</td>
						<td><textarea cols=\"80\" rows=\"3\" onchange=\"modified=true;\" class=\"text\" name=\"altlinks\">{$altlinks}</textarea></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Rules:</td>
						<td><textarea cols=\"80\" rows=\"3\" onchange=\"modified=true;\" class=\"text\" name=\"rules\">{$rules}</textarea></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">HMTL code:</td>
						<td>
							<textarea cols=\"80\" rows=\"3\" onchange=\"modified=true;\" class=\"text\" name=\"htmlcode\">{$config->htmlcode}</textarea>
							<div>
								&#123;&#36;URL&#125; - Website URL<br />
								&#123;&#36;ANCHOR&#125; - A random selected anchor<br />
								&#123;&#36;TITLE&#125; - A random selected title<br />
								&#123;&#36;DESCRIPTION&#125; - Description
							</div>
						</td>
						<td class=\"help\"></td>
					</tr>
				</table>
			</div>
		</fieldset>
	</div>

	<div style=\"margin:10px auto;\">
		<fieldset class=\"expandable hidden\" id=\"fs_link_verification_settings\">
			<legend>Link verification settings</legend>
			<div class=\"contractor\">
				<table class=\"table\">
					<tr>
						<td class=\"key\">Use title AND anchor:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"usetitle\" 
							value=\"1\" {$config->usetitle} /></td>
						<td></td>
					</tr>
					<tr>
						<td class=\"key\">Site anchor length:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" 
							name=\"anchorlength\" value=\"{$config->anchorlength}\" style=\"width:50px;\"/> {$anchorlengthtype} (0:unlimited)</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Site title length:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" 
							name=\"titlelength\" value=\"{$config->titlelength}\" style=\"width:50px;\"/> {$titlelengthtype} (0:unlimited)</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Site descri. length:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" 
							name=\"descriptionlength\" value=\"{$config->descriptionlength}\" style=\"width:50px;\"/> {$descriptionlengthtype} (0:unlimited)</td>
						<td class=\"help\"></td>
					</tr>

					
					<tr>
						<td class=\"key\">Linkback&nbsp;required:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"linkbackrequired\" 
							value=\"1\" {$config->linkbackrequired} /></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Reject nofollow links:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"rejectnofollow\" 
							value=\"1\" {$config->rejectnofollow} /></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Disable recip. field:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" 
							name=\"disablerecipfield\" id=\"disablerecipfield\" 
							value=\"1\" {$config->disablerecipfield} /></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Same domain:</td>
						<td>{$samedomainselect}
							<em>domain of url and reciprocal url</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Min. PageRank&trade;:</td>
						<td>{$minpagerank}</td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Google Datacenter(s)<br />(one pr. line)<br />(use IP or domain)</td>
						<td><textarea cols=\"80\" rows=\"5\" onchange=\"modified=true;\" class=\"text\" name=\"googledatacenters\">{$googledatacenters}</textarea></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Linkbot User-Agent:<br />(one pr. line)</td>
						<td><textarea cols=\"80\" rows=\"5\" onchange=\"modified=true;\" class=\"text\" name=\"linkbotagent\">{$config->linkbotagent}</textarea></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Unique domains:</td>
						<td>
							<input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"linkbotuniquedomains\" 
							value=\"1\" {$config->linkbotuniquedomains} />
							<em>Only allow one link pr. domain</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Links/IP:</td>
						<td>
							<input onchange=\"modified=true;\" type=\"text\" class=\"text\" 
							name=\"linkbotuniqueips\" value=\"{$config->linkbotuniqueips}\" style=\"width:50px;\"/>
							<em>Max. number of links from an IP. (0:unlimited)</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Ignore trailing slash:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"linkbotignoretrailingslash\" 
							value=\"1\" {$config->linkbotignoretrailingslash} />
							<em>domain.com and domain.com/ is the same with this enabled</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Disregard www:</td>
						<td>
							<input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"linkbotdisregardwww\" 
							value=\"1\" {$config->linkbotdisregardwww} />
							<em>www.domain.com and domain.com is the same with this enabled</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Validate anchor:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"verifyanchor\" 
							value=\"1\" {$config->verifyanchor} />
							<em>The text between &gt; and &lt;/a&gt; must be an exact match</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Index exchange only:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"indexexchange\" 
							value=\"1\" {$config->indexexchange} />
							<em>Only root link exchanges</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Disallow querystring:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"noquerystring\" 
							value=\"1\" {$config->noquerystring} />
							<em>Reject URLs having ?</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Max. outbound links:</td>
						<td>
							<input onchange=\"modified=true;\" type=\"text\" class=\"text\" 
							name=\"maxoutboundlinks\" value=\"{$config->maxoutboundlinks}\" style=\"width:30px;\"/>
							{$maxoutboundtypeselect}
							<em>Max. number of external links on reciprocal URL. (0:unlimited)</em>
						</td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Disable blacklisted:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"disableblacklisted\" 
							value=\"1\" {$config->disableblacklisted} />
							<em>Disable links found in the blacklist</em>
						</td>
						<td class=\"help\"></td>
					</tr>
				</table>
			</div>
		</fieldset>
	</div>

	<div style=\"margin:10px auto;\">
		<fieldset class=\"expandable hidden\" id=\"fs_command_line_settings\">
			<legend>Command line settings</legend>
			<div class=\"contractor\">
				<table class=\"table\">
					<tr>
						<td class=\"key\">Enable:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"commandlineenable\" 
							value=\"1\" {$config->commandlineenable} /></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Send summary:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"commandlinesummary\" 
							value=\"1\" {$config->commandlinesummary} /></td>
						<td class=\"help\"></td>
					</tr>
				</table>
			</div>
		</fieldset>
	</div>

	<div style=\"margin:10px auto;\">
		<fieldset class=\"expandable hidden\" id=\"fs_remote_access_settings\">
			<legend>Remote access settings</legend>
			<div class=\"contractor\">
				<table class=\"table\">
					<tr>
						<td class=\"key\">Enable:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"remoteenable\" 
							value=\"1\" {$config->remoteenable} /></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Send email summary:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"remotesummary\" 
							value=\"1\" {$config->remotesummary} /></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Remote passphrase:</td>
						<td><input onchange=\"modified=true;\" type=\"text\" class=\"text\" 
							name=\"remotepass\" value=\"{$config->remotepass}\" /></td>
						<td class=\"help\"></td>
					</tr>
					<tr>
						<td class=\"key\">Limit IPs:</td>
						<td><input onchange=\"modified=true;\" class=\"checkbox\" type=\"checkbox\" name=\"remotelimitips\" 
							value=\"1\" {$config->remotelimitips} /></td>
						<td class=\"help\"></td>
					</tr>
					<tr valign=\"top\">
						<td class=\"key\">Accepted IPs<br />(one pr. line)</td>
						<td><textarea cols=\"80\" rows=\"5\" onchange=\"modified=true;\" class=\"text\" name=\"remoteips\">{$remoteips}</textarea></td>
						<td class=\"help\"></td>
					</tr>
				</table>
			</div>
		</fieldset>
	</div>

	<div class=\"center\" style=\"padding-bottom:10px;\"><input class=\"button save\" type=\"submit\" name=\"ok\" value=\"Save\" onclick=\"modified=false;\" /></div>

</form>

";
echo template::footer();

					break;
				case 'tools':

switch( linkex::get( 'action', $_REQUEST, 'overview' ) ) {
case 'autoadd': // {{{
ob_implicit_flush(true);
session_write_close();

echo template::header( array( 'title' => 'Tools' ) );

$_POST['url'] = linkex::get( 'url', $_POST, $config->url );
$_POST['data'] = linkex::get( 'data', $_POST, '' );

if ( strlen( trim( $_POST['data'] ) ) > 0 ) {

	$legend = 'Adding links';
	echo "				<div style=\"margin:10px 0px;\">
					<fieldset>
						<legend id=\"legend\">{$legend}</legend>
						<div><pre id=\"progress\" style=\"font-size:11px;min-height:100px;margin-left:5px;\">    ID  Domain                         Status                                              PageRank BackL.Status<br /> ===============================================================================================================<br /></pre></div>
					</fieldset>
				</div>
				<script type=\"text/javascript\">
			/*<![CDATA[*/
			function _p(str){ var elem=document.getElementById('progress'); if(elem){ elem.innerHTML +=str; } }
			function _t(str){ var elem=document.getElementById('legend'); if(elem){ elem.innerHTML=str; } }
			/*]]>*/
		</script>

";
	echo template::footer();
	linkex::flush();
	
	$links = array_map( 'trim', explode( "\n", trim( $_POST['data'] ) ) );
	foreach ( $links AS $link ) {
		$dom = linkex::getDomain( str_replace( 'www.', '', strtolower( $link ) ) );
		template::progress( sprintf( "%-15s", substr( $dom, 0, 14 ) ) ); 
		$con = linkex::fetch( $link );
		if ( preg_match( '#^HTTP/\d+\.\d+\s+200#', linkex::get( 'headers', $con, '' ) ) ) {
			$f=0;
			foreach( autoadd::knownscripts() AS $script=>$regex ) {
				if ( preg_match( $regex, $con{'contents'} ) ) {
					template::progress( sprintf( '[ %-13s ]', $script ) );
					$f=1;
					$res = autoadd::$script( $con, $_POST['url'] );
					if ( $res === true ) {
						template::progress( ' [ OK ]' );
					} else {
						template::progress( ' [ '.$res.' ]' );
					}
					break;
				}
			}
			if ( $f==0 ) {
				template::progress( '[ Link Script not recognized ]' );
			}
		} else {
			template::progress( sprintf( ' [ ERROR: Invalid response %-20s ]', linkex::get( 'headers', $con ) ) );
		}
		template::progress( '<br>' );
	}
	exit;
} else {
	$cat = $config->defaultcategories;
	$categories = linkex::categories( LOGGEDIN );
	$cats = array();
	foreach( $categories AS $cid=>$name ) {
		$cats[] = new Category( $cid );
	}
	$categories = $cats;
	unset( $cats );
	linkex::sort( $categories, 'name', 'asc' );
	$cats = array();
	foreach( $categories AS $c ) {
		$cats{ $c->id } = $c->name;
	}
	$categories = $cats;
	unset( $cats );

	$categories = linkex::selector( 'categories', $categories, 
		linkex::get( 'categories', $_POST, $cat ), LOGGEDIN, null, array( 'style' => '' ) );

	$formaction = htmlentities( $_SERVER['REQUEST_URI'] );
	echo "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Linking Details</legend>
		<form method=\"post\" action=\"{$formaction}\">

			<table class=\"table\">

				<tr>
					<td class=\"key\">URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"url\" value=\"{$_POST['url']}\" /></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Categories:</td>
					<td>{$categories}</td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Link Sites:<br />
						(One URL pr. line)<br />
					(URL to trade form)</td>
					<td><textarea cols=\"80\" rows=\"3\" style=\"height:150px;\" class=\"text\" name=\"data\">{$_POST['data']}</textarea></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><br /><input type=\"submit\" class=\"button\" value=\"OK\" /></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>
";
}

echo template::footer();

	break; // }}}
case 'email': // {{{
	$linkids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
	$list = array();
	$email2id = array();
	foreach( $linkids AS $lid ) {
		$l = new link( $lid );
		if ( strlen( $l->email ) > 0 ) {
			if ( linkex::get( $l->email, $list, false ) === false ) {
				$list[ $l->email ] = array( $l->ldom );
				$email2id[ $l->email ] = array( $l->id );
			} else {
				$list[ $l->email ][] = $l->ldom;
				$email2id[ $l->email ][] = $l->id;
			}
		}
	}
	if ( linkex::get( 'subject', $_POST, false ) !== false && linkex::get( 'sendto', $_POST, false ) !== false ) {
		echo template::header( array( 'title' => 'Tools &raquo; Send email' ) );
		$subject = linkex::get( 'subject', $_POST, '' );
		$body = linkex::get( 'body', $_POST, '' );
		$sendto = linkex::get( 'sendto', $_POST, array() );

		$ids = array();	
		foreach( $sendto AS $to ) {
			$ids = $ids + linkex::get( $to, $email2id, array() );
		}

		foreach( $ids AS $id ) {
			$l = new link( $id );
			linkex::mail( $l->email, $subject, $body );
		}

		echo "Done sending mails..";
		echo template::footer();
	} else {
		$emails = array();
		foreach( $list AS $e=>$l ) {
			$emails[ $e ] = sprintf( '%s (%s)', $e, join(', ',$l ) );
		}
		$selected = linkex::get( 'sendto', $_REQUEST, array() );
		if ( is_string( $selected ) ) {
			$selected = explode( ',', $selected );
		}
		$emails = linkex::selector( 'sendto', $emails, $selected, true, 'select', array( 'style'=>'width:400px;' ) );
		$_SERVER['REQUEST_URI'] = htmlentities( $_SERVER['REQUEST_URI'] );

		echo template::header( array( 'title' => 'Tools &raquo; Send email' ) );
		echo "<div style=\"margin:10px;\">
	<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
		<table>
			<tr valign=\"top\">
				<td class=\"key\">To:</td>
				<td>{$emails}</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Subject:</td>
				<td><input class=\"text\" type=\"text\" name=\"subject\" style=\"width:400px;\" value=\"\" /></td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Message:</td>
				<td><textarea class=\"text\" name=\"body\" style=\"height:150px;width:400px;\" id=\"body\"></textarea></td>
			</tr>
			<tr>
				<td></td>
				<td>
					<input class=\"button\" type=\"submit\" name=\"submit\" value=\"Send\" />
				</td>
			</tr>
		</table>
	</form>
</div>

";
		echo template::footer();
	}
	break; // }}}
case 'import': // {{{
	echo template::header( array( 'title' => 'Tools &raquo; Import' ) );
	if ( linkex::get( 'seperator', $_POST, false ) && linkex::get( 'input', $_POST, false ) ) {

		if ( linkex::get( 'unique', $_POST, false ) !== false ) {
			$doms = array();
			// We need to make sure the domains are unique, so we make a list of all out domains
			$linkids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
			foreach ( $linkids AS $lid ) {
				$l = new link( $lid );
				$doms[] = $l->ldom;
				unset( $l );
			}
		}

		$seperator = preg_quote( linkex::get( 'seperator', $_POST, '' ), '#' );
		$fields = explode( ',', linkex::get( 'fields', $_POST, '' ) );
		$field_count = sizeof( $fields );
		$categories = linkex::get( 'categories', $_POST, $config->defaultcategories );
		$verify = linkex::get( 'verify', $_POST, 0 );
		$lines = explode( "\n", str_replace( "\r", '', linkex::get( 'input', $_POST, '' ) ) );

		$legend = 'Adding new links...';	
		echo "				<div style=\"margin:10px 0px;\">
					<fieldset>
						<legend id=\"legend\">{$legend}</legend>
						<div><pre id=\"progress\" style=\"font-size:11px;min-height:100px;margin-left:5px;\">    ID  Domain                         Status                                              PageRank BackL.Status<br /> ===============================================================================================================<br /></pre></div>
					</fieldset>
				</div>
				<script type=\"text/javascript\">
			/*<![CDATA[*/
			function _p(str){ var elem=document.getElementById('progress'); if(elem){ elem.innerHTML +=str; } }
			function _t(str){ var elem=document.getElementById('legend'); if(elem){ elem.innerHTML=str; } }
			/*]]>*/
		</script>

";
		echo template::footer();
		flush();
		$progress = '';
		$title = '';

		foreach( $lines AS $line ) {
			$list = preg_split( "#".$seperator."#", trim( $line ) );
			if ( sizeof( $list ) == sizeof( $fields ) ) {
				$l = new link;
				for( $i=0; $i<sizeof( $fields ); $i++ ) {
					switch( $fields[$i] ) {
					case 'email':
						$l->email = $list[$i];
						break;
					case 'rurl':
						$l->rurl = $list[$i];
						break;
					case 'lurl':
						$l->lurl = $list[$i];
						break;
					case 'anchor':
						$l->anchor = $list[$i];
						break;
					case 'description':
						$l->description = $list[$i];
						break;
					case 'randlurl':
						$l->lurl = $list[$i];
						$l->rurl = $list[$i];
						break;
					}
				}
				$l->update();
				if ( ( $verify==1 && ( $res = $l->hasBacklink() ) && linkex::get( 'res', $res, 0 ) != 0 ) ) {
					$p = sprintf( 'Skipping line due to missing backlink<br />&nbsp;&nbsp;(%s)', trim( $line ) );
				} elseif ( linkex::get( 'unique', $_POST, false ) !== false && sizeof( $doms ) > 0 && in_array( $l->ldom, $doms ) ) {
					$p = sprintf( 'Skipping line since there allready exists a link to %s', $l->ldom );
				} else {
					$l->categories = $categories;
					$l->save();
					$p = sprintf( 'Added link' );
				}
			} else {
				$p = sprintf( 'Skipping line due to mismatch in field count<br />&nbsp;&nbsp;(%s)', trim( $line ) );
			}
			printf( '<script type="text/javascript">_p("%s<br />");</script>', $p );
			flush();
		}
	} else {

		$_SERVER['REQUEST_URI'] = htmlentities( $_SERVER['REQUEST_URI'] );
		$categories = linkex::categories( true );
		$categories = linkex::selector( 'categories', $categories );

		echo "<div style=\"margin:10px;\">
	<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
		<input type=\"hidden\" name=\"fields\" id=\"fields\" value=\"\" />
		<table>
			<tr>
				<td class=\"key\">Input seperator:</td>
				<td>
					<input type=\"text\" class=\"text\" name=\"seperator\" style=\"width:50px;\" id=\"seperator\" />
					(tip: use <em>&#92;t</em> for tab, or <em>&#92;s+</em> for one or more space characters)
				</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Input fields:</td>
				<td>
					<table style=\"width:auto;\">
						<tr>
							<td style=\"width:180px;\">
								<select name=\"listA\" size=\"10\" id=\"listA\" style=\"width:180px;\">
									<option value=\"email\">Email</option>
									<option value=\"rurl\">Recip URL</option>
									<option value=\"lurl\">Linking URL</option>
									<option value=\"anchor\">Site title</option>
									<option value=\"description\">Description</option>
									<option value=\"randlurl\">Recip AND linking URL</option>
								</select>
							</td>
							<td style=\"text-align:center;width:100px;\">
								<a href=\"#\" style=\"border:1px solid #ccc;padding:5px;padding-top:2px;\" id=\"moveBA\">&laquo;</a> 
								<a href=\"#\" style=\"border:1px solid #ccc;padding:5px;padding-top:2px;\" id=\"moveAB\">&raquo;</a></td>

							<td style=\"width:180px;\">
								<select name=\"listB\" size=\"10\" id=\"listB\" style=\"width:180px;\"></select>
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr>
				<td class=\"key\">Input example:</td>
				<td><div id=\"example\" style=\"font-family:monospace;\"></div></td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Categories:</td>
				<td>{$categories}</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Verify linkback:</td>
				<td><input type=\"checkbox\" class=\"checkbox\" name=\"verify\" value=\"1\" /> (only links with a valid backlink will be imported)</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Unique domains:</td>
				<td><input type=\"checkbox\" class=\"checkbox\" name=\"unique\" value=\"1\" /> (Do not import links when there allready exists links to same domain)</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Input:</td>
				<td><textarea name=\"input\" class=\"text\" style=\"width:450px;height:200px;\"></textarea></td>
			</tr>
			<tr>
				<td></td>
				<td><input type=\"submit\" value=\"OK\" class=\"button\" /></td>
			</tr>
		</table>
	</form>
</div>

<script type=\"text/javascript\">
			/*<![CDATA[*/
			function update(){ var keys=new Array(); var text=new Array(); $(\"select#listB\").each(function(){ var o=this.options; for(var i=0; i<o.length; i++){ keys.push(o[i].value); text.push(\"[\"+o[i].text+\"]\"); } }); $(\"#fields\").val(keys.join(\",\")); $(\"#example\").html(text.join($(\"input#seperator\").val())); } $(document).ready(function(){ $(\"select#listA\").dblclick(function(){ $(this).find(\"option:selected\").remove().appendTo(\"select#listB\"); update(); }); $(\"select#listB\").dblclick(function(){ $(this).find(\"option:selected\").remove().appendTo(\"select#listA\"); update(); }); $(\"input#seperator\").keyup(function(){ update()}).blur(function(){ update()}); $(\"a#moveAB\").click(function(){ $(\"select#listA\").trigger(\"dblclick\")}); $(\"a#moveBA\").click(function(){ $(\"select#listB\").trigger(\"dblclick\")}); });
			/*]]>*/
		</script>

";
		echo template::footer();
	}
	break; // }}}
case 'overview': // {{{
	echo template::header( array( 'title' => 'Tools' ) );
	echo "<div style=\"margin:10px;\">
	<table>
		<tr>
			<td class=\"key\"><a href=\"$URI?page=admin&amp;view=tools&amp;action=import\">Mass add</a></td>
			<td>Batch import links into LinkEX</td>
		</tr>
		<tr>
			<td class=\"key\"><a href=\"$URI?page=admin&amp;view=tools&amp;action=email\">Send email</a></td>
			<td>Send an email to one or more webmasters</td>
		</tr>
		<tr valign=\"top\">
			<td class=\"key\"><a href=\"$URI?page=admin&amp;view=tools&amp;action=autoadd\">Autoadd</a></td>
			<td>Automatically add your site to other link exchange scripts.<br />(BETA. Let me know how it works for you)</td>
		</tr>
		<tr valign=\"top\">
			<td class=\"key\"><a href=\"$URI?page=admin&amp;view=tools&amp;action=pageranktest\">Pagerank Test</a></td>
			<td>Having problems with PageRank? Use this tool to debug the communication with Google.</td>
		</tr>
		<tr valign=\"top\">
			<td class=\"key\"><a href=\"$URI?page=admin&amp;view=tools&amp;action=pagerankcheck\">Manual Pagerank Check</a></td>
			<td>Check the pagerank for an URL</td>
		</tr>
	</table>
</div>
";
	echo template::footer();
	break; // }}}
case 'pagerankcheck':
	echo template::header( array( 'title' => 'Pagerank Test' ) );
	$pagerank = false;
	if ( false !== ( $url = LinkEX::get( 'url', $_POST, false ) ) && preg_match( '/^https?:\/\/(.*\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\.[a-z]+(.*)?/i', $url ) ) {
		$pr = new Google;
		$pagerank = $pr->getPageRank( $url );
		$url = htmlentities( $url );
	} else {
		$url = 'http://';
	}
	echo "<div style=\"margin:10px;\">
	<form method=\"post\">
		<table>
			<tr>
				<td class=\"key\">URL:</td>
				<td><input type=\"text\" class=\"text\" name=\"url\" value=\"{$url}\" /></td>
			</tr>
			<tr>
				<td class=\"key\"></td>
				<td>
					<input class=\"button save\" type=\"submit\" name=\"ok\" value=\"Check\" />
				</td>
			</tr>
".((false !== $pagerank)?("
			<tr>
				<td class=\"key\">URL:</td>
				<td>{$url}</td>
			</tr>
			<tr>
				<td class=\"key\">PageRank:</td>
				<td>{$pagerank} / 10</td>
			</tr>
"):(""))."
		</table>
	</form>
</div>
";
	echo template::footer();
	break; // }}}
	break;
case 'pageranktest': // {{{
	echo <<<END
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>LinkEX &raquo; Test Pagerank algorithm</title>
	</head>
	<body>
		<pre>
END;

//83fbba4523f873252
//773196802182
	$pr = new Google;
	$pr->hosts = $config->googledatacenters;
	$url = 'http://linkex.dk';
	echo "Testing pagerank for: $url\n";
	echo "Calculation Google Cookie (expecting 8769977f4)\n";
	$cookie = $pr->getCH( $url );
	echo "  $cookie - ";
	if ( $cookie == "8769977f4" ) {
		echo "<span style='color:green;'>passed</span>\n";

		$p = $pr->getPageRank( 'http://linkex.dk' );
		if ( -1 != $p ) {
			echo "  <span style='color:green;'>PageRank for $url - $p</span>\n";
			echo "  <span style='color:green;'>Test ended successfully</span>\n";
		} else {
			echo "  <span style='color:red;'>Did not find Rank_ in body of document</span>\n";
		}		
		echo "<br /><br />" . $pr->debug['sent'] . "<br />" . htmlentities($pr->debug['received']);
	} else {
		echo "<span style='color:red;'>failed</span>\n";
	}
	echo <<<END
		</pre>
	</body>
</html>
END;
	break; // }}}
}

					break;
				case 'upgrade':

function debug( $str ) { // {{{
	echo "<script type=\"text/javascript\">_p('".$str."<br />');</script>";
	linkex::flush();
} // }}}

echo template::header( array( 'title' => 'Upgrading  LinkEX' ) );
$legend = 'Upgrading LinkEX';
echo "				<div style=\"margin:10px 0px;\">
					<fieldset>
						<legend id=\"legend\">{$legend}</legend>
						<div><pre id=\"progress\" style=\"font-size:11px;min-height:100px;margin-left:5px;\">    ID  Domain                         Status                                              PageRank BackL.Status<br /> ===============================================================================================================<br /></pre></div>
					</fieldset>
				</div>
				<script type=\"text/javascript\">
			/*<![CDATA[*/
			function _p(str){ var elem=document.getElementById('progress'); if(elem){ elem.innerHTML +=str; } }
			function _t(str){ var elem=document.getElementById('legend'); if(elem){ elem.innerHTML=str; } }
			/*]]>*/
		</script>

";
echo template::footer();
linkex::flush();

if ( ( $fp = @fopen( 'index.php', 'a' ) ) === false ) {
	// Unable to write to index.php
	debug( 'Cannot open index.php for writing. Please check the permissions.' );
	exit;
}

fclose ( $fp );
debug( 'Cheking file permissions.. done' );

if ( @copy( __FILE__, BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'index.'.date(  'Ymd' ).'.php' ) === false ) {
	debug( 'Unable to backup LinkEX script' );
	exit;
}
debug( 'Backing up current version.. done' );

if ( linkex::get( 'beta', $_REQUEST, 0 ) == 1 ) {
	$md5 = linkex::fetch( 'http://linkex.dk/releases/current.beta.md5', array( 'utf8encode' => false ) );
} else {
	$md5 = linkex::fetch( 'http://linkex.dk/releases/current.md5', array( 'utf8encode' => false ) );
}
if ( ( $error = linkex::get( 'error', $md5, false ) ) !== false ) {
	debug( 'Error while fetching version checkum ('.$md5['error'].')' );
	exit;
} else if ( strlen( trim( linkex::get( 'contents', $md5, '' ) ) ) != 32 ) {
	debug( 'Invalid response while fetching version checksum.' );
	exit;
}
$checksum = trim( linkex::get( 'contents', $md5, '' ) );
debug( 'Fetching new version checksum.. ['.$checksum.']' );

if ( linkex::get( 'beta', $_REQUEST, 0 ) == 1 ) {
	$script = linkex::fetch( 'http://linkex.dk/releases/current.beta.tar', array( 'utf8encode' => false ) );
} else {
	$script = linkex::fetch( 'http://linkex.dk/releases/current.tar', array( 'utf8encode' => false ) );
}
if ( ( $error = linkex::get( 'error', $md5, false ) ) !== false ) {
	debug( 'Error while fetching new script ['.$md5['error'].']' );
	exit;
}
$script = linkex::get( 'contents', $script, '' );
debug( 'Fetching new version data file.. done ['.round(strlen($script)/1024,1).'kb]' );

if ( strcmp( strtolower( md5( $script ) ), strtolower( $checksum ) ) != 0 ) {
	debug( 'Verifying script checksum.. Error! Checksum mismatch ['.md5( $script).']' );
	exit;
}
debug( 'Verifying script checksum.. done' );

linkex::fileput( __FILE__, $script );
debug( 'Installing new version.. done' );
debug( '<br />Upgrade complete.' );

					break;
				default:
					linkex::redirect( BASEURI, 404 );
				}
			} else {
				echo template::header( array( 'title' => 'Please login', 'metarobots' => 'noindex,follow' ) );
				echo "<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Please login</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<table>
				<tr>
					<td class=\"key\">Username:</td>
					<td><input type=\"text\" class=\"text\" name=\"username\" value=\"\" style=\"width:150px;\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password:</td>
					<td><input type=\"password\" class=\"text\" name=\"password\" value=\"\" style=\"width:150px;\" /></td>
				</tr>
				<tr>
					<td class=\"key\"><label for=\"remember\">Remember me:</label></td>
					<td><input type=\"checkbox\" class=\"checkbox\" name=\"remember\" value=\"1\" style=\"margin:0px;\" id=\"remember\" /></td>
				</tr>
				<tr>
					<td></td>
					<td><input type=\"submit\" name=\"ok\" value=\"OK\" class=\"button\" /></td>
				</tr>
				<tr>
					<td></td>
					<td><a href=\"$URI?page=resetpassword\">I have forgotten my username/password</a></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>
";
				echo template::footer();
			}
			break;
		case 'check':
@set_time_limit( 0 );
// Remote check
function checkoutput( $code, $str ) { // {{{
	die( "{$code}:{$str}
" );
} // }}}
// {{{ Is this thing enabled?
if ( intval( $config->remoteenable ) == 0 ) {
	checkoutput( 1, 'Remote access is not enabled' );
}
// }}}
// {{{ IP check
if ( intval( $config->remotelimitips ) == 1 ) {
	$ips = $config->remoteips;
	$found = false;
	$remote = linkex::get( 'REMOTE_ADDR', $_SERVER, '' );
	foreach( $ips AS $ip ) {
		if ( linkex::compareIPs( $ip, $remote ) == 0 ) {
			$found = true;
			break;
		}
	}
	if ( $found !== true ) {
		checkoutput( 2, 'Your IP ('.$remote.') is not in the accepted IP list' );
	}
}
// }}}
// {{{ Passphrase check
if ( ( $pass = $config->remotepass ) && strlen( $pass ) > 0 ) {
	if ( linkex::get( 'passphrase', $_GET, false ) != $pass ) {
		checkoutput( 3, 'Invalid or missing passphrase' );
	}
}
// }}}

$report = linkex::verifybacklinks( linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR ) );
if ( $config->remotesummary == 1 ) {
	$report = template::report( $report );
	linkex::mail( $config->email, 'Link verification report', $report );
}

checkoutput( 0, 'OK' );

			break;
		case 'about':
			echo template::header( array( 'title' => 'About', 'metarobots' => 'noindex,follow' ) );
			echo template::about();
			echo template::footer();
			break;
		case 'logout':
			$path = dirname( linkex::get( 'SCRIPT_NAME', $_SERVER, '/' ) );
			setcookie( '_authcookie', '', time() - 3600, $path );
			unset( $_SESSION['_authcookie'] );
			linkex::redirect( BASEURI, 301 );
		case '':
			// Add link

if ( !LOGGEDIN && intval( $config->disablepublicform ) == 1 ) {
	echo template::header( array( 'title' => 'Add link', 'metadescription' => 'Exchange hardlinks with '.$config->domain ) );
	echo "<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>Form disabled</legend>
		<div style=\"padding:10px;\">
			Please contact the webmaster to setup a link trade.
		</div>
	</fieldset>
</div>
";
	echo template::footer();
} else {
	if ( sizeof( $_POST ) > 0 ) {
		if (
			(
				intval( $config->usecaptcha ) == 0 
			) || (
				LOGGEDIN
			) || ( 
				intval( $config->usecaptcha ) == 1 &&
				linkex::get( 'captcha', $_POST, false ) &&
				linkex::get( 'captcha', $_SESSION, false ) && linkex::get( 'result', $_SESSION['captcha'], false ) &&
				$_POST['captcha'] == $_SESSION['captcha']['result'] 
			)
		) {
			$link = new link;

			$link->wmip = $_SERVER['REMOTE_ADDR'];	
			$link->lurl = htmlentities( linkex::get( 'lurl', $_POST, '' ) );
			if ( 
				$config->disablerecipfield == 1 && !LOGGEDIN &&
				$config->samedomain != 2
		 	) {
				$link->rurl = $link->lurl;
			} else {
				$link->rurl = htmlentities( linkex::get( 'rurl', $_POST, '' ) );
			}
			// Damn stupid noobish exploit
			$link->anchor = htmlentities( trim( linkex::get( 'anchor', $_POST, '' ) ) );
			if ( $config->usetitle == 1 ) {
				$link->title = htmlentities( trim( linkex::get( 'title', $_POST, '' ) ) );
			} else {
				$link->title = $link->anchor;
			}

			$link->description = htmlentities( trim( linkex::get( 'description', $_POST, '' ) ) );
			$link->categories = linkex::get( 'categories', $_POST, $config->defaultcategories );
			if ( !is_array( $link->categories ) ) {
				$link->categories = array( $link->categories );
			}
			$link->categories = linkex::map( 'intval', $link->categories );

			$link->email = htmlentities( trim( linkex::get( 'email', $_POST, '' ) ) );

			// Start link validation
			// {{{ Check the title
			if ( $config->usetitle == 1 && strlen( $link->title ) == 0 ) {
				$errors[] = 'Please fill out the title';
			}
			// }}}
			// {{{ Check the anchor
			if ( strlen( $link->anchor ) == 0 ) {
				if ( $config->usetitle == 1 ) {
					$errors[] = 'Please fill out the anchor text';
				} else {
					$errors[] = 'Please fill out the title text';
				}
			}
			// }}}
			// {{{ Check the lurl
			if ( strlen( $link->lurl ) == 0 ) {
				$errors[] = 'Please fill out the URL';
			} else if ( !preg_match( '/^https?:\/\/(.*\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\.[a-z]+(.*)?/i', $link->lurl ) ) {
				$errors[] = 'The URL &quot;'.$link->lurl.'&quot; in invalid';
			}
			// }}}
			// {{{ Check the email
			if ( strlen( $link->email ) == 0 ) {
				$errors[] = 'Please enter an email address';
			} else if ( !preg_match( '/\S+@[a-z0-9]([a-z0-9-]*[a-z0-9])?\.[a-z]+(.*)?/i', $link->email ) ) {
				$errors[] = 'The email &quot;'.$link->email.'&quot; is invalid';
			}
			// }}}
			// {{{ Check the rurl
			if ( intval( $config->disablerecipfield ) == 0 ) {
				if ( strlen( $link->rurl ) == 0 ) {
					$errors[] = 'Please fill out the reprocial URL';
				} else if ( !preg_match( '/^https?:\/\/(.*\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\.[a-z]+(.*)?/i', $link->rurl ) ) {
					$errors[] = 'The reprocial URL &quot;'.$link->rurl.'&quot; in invalid';
				}
			}
			// }}}
			// {{{ Check the categories
			if ( $config->publiccategories == 1 ) {
				if ( sizeof( $link->categories ) == 0 ) {
					$errors[] = 'Please select a category';
				}
			}
			// }}}
			$link->update();
			$link->updateIPs();
			// {{{ indexexchange
			if ( $config->indexexchange == 1 ) {
				$elems = @parse_url( $link->lurl );
				if ( linkex::get( 'path', $elems, '/' ) != '/' ) {
					$errors[] = 'Only index exchanges allowed';
				}
				if ( $link->lurl != $link->rurl ) {
					$elems = @parse_url( $link->rurl );
					if ( linkex::get( 'path', $elems, '/' ) != '/' ) {
						$errors[] = 'Only index exchanges allowed';
					}
				}
			}
			// }}}
			// {{{ noquerystring
			if ( $config->noquerystring == 1 ) {
				if ( strpos( $link->lurl, '?' ) !== false ) {
					$errors[] = 'No querystrings allowed';
				}
				if ( $link->rurl != $link->lurl && strpos( $link->rurl, '?' ) !== false ) {
					$errors[] = 'No querystrings allowed';
				}
			}
			// }}}
			// {{{ Same domain?
			switch( intval( $config->samedomain ) ) {
			case 1:
				if ( linkex::compareURLs( $link->ldom, $link->rdom ) != 0 ) {
					$errors[] = 'The submitted URLs must be on the same domain';
				}
				break;
			case 2:
				if ( intval( $config->disablerecipfield ) == 0 && linkex::compareURLs( $link->ldom, $link->rdom ) == 0 ) {
					$errors[] = 'The submitted URLs must be on different domains';
				}
				break;
			}
			// }}}
			// {{{ Check the length's
			if ( sizeof( $errors ) == 0 && (( LOGGEDIN && linkex::get( 'skiplengths', $_POST, 0 ) == 0 ) || !LOGGEDIN ) ) {
				// First the anchor
				if ( $config->anchorlength > 0 ) {
					if ( $config->anchorlengthtype == 'w' )  {
						// Max words
						if ( sizeof( preg_split( '#\s+#', $link->anchor ) ) > $config->anchorlength ) {
							$errors[] = sprintf( 'Your site anchor text is too long' );
						}
					} else {
						// Max len
						if ( strlen( $link->anchor ) > $config->anchorlength ) {
							$errors[] = sprintf( 'Your site anchor text is too long' );
						}
					}
				}
				// Then the title
				if ( $config->usetitle == 1 && $config->titlelength > 0 ) {
					if ( $config->titlelengthtype == 'w' )  {
						// Max words
						if ( sizeof( preg_split( '#\s+#', $link->title ) ) > $config->titlelength ) {
							$errors[] = sprintf( 'Your site title is too long' );
						}
					} else {
						// Max len
						if ( strlen( $link->title ) > $config->titlelength ) {
							$errors[] = sprintf( 'Your site title is too long' );
						}
					}
				}

				// Then the description
				if ( $config->descriptionlength > 0 ) {
					if ( $config->descriptionlengthtype == 'w' ) {
						// Max words
						if ( sizeof( preg_split( '#\s+#', $link->description ) ) > $config->descriptionlength ) {
							$errors[] = sprintf( 'Your site description is too long' );
						}
					} else {
						// Max len
						if ( strlen( $link->description ) > $config->descriptionlength ) {
							$errors[] = sprintf( 'Your site description is too long' );
						}
					}
				}
			}
			// }}}
			//  {{{ Check for dublicate domains/ips
			if ( ( LOGGEDIN && linkex::get( 'skipdupes', $_POST, 0 ) == 0 ) || !LOGGEDIN ) {
				$linkids = linkex::listfiles( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR );
				$ipcount = 0;
				foreach ( $linkids AS $lid ) {
					$l = new link( $lid );
					$ipcount += ( linkex::compareIPs( $l->rdomip, $link->rdomip ) == 0 ) ? 1:0;
					if ( $config->linkbotuniquedomains == 1 ) {
						if ( linkex::compareURLs( $link->ldom, $l->ldom ) == 0 ) {
							$errors[] = 'We allready have a link to &quot;'.$l->ldom.'&quot;';
							break;
						} else if ( linkex::compareURLs( $link->rdom, $l->rdom ) == 0 ) {
							$errors[] = 'We allready have a link from &quot;'.$l->rdom.'&quot;';
							break;
						}
					} else {
						if ( linkex::compareURLs( $link->lurl, $l->lurl ) == 0 ) {
							$errors[] = 'We allready have a link to &quot;'.$l->lurl.'&quot;';
							break;
						} else if ( linkex::compareURLs( $link->rurl, $l->rurl ) == 0 ) {
							$errors[] = 'We allready have a link from &quot;'.$l->rdom.'&quot;';
							break;
						}
					}
					unset( $l );
				}
				if (
					intval( $config->linkbotuniqueips )>0 && 
					$ipcount >= intval( $config->linkbotuniqueips )
				) {
					$errors[] = 'We allready have '.intval($ipcount).' links from &quot;'.$link->rdomip.'&quot;';
				}
			}
			// }}}
			// {{{ Check the blacklist
			if ( ( LOGGEDIN && linkex::get( 'skipblacklist', $_POST, 0 ) == 0 ) || !LOGGEDIN ) {
				if ( sizeof( $errors ) == 0 && linkex::get( 'skipblacklist', $_POST, 0 ) == 0 && ( $reason = $link->blacklisted() ) !== false ) {
					$errors[] = $reason;
				}
			}
			// }}}
			// {{{ Make sure a backlink is present
			$link->lastchecked = time();
			if ( 
				sizeof( $errors ) == 0 && 
				( ( LOGGEDIN && linkex::get( 'skipbacklinkcheck', $_POST, 0 ) == 0 ) || !LOGGEDIN ) && 
				( ( $config->linkbackrequired == 1 ) || ( intval( $config->maxoutboundlinks ) > 0 ) ) && 
				( $e=$link->hasBacklink() ) && 
				linkex::get( 'res', $e, 0 ) != 0 
			) {
				switch( linkex::get( 'res', $e, 0 ) ) {
				case '1':
					$errors[] = 'Unable to verify backlink. '.linkex::get( 'reason', $e, '' );
					break;
				case '2':
					$errors[] = 'None of the links found on &quot;'.$link->rurl.'&quot; could be accepted. ' .
						linkex::get( 'reason', $e, '' );
					break;
				case '4':
					$errors[] = 'The anchor text of the backlink did not match the req'.'uired anchor text.';
					break;
				case '8':
					$errors[] = 'None of the links found on &quot;'.$link->rurl.'&quot; could be accepted. ' .
						linkex::get( 'reason', $e, '' );
					break;
				case '16':
					$errors[] = linkex::get( 'reason', $e, '' );
					break;
				default:
					$errors[] = 'Iternal error';
					break;
				}
			}
			$link->skipcheck = ( LOGGEDIN && linkex::get( 'skipbacklinkcheck', $_POST, 0 ) == 1 ) ? 1:0;
			// }}}
			// {{{ Check the min PageRank
			// The pagerank must be checked if:
			// ( config->minpagerank > 0 && !LOGGEDIN ) || ( LOGGEDIN && linkex::get( 'skippagerank', $_POST, 0 ) == 0 )
			if ( 
				sizeof( $errors ) == 0 &&
				$config->minpagerank > 0 &&
				!( LOGGEDIN && linkex::get( 'skippagerank', $_POST, 0 ) != 0 )
			) {
				if ( $link->getRPageRank( false ) < $config->minpagerank ) {
					$errors[] = 'We&nbsp;require a min. PR'.$pr.', your site has a PR'.$link->getRPageRank( false ).'';
				}
			}
			// }}}
			if ( sizeof( $errors ) == 0 ) {
				$link->save();
				$link = new link( $link->id );
				if ( !LOGGEDIN && strlen( $config->email ) > 4 ) {
					$_SERVER['HTTP_HOST'] = str_replace( 'www.', '', strtolower( linkex::get( 'HTTP_HOST', $_SERVER, 'unknown' ) ) );
					$host = $_SERVER['HTTP_HOST'];
					linkex::mail( $config->email, 'LinkEX: new link @ '.linkex::get( 'HTTP_HOST', $_SERVER, 'unknown' ), "This is a message from {$host}.

A new link was just added:
By:                {$link->wmip}
Email:             {$link->email}

 Outbound link:  {$link->lurl} 
            IP:  {$link->ldomip}
      PageRank:  {$link->lpagerank}
 Indexed pages:  {$link->lindexed}
   Anchor text:  {$link->anchor}
    Title text:  {$link->title}

  Inbound link:  {$link->rurl}
            IP:  {$link->rdomip}
      PageRank:  {$link->rpagerank}
 Indexed pages:  {$link->rindexed}

" );
				}

				echo template::header( array( 'title' => 'Link added' ) );
				echo "<div style=\"margin:10px auto;\">
	<fieldset>
		<legend>Rules</legend>
		<div class=\"article\">
			<p>Thank you for adding your link to our database.<br />
			Please make sure you allways keep a link to our site, otherwise your link will be disabled from our site.</p>
			<p>Like the looks of this script? Get yours for free, head over to <a href=\"http://linkex.dk\">LinkEX</a> and check out this free script.</p>
		</div>
	</fieldset>
</div>
";
				echo template::footer();
				exit;
			}
		} else {
			// Captcha failed
			$errors[] = 'Spam check failed. Please retry';
		}
	}

	echo template::header( array( 'title' => 'Add link', 'metadescription' => 'Exchange hardlinks with '.$config->domain.'. Instant linkexchange' ) );
	$rules = linkex::fileget( BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'rules', "We are constantly looking for new perm link exchanges to improve link popularity and page rank.<br />
Please remember that this is not about traffic, it's about the link.<br />
Play fair!
" );
	$anchor = $config->anchor;
	$anchor = $anchor[ mt_rand( 0, sizeof( $anchor )-1 ) ];
	$title = $config->title;
	$title = $title[ mt_rand( 0, sizeof( $title )-1 ) ];
	$htmlcode = str_replace(
		array( '{$URL}', '{$ANCHOR}', '{$DESCRIPTION}', '{$TITLE}' ),
		array( 
			htmlentities( $config->url ), 
			htmlentities( $anchor ), 
			htmlentities( $config->description ),
			htmlentities( $title )
		),
		$config->htmlcode
	);
	if ( intval( $config->publiccategories ) == 1 || LOGGEDIN ) {
		$categories = linkex::categories( LOGGEDIN );
		$cats = array();
		foreach( $categories AS $cid=>$name ) {
			$cats[] = new Category( $cid );
		}
		$categories = $cats;
		unset( $cats );
		linkex::sort( $categories, 'name', 'asc' );
		$cats = array();
		foreach( $categories AS $c ) {
			$cats{ $c->id } = $c->name;
		}
		$categories = $cats;
		unset( $cats );

		$categories = linkex::selector( 'categories', $categories, 
			linkex::get( 'categories', $_POST, $categories ), LOGGEDIN, null, array( 'style' => 'width:auto;max-width:300px;' ) );
	} 
	if ( intval( $config->usecaptcha ) == 1 && !LOGGEDIN ) {
		$c = new captcha;
		$captcha = $c->html(); 
	}
	if ( LOGGEDIN ) {
		$skipbacklinkcheck = linkex::checkbox( linkex::get( 'skipbacklinkcheck', $_POST, 0 ) );
		$skippagerank = linkex::checkbox( linkex::get( 'skippagerank', $_POST, 0 ) );
		$skipblacklist = linkex::checkbox( linkex::get( 'skipblacklist', $_POST, 0 ) );
		$skiplengths = linkex::checkbox( linkex::get( 'skiplengths', $_POST, 0 ) );
		$skipdupes = linkex::checkbox( linkex::get( 'skipdupes', $_POST, 0 ) );
	}

	$_POST['email']				= htmlentities( linkex::get( 'email', $_POST, ( (LOGGEDIN)?$config->email:'') ) );
	$_POST['lurl']				= htmlentities( linkex::get( 'lurl', $_POST, '' ) );
	$_POST['rurl']				= htmlentities( linkex::get( 'rurl', $_POST, '' ) );
	$_POST['title']				= htmlentities( linkex::get( 'title', $_POST, '' ) );
	$_POST['anchor']			= htmlentities( linkex::get( 'anchor', $_POST, '' ) );
	$_POST['description'] = htmlentities( linkex::get( 'description', $_POST, '' ) );

	echo "<div style=\"margin:10px auto;\">
	<fieldset>
		<legend>Rules</legend>
		<table class=\"table\">
			<tr>
				<td colspan=\"2\">
					<div class=\"article\">
						{$rules}
					</div>
				</td>
			</tr>
			<tr>
				<td class=\"key\">Linkback:</td>
				<td>".(($config->linkbackrequired == 1)?("Required"):("Not required"))."</td>
			</tr>
			<tr>
				<td class=\"key\">Min. PageRank&trade;:</td>
				<td><div class=\"pagerank pr{$config->minpagerank}\"></div></td>
			</tr>
			".(($config->maxoutboundlinks>0)?("
			<tr>
				<td class=\"key\">Max. links:</td>
				<td>{$config->maxoutboundlinks} external links on reciprocal link URL</td>
			</tr>
			"):(""))."
		</table>
	</fieldset>
</div>
<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Our linking details</legend>
		<table class=\"table\">
			".(($config->showemail == 1)?("
			<tr>
				<td class=\"key\">Email:</td>
				<td>{$config->email}</td>
			</tr>
			"):(""))."
			<tr>
				<td class=\"key\">URL:</td>
				<td style=\"width:480px;\">{$config->url}</td>
			</tr>
			<tr>
				<td class=\"key\">Site anchor:</td>
				<td>{$anchor}</td>
			</tr>
				<tr>
				<td class=\"key\">Site title:</td>
				<td>{$title}</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">Site description:</td>
				<td>{$config->description}</td>
			</tr>
			<tr valign=\"top\">
				<td class=\"key\">HTML code:</td>
				<td></td>
			</tr>
			<tr valign=\"top\">
				<td colspan=\"2\" class=\"center pre\">{$htmlcode}</td>
			</tr>
		</table>
	</fieldset>
</div>

<div style=\"margin:10px auto;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Your linking details</legend>
		<form method=\"post\" action=\"$URI\">
			<table class=\"table\">
				".(($config->usetitle==1)?("
				<tr>
					<td class=\"key\">Site anchor:</td>
					<td><input type=\"text\" class=\"text\" name=\"anchor\" value=\"{$_POST['anchor']}\" />
						".(($config->anchorlength>0 && $config->anchorlengthtype == 'w')?(" max {$config->anchorlength} words"):(""))."
						".(($config->anchorlength>0 && $config->anchorlengthtype == 'c')?(" max {$config->anchorlength} characters"):(""))."
					</td>
				</tr>
				<tr>
					<td class=\"key\">Site title:</td>
					<td><input type=\"text\" class=\"text\" name=\"title\" value=\"{$_POST['title']}\" />
						".(($config->titlelength>0 && $config->titlelengthtype == 'w')?(" max {$config->titlelength} words"):(""))."
						".(($config->titlelength>0 && $config->titlelengthtype == 'c')?(" max {$config->titlelength} characters"):(""))."
					</td>
				</tr>
				"):("
				<tr>
					<td class=\"key\">Site title:</td>
					<td><input type=\"text\" class=\"text\" name=\"anchor\" value=\"{$_POST['anchor']}\" />
						".(($config->titlelength>0 && $config->titlelengthtype == 'w')?(" max {$config->titlelength} words"):(""))."
						".(($config->titlelength>0 && $config->titlelengthtype == 'c')?(" max {$config->titlelength} characters"):(""))."
					</td>
				</tr>
				"))."
				<tr>
					<td class=\"key\">Your URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"lurl\" value=\"{$_POST['lurl']}\" /></td>
				</tr>
				".(($config->disablerecipfield == 0 || $config->samedomain == 2)?("
				<tr>
					<td class=\"key\">Reciprocal link URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"rurl\" value=\"{$_POST['rurl']}\" /> 
						".(($config->samedomain == 1)?("Must be on the same domain as above"):(""))."
						".(($config->samedomain == 2)?("Must be on a different domain as above	"):(""))."
					</td>
					<td class=\"help\"></td>
				</tr>
				"):(""))."
				<tr>
					<td class=\"key\">Your email:</td>
					<td><input type=\"text\" class=\"text\" name=\"email\" value=\"{$_POST['email']}\" /></td>
				</tr>
				<tr valign=\"top\">
					<td class=\"key\">Site description:</td>
					<td>
						<textarea cols=\"80\" rows=\"3\" class=\"text\" name=\"description\">{$_POST['description']}</textarea> 
						".(($config->descriptionlength>0 && $config->descriptionlengthtype == 'w')?(" max {$config->descriptionlength} words"):(""))."
						".(($config->descriptionlength>0 && $config->descriptionlengthtype == 'c')?(" max {$config->descriptionlength} characters"):(""))."
					</td>
				</tr>
				".(($config->usecaptcha && !LOGGEDIN)?("
				<tr>
					<td class=\"key\">Spam check:</td>
					<td>
						<table cellpadding=\"0\" cellspacing=\"0\">
							<tr>
								<td style=\"width:100px;\">{$captcha}</td>
								<td><input type=\"text\" name=\"captcha\" value=\"\" class=\"text\" style=\"width:50px;\" /></td>
							</tr>
						</table>
					</td>
					<td class=\"help\"></td>
				</tr>
				"):(""))."
				".(($config->publiccategories || LOGGEDIN)?("
				<tr valign=\"top\">
					<td class=\"key\">Category:</td>
					<td>{$categories}</td>
					<td class=\"help\"></td>
				</tr>
				"):(""))."
				".((LOGGEDIN)?("
				<tr>
					<td class=\"key\"></td>
					<td colspan=\"3\"><br />Since you are logged in, you have additional options:</td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skipbacklinkcheck\" value=\"1\" {$skipbacklinkcheck} /> Ignore missing backlink.</label></td>
					<td></td>
				</tr>				
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skippagerank\" value=\"1\" {$skippagerank} /> Ignore PageRank&trade;.</label></td>
					<td></td>
				</tr>				
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skipblacklist\" value=\"1\" {$skipblacklist} /> Ignore blacklist.</label></td>
					<td></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skiplengths\" value=\"1\" {$skiplengths} /> Ignore max. length on title and description.</label></td>
					<td></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><label><input type=\"checkbox\" class=\"checkbox\" name=\"skipdupes\" value=\"1\" {$skipdupes} /> Ignore dublicate domains/IPs.</label></td>
					<td></td>
				</tr>				
				"):(""))."
				<tr>
					<td class=\"key\"></td>
					<td><br /><input type=\"submit\" class=\"button\" value=\"Add my link\" /></td>
					<td class=\"help\"></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>
";
	echo template::footer();

}

			break;
		default:
			linkex::redirect( BASEURI, 404 );
		}
	}
} else {

$_username = linkex::get( '_username', $_POST, '' );
$_password1 = linkex::get( '_password1', $_POST, '' );
$_password2 = linkex::get( '_password2', $_POST, '' );
$_email = linkex::get( '_email', $_POST, '' );
$_url = linkex::get( '_url', $_POST, 'http://'.linkex::get( 'HTTP_HOST', $_SERVER, '' ) );
$_anchor = linkex::get( '_anchor', $_POST, '' );

if ( linkex::get( 'ok', $_POST, false ) !== false ) {
	// Form is posted
	// {{{ Check if we have a username
	if ( strlen( trim( $_username ) ) == 0 ) {
		$errors[] = 'Please enter a username';
	}
	// }}}
	// {{{ Check the password(s)
	if ( strlen( trim( $_password1 ) ) == 0 ) {
		$errors[] = 'Please enter a password';
	} else if ( trim( $_password1 ) != trim( $_password2 ) ) {
		$errors[] = 'The two passwords did not match, please try again.';
	}
	// }}}
	// {{{ Check the email
	if ( strlen( trim( $_email ) ) == 0 ) {
		$errors[] = 'Please enter an email address';
	} else if ( !preg_match( '/\S+@[a-z0-9]([a-z0-9-]*[a-z0-9])?\.[a-z]+(.*)?/i', $_email ) ) {
		$errors[] = 'The email &quot;'.$_email.'&quot; is invalid';
	}
	// }}}
	// {{{ Check the URL
	if ( strlen( trim( $_url ) ) == 0 ) {
		$errors[] = 'Please fill out the URL of your website';
	} else if ( !preg_match( '/^https?:\/\/(.*\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\.[a-z]+(.*)?/i', $_url ) ) {
		$errors[] = 'The URL &quot;'.$_url.'&quot; in invalid /^https?:\/\/(.*\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\.[a-z]+(.*)?/i';
	}
	// }}}
	// {{{ Check the anchor
	if ( strlen( trim( $_anchor ) ) == 0 ) {
		$errors[] = 'Please fill out the title of your website';
	}
	// }}}

	if ( sizeof( $errors ) == 0 ) {
		$dirs = array(
			BASEDIR . DIRECTORY_SEPARATOR .'data',
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'categories' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blacklist' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'links' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR,
			BASEDIR . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR
		);

		foreach( $dirs AS $d ) {
			if ( !is_dir( $d ) && @mkdir( $d, 0777 ) === false ) {
				$errors[] = 'Unable to create directory &quot;'.$d.'&quot;';
				break;
			}
			@chmod( $d, 0777 );
		}
		$config = new config;
		$config->password = md5( $_username .'---'. $_password1 );
		$config->email = $_email;
		$config->url = $_url;
		$config->anchor = array( $_anchor );
		$config->defaultcategories = array( '1001' );

		if ( sizeof( $errors ) == 0 ) {
			$config->save();

			linkex::fileput( 
				BASEDIR . DIRECTORY_SEPARATOR .'data'. DIRECTORY_SEPARATOR .'config'. DIRECTORY_SEPARATOR .'uid', '1000' );

			$cat = new category;
			$cat->name = 'Default';
			$cat->save();
			unset( $cat );

			echo template::header( array( 'title' => 'Installation complete' ) );
			echo "<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>All done</legend>
		<div class=\"article\">
			You LinkEX is now ready to use, <a href=\"index.php?page=admin\">log in here</a>, and check out the opportunities with this script.
		</div>
	</fieldset>
</div>
";
			echo template::footer();

			exit;
		}
	}	
}

echo template::header( array( 'title' => 'Installation' ) );
echo "<div style=\"margin:10px 0px;\">
	<fieldset>
		<legend>Welcome to LinkEX</legend>
		<div class=\"article\">
			Thank you for choosing LinkEX. Hopefully LinkEX will help you build a strong network of links, 
			and lessen the workload for you at the same time.<br />
			<br />
			In order to start using LinkEX, you need to fill out the form below.
		</div>
	</fieldset>
</div>
";
echo "<div style=\"margin:10px 0px;\">
	<fieldset style=\"margin:10px auto;\">
		<legend>Settings</legend>
		<form method=\"post\" action=\"{$_SERVER['REQUEST_URI']}\">
			<table class=\"table\">
				<tr>
					<td class=\"key\">Username:</td>
					<td><input type=\"text\" class=\"text\" name=\"_username\" value=\"{$_username}\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password:</td>
					<td><input type=\"password\" class=\"text\" name=\"_password1\" value=\"{$_password1}\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Password (again):</td>
					<td><input type=\"password\" class=\"text\" name=\"_password2\" value=\"{$_password2}\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Email:</td>
					<td><input type=\"text\" class=\"text\" name=\"_email\" value=\"{$_email}\" /></td>
				</tr>
				<tr>
					<td colspan=\"2\">&nbsp;</td>
				</tr>
				<tr>
					<td class=\"key\">Website URL:</td>
					<td><input type=\"text\" class=\"text\" name=\"_url\" value=\"{$_url}\" /></td>
				</tr>
				<tr>
					<td class=\"key\">Website Title:</td>
					<td><input type=\"text\" class=\"text\" name=\"_anchor\" value=\"{$_anchor}\" /></td>
				</tr>
				<tr>
					<td class=\"key\"></td>
					<td><input type=\"submit\" class=\"button\" name=\"ok\" value=\"OK\" /></td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>
";
echo template::footer();

}

?>
