var ImagePreloadContainer = {
	preload_container: null,
   
    createPreloadContainer: function() {
    	if (!ImagePreloadContainer.preload_container) {
	        jQuery(document.body).prepend("<div id='ImagePreloadContainer' style='position: absolute; left: -3000px; width: 1000px; overflow: hidden;'></div>");
	        ImagePreloadContainer.preload_container = jQuery('#ImagePreloadContainer');
    	}
    },
    
    preload: function(img_src) {
    	ImagePreloadContainer.createPreloadContainer();
		jQuery(ImagePreloadContainer.preload_container).append('<img src="'+img_src+'" alt="">');
	}
};

var AvatarViewer = {
	do_preload: true,
	timeout_handler: null,
	timeout_value: 500,
	
	init: function() {
		// collect all avatar links
		jQuery('a[avatar]').each(function(i, el){
			if (el.getAttribute('avatar')) {
				jQuery(el).mouseover(AvatarViewer.eventOverItem);
				jQuery(el).mouseout(AvatarViewer.eventOutItem);
				if (AvatarViewer.do_preload) {
					ImagePreloadContainer.preload(el.getAttribute('avatar'));
				}
			}
		});
	},
	
	clearTimeout: function() {
		if (AvatarViewer.timeout_handler) {
			clearTimeout(AvatarViewer.timeout_handler);
		}
	},
	
	eventOverItem: function(e) {
		var el = e.currentTarget;
		var src = el.getAttribute('avatar');
		var title = el.getAttribute('avatar_title') ? el.getAttribute('avatar_title') : '';
		var offset = jQuery(el).offset();
		var posX = offset.left - 20;
		var posY = offset.top - 20;
		
		AvatarViewer.showAvatar(src, el.href, title, posX, posY);
	},
	
	eventOverAvatar: function(e) {
		AvatarViewer.clearTimeout();
	},
	
	eventOutItem: function(e) {
		AvatarViewer.timeout_handler = setTimeout('AvatarViewer.hideAvatar();', AvatarViewer.timeout_value);
	},
	
	eventOutAvatar: function(e) {
		AvatarViewer.timeout_handler = setTimeout('AvatarViewer.hideAvatar();', AvatarViewer.timeout_value);
	},
	
	showAvatar: function(src, url, title, pos_x, pos_y) {
		AvatarViewer.clearTimeout();
		AvatarViewer.hideAvatar();
		jQuery(document.body).append(
				"<div id='AvatarViewerContainer' style='position: absolute; width: 1px; height: 1px; overflow: hidden; left: "+(pos_x-3000)+"px; top:"+pos_y+"px;z-index: 1000;'>"
				+ "<a href='"+url+"'><img id='AvatarViewerCurrentImage' class='rounded rc10' src='/img/x.gif' alt='"+title+"' title='"+title+"'></a>"
				+ "<div class='n'></div><div class='ne'></div><div class='e'></div><div class='se'></div><div class='s'></div><div class='sw'></div><div class='w'></div><div class='nw'></div>"
				+ "</div>"
		);
		var container = jQuery('#AvatarViewerContainer')[0];
		var image = jQuery('#AvatarViewerCurrentImage')[0];
		jQuery(image).load(function(){
			var wh = {width: jQuery(image).width(), height: jQuery(image).height()};
			jQuery(container).css({
				left: (pos_x - wh.width - 20) + 'px',
				top: (pos_y) + 'px',
				paddingTop: '0px',
				paddingBottom: '0px',
				paddingLeft: '0px',
				paddingRight: '0px',
				width: wh.width+'px',
				height: wh.height+'px',
				backgroundColor: 'transparent',
				overflow: 'visible'
			});
		});
		
		jQuery(image).mouseover(AvatarViewer.eventOverAvatar);
		jQuery(image).mouseout(AvatarViewer.eventOutAvatar);
		
		// it should be set only after "onload" event handler!
		image.src = src;
	},
	
	hideAvatar: function() {
		if (jQuery('#AvatarViewerContainer')) {
			jQuery('#AvatarViewerContainer').remove();
		}
	}
};


//
// LoadedGalleryScroller class definition starts here
//
function LoadedGalleryScroller() {
    this.num_images = 3;
    this.total_images = null;
    this.block_width = 270;
    
    this.container = null;
    this.subcontainer = null;
    this.img_container_class = 'featured-photo';
    
    this.loaded_images = {};
    this.current_first_image = 0;
    
    this.output_img_only = false;
}
    
	// Initiation example
	/*
			jQuery(document).ready(function(){
				var PhotoGallery = new LoadedGalleryScroller();
				PhotoGallery.num_images = 4;
				PhotoGallery.block_width = 182;
				PhotoGallery.output_img_only = false; // output in html code image only (if true) or image and additional info (if false)
				PhotoGallery.init(jQuery('#photos')[0], jQuery('#photos-subcontainer')[0], 'featured-photo')
			 });
	*/

    LoadedGalleryScroller.prototype.init = function(wrapper, subwrapper, image_block_class) {
    	this.container = jQuery(wrapper);
    	this.subcontainer = jQuery(subwrapper);
    	this.img_container_class = image_block_class;
    	
    	var gs = this;
    	jQuery('#'+this.container.attr('id')+' .feat-control-next').click(function() {
    	    gs.eventScrollNext();
    	});
    	jQuery('#'+this.container.attr('id')+' .feat-control-prev').click(function() {
    	    gs.eventScrollPrev();
    	});
    	
    	this.importImageDataFromDocument(0);
    	
        this.updateControls();
    };
    
    LoadedGalleryScroller.prototype.eventScrollNext = function(e) {
    	this.scrollNext(this.num_images);
    };
    
    LoadedGalleryScroller.prototype.eventScrollPrev = function(e) {
    	this.scrollPrev(this.num_images);
    };
    
    LoadedGalleryScroller.prototype.scrollNext = function() {
    	var num_slides = arguments && arguments[0] ? arguments[0] : 1;
    	
        // calculate next image key
        var key = this.current_first_image + this.num_images;
        
        // check, if we already loaded it
        //if (typeof this.loaded_images[key] != 'undefined') {
        if (key<this.total_images) {
            var img_to_show = this.loaded_images[key]
        }
        else {
            // need to load
            var img_to_show = {src: false};
        }
        
        if (!img_to_show.src) {
            return false; // can't scroll - it's already the end
        }
        
        var GS = this;
        
        // get first and "new first" image block s
        var el = jQuery('#'+GS.container.attr('id')+' .'+GS.img_container_class+':nth-child('+parseInt(1+GS.current_first_image)+')')[0];
        var el_new_first = jQuery('#'+GS.container.attr('id')+' .'+GS.img_container_class+':nth-child('+parseInt(2+GS.current_first_image)+')')[0];
       
        // get new visible image block
        var el_new_visible = jQuery('#'+GS.container.attr('id')+' .'+GS.img_container_class+':nth-child('+parseInt(1+key)+')')[0];
        jQuery(el_new_visible).removeClass('hidden');
        
        // hide first image and set proper class to new first
        var left_shift = '-' + GS.block_width + 'px';
        jQuery(el).animate({marginLeft: left_shift}, 100, 'linear', function() {
        	jQuery(el).addClass('hidden');
        	jQuery(el).removeClass('first');
        	jQuery(el).css({marginLeft: ''});
        	
        	jQuery(el_new_first).addClass('first');
        	
	        GS.current_first_image++;        
	        GS.updateControls();

		    num_slides--;
		    if (num_slides>0) {
		    	GS.scrollNext(num_slides);
        	}
        });
    };
    
    LoadedGalleryScroller.prototype.scrollPrev = function() {
    	var num_slides = arguments && arguments[0] ? arguments[0] : 1;
    	
        // calculate new image key
        var key = this.current_first_image - 1;
        
        // check, if we already loaded it
        if (typeof this.loaded_images[key] != 'undefined') {
            var img_to_show = this.loaded_images[key]
        }
        else {
            // need to load
            var img_to_show = {src: false};
        }
        
        if (!img_to_show.src) {
            return false; // can't scroll - it's already the end
        }
        
        var GS = this;
        
        // get first and "new first" image block s
        var el = jQuery('#'+GS.container.attr('id')+' .'+GS.img_container_class+':nth-child('+parseInt(1+GS.current_first_image)+')')[0];
        var el_new_first = jQuery('#'+GS.container.attr('id')+' .'+GS.img_container_class+':nth-child('+parseInt(GS.current_first_image)+')')[0];
       
        // get "latest" shown block
        var el_new_hidden = jQuery('#'+GS.container.attr('id')+' .'+GS.img_container_class+':nth-child('+parseInt(1+this.current_first_image+this.num_images)+')')[0];
        
        // show new first block, set proper class to previous first and hide "latest"
        jQuery(el_new_first).addClass('first');
        var left_shift = this.block_width+1;
        left_shift = '-' + left_shift + 'px';
        jQuery(el_new_first).css({marginLeft: left_shift});
        jQuery(el_new_first).removeClass('hidden');
        jQuery(el).removeClass('first');
        
        jQuery(el_new_first).animate({marginLeft: '0px'}, 100, 'linear', function() {
        	jQuery(el_new_first).css({marginLeft: ''});
        	
        	jQuery(el_new_hidden).addClass('hidden');
        	
	        GS.current_first_image--;
	        GS.updateControls();

		    num_slides--;
		    if (num_slides>0) {
		    	GS.scrollPrev(num_slides);
        	}
        });
    };
    
    LoadedGalleryScroller.prototype.addToLoaded = function(key, img_obj) {
        this.loaded_images[key] = img_obj;
    };
    
    LoadedGalleryScroller.prototype.imageBlockToHtml = function(img_obj, is_first, img_only) {
    	if (img_only) {

	        return	'<div class="featured-photo'+(is_first?' first':'')+'"><a href="'+img_obj.url+'" class="zoom-link"><img src="'
	        		+img_obj.src+'" alt="" title="'+img_obj.name+'"></a></div>';

    	}
    	else {
	        return	'<div class="featured-photo'+(is_first?' first':'')+'"><img src="'
	        		+img_obj.src+'" alt="" title="'+img_obj.name+', '+img_obj.age+'"><p class="caption"><a href="'
	        		+img_obj.url+'" class="profile-link">'+img_obj.name+'</a> <span class="age">'
	        		+img_obj.age+'</span></p></div>';
    	}
    };
    
	LoadedGalleryScroller.prototype.importImageDataFromDocument = function(start_key) {
		var k = start_key;
		var gs = this;
		jQuery('#'+this.container.attr('id')+' .'+this.img_container_class+' img').each(function(i, el) {
		    var a = jQuery(el).closest('div').find('a.profile-link')[0];
			if (typeof a == 'undefined' || !a) {
				a = jQuery(el).closest('div').find('a.zoom-link')[0];
				var name = jQuery(a).attr('title');
			}
			else {
				var name = (a) ? a.innerHTML : '';
			}
			var url = (a) ? a.href : '';
			var span = jQuery(el).closest('div').find('span.age')[0];
			var age = (span) ? span.innerHTML : '';
			gs.addToLoaded(k, {src: el.src, name: name, age: age, url: url});
			k++;
		});
		
		this.total_images = k;
	};
    
    LoadedGalleryScroller.prototype.lastShownImageSrc = function() {
    	return this.loaded_images[this.current_first_image+this.num_images-1].src;
    };

    LoadedGalleryScroller.prototype.firstShownImageSrc = function() {
    	return this.loaded_images[this.current_first_image].src;
    };
    
    LoadedGalleryScroller.prototype.updateControls = function() {
    	var gs = this;
    	var key = this.current_first_image + this.num_images;
    	if (gs.total_images>key) {
    	    jQuery('#'+this.container.attr('id')+' .feat-control-next.inactive').removeClass('inactive');
    	}
    	else {
    	    jQuery('#'+this.container.attr('id')+' .feat-control-next').toggleClass('inactive', true);
    	}
    	
    	key = this.current_first_image - 1;
    	if (typeof gs.loaded_images[key] != 'undefined' && gs.loaded_images[key].src) {
    	    jQuery('#'+this.container.attr('id')+' .feat-control-prev.inactive').removeClass('inactive');
    	}
    	else {
    	    jQuery('#'+this.container.attr('id')+' .feat-control-prev').toggleClass('inactive', true);
    	}
    };
//
// LoadedGalleryScroller class definition ends here
//

var CollapsingBlocks = {
	preload_container: null,
   
	init: function() {
	    // Hide collapsed blocks and drop 'collapsed' class for them - we'll be checking state through collapser's (control) class
		jQuery('.collapser.collapsed[controls]').each(function() {
			var block = jQuery('#'+jQuery(this).attr('controls')).hide().removeClass('collapsed');
		});
		
		jQuery('.collapser[controls]').each(function() {
		    if (!jQuery(this).hasClass('collapsed')) {
				var block = jQuery('#'+jQuery(this).attr('controls')).removeClass('collapsed').show();
			}
		});
		
		// set 'click' event listeners
		jQuery('.collapser[controls]').click(function() {
		    CollapsingBlocks.eventClick(jQuery(this));
		});
	},
	
	eventClick: function(el) {
	    if (el.hasClass('collapsed')) {
	        CollapsingBlocks.show(el);
	    }
	    else {
	        CollapsingBlocks.hide(el);
	    }
	},
	
	hide: function(collapser) {
	    if (!collapser.hasClass('collapsed')) {
	        jQuery('#'+collapser.attr('controls')).slideUp('normal', function() {
	        	collapser.addClass('collapsed').html( collapser.html().replace('Hide', 'Show').replace('hide', 'show') );
	        });
	        
	    }
	},
	
	show: function(collapser) {
	    if (collapser.hasClass('collapsed')) {
	        jQuery('#'+collapser.attr('controls')).slideDown('normal', function() {
		        collapser.removeClass('collapsed').html( collapser.html().replace('Show', 'Hide').replace('show', 'hide') );
	        });
	    }
	}
};


//
// Init scripts on document load
//
//
jQuery(document).ready(function(){
	if (jQuery('#photos')[0]) {
		var PhotoGallery = new LoadedGalleryScroller();		
		PhotoGallery.block_width = 270;
		PhotoGallery.init(jQuery('#photos')[0], jQuery('#photos-subcontainer')[0], 'featured-photo');
	}
	
	if (jQuery('#featured')[0]) {
		var Featured = new LoadedGalleryScroller();		
		Featured.num_images = 4;
		Featured.block_width = 182;
		Featured.init(jQuery('#featured')[0], jQuery('#featured-subcontainer')[0], 'featured-photo');
	}
	
	jQuery("a.zoom-link").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': false, 'centerOnScroll': false, 'imageScale': false }); 
	
	CollapsingBlocks.init();
	AvatarViewer.init();
});

function mailAddressIsValid(mailAddress)
{
	re_email = new RegExp("^[0-9a-z]{1}([-_.]?[0-9a-z]{1})*[@]{1}[0-9a-z]{1}([-.]?[0-9a-z]{1})*[.]{1}[a-z]{2,4}$","ig");
	if (re_email.test(mailAddress))
		return true;
	else
		return false;
}

function fnCheckJoinForm()
{

try
{
	re = /[ ]+$/g;
	re1 = /^[ ]+/g;

	temp = document.forms["form1"].elements["NickName"].value;
	temp = temp.replace(re,"").replace(re1,"");
	document.forms["form1"].elements["NickName"].value = temp;
		
	temp = document.forms["form1"].elements["RealName"].value;
	temp = temp.replace(re,"").replace(re1,"");
	document.forms["form1"].elements["RealName"].value = temp;
		
	temp = document.forms["form1"].elements["Email1"].value;
	temp = temp.replace(re,"").replace(re1,"");
	document.forms["form1"].elements["Email1"].value = temp;
		
	temp = document.forms["form1"].elements["Password1"].value;
	temp = temp.replace(re,"").replace(re1,"");
	document.forms["form1"].elements["Password1"].value = temp;

	temp = document.forms["form1"].elements["Password2"].value;
	temp = temp.replace(re,"").replace(re1,"");
	document.forms["form1"].elements["Password2"].value = temp;
	
	temp = document.forms["form1"].elements["securityImageValue"].value;
	temp = temp.replace(re,"").replace(re1,"");
	document.forms["form1"].elements["securityImageValue"].value = temp;
		
	var str_alert = "";
		
	if (document.forms["form1"].elements["NickName"].value == "")
		str_alert += "- Please enter your Nickname. Nickname must be from 2 to 20 characters long\n";
	else if (document.forms["form1"].elements["NickName"].value.length < 2 || document.forms["form1"].elements["NickName"].value.length > 20)
		str_alert += "- Nickname must be from 2 to 20 characters long\n";

	if (document.forms["form1"].elements["RealName"].value == "")
		str_alert += "- Please enter your First name\n";

	var iYear = parseInt(document.forms["form1"].elements["YearOfBirth"].value);
	var iMonth = parseInt(document.forms["form1"].elements["MonthOfBirth"].value);
	var iDay = parseInt(document.forms["form1"].elements["DayOfBirth"].value);
	
	if(!(iYear && iMonth && iDay))
	{
		str_alert += "- The Date of birth your entered is invalid. Please enter correct date\n";
	}
	else
	{
		var d = new Date(iYear, iMonth - 1, iDay);

		if(!(d.getFullYear() == iYear && d.getMonth() + 1 == iMonth && d.getDate() == iDay))
		{
			str_alert += "- The Date of birth your entered is invalid. Please enter correct date\n";			
		}
	}	

	if (document.forms["form1"].elements["Country"].value == "")
		str_alert += "- Please select your Country\n";

	if (document.forms["form1"].elements["Email1"].value == "")
		 str_alert += "- Please enter your Email\n";
	else if (!mailAddressIsValid(document.forms["form1"].elements["Email1"].value))
		str_alert += "- Email address format is invalid. Please enter correct email\n";

	if (document.forms["form1"].elements["Password1"].value == "") 
		str_alert += "- Please enter Password. Password must be from 4 to 20 characters long\n";
	else if(document.forms["form1"].elements["Password1"].value.length < 4 || document.forms["form1"].elements["Password1"].value.length > 20)
		str_alert += "- Password must be from 4 to 20 characters long\n";

	if (document.forms["form1"].elements["Password2"].value == "") 
		str_alert += "- Please confirm your password\n";
	else if(document.forms["form1"].elements["Password1"].value != document.forms["form1"].elements["Password2"].value)
		str_alert += "- Passwords did not match\n";
		
	if (document.forms["form1"].elements["securityImageValue"].value == "")
		str_alert += "- Please enter code from security image\n";

	if(!document.forms["form1"].elements["i_agree"].checked)
	{
		str_alert += "- Please read \"Terms of Use\" before joining\n";
	}
		
	if (!str_alert)
	{	
		return true;
	}
	else
	{
		str_alert = "Please correct the following:\n" + str_alert;
		alert(str_alert);
		return false;	
	}
}
catch (e)
{
//alert(e.message);
;
}

}

function gebi(gid) { return document.getElementById(gid); }

/**
 * insert emotion item
 */
function emoticon( txtarea, text ) {

	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

