;(function($) {

$.fn.extend({
	// Call specified method of control (check by class name)
	'rounded':	function(corners) {
		var classes = corners.split(',') || [];
		
		this.each(function(index, node) {
			node = $(node);
			node.css('position', 'relative');
			
			for(var i=0; i<classes.length; i++) {
				node.append($(String.format('<b class="corner {0}"></b>', classes[i])));
			}
			
			// FIXME: Why does the right corner position depend on element width in Internet Explorer?
			if($.browser.msie) {
				var width = node.width();
				node.find('b.rt, b.rl').each(function(index, b) {
					if((width - b.offsetLeft) > 1) b.style.right = '-1px';
					
					//var Dx = width - b.offsetLeft;
					//alert(b.parentNode.innerHTML + '\n' + Dx);
					//if(Dx > 1)  b.style.right = '-' + (Dx - 1)+ 'px';
				});
			}
		});
		
		return this;
	}
});
	
})(jQuery);


// Global rounded elements
$(document).ready(function() {
	$('.rounded').each(function() {
		var node = $(this);
		var corners = ['lt', 'rt', 'lb', 'rb'];
		var node_corners = [];
		for(var i=0; i<corners.length; i++) {
			if(node.hasClass(corners[i])) node_corners.push(corners[i]);
		}
		node.rounded(node_corners.join(','));
	});
});

// Various Fiexes  (IE6 special)
$(document).ready(function() {
	// Empty nodes behavior
	$('p.error:empty').hide();
	$('div.accordion dl.vertical dt:empty').hide();
	//$('div.MyProfile p.description:empty').hide();
});

// Fields' hint behavior
$.fn.extend({
	'hintable': function() {
		var hintbody = $('#fieldshint');
		var hinttail = $('#fieldshint #tail');
		var hintfired = false;
		
		this.each(function(index, node) {
			var node = $(node);
			node.attr('hint', node.attr('title'));
			node.attr('title', '');
			
			node.hover(
				function(event) {
					// onMouseOver
					var title = $(this).attr('hint');
					if(title != '') {
						$(this).after(hintbody);
						
						var position	= $(this).position();
						var width		= $(this).width();
						var height		= $(this).height();
						
						hintbody.find('#hint').html(title);
						
						var parent = $(this).parent('.hint-container');
						if(parent.length == 0) parent = $(this).parent();
						
						hintbody.css({
							'left':	parent.position().left,
							'top':	position.top + height
						});
						
						hinttail.css('left',	position.left + width/2 - parent.position().left);
						
						this.title = '';
						
						$(this).focus();
						hintfired = true;
						
						// Small jump into the future because IE!!!
						setTimeout(function() {
							if(hintfired) hintbody
								.addClass('bottom')
								.removeClass('right')
								.show()
								.bgiframe();
						}, 10);
					}
				},
				
				function(event) {
					// onMouseOut
					this.title = hintbody.find('p').html();
					
					$(this).blur();
					hintfired = false;
					
					hintbody
						.appendTo(document.body)
						.removeClass('bottom')
						.hide();
				}
			);
		});
	}
});

$(document).ready(function() {
	var fieldshint =  $('<div id="fieldshint"><div id="hint"></div></p><div id="tail"></div></div>');
	$(document.body).append(fieldshint);
						   
	$('dd input, dd select')
		.focus(function(event) {
			var title = $(event.target).attr('hint');
			if(title != '') {
				if(this.tagName.toUpperCase() == 'SELECT' && !$(this).attr('multiple')) {
					// skip hint appearance for Single Select
					return;
				}
				
				$(event.target).after(fieldshint);
				
				var position	= $(event.target).parents('dd').position();
				var width		= $(event.target).parents('dd').width();
				
				fieldshint.find('#hint').html(title);
				
				fieldshint.css('left',	position.left + width);
				fieldshint.css('top',	position.top - 4);
				
				fieldshint
					.addClass('right')
					.removeClass('bottom')
					.show()
					.bgiframe();
			}
		})
		
		.blur(function(event) {
			fieldshint.removeClass('right');
			fieldshint.hide();
		})
		
		.each(function() {
			var node = $(this);
			node.attr('hint', node.attr('title'));
			node.attr('title', '')
		});
	
	$('.hintable[title]').hintable();
});

// Tabs behavior
$(document).ready(function() {
	$('div.tabs ul li a[rel]').click(function(event) {
		if(!$(this).hasClass('disabled')) {
			$('div.tabs ul li a[rel]').each(function(index, node) {
				$(String.format('#{0}', $(node).attr('rel'))).hide();
			});
			$('div.tabs ul li.selected').removeClass('selected');
			
			$(String.format('#{0}', $(this).attr('rel'))).show();
			$(this).parents('li').addClass('selected');
		}
	});
	
	$('div.tabs ul li.selected a[rel]').click();
});

// Overflowed elements' hint 
$(document).ready(function() {
	$('dl.memberDetail dd, div.member div.icon a, div.Gallery div.galleryThumbnails div.scrollable div.thumbnails div.thumbnail div.description').each(function(index, node) {
		if(node.scrollWidth > node.clientWidth) {
			node.title = $(node).text();
		}
	});
});

// Accrordion behavior
$(document).ready(function() {
	$('div.accordion div.page h3')
		.each(function() {
			var h3 = $(this);
			h3.html(String.format('<span class="icon">{0}</span>', h3.text()));
		})
		.click(function(event) {
						//debugger;
			var h3		= $(this);
			var div		= h3.siblings('div');
			var page	= h3.parents('div.page');
			
			if(!page.hasClass('closed')) {
				// Close element
				page
					.addClass('closed')
					.children('div').slideUp();
				
			} else {
				// Close other elements
				$('div.accordion div.page:not(.closed)')
					.addClass('closed')
					.children('div').slideUp();
				
				// Open current element
				page
					.removeClass('closed')
					.children('div').slideDown();
			}
			
			event.preventDefault();
			event.stopPropagation();
		});
		
	$('div.accordion div.page.closed h3').each(function() {
		$(this).siblings('div').hide();
	});
});

// Form behavior, prevent double-submit 
$(document).ready(function() {
	$('form').submit(function(event){
		if(!this.submitted) {
			return (this.submitted = true);
		}
		else {
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
	});
});

// Clicable nodes begavior
$(document).ready(function() {
	$('.clickable').live('click', function() {
		location.href = $(this).attr('href');
	});
});

// Popup hint on members' photo
$.DF.require('/scripts/jquery.ajax.js');
$.DF.require('/scripts/libs/jquery.bgiframe.min.js');
$(document).ready(function() {
	var _menu = $('<div></div>')
			.css('position', 'absolute')
			.css('z-index', 1000)
			.hide()
			.appendTo(document.body);
	
	var _photo, _timer, _id;
	
	$('div.member .photo, table.mail td.from a, div.MailboxHome span.author a').mouseover(function(event) {
		clearTimeout(_timer);
		
		_timer = setTimeout(function() {
			_photo = $(event.target);
			var id = _photo.attr('id');
			
			_id = id;
			
			if(id != '') {
				$.DF.AjaxRender.ViewProfileContextMenu({userId:id}, null, function(html) {
					if(id == _id) {
						_menu.html(html);
						
						var px = _photo.offset().left,	py = _photo.offset().top;
						var pw = _photo.width(), 		ph = _photo.height();
						
						var W = $(window).width(),	H = $(window).height();
						var w = _menu.width(),		h = _menu.height();
						
						var X = $(window).scrollLeft(), Y = $(window).scrollTop();
						var x = px, y = py;
						
						if((x + w) > (W + X) && (px + pw - w > X)) x = px + pw - w;
						if((y + h) > (H + Y) && (py + ph - h > Y)) y = py + ph - h;
						
						_menu.moveTo(x, y).show('slow', function() {
							if($.browser.msie) _menu.bgiframe();
							$().trigger('df:photos:ready');
						});
					}
				});
			}
		}, 300);
	}).attr('alt', '');
	
	$('div.member img.photo, table.mail td.from a, div.MailboxHome span.author a').mouseout(function(event) {
		clearTimeout(_timer);
		_id = null;
		
		_timer = setTimeout(function() {
			_menu.hide();
		}, 200);
	});
	
	_menu.mouseover(function(event) {
		clearTimeout(_timer);
	});
	
	_menu.mouseout(function(event) {
		clearTimeout(_timer);
		_id = null;
		
		_timer = setTimeout(function() {
			_menu.hide();
		}, 200);
	});
	
	$('div.ContextMenu div.ViewProfileMenu a').live('click', function(event) {
		_menu.hide();
	});
});

// Add special class (background, text etc.) for disabled SELECT
$(document).ready(function() {
	$('div.AdvancedSearch input:disabled, div.AdvancedSearch select:disabled')
		.addClass('disabled')
		.val('');
});

// Hint for no-photo, private etc.
$(document).ready(function() {
	var size2position = {
		125:	{left:8, bottom:8, width:108, height:31},
		140:	{left:15, bottom:12, width:110, height:31},
		210:	{left:25, bottom:19, width:160, height:37}
	};
						   
	$().bind('df:photos:ready', function() {
		$('img.photo[src*=theme/photos]:not([src*=video_preview]):not([src*=photo_xxx])').each(function() {
			var img = $(this), a = img.parent('a'), data = size2position[img.width()];
			if(a.css('position') != 'relative' && data != null) {
				a.css('position', 'relative').css('display', 'block').width(img.width()).height(img.height());
				
				$(String.format('<div class="photohint" style="left:{1}px; bottom:{2}px; width:{3}px; height:{4}px; line-height:{4}px;">{0}</div>', 
								img.attr('alt'),
								data.left,
								data.bottom,
								data.width,
								data.height
				)).appendTo(a);
			}
		});
		
		$('img.photo[src*=theme/photos/photo_xxx]').each(function() {
			var img = $(this), a = img.parent('a'), data = size2position[img.width()];;
			if(a.css('position') != 'relative' && data != null) {
				a.css('position', 'relative').css('display', 'block').width(img.width()).height(img.height());
				
				$(String.format('<div class="photohint-xxx">{0}</div>', img.attr('alt').replace(' ', '<br />'))).appendTo(a);
			}
		});
	});
	
	$().trigger('df:photos:ready');
});

// UI Effects (for index page etc.)
$(document).ready(function() {
	$('.ui-slideshow').each(function() {
		var node = this;
		var items = $(node).find('.ui-slideshow-item'), length = items.hide().length, index = 0;
		var optionShowTime	= parseInt(getOption(node, 'ui-slideshow-showtime'))	|| 3000;
		var optionFadeTime	= parseInt(getOption(node, 'ui-slideshow-fadetime'))	|| 500;
		
		if(length > 0) {
			$(items.get(index)).fadeIn(optionFadeTime);
			
			setInterval(function() {
				$(items.get(index)).fadeOut(optionFadeTime);
				index = (index + 1)%length;
				$(items.get(index)).fadeIn(optionFadeTime);
			}, optionShowTime);
		}
	});
	
	$('.ui-random').each(function() {
	});
	
	$('a.ui-popup-link').click(function(event) {
		var node = this;
		var url = $(this).attr('href');
		var width = parseInt(getOption(node, 'ui-popup-width'))	|| 640;
		var height = parseInt(getOption(node, 'ui-popup-height'))	|| 480;
		
		$.DF.Popup.open(String.format('<div class="FramePopup"><img src="/theme/images/ico_close.gif" width="16" height="16" alt="" id="close"><iframe src="{0}" width="{1}" height="{2}" frameborder="0"></iframe></div>', url, width, height));
		$('div.FramePopup img#close').click($.DF.Popup.close);
		
		event.preventDefault();
	});

	function getOption(node, option) {
		var matched = node.className.match(new RegExp(String.format('{0}-(\\d+)', option), 'i'));
		if(matched && matched[1])
			return matched[1]
		else
			return null;
	}
});

// PNG Fix for IE6
// Should be last at all
$(document).ready(function() {
	//if($.isFunction($(document).pngFix)) { $(document).pngFix( { blankgif:'/theme/images/empty.gif' } );}
	if($.isFunction(jQuery.ifixpng)) {
		jQuery.ifixpng('/theme/images/empty.gif');
		jQuery('img').ifixpng();
	}
});
