﻿(function($, window){

	$.fn.extend({
	
		newsPicGallery: function(dataArray, width, height, morelnk){
		
			var htmlBuffer = [];

			htmlBuffer.push('<div class="gallery_dotct">');

			for (var i = 0; i < dataArray.length; i++){
				var data = dataArray[i];
				if (!data){
					continue;
				}
				htmlBuffer.push(['<a href="', data.link, '" pic="', data.pic, '" title="', data.title.replace(/\'/ig, '\'').replace(/\"/ig, '\"'), '"></a>'].join(''));
			}

			htmlBuffer.push('</div>');

			// append 'more' link
			if (morelnk){
				htmlBuffer.push(['<a href="', morelnk.url, '" class="more">', morelnk.title, '</a>'].join(''));
			}

			// append title label
			htmlBuffer.push('<div class="labelct"></div>');

			// append pics ct (active & inactive)
			htmlBuffer.push('<img src="" alt="" class="active" /><img src="" alt="" class="inactive" />');
			
			// set size, className and html
			this.width(width).height(height).addClass('gallery_ct').html(htmlBuffer.join(''));

			// get dotct
			var dotct = this.find('div.gallery_dotct'), timer = null;

			// bind dot events
			dotct.click(function(e){
			
				if (e.target.tagName.toLowerCase() != 'a'){
					return false;
				}

				var a = $(e.target);
				if (a.hasClass('selected')){
					return false;
				}

				if (timer){
					window.clearTimeout(timer);
					slideInterval = null;
				}

				$(this).find('a').removeClass('selected');
				a.addClass('selected');

				var ct = a.parents('div.gallery_ct'), label = ct.find('div.labelct'),
					imgActive = ct.find('img.active'), imgInactive = ct.find('img.inactive');
				
				// set label invisible first
				label.css({opacity: 0});

				if (imgActive.attr('src') != ''){
					imgInactive.attr('src', imgActive.attr('src'));
				}

				imgActive.css({opacity: 0}).attr('src', a.attr('pic'))
					.animate(
						{opacity: 1}, 600, 
						// after image shown, set label visible
						function(){
							
							// show label
							label.text(a.attr('title')).attr('title', a.attr('title')).animate({opacity: 0.7}, 600);
							
							// set timer
							timer = window.setTimeout(function(){
								var next = dotct.find('a.selected').next('a');
								if (next.length == 0){
									next = dotct.find('a:eq(0)');
								}
								next.click();
							}, 5000);
						
						});

				return false;
			});

			// bind image & label events
			this.find('img.active, div.labelct').click(function(){
				window.open(dotct.find('a.selected').attr('href'));
			});

			// prepare first show
			dotct.find('a:eq(0)').click();
		}

	});

})(jQuery, window);

