/* Id jchine-v.x.x.js 2009-2-12 */

(function($){
	$.fn.dropshadow = function() {
		return this.each(function(){
		if ($(this).parent().parent() && !$(this).parent().parent().hasClass('dropshadow-wrap'))
		{
			$(this).wrap('<div class="dropshadow-wrap"><div style="position: relative; top: -5px; left: -5px;"></div></div>');
			//$('.dropshadow-wrap').css({opacity: '0.999999'});
			if ($.fn.pngfix)
			{
				$('.dropshadow-wrap').pngfix();
			}
		}
		});
	};
	$.fn.popupsuggest = function(options){
		options = $.extend({
			ele: '',
			width: '300px',
			onShow: null,
			onHide: null,
			handler: 'click'
		}, options || {});
		
		return this.each(function(){
			var $$ = $(this);
			
			var target;
			var timeout;
			var _hideListener = null;
			var hasFocus;
			initPopup();
				
			target.hover(function(){
				_focus();
			}, function(){
				_blur();
			});

			$$.bind(options.handler, function(){
				_show();
			});
			
			_hideListener = _hide;

			$$.bind('hide', function(){
				hasFocus = false;
				_hide();
			});
			$$.bind('show', function(){
				_show();			
			});
			function initPopup(){
				$$.css({cursor: 'pointer'});
				$(options.ele).dropshadow().css({'z-index': 100000});
				target = $(options.ele).parent().parent().hide();
				
			}

			function _focus(){
				hasFocus = true;
			}

			function _blur(){
				hasFocus = false;
			}

			function _hide(){
				
				if (hasFocus)
					return ;

				target.hide('slow');
			}

			function _show() {
				var p = $$.position();
				$(options.ele).width(options.width);
				var l =  (p.left-parseInt(options.width)+$$.width() <= 0)  
					? p.left 
					:  p.left-parseInt(options.width)+$$.width() ;

				target.css({position: 'absolute', left: l+'px', top: p.top+parseInt($$.height())+10+'px'});
				target.show('slow');
				
				if (_hideListener)
				{
					_unregisterHideListener();
				}

				if (!timeout)
				{
					timeout = setTimeout(_registerHideListener, 150);
				}
				
			};

			function _registerHideListener() {
				$(document).bind('click', function(){
					_hideListener();
				});	
			};

			function _unregisterHideListener() {
				$(document).unbind('click');
				if (timeout) {
					clearTimeout(timeout);
					timeout = null;
				}
			}			
		});
	};
	$.fn.tooltip = function(options){
		options = $.extend({
			title: 'test'
		},  options || {});
	
		return this.each(function(){
			//$.dropshadow();
			var $$ = $(this);
			$$.attr('title') ? options.title = $$.attr('title') : void(0);
			$$.attr('title', '');
			var handler;
			var p = $$.position();
			$$.hover(function(){
				_show();
			}, function(){
				_hide();
			});

			function _show(){
				$(document.body).append('<div id="tooltip_chine">'+options.title+' '+'</div>');
				handler = $('#tooltip_chine');
				handler.css({position: 'absolute', left: p.left+'px', top: p.top-$$.height()+'px'/*, border: '2px red solid'*/});
			}
			function _hide(){
				handler.remove();
			}
		});
	};
	$.fn.slide = function(settings) {
		settings = $.extend({
			play: true,
			pw: -488,
			ph: 248,
			tabw: 60,
			delay_time: 5000,
			pause_callback: null,
			group: 4
		}, settings || {});

		return this.each(function(){
			var $$ = $(this);
			var ctl = $('.ctl_bar', $$);
			var btnbar = $('div.btns', $$); 
			var btns = $('a.prev, a.next', $$);
			var playbtn = $('a.play_pause, img.playbtn', $$);
			var tip = $('span.index_status', $$); 
			var tabs = $('div.imgs li:not(:last-child)', ctl);
			var tabcur = $('li.cur_box', ctl);
			var con = $('div.cons div.img_item', $$);
			var total = tabs.length || $('.img_item', $$).size();
			var idxA  = [0, total-1];
			var curIdx = 0;
			var last_time = 0;
			var autoplay_timer = null;
			var autoplay_process = $('>i',tabcur);
			var inNav = false;
			var t_s = 1000;
			var tabw = settings.tabw;
		
			tip.html(1+'/'+total);

			//$('.img_item').width(-settings.pw+'px');
			playbtn.click(function(ev){
				playbtn.toggleClass('on_pause');
				if (settings.pause_callback)
				{
					settings.pause_callback();
				}
				autoPlay(!playbtn.hasClass('on_pause'));
				
				return false;
			});
			if(settings.play){
				playbtn.removeClass('on_pause');
				autoPlay(true);
			}else{
				playbtn.addClass('on_pause');
			}

			tabs.each(function(idx,tab){
				$(tab).click(function(ev){
					navTo(idx);
					return false;
				});
			});

			$('a.prev, img.prev', $$).click(function(){
				navTo(curIdx-1);
			});

			$('a.next, img.next', $$).click(function(){
				navTo(curIdx+1);
			});
			
			function navTo(idx){
				if(inNav||curIdx==idx||idxA[1]==0)return false;
				inNav=true;
				if(idx<idxA[0]){
					idx=idxA[1];
					con.stop().animate({'top':settings.ph},{
						'duration':t_s*.6,
						'complete':function(){
							con.css('left',idx*settings.pw);
							con.animate({'top':0},{
									'duration':t_s*.4,'complete':function(){
									last_time=(new Date).getTime();
									inNav=false;
								}
							});
						}
					});
				}else if(idx>idxA[1]){
					idx=idxA[0];
					con.stop().animate({'top':settings.ph},{
						'duration':t_s*.6,
						'complete':function(){
							con.css('left',idx*settings.pw);
							con.animate({'top':0},{
								'duration':t_s*.4,
								'complete':function(){
									last_time=(new Date).getTime();
									inNav=false;
								}
							});
						}
					});
				}else{
					con.stop().animate({'left':idx*settings.pw},{
						'duration':t_s,
						'complete':function(){
							last_time=(new Date).getTime();
							inNav=false;
						}
					});
				}
				if (idxA[1] >= settings.group && (idx % settings.group == 0 || idx > idxA[1])) {
					$('div.imgs', $$).css({position: 'absolute'}).stop().animate({'left':-idx*tabw},{
						'duration':t_s,
						'complete':function(){
							last_time=(new Date).getTime();
							inNav=false;
						}
					});
				}
				tabcur.animate({'left':idx*tabw},{'duration':t_s*.6});
				curIdx=idx;
				tip.html((idx+1)+'/'+total);

				return true;
			}


			function autoPlay(f){
				if(settings.play !== null){
					clearInterval(autoplay_timer);
					autoplay_timer=null;
				}
				if(f){
					autoplay_process.show();
					last_time=(new Date).getTime();
					autoplay_timer=setInterval(function(){
						if(!inNav){
							var passed=(new Date).getTime()-last_time;
							if(passed>=settings.delay_time){
								navTo(curIdx+1);
							}else{
								autoplay_process.css('width',(((passed/settings.delay_time)*100|0)%100)+'%');
							}
						}
					},80);
				}else{
					autoplay_process.hide();
				}
			}

		});
	};
	$.fn.imgsnap = function(settings){
		settings = $.extend({
			width: 80,
			height: 80,
			direction: 'center middle',
			pA: ['left', 'center', 'right', 'top', 'middle', 'bottom']
		}, settings || {});

		return this.each(function(){
			var $$ = $(this);
			//fixbug IE a tag 
			
			
			if ($$.parent().get(0) && $$.parent().get(0).tagName == "A")
			{
				var w = $$.parent().eq(0);
			} else {
				var w = $$;
			}
		
			
			w.wrap($('<div></div>').css({position: 'relative', width: parseInt(settings.width)+'px', height: parseInt(settings.height)+'px', 'overflow': 'hidden'}));
			//center middle
			$$.load(function(){
				$$.css({position: 'absolute', 'left': Math.floor(settings.width/2.0 - $$.width()/2.0)+'px', top: Math.floor(settings.height/2.0 - $$.height()/2.0)+'px'});
			});
			if ($$.width() > 0)
			{
				$$.css({position: 'absolute', 'left': Math.floor(settings.width/2.0 - $$.width()/2.0)+'px', top: Math.floor(settings.height/2.0 - $$.height()/2.0)+'px'});
			}
			/*
			function getDirection(direct) {
				return jQuery.inArray(direct, pA);
			}
			function getPosition(direction){
				var tmp = settings.direction.split(' ');
				switch (getDirection(tmp[0]))
				{
				case 0:
				case 1:
				case 2:
				
				}
			}*/
		});

		
	};

	$.fn.tabsLite = function(options) {
		options = $.extend({
		/*target: [], handler: [], */
			e: 'click',
			selClass: 'sel',
			selectIdx: 0
		}, options || {});

		return this.each(function(){
			var $$ = $(this);
			//init
			if(options.handler.length>0){
				$(options.target.join(",")).hide();
				$(options.target[options.selectIdx]+'').show();
				$(options.handler.join(",")).removeClass(options.selClass);
				$(options.handler[options.selectIdx]+'').addClass(options.selClass);
			}
			//bind event
			$.each(options.handler, function(i){
				$(this +'').bind(options.e, function(){
					$(options.target.join(",")).hide();
					$(options.handler.join(",")).removeClass(options.selClass);
					$(options.handler[i]+'').addClass(options.selClass);
					$(options.target[i]+'').show();
				});
			});

		});
	};
/*
	例子：
	<script type="text/javascript">
	 
		jQuery(document).ready(function(){
			jQuery('#promotion_info').marquee({time: 2000, step: jQuery('#promotion_info li').height()});
			jQuery('#promotion_info').hover(
				function(){ jQuery('#promotion_info').marqueeStop(); },
				function(){ jQuery('#promotion_info').marqueePlay();}
			);
		}); 
	</script>
	<ul id="promotion_info">
		<li>111</li>
		<li>111</li>
		<li>111</li>
	</ul>
*/
	var ELMS = [];
 	$.fn.jqMarquee = function(settings) {	
		settings = $.extend({}, arguments.callee.defaults, settings);
		$(this).each(function(){
			this.$settings=settings;
			this.$pause=false;
			this.$click=false;
			this.$counter=settings.delay;
			$(this).hover(function(){
				$(this).jqMarqueePause(true);
			}, function(){ 
				$(this).jqMarqueePause(false);
			});
			ELMS.push(this);
		});
	};
	$.fn.jqMarquee.defaults = {delay:60,step:2};
	$.fn.jqMarqueePause = function(pause) {return this.each(function() {this.$pause = pause;});};
	$.fn.jqMarqueeClick = function(click) {return this.each(function() {this.$click = click;});};
	setInterval(jQscroll, 50);
	function jQscroll() {
		for (var i = 0; i < ELMS.length; i++) {
			var elm = ELMS[i];
            if($('li', elm).length<=elm.$settings.number) {$(elm).jqMarqueePause(true);}
			if (elm && !elm.$pause&&!elm.$click) {
				if (elm.$counter == 0) {
					var ul 	= $('> ul', elm)[0];
					if (!elm.$steps) {
						elm.$steps = $('> li:last-child', ul).height();
						elm.$step = 0;
					}
					if ((elm.$steps + elm.$step) <= 0) {
						elm.$counter = elm.$settings.delay;
						elm.$steps = false;
						$(ul).css('top', '0').find('> li:last-child').after($('> li:first-child', ul));
					} else {
						elm.$step -= elm.$settings.step;
						if (-elm.$step > elm.$steps) {
							elm.$step = -elm.$steps;
						}
						ul.style.top = elm.$step + 'px';
					}
				} else {
					elm.$counter--;
				}
			}
		}
	};
	var methods = {
        marquee: function marquee(user_settings) {
            var self = $(this);            
			var sch = self.attr('scrollHeight');
			self.append(self.html());
            var settings = {
                timeout: null,                
                events: {
                    play: function(evt) {
                        var self = $(this);						
						var sct = self.scrollTop();
						if(sct>=sch)self.scrollTop(sct=sct-sch);
						self.animate({scrollTop:sct+settings.step-sct%settings.step},2000,function(){
							if(settings.timeout) clearTimeout(settings.timeout);
							settings.timeout = setTimeout(function(){self.marqueePlay()},settings.time);
						});
                    },
                    stop: function(evt) {
                        var self = $(this);
                        clearTimeout(settings.timeout);self.stop();
                    }
                }
            };
            if(self.data("marquee.settings")) {
                settings = self.data("marquee.settings");
            }
            settings = $.extend(user_settings, settings);            
            for(var event in settings.events) {
                var evt = "marquee." + event;
                self.unbind(evt);
                self.bind(evt, settings.events[event]);
            }            
            self.data("marquee.settings", settings);
			self.marqueePlay();
            return self;
        },
        marqueePlay: function() {
            $(this).trigger("marquee.play");         
        },
        marqueeStop: function() {
            $(this).trigger("marquee.stop");
        }
    };
    $.each(methods, function(i) {
        $.fn[i] = this;
    });

	$.fn.hint = function(){
		return this.each(function(){			
			var hint = $(this).val();
			$(this).addClass("grey");
			$(this).bind('focus', function(){
				$(this).removeClass("grey");
				if ($(this).val() == hint) {
					$(this).val("");
					//$(this).removeClass("grey");
				}
			});
		});
	};
	$.fn.newNav = function(){
		if ( jQuery.browser.msie ) {
			var agent=/(?:MSIE.(\d+\.\d+))/.exec(navigator.userAgent);
			var _ie;
			if(agent){
				_ie=agent[1]?parseFloat(agent[1]):NaN;
				if(_ie>=8&&!window.HTMLCollection){_ie=7;}
			}
			if (_ie < 7) return;
		
		}
		return this.each(function(){
			var $$ = $(this);
			var p = $$.position();
			
			$('<span class="new">&nbsp;</span>')
			.css({position: 'absolute', top: (p.top-10), left: (p.left+$$.width()-5), padding:0,margin:0})
			.appendTo( $$.parent().parent() );
		});
	};
	$.fn.selectentry = function(options){
		options = $.extend({
			'selectClass': 'sel',
			'item': ''
		}, options || {});
		return this.each(function(){
			$$ = $(this);
			if (!$('input[name=search_entry]', $$).size())
			{
				$$.append('<input type="hidden" name="search_entry" value="'+$('li:contains('+options.selectClass+')', $$).eq(0).text()+'" />');
			}
			if (options.item != '') {
				$('li', $$).each(function(){

					if($(this).text().toLowerCase() == options.item.toLowerCase()) {
						$('li', $$).removeClass(options.selectClass);
						$(this).addClass(options.selectClass);
						$('input[name=search_entry]', $$).val( $(this).text() );
					}
				});
			}
			$('input[name=search_entry]').val( $('li.'+options.selectClass, $$).text() );

			$('li', $$).bind('click', function(){
				$('li', $$).removeClass(options.selectClass);
				$(this).addClass(options.selectClass);
				$('input[name=search_entry]', $$).val( $(this).text() );
			});
		});
	};
})(jQuery);

var Chine = { 
	tinyMCE:  {
		/*
		 * insert content: Chine.tinyMCE.getInstance().execCommand('mceInsertContent',false,'<b>Hello world!!</b>');
		 *
		 * get content: Chine.tinyMCE.getInstance().get('elm1').getContent()
		 * 
		*/
		config: {
			default_: {
				mode : "textareas",
				theme : "advanced",
				//plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",
				plugins : "",
				theme_advanced_buttons1 :"",
				theme_advanced_buttons2 :"",
				theme_advanced_buttons3 :"",
				theme_advanced_buttons4 :"",
				// Theme options
				/*theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
				theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
				theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",*/

				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : false

				// Example word content CSS (should be your site CSS) this one removes paragraph margins
				//content_css : "css/word.css",
			},
			comment: {
				mode : "exact",
				theme : "advanced",
				skin : "chine",
				/*elements : "elm12",*/
				plugins : "emotions,inlinepopups",
				theme_advanced_buttons1 : "bold,italic,underline,emotions"
			},
			editor: {
				mode: "exact",
				theme: "advanced",
				skin: "chine",
				plugins: 'paste,inlinepopups',
				theme_advanced_buttons1 : "bold,italic,underline,pasteword,|,outdent,indent,|,justifyleft,justifycenter,justifyright,justifyfull",
				theme_advanced_resizing : true
			}
		},
		create: function(conf, ele){
			
			if (typeof conf == 'string') {
				
				for (p in Chine.tinyMCE.config)
				{
					if ( p==conf && Chine.tinyMCE.config[p] )
					{
						conf = Chine.tinyMCE.config[p];
					}
				}
			} 
			if (typeof conf == 'string') {
				conf = {};
			}
			
			if (conf.mode == 'exact' && ele)
			{
				conf.elements = ele;
			}
			
			conf = jQuery.extend(Chine.tinyMCE.config.default_, conf || {});
			//console.log(conf);
			tinyMCE.init(conf);
		},
		getInstance: function(editor_id){
			if (editor_id!=undefined && editor_id!='')
			{
				//return window.tinyMCE.getEditorInstance(editor_id)
				return window.tinyMCE.get(editor_id)
			} else
			
			return window.tinyMCE;
		},
		toolBar: function(conf){
			if (typeof conf == 'string') {
				
				for (p in Chine.tinyMCE.config)
				{
					if ( p==conf && Chine.tinyMCE.config[p] )
					{
						conf = Chine.tinyMCE.config[p];
					}
				}
			} 
			if (typeof conf == 'string') {
				conf = {};
			}
			
			if (conf.mode == 'exact' && ele)
			{
				conf.elements = ele;
			}
			
			conf = jQuery.extend(Chine.tinyMCE.config.default_, conf || {});
			return conf;
		}
	}
};

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie=function(a,b,c){if(typeof b!='undefined'){c=c||{};if(b===null){b='';c.expires=-1}var d='';if(c.expires&&(typeof c.expires=='number'||c.expires.toUTCString)){var e;if(typeof c.expires=='number'){e=new Date();e.setTime(e.getTime()+(c.expires*24*60*60*1000))}else{e=c.expires}d='; expires='+e.toUTCString()}var f=c.path?'; path='+(c.path):'';var g=c.domain?'; domain='+(c.domain):'';var h=c.secure?'; secure':'';document.cookie=[a,'=',encodeURIComponent(b),d,f,g,h].join('')}else{var j=null;if(document.cookie&&document.cookie!=''){var k=document.cookie.split(';');for(var i=0;i<k.length;i++){var l=jQuery.trim(k[i]);if(l.substring(0,a.length+1)==(a+'=')){j=decodeURIComponent(l.substring(a.length+1));break}}}return j}};


function getEditorContents(item){
	var oEditor = FCKeditorAPI.GetInstance(item) ;
    return  oEditor.GetXHTML( true );  
}
function SetContents(item, str){
	
	var oEditor = FCKeditorAPI.GetInstance(item) ;
	oEditor.SetHTML( str ) ;
}
function changepic(){
	document.getElementById('verifypic').src='/users/checkcode/sst/'+new Date().getTime();
}

function inArray(val, array){
	for(var i=0; i< array.length; i++)
		if(array[i] == val)
			return i;
	return -1;
}
function getPageSize(){
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) { // all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}


	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}
/*
function tosignin() {
	top.location.href="/";
	return false;
}

function tosignup() {
	top.location.href="/user/register";
	return false;
}
*/
function tosignin() {
	if (window.login_url)
	{
		top.location.href=window.login_url;
	} else
		top.location.href="/";
	return false;
}

function tosignup() {
	if (window.register_url)
	{
		top.location.href=window.register_url;
	} else
		top.location.href="/user/register";
	return false;
}
function ucwords(str){
	return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
}

$(document).ready(function(){
	$('a.adv-search, span.advance').click(function(){
		$('div.adv-search').show('slow');
	});
	$('div.adv-search img.close').css('cursor', 'pointer');
	$('div.adv-search a.close, div.adv-search img.close').click(function(){
		$('div.adv-search').hide('slow');
	});
	$('input.hint, input.input_l').hint();
	$('.local_left span.m_26').parent().parent('li').addClass('sel');//who's profile
	$('.m_28').newNav();
	$(document.head).append('<link rel="shortcut icon" href="/chine_images/favicon.ico" />');

	$('div.wr_up, div.wr_up2').css('cursor', 'pointer').click(function(e){
			$(this).find('a').trigger('click');
			return false;
	});
	
});

