/* detect IE and IE6 */	   
var isIE=(navigator.userAgent.indexOf("IE")>-1)?true:false;
var isIE6=(navigator.userAgent.indexOf("IE 7")==-1 && navigator.userAgent.indexOf("IE 8")==-1 && navigator.userAgent.indexOf("IE 6")>-1)?true:false;
var isFF2=(navigator.userAgent.indexOf("Firefox/2")>-1)?true:false;
var isOpera=(navigator.userAgent.indexOf('Opera') >-1)?true:false;
var isFF30=(navigator.userAgent.indexOf("Firefox/3.0")>-1)?true:false;
var tb_pathToImage = /*webPath+*/"/js/thickbox/preloader.gif";
var jsBreakWord = isOpera||isFF30;

$(document).ready(function(){
	if (isIE6) {
		$('img[@src$=.png]:not(.nofix), input[@src$=.png]:not(.nofix), .png_bg').ifixpng();
	}
	if (jsBreakWord){
		fnBreakWordAll({word:1,re:'[\\w]'});
	}
	// adding min, max & close buttons to the panels
	var titleOperation = '<p class="buttons"><a href="#" class="restore" style="display:none;">'+common_restorepanelsview+'</a><a href="#" class="btn_min" title="'+common_minimize+'"></a><a href="#" class="btn_max" title="Maximize"></a><a href="#" class="btn_close" title="'+common_close+'"></a></p>';
	$(".rounded[id!='compose'] h1").each(function(){
		var elem = $(this);
		// Skip the element if it contains a class named no_operation
		if(!elem.hasClass('no_operation')){
			elem.prepend(titleOperation);
			if (elem.parents(".rounded").attr("id")=='blog'){
				elem.find("p.buttons").after('<a href="'+webPath+'/blog/createBlog?flag=home" class="bold float_right padding_right_10" style="font-size:1ex;text-decoration:none">Post blog</a>');
			}
		}
	});
	if ($('.mailBox')){
		//$('.mailBox li').prepend('<p class="buttons"><a href="#TB_inline?&width=300&height=120&inlineId=confirmDialog" class="thickbox btn_del" title="'+common_delete+'" onclick="setWhatToDel_mail(this);">'+common_delete+'</a></p>');
		try {
			tb_init('a.thickbox');
		}
		catch(err) { }
	}

	if (isIE || jQuery.browser.opera || isFF2) { 
		$("div#wrap").nifty("transparent top");
		$('.rounded h1').nifty("transparent top");
		// display: inline-block fix for IE8
		$('.rounded h1').each(function(){
			elem=$(this);
			if (isIE && elem.css('display')=='inline-block'){
				elem.css('display','block');
			}
		});
		if ($("#addComment").length>0) 
			$("#addComment").nifty();
	}
	
	// double clicking title area causes max or min effect
	$('.rounded h1').dblclick(function(){
		$(this).find(".buttons").find(".btn_max").click();
	});
		
	// clearfix
	if ($('.websites').length > 0){
		$('.websites>div').addClass('clearfix');
	} 
	if ($('.webshots').length > 0){
		$('.webshots dt').addClass('clearfix');
	}

//newsfeed and website_entry
	if ($(".website_entry, .newsfeedcontent").length > 0){
		initLikeControls('.website_entry, .newsfeedcontent');
		//var w=$('.user_review_entry').width();
		//$('.user_review_entry').css({'width':w+'px','overflow-x':'auto'});
	}
	
	// inits
	if ($("#profile_homepage").length > 0){
		initCookieState();			// arrange the panels before setting the
									// sortables, in other case panels wouldn't
									// be draggable
		initSortables();			// sortables
		initHomeAjaxActions();
		// toMaximize
	}
	if ($("#websites").size() > 0){	// simple websites list pagination
		var page=$_GET("page");
		page=(page=="")?1:page;
		var count=10;
		var currentPage=location.href;
		if (currentPage.indexOf("page=")==-1){
			if (currentPage.indexOf("?")==-1)
				currentPage+="?page=1&count="+count;
			else
				currentPage+="&page=1&count="+count;
		}
		var prevPage=(page>1)?currentPage.replace(/page=\d+/,'page='+(parseInt(page)-1)):"";
		if (page==1){
			$('.arr_left').parent().html('<span class="arr_left"></span>');
		}
		else{
			$('.arr_left').attr('href',prevPage);
		}
		var nextPage=currentPage.replace(/page=\d+/,'page='+(parseInt(page)+1));
		$('.arr_right').attr('href',nextPage);
		/*
		 * if (page==5){ $('.arr_right').parent().html('<span
		 * class="arr_right"></span>'); } else{
		 * $('.arr_right').attr('href',nextPage); }
		 */
	}
	if ($("#website_reviews_page").size() > 0){

		var paramVal =  $_GET('urlId');
		if (paramVal){
			initReviewsAjaxActions('urlId', paramVal);
		} else {
			initReviewsAjaxActions('url', $_GET('url'));
		}
		//$('#addComment').hide();
		//initPopularTags();
		$.ajax({	// refresh status of like/dislike icons
				url: webPath + "/ratingInfo",
				type: "GET",
				beforeSend: function(xhr){
					xhr.setRequestHeader('Location', locationURL);
				},
				error: function(){
				},
				success: websitereviewsrefreshStatus	
		});
		
		$("#btnLiked").click(function(e){	/* add/edit review form submit */
				addCommentOnClick("like");
				return false;
		});	
		$("#btnDisliked").click(function(){
				addCommentOnClick("dislike");
				return false;
		});
		
		// $('.vote').bind("click",rateLiked);
		// $('.votebad').bind("click",rateDisliked);
		$('#add_tags').Autocomplete({
				mode: 'local',
				source: webPath+'/search/searchTag',
				delay: 500,
				helperClass: 'autocompleter website_autocompleter',
				selectClass: 'selectAutocompleter',
				multiple: true,
				multipleSeparator: ' ',
				pageSize: 10
			}
		);
	$('#add_tags').start();
	// end website reviews init
	}
	if ($("#personal_information").size() > 0){
		initDateSelects();
		var ratedG=$("label[for='myContentRatingGENERAL']");
		ratedG.html("<img src='"+webPattern+"/images/ico_rating_g.png' /> "+ratedG.html());
		var ratedR=$("label[for='myContentRatingRESTRICTED']");
		ratedR.html("<img id='ico_rating_r' src='"+webPattern+"/images/ico_rating_r.png' /> "+ratedR.html());
		var ratedX=$("label[for='myContentRatingXXX']");
		ratedX.html("<img id='ico_rating_x' src='"+webPattern+"/images/ico_rating_x.png' /> "+ratedX.html());
		$("label[for='myContentRatingGENERAL'] span, label[for='myContentRatingRESTRICTED'] span, label[for='myContentRatingXXX'] span").css({position:"relative", top:"-5px"});
	}
	
	if ($("#thisBlogContent").size() > 0){	// blog entry page
		$('#maincontent').removeClass('with_tags');
		columnsWidth();
		$("#thisBlogContent").load(webPath+'/blog/blogText?blogID='+blogId);	// variable
																				// blogId
																				// is
																				// defined
																				// in
																				// blog.jsp
	}
	if ($("#people").size() > 0){	// people pages - submenu links observers
		$('a#addToFriends').click(function(){
			$('#addFriendForm').get(0).submit(); 
			showMessage(common_sentfriendto+userName+'.'); 
			return false;
		});
		$('a#sendMessage').click(function(){
			$("#forwardUrl").val(location.href);
			$('#sendMessageForm').get(0).submit();
			return false;
		});
		initPeopleSearch();
	}
	initTooltips();	// tooltips

  	// scrolbars
  	var scrollbars = $(".scrollable");
	if (scrollbars.length > 0) {
		scrollbars.each(function(){
			var elem = $(this);
			elem.height(elem.children("div").eq(0).height());	
			elem.css('overflow-y','scroll');	
			elem.children("div:last").css({borderBottom: "none", marginBottom:"0em"});  // removes
																						// borderBottom
																						// in
																						// the
																						// last
																						// entry
																						// of
																						// scrollable
																						// divs
		});
		// setScroll();
		// scrollbars.jScrollPane({showArrows:true, scrollbarWidth: 17});
	}
	if ($('#left_column').length>0 && $('#right_column').length>0){
		columnsWidth();
		updateColumnHeight(); 
	}
	if ($('#submenu').children().length > 0){
		if ($('#profile_homepage').length==0)
			$('#right_column').css("paddingTop", "1em");
	}
	// selectboxes replacement
	if ($("select").length > 0) {
		if ($('#personal_information').length==0){	// not personal information
													// page
			$("select").each(function(){
				if (!$(this).hasClass("originalStyle"))
					$(this).selectbox();	
			});
		}
		else	
			$('#search_area').selectbox();
	}
	// file inputs
	if (!isIE){
		if ($("input[type=file]").length > 0) {
			//$("input[type=file]").filestyle({ image: webPattern+"/images/forms_btn_file.png", imageheight : 20, imagewidth : 83, width : 200});
		}
	}	// decorating text inputs
	$("input[type='text'], input[type='password'], input.file").addClass('bg');
	$("input[type='text'], textarea, input.file").addClass('border');
	if (!isIE6){
	$("input[type='text'], input[type='password'], input.file").bind("focus",function(){
			$(this).css("backgroundImage","url("+webPattern+"/images/forms_input_bg_focus.png)"); 
	    }).bind("blur",function(){
			$(this).css("backgroundImage","url("+webPattern+"/images/forms_input_bg.jpg)"); 
	    });
	$("textarea").bind("focus",function(){
			$(this).css("backgroundImage","url("+webPattern+"/images/forms_textarea_bg_focus.png)"); 
	    }).bind("blur",function(){
			$(this).css("backgroundImage","url("+webPattern+"/images/forms_textarea_bg.png)"); 
	    });
	}
	else{
		$("input[type='text'], input[type='password'], input.file").bind("focus",function(){
			$(this).get(0).focus();
	    });
	}
	
	// scaling tags
	if ($('ul.tags a').length>0){
		$('ul.tags a').each(function(){
			var params = $(this).attr('rel').split(/;/);
			var size = scaleTags( parseInt(params[0]), parseInt(params[1]), parseInt(params[2]));
			$(this).css('fontSize', size+'%');
		}); 
	}
	
	
    // observers
	$(window).bind("resize", function(){
		if ($('#left_column').length>0 && $('#right_column').length>0){
			setTimeout(function(){
				columnsWidth();
				updateColumnHeight(); 
			},700);
		}
	});
	// buttons min, max, close
	$(".buttons a:not(.btn_del)").bind("click", function(e){
		$(this).attr("href","javascript:void(0)");
	});
	$(".btn_min").bind("click", function(e){
		doMinimize.apply(this);
	});
	$(".btn_max, .restore").bind("click", function(e){
		var minBtn=$(this).siblings(".btn_min");	// if we maximize minimized
													// panel - delete minimized
													// effect
		if (minBtn.hasClass("btn_min_active")){
			doMinimize.apply(minBtn);
			$(this).parents(".rounded").children("div").css("height","auto");
		}
		if (isMaximum()){	 // collapse
			$(this).parents(".rounded").removeClass("maxWindow");
			doRestore.apply(this);
		}
		else{			// expand
			$(this).parents(".rounded").addClass("maxWindow");
			doMaximize.apply(this);
		}
	});
	var doMinimize = function(ID){
		minimizingPanel($(this));
	};
	var doRestore = function(hideID){
		$(".fieldhidden").hide();
		var elem = $(this);
		elem.parents(".rounded").remove();
		$(".restore").hide();
		$("buttons a.restore").hide();	// "Restore panels view" is hidden
		$('.div_underline').css('border-bottom', 'none');
		$('.div_underline').css('padding-bottom', 'none');
		$('#left_column').show();
		$('#right_column').show();
		initSortables();
		updateColumnHeight();
		// add temp id
		$('#maincontent').find('.rounded').each(function(){
			$(this).attr("id",$(this).attr("id").replace("_temp",""));	// add
																		// "_temp"
																		// to
																		// the
																		// id of
																		// rounded
			$(this).children().each(function(){	// do such things with children
												// if their ids contain "_temp"
				var tempid=$(this).attr("id");
				if (tempid.indexOf("_temp")>0){
					$(this).attr("id",tempid.replace("_temp",""));
				}
			});
			// append simple paginator
			if ($(this).attr("id")=="liked") 
				$(this).find("#pageliked").append("<div id='paginator'></div>");
			if ($(this).attr("id")=="recommended") 
				$(this).find("#recommendURL").append("<div id='paginator_recommend'></div>");
		});
		// redraw simple paginator
		pageNumber=pageNumber || 1;
		recordTotal=recordTotal || 10;
		drawSimplePaginator("pageliked","paginator",webPath+"/like/liked",pageNumber,recordTotal);
/* ! */		drawSimplePaginator("recommendURL","paginator_recommend",webPath+"/home/showRecommend",1,10);
	};
	
	
	var doMaximize = function(displayID){
		$(".fieldhidden").show();
		var elem = $(this);
		var parentRound=elem.parents(".rounded");
		reComputeHeight('#maincontent');
		$('.div_underline').css('border-bottom', '1px solid #CFD8D4');
		$('.div_underline').css('padding-bottom', '10px');
		$('#left_column').hide();
		$('#right_column').hide(); 
		$(".restore").show();  // "Restore panels view" is visible
		elem.attr("title",common_restorepanelsview);
		$('div.column').each(function(){	// disable sortables functionality
											// in maximized state
			$(this).SortableDestroy();
		});
		// add temp id to the original panel and its children
		parentRound.attr("id",parentRound.attr("id")+"_temp");
		var idArr=["pageliked","pagedisliked","recommendURL","blogContent","user_friend"];	// the
																							// ids
																							// of
																							// elements
																							// need
																							// to
																							// be
																							// javascripted
																							// after
																							// maximizing
		var idFound="";	// found in children id which value corresponds the
						// array (+"_temp")
		parentRound.children().each(function(){
			if ($(this).attr("id")+""!="undefined" && $(this).attr("id")+""!=""){
				for (var i=0; i<idArr.length; i++){
					if ($(this).attr("id")==idArr[i]){
						idFound=idArr[i]+"_temp";
						$(this).attr("id",idFound);
						break;
					}
				}
			}
		});
		parentRound.clone(true).insertBefore("#left_column"); 
		$('#maincontent>.rounded .btn_max').toggleClass("btn_max_active");
		$('#maincontent>.rounded h1').css('cursor','default');
		// remove temp id in maximized panel and its children
		var maximizedRounded=$('#maincontent>.rounded');
		maximizedRounded.attr("id", maximizedRounded.attr("id").replace("_temp",""));
		if (idFound){
			maximizedRounded.children("#"+idFound).attr("id", idFound.replace("_temp",""));
		}
		maximizedRounded.children("div").show();
		// needs appending some extra content, after insertBefore
		if (maximizedRounded.attr("id")=="liked"){ 
			initMaxLikedUrlPanel(1,10);
		}
		if (maximizedRounded.attr("id")=="disliked"){ 
			maximizedRounded.show();
			initMaxDislikedUrlPanel(1,10);
		}
		if (maximizedRounded.attr("id")=="recommended") 
			ajaxUrl(webPath+"/home/showRecommend?firstRowsCount=10","recommendURL","paginator_recommend",false,function(){
				$("#recommendURL").children("div[class!='pagination']").addClass("div_list");
				$('#recommendURL').append('<p class="clearfix"></p>');
				$('#recommendURL').parents(".rounded").css({background:'none', border:'none'});
				//fixEntriesHeight();
				if (isIE)	$('#recommendURL').css('height','auto');
				//initReportHandlers(maximizedRounded);
				initReportHandlers($(".btn_report"));
			});
		if (maximizedRounded.attr("id")=="blog"){	
			$('#blogContent>div').css({borderBottom:'1px solid #CFD8D4', paddingBottom:'10px'});
			$('#blogContent').append('<div class="clearfix"></div>');
		}
		
		
	};
	var isMaximum = function(){
		if ($("#likedpaginator").length>0){
			$("#likedpaginator").hide();
		}
		if ($('#left_column').css("display") == "none" && $('#right_column').css("display") == "none"){
			return true;
		}	
		return false;
	};
	
	$(".btn_close").bind("click", function(e){
		var thisParent = $(this).parents(".rounded");
		if (!isMaximum()){
			thisParent.animate({ opacity: "hide" }, "normal");
			thisParent.remove();	// remove the whole panel to make the cookie
									// (panels' order) correct
		}
		else{			   // if we close the maximized panel - we should
							// remove it and open all others
			var id = thisParent.attr("id");	
			thisParent.remove();
			$(".buttons a.restore").hide();	// "Restore panels view" is hidden
			$('#left_column').show();
			$('#right_column').show();
			$('#' + id).hide();
		}
		updateCookieState();
	});	

// trigger max click if max is in location
	if ($('#profile_homepage').length>0){
		var toMaximize=$_GET("max");
		if (toMaximize!=""){
			var objToMax=$('#maincontent').find('#'+toMaximize);
			if (objToMax && objToMax.hasClass('rounded')) {
				var maxBtn = objToMax.children('h1').children('.buttons').children('.btn_max');
				maxBtn.triggerHandler("click");
			}
		}
	}
	// report buttons
	if ($('#website_reviews_page').length==0 && $('#homepage').length==0){	// not
																			// website
																			// reviews
																			// and
																			// home
																			// page
		initReportHandlers($('.websites'),true);
	}
	$('#panelsDefault').click(function(){
		$.cookie('leftColumn',null);
		$.cookie('rightColumn',null);
		initCookieState();
		location.reload();
	});
	
	// rollover effect in service links
	$('.services a').hover(
			function(){
				var str="";
				var id=$(this).attr("id")+"";
				if (id=="service_opt" || id=="service_inbox" || id=="service_logout" || id=="service_help" || id=="service_login" || id=="service_signup" || id=="service_bookmark"){
					switch(id){
						case "service_opt":	str=common_options; break;
						case "service_inbox":	str=$('#inbox_src').html(); break;
						case "service_logout":	str=common_logout; break;
						case "service_help":	str=common_help; break;
						case "service_login":	str=common_login; break;
						case "service_signup":	str=common_signupm; break;
						case "service_bookmark":	str=common_addbookmark; break;
					}
					$('#services_tooltip').html(str);
					// $('#services_tooltip').animate({width: "140px",minWidth:
					// "140px"}, 300);
				}
			},
			function(){
				var id=$(this).attr("id")+"";
				if (id=="service_opt" || id=="service_inbox" || id=="service_logout" || id=="service_help" || id=="service_login" || id=="service_signup" || id=="service_bookmark"){
				if (unreadWarning)	
					$('#services_tooltip').html("<span style='color:#bd1700'>"+common_unreadmessages+"</a>");
				else
					$('#services_tooltip').html('');
					// $('#services_tooltip').animate({width: "0px",minWidth:
					// "0px" }, 300);
				}
			}
	);
	
	// delete message
	// button Yes in the delete confirm form should delete message by id.
	// message id is in its href - it was added by setWhatToDel()
	$('#msgIdContainer').click(function(){	
		var msgId=$(this).attr('href').substring(1);
		if (msgId.length>0)
			location.href=webPath+'/mail/deleteMessage?messageID='+msgId;
	});
	
	
	$('.reply').bind("click", function(e){		// report submenu
		$(this).next(".editor").toggle();
	});
	
	// search button rollover - input image
	$('.search_btn,#search_btn').hover(	
		function(){
			var obj=($(this).get(0).tagName.toLowerCase()=="a")?$(this).children("img"):$(this); 
			// detect if it's link or input image
			var oldsrc=obj.attr('src');
			obj.attr('src',oldsrc.replace('forms_btn_search.png','forms_btn_search_over.png'));
		},
		function(){
			var obj=($(this).get(0).tagName.toLowerCase()=="a")?$(this).children("img"):$(this); 
			// detect if it's link or input image
			var oldsrc=obj.attr('src');
			obj.attr('src',oldsrc.replace('forms_btn_search_over.png','forms_btn_search.png'));
		}
	);
	$('#search_btn').bind("click",searchHopsurf);
	$('#search_query').bind("keypress",function(evt){
		var keyCode = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode :	evt.which ? evt.which : void 0;
		if (keyCode==13){
			var autocompleterEl=$('#autocompleteHelper_search_query');
			if (autocompleterEl.length==0 || (autocompleterEl.length>0 && autocompleterEl.css('display')!='block'))
				searchHopsurf();
		}
	});
	
	// advanced friends search
	$('#adv_search_link').bind('click',function(){	
		if ($('#adv_search').css('display')=='none'){
			$('#adv_search_link').html(common_hideadvancedsearch);
		}else{
			$('#adv_search_link').html(common_advancedsearch);
		}
		$('#adv_search').slideToggle("normal");
	});
	
	// add review in website reviews page
	$('#showAddComment, #editReview').click(function(){
		$('#addComment').slideDown();
		$('#addComment .jquery-custom-selectboxes-replaced').css('width','125px');
		$('#addComment .jquery-selectbox-list').css('width','125px');
		if ($(this).attr("id")+""=="showAddComment"){
			$(this).remove();
			$('#addComment h2').html(common_addreview);
			$('#addComment textarea').val("");
			$('#addComment #add_tags').val("");
		}
		else {	// editReview
			$('#userReview').hide();
			// $('#addComment
			// textarea').val($.trim($('#userReviewText').text()).replace(/\s+/g,"
			// "));
			$('#addComment #add_tags').val($('#userReview .tags span').text());
			$('#addComment h2').html(common_editreview);
			// init user tags to input field
			var str="";
			$('#userReview span.tags a').each(function(){
				str+=" "+$.trim($(this).text());
			});
			if (str!="") 
				$('#add_tags').val($('#add_tags').val()+str);
		}
		return false;
	});
	
	
// $("#addComment input[type='image']").click(function(){
// showMessage(common_websitesaved);
// });
	
	// Liked/Disliked links in homepage
	$('.likelink').bind('click', function(e){
		if($('.pageliked').length == 0){
			$('.likelink').css('textDecoration','none');
			$('.dislikelink').css('textDecoration','underline');
			$('.pagedisliked').remove();
			$('.liked').append($().data('#pageliked'));
		}
	});
	$('.dislikelink').bind('click', function(e){
		if($('.pagedisliked').length == 0){
			$('.likelink').css('textDecoration','underline');
			$('.dislikelink').css('textDecoration','none');
			$('.pageliked').remove();
			var pageDisLike = $().data('#pagedisliked');
			pageDisLike.show();
			$('.liked').append(pageDisLike);
		}
	});
	
	// Thickbox window closing
	$('.close_window').bind("click",function(){
		if (top!=self){
			if (top.tb_pathToImage && top.tb_pathToImage!='undefined') 
				top.tb_remove();
		}
	});
	
	if ($("#tagcodecloud").size() > 0) {
		tagCodeInit();
		$('#tagcodecloud a').click(function(){
			toggleTag(this);
			return false;
		});
	}
	
	if ($("#service_logout").size() > 0){
		$("#service_logout").dblclick(function(){
			$(this).trigger("click");
			return false;
		}).click(function(){
			//$(this).attr('href',null);
			//$(this).unbind();
		});
	}
});


// Thickbox position override for IE7
if (top.tb_pathToImage && top.tb_pathToImage!='undefined'){
	if (isIE || $.browser.opera || $.browser.safari){
		function tb_position() {
				var w0,h0;
				if ($.browser.opera || $.browser.safari) {w0=window.innerWidth; h0=window.innerHeight;}
				if (isIE){w0=document.documentElement.clientWidth; h0=document.documentElement.clientHeight;}
				var y=0.5*(h0-TB_HEIGHT);
				var x=0.5*(w0-TB_WIDTH);
				if (!isIE6)
					$("#TB_window").css({position: "absolute", left: x+"px", top: y+"px", margin: "0px"});
				else
					$("#TB_window").css({position: "absolute", left: x+"px", margin: "0px"});
		}
	}
}
	
/* init Sortables */
function initSortables(){
	$('div.column').each(function(){
		var elem = $(this);
		activateSortable(elem);
	});
}
function activateSortable(el){
	el.Sortable({	// columns - containers of draggable objects
			accept: 'rounded',	 // the draggable objects
			helperclass: 'activeBorder',	// sortHelper - the class of target
											// frame
			activeclass : 	'sortableactive', // all except draggable while
												// dragging
			hoverclass : 	'sortablehover',  // all the column on hover while
												// dragging
			handle: 'h1',	// what we're dragging
			tolerance: 'pointer',
			onChange : function(ser){
				// serialize(ser);
			},
			onStart : function(){
				$.iAutoscroller.start(el, $('body'));
			},
			onStop : function(){
				$.iAutoscroller.stop();
				updateCookieState();
				updateColumnHeight();
				if (isIE){	// fix ie7 bug
					$('div.column').each(function(){	// disable sortables
														// functionality in
														// maximized state
						$(this).SortableDestroy();
					});
					initSortables();
				}
			}
		});
}
/* columns width correction for low resolutions */
function columnsWidth(){ 
	if ($('#left_column') && $('#right_column')){
		var left = "48%";
		var right = '50%';
		if (document.body.clientWidth <= 760){
			$('#left_column').css({'float': "none", 'width': "100%"});
			$('#right_column').css({marginLeft: "0px"});	
		}
		else{
			if ($(".with_tags").length > 0){
				left = right = "75%";
			}
			$('#left_column').css({'float': "left", 'width': left});
			$('#right_column').css({marginLeft: right});
		}
	}
	if ($("#search")){
		if (document.body.clientWidth <= 760){	 // or some else
			 // move search
			 $("#search").hide();
		}
		else{
			$("#search").show();
		}				  
	}
	setTimeout(function(){setScroll();  },500);	 
}  

/* update maincontent height on window resize */
function updateColumnHeight(){
	if ($("#maincontent")){
		var h = 0;											  
		var hmin = 500;
		// if left_column and right_column height is less than 500px, we set a
		// default height to them.
		var h1 = $('#left_column').height();
		var h2 = $('#right_column').height();
		if ($('#right_column').css("marginLeft") =="0px") { // right column is under left
			//h = h1 + h2 + 20;
			$("#maincontent").height("auto"); 
		}
		else {
			h = h1 > h2 ? (h1 > hmin ? h1 : hmin) : (h2 > hmin ? h2 :hmin);	// max height
			h += Math.max((parseInt($('#right_column').css('marginTop')) + parseInt($('#right_column').css('paddingTop'))), (parseInt($('#left_column').css('marginTop')) + parseInt($('#left_column').css('paddingTop'))));
			h += 80;// $('#footer).height()+10;
			if (jQuery.browser.opera || (isIE && !isIE6)) h += 20;  /* fix wrong height in  opera and ie7  */		
			$("#maincontent").height(h); 
		}
	}
} 
/* correcting panels height after ajax content loading */
function panelsHeight(selector){
	setTimeout(function(){
		var dh=(selector.find('.arr_div').length>0)?20:0;	// if it has
															// paginator its
															// height needs to
															// be 20px more
		if ($.browser.opera) {
			dh+=10;
		}
		var h=selector.find('.screenshot').height()+dh;
		if (h>0){
			selector.css('minHeight',h + 'px');
			if (isIE){
				if (dh==0)
					selector.css('height','auto');
				else
					selector.css('height',h + 'px');
			}
		}
	},600);
}
/* fixes entries' height after panel maximizing */
function fixEntriesHeight(){
	$('#maincontent>.rounded div:first').children("div").each(function(i){
		//panelsHeight($(this));
		$(this).append("<p class='clearfix'>&nbsp;</p>");
	});
}

/* Parse location string */
function $_GET(key){
    var hash=getURLdata();
    var value="";
    if (hash){
        for (var i=0; i<hash.length; i++){
            if (hash[i][0]==key){
                value=hash[i][1];
                break;
            }
        }         
    }
    return value;
}
function getURLdata(){
    if (location.search.length>1){
        var get_params=location.search.substring(1);
        var get_params_arr=get_params.split("&");
        var get_hash=[];
        for (var i=0; i<get_params_arr.length; i++){
            get_hash[i]=new Array();
            get_hash[i][0]=get_params_arr[i].split("=")[0];
            get_hash[i][1]=get_params_arr[i].split("=")[1];
        }
        return get_hash;
    }                    
    return null;
}

function initTooltips(){
	if($('.with_tooltip').length > 0){
		$('.with_tooltip').ToolTip({
			className: 'tooltip',
			position: 'mouse',
			delay: 0
		});
	}
	if($('.with_tooltip_left').length > 0){
		$('.with_tooltip_left').ToolTip({
			className: 'tooltip',
			position: 'left',
			delay: 200
		});
	}
}

/* applies scrollbar to elements .scrollable */
function setScroll(){
	/*
	 * $('.scrollable').each(function(){ var elem = $(this);
	 * elem.height(elem.children("div").eq(0).height());
	 * elem.width(elem.parent(".rounded").children("h1").width()); //
	 * console.log("h1 "+i+" //
	 * "+$(this).parent(".rounded").children("h1").width()); if
	 * (elem.parent(".jScrollPaneContainer").length>0)
	 * elem.parent(".jScrollPaneContainer").width(elem.parent(".rounded").children("h1").width());
	 * });
	 */					   
}

/* Scale tag size */
function scaleTags(count, minTagCount, maxTagCount){
	part = count / maxTagCount - minTagCount / maxTagCount;
	// Exponential scaling
	// See: http://en.wikipedia.org/wiki/Exponential_distribution
	var scaleFunc = function(x) { 
		var lambda = 2.5;
		return (1-Math.exp(-lambda*x));
	};
	var minFont=0.8;
	var maxFont=2.4;
	var size = ( scaleFunc(part) * (maxFont-minFont)+minFont) * 100; 
	if (!isNaN(size)) 
		return size;
	else 
		return null;
}

function reComputeHeight(id){
	$(".fieldhidden").show();
	$(id).css('height', '');
}

function addEvent(element, type, func){
	if(element.addEventListener){
		element.addEventListener(type, func, false);
	}else{
		element.attachEvent('on' + type, func);
	}
}

/* search functionality */
function searchHopsurf(){
	var action = {
		tags: webPath + '/search/tags?search=',
		keywords: webPath + '/search/keyword?search=',
		liked: webPath + '/search/likes?search=',
		disliked: webPath + '/search/dislikes?search='
	};
	var query=$.trim($("#search_query").val());
	if(query != ''){
		var where=$("#search_area").val();
		var searchStr = action[where] + encodeURI(encodeURI(query));
		location.href=searchStr;	
	}
}

/* show message */
var startDt, timer;
var msgIsHidden=true;

function showMessage(text){	// message init
	msgIsHidden=false;
	var msg=$("<div></div>");
	msg.addClass("message");
	msg.html(text);
	msg.hide();
	$(top.document.body).append(msg);
	
	msg.fadeIn("normal");
	centerMessage(msg);
	startDt=new Date();
	timer=setInterval("checkMessage()",500);
}
function checkMessage(){	// hiding message after 2.5 seconds
	var nowDt=new Date();
	var diffTime=1000*2.5;	// 2.5 sec
	if (nowDt.getTime()-startDt.getTime()>=diffTime){
		$(top.document.body).find(".message").each(function(){
			var curMsg=$(this);
			if (curMsg.css("display")!="none"){
				curMsg.fadeOut("fast"); 
				setTimeout(function(){curMsg.remove();},600);
				msgIsHidden=true;
			}
		});
		clearInterval(timer);
	}
}
function centerMessage(msg){	// center the message in the window
	var y=0;
	var x=0.5*($(top.document.body).width()-msg.width());
	msg.css("left",x).css("top",y);
}

// clicking on the tags in addReview form in website review page
function addTag(tagID){
	var allTags = $("#add_tags").val();
	var allTagsArr = allTags.split(" ");
	var tagValue = $("#tagsHTML"+tagID).text();
	var isNew=true;
	for(var i=0; i<allTagsArr.length; i++){
		if (allTagsArr[i]==tagValue){
			isNew=false;
			break;
		}
	}
	if (isNew){
		allTags += tagValue+" ";
		$("#add_tags").val(allTags);
	}
}
/* ajax preloaders */
function setPreloader(containerId){
	var preloader='<div class="loading" style="text-align:center;"><img style="margin-top:20px;" src="'+webPattern+'/images/ajax-loader-big.gif"/></div>';
	$("#"+containerId).children().each(function(){
		$(this).hide();
	});
	$("#"+containerId).prepend(preloader);
}
function removePreloader(containerId){
	$("#"+containerId).children(".loading").remove();
	$("#"+containerId).children().each(function(){
		$(this).show();
	});
}

// report buttons
function makeReport(obj, type){
// websites & comments
	var elem = obj;
	var reportId=elem.attr("rel")||0;
	var mainUrl="";
	var data={};
	var text="";
	if (type=='website'){
		mainUrl=webPath+"/web/urlReport";
		var href = elem.parents(".report_submenu").nextAll('div').eq(1).children("h4").children("a").attr("href");

		var url;
		if (isToolbarVisible) {
			url = href;
		} else {
			url = unescape(href.split("?")[1].substring(4));
		}	

		data={ url: url, reportId : reportId };
		text=common_website;
	}
	else if (type=='comment'){
		mainUrl=webPath+"/web/reviewReport";
		var urlId=$_GET("urlId")||"";
		var user=$.trim(elem.parents(".report_submenu").parent().children(".userpic").attr("title"));
		data={ urlId: urlId, username: user, reportId : reportId };
		text=common_comment;
	}
	$.ajax({
	   type: "POST",
	   url: mainUrl,
	   data: data,
	   cache:false,
		success: function(responseText){
			elem.parents(".report_submenu").hide();
			showMessage(common_youreportedthis+text+" "+common_as+elem.text());
		},
		error: function(){
			alert(common_sorryajaxerror);
		}
	});
}
	
/* paginator */
	
	/*
	 * containerId - id of conatiner to be paginated, e.g. 'pageliked' id - id
	 * of paginator container, must have class="pagination" url - common url in
	 * ajax onclick handler num - current page number amount - amount of pages
	 * count - number of entries in the page, optional - 10 by default
	 */
	function drawPaginator(containerId, id, url, num, amount, count){
		amount=amount || 8;
		count=count || 10;
		num=parseInt(num);
		var prev=(num==1)?"<span class='disabled'>&#9668;</span>":"<a class='prev' href='"+url+"?page="+(num-1)+"&count="+count+"'>&#9668;</a>";
		var next=(num==amount)?"<span class='disabled'>&#9658;</span>":"<a class='next' href='"+url+"?page="+(num+1)+"&count="+count+"'>&#9658;</a>";
		if (amount==1){
			prev="";
			next="";
		}
		var str=prev;
		
		if (amount > 8){
			if (num < 8){
				for (var i=1; i<=8; i++){
					if (i==num)
						str+="<span class='current'>"+i+"</span>";
					else
						str+="<a href='"+url+"?page="+i+"&count="+count+"'>"+i+"</a>";
				}
			}else{
				for (var i=1; i<=2; i++){
					if (i==num)
						str+="<span class='current'>"+i+"</span>";
					else
						str+="<a href='"+url+"?page="+i+"&count="+count+"'>"+i+"</a>";
				}	
				str+="...&nbsp;";
				for (var i = num - 3; i < num; i++) {
						str+="<a href='"+url+"?page="+i+"&count="+count+"'>"+i+"</a>";
				}
				str+="<span class='current'>"+num+"</span>";
				if (amount > num + 3) {
					for (var i = num + 1; i <= num + 3; i++) {
						if (i==num)
							str+="<span class='current'>"+i+"</span>";
						else
							str+="<a href='"+url+"?page="+i+"&count="+count+"'>"+i+"</a>";
					}
				}else{
					for (var i = num + 1; i <= amount; i++) {
						if (i==num)
							str+="<span class='current'>"+i+"</span>";
						else
							str+="<a href='"+url+"?page="+i+"&count="+count+"'>"+i+"</a>";
					}
				}
			}

		}
		
		if (amount > 1 && amount <= 7){
			for (var i=1; i<=amount; i++){
				if (i==num)
					str+="<span class='current'>"+i+"</span>";
				else
					str+="<a href='"+url+"?page="+i+"&count="+count+"'>"+i+"</a>";
			}
		}
		
		str+=next;
		if (id=="paginator_recommend")
			str="<a href='"+url+"?firstRowsCount=10'>Next page</a><a class='next' href='"+url+"?firstRowsCount=10'>&#9658;</a>";
		$("#"+containerId).find("#"+id).html(str);
		if (!$("#"+id).hasClass("pagination")) 
			$("#"+id).addClass("pagination");
		// links click handler
		$("#"+containerId).find("#"+id).find("a").click(function(){
			ajaxUrl($(this).attr("href"),containerId, id); 
			return false;
		});
	}
	
	function drawSimplePaginator(containerId, id, url, num, amount){
		amount=amount || 8;
		num=parseInt(num);
		var prev=(num==1)?"<span class='arr_left'></span>":"<a class='arr_left' href='"+url+"?page="+(num-1)+"&count=1'></a>";
		var next=(num==amount)?"<span class='arr_right'></span>":"<a class='arr_right' href='"+url+"?page="+(num+1)+"&count=1'></a>";
		if (id=="paginator_likers"){	// add urlId parameter
			var urlId=$_GET('urlId');
			prev=prev.replace("?","?urlId="+urlId+"&");
			next=next.replace("?","?urlId="+urlId+"&");
		}
		var str="<table class='arr_div'><tr><td>"+prev+"</td><td>"+next+"</td></tr></table>";
		if (id=="paginator_recommend")
			var str="<table class='arr_div'><tr><td><a class='arr_right' href='"+url+"?firstRowsCount=1'></a></td></tr></table>";
		$("#"+id).html(str);
		if ($("#"+id).hasClass("pagination")) 
			$("#"+id).removeClass("pagination");
		// links click handler
		$("#"+id).find("a").click(function(){
			ajaxUrl($(this).attr("href"), containerId, id, true, function(){
				if (id=="paginator_recommend") tb_init('a.thickbox'); // initialize thickbox window for next recommendation link.
			});
			return false;
		});
	}

	/*
	 * url - the whole url with parameters, it's parsed containerId - id of
	 * container filled of responseHtml pagId - id of paginator to be redrawn
	 * simple - boolean, whether to draw simple or full paginator callback -
	 * optional callback function
	 */
	function ajaxUrl(url, containerId, pagId, simple, callback){	
		setPreloader(containerId);
		var origUrl=url.split("?")[0];
		var pageNum=url.split("?")[1].substring(url.split("?")[1].indexOf("page=")+5,url.split("?")[1].indexOf("&",url.split("?")[1].indexOf("page=")));
		// if userName is set
		var newUserName=url.indexOf("userName")>-1 ? url.split("?")[1].substring(url.split("?")[1].indexOf("userName=")+9) : "";	// last
																																	// param
		if (newUserName==""){
			var countNum=url.split("?")[1].substring(url.split("?")[1].indexOf("count=")+6);
		}
		else{
			var countNum=url.split("?")[1].substring(url.split("?")[1].indexOf("count=")+6,url.split("?")[1].indexOf("&",url.split("?")[1].indexOf("count=")));
		}
		switch(pagId){
			case 'paginator_recommend':{
				$.get(url, function(responseText){	// get with constant request
				   onSuccessHandler(responseText,containerId,pagId,simple,origUrl,1,10);
				   if(callback)	callback();
				 });
				break;
			}
			case 'paginator_likers': {
				/*
				 * $.get(webPath+"/"+url, function(responseText){ //get with
				 * constant request alert(responseText); //
				 * onSuccessHandler(responseText,containerId,pagId,simple,origUrl,pageNum,pageCountLikers); //
				 * if(callback) callback(); });
				 */
				
				break;
			}
			default: {
				var dataObj= (newUserName=="") ?  {page: pageNum, count: countNum} : {page: pageNum, count: countNum, userName: newUserName};
				$.ajax({								// post with request
														// containing additional
														// parameters
					url: origUrl,
					data: dataObj,
					type: "POST",
					error: function(){
						alert(common_error);
					},
					success: function(responseText){
						onSuccessHandler(responseText,containerId,pagId,simple,origUrl,pageNum,recordTotal);
						if (newUserName!=""){
							var rightArr=$('#'+containerId).find('a.arr_right');
							var leftArr=$('#'+containerId).find('a.arr_left');
							rightArr.attr('href',rightArr.attr('href')+'&userName='+newUserName);
							leftArr.attr('href',leftArr.attr('href')+'&userName='+newUserName);
						}
						if ($("#paginator").length>0&&$("#likedpaginator").length>0){
							$("#likedpaginator").hide();
						}
						if(callback)	callback();
					}
				});
			}
		}
		return false;
	}
	// onSuccess handler for ajaxUrl (used after all types of ajax requests)
	function onSuccessHandler(responseText,containerId,pagId,simple,origUrl,pageNum,recordTotal){
		// removePreloader(containerId);
		if($("#"+containerId).length>0)
			$("#"+containerId).html(responseText);
		if ($('#'+pagId).parents('.rounded').parent().attr('id')=='maincontent'){	// panel is maximized - full paginator
			simple=false;
		}
		if (simple)
			drawSimplePaginator(containerId,pagId,origUrl,pageNum,recordTotal);
		else{
			window.scroll(0, -65000);
			redrawFullPaginator(containerId,pagId,origUrl);
		}
		if (!simple){	// tune appearance of div list
			$("#"+containerId).children("div[class!='pagination']").addClass("div_list");
			$("#"+containerId).parents(".rounded").css({background:'none', border:'none'});
		}
		initTooltips();
		initLikeControls('#'+containerId);
		initReportHandlers($('#'+containerId));
	}
// redraw full paginator
// pageNumber, pagesAmount, pageCount - global vars, defined in liked.jsp
function redrawFullPaginator(containerId,id,url){
	if ($("#"+containerId).find("#"+id).length>0)
		$("#"+containerId).find("#"+id).remove();
	// This element is just used to identify how many total amount of record
	if($('#recordTotal').length > 0){
		var recordTotal = parseInt($('#recordTotal').html());
		if(!isNaN(recordTotal) && recordTotal == 0){
			return;
		}
	}
	$('#maincontent>.rounded').find("#"+containerId).append("<div id='"+id+"' class='pagination'></div>");
	pageNumber=pageNumber || 1;
	pagesAmount=pagesAmount || 8;
	pageCount=pageCount || 10;
	drawPaginator(containerId,id,url,pageNumber,pagesAmount,pageCount); 
}


/**
 * Ajax url: request url sid: html id
 */
function ajaxGet(url, sid, callback) { 
	$.ajax({
		url: webPath + url,
		type: "GET",
		success: function(html){
			var id = '#'+sid;
			$().data(id, $(id));
			$(id).append(html).show();
			if (jsBreakWord){
				fnBreakWordAll({word:1,re:'[\\w]'});
			}
			if(callback){
				callback();
			}
		}
	});
}

/**
 * Ajax url: request url sid: html class name
 */
function ajaxGetByClass(url, sid, callback) { 
	$.ajax({
		url: webPath + url,
		type: "GET",
		success: function(html){
			var id = '.'+sid;
			$().data(id, $(id));
			$(id).append(html).show();
			if(callback){
				callback();
			}
		}
	});
}
	
function setRemoveEvent(eventID){
	$('#removeEvent').attr('href','javascript:removeRevents("'+eventID+'")');
}

function removeRevents(eventID){
	$.ajax({
		url: webPath + "/rest/revents/delete?eventID="+eventID,
		type: "DELETE",
		success: function(html){
			showMessage(delete_event_success);
			$(".eventsPanel").empty();
			if($("#events").hasClass("maxWindow")){
				ajaxGetByClass("/home/events","eventsPanel",function(){checkIfMinimized("eventsContent");});
			}else{
				ajaxGet("/home/events","eventsContent",function(){checkIfMinimized("eventsContent");});
			}
			
		}
	});
}

function setRemoveLikedUrl(urlID,page,pageCount){
	$('#removeLikedUrl').attr('href','javascript:removeLikedUrl("'+urlID+'","'+page+'","'+pageCount+'")');
}

function removeLikedUrl(urlID,page,pageCount){
	$.ajax({
		url: webPath + "/rest/url/delete?urlID="+urlID,
		type: "DELETE",
		success: function(html){
			showMessage(delete_url_success);
			$("#pageliked").empty();
			
			if($("#liked").hasClass("maxWindow")){
				initMaxLikedUrlPanel(page,pageCount);
			}if($("#disliked").hasClass("maxWindow")){
				initMaxDislikedUrlPanel(page,pageCount);
			}else{
				initLikedUrlPanel();
			}
		}
	});
}

var initMaxLikedUrlPanel = function(page,pageCount){
	
	ajaxUrl(webPath+"/like/liked?page="+page+"&count="+pageCount,"pageliked","paginator",false,function(){
		$("#pageliked").children("div[class!='pagination']").addClass("div_list");
		$('#pageliked').append('<p class="clearfix"></p>');
		$('#pageliked').parents(".rounded").css({background:'none', border:'none'});
		//fixEntriesHeight();
		//initReportHandlers($("#liked"));
		if ($("#likedpaginator").length>0){
			$("#likedpaginator").hide();
		}
		initReportHandlers($(".btn_report"));
	});
	
};
var initMaxDislikedUrlPanel = function(page,pageCount){
	
	ajaxUrl(webPath+"/like/disliked?page="+page+"&count="+pageCount,"pagedisliked","paginator",false,function(){
		$("#pagedisliked").children("div[class!='pagination']").addClass("div_list");
		$('#pagedisliked').append('<p class="clearfix"></p>');
		$('#pagedisliked').parents(".rounded").css({background:'none', border:'none'});
		//fixEntriesHeight();
		//initReportHandlers($("#disliked"));
		initReportHandlers($(".btn_report"));
	});
	
};

/**
 * Ajax handler for websiteReviews.jsp
 * 
 * @return
 */
function initReviewsAjaxActions(paramName, urlId) {
	params = "?" + paramName + "=" + urlId; // where is printf for javascript?
											// :]
	ajaxGet("/web/getUrlReviews" + params, "reviews",function(){
		initTooltips();
		initReportHandlers($('#website_info'),true);							// report
																				// buttons
		$('#reviews .report_submenu li a').bind('click',function(){		// comments
																		// to
																		// the
																		// review
			makeReport($(this),'comment');
			return false;
		});
	});
	ajaxGet("/web/getUrlLikers" + params, "likers", function(){
		initTooltips();
		drawSimplePaginator("likers","paginator_likers","/web/getUrlLikers", pageNumberLikers, pageCountLikers);
	});
	ajaxGet("/web/getSimilarUrls" + params, "similar_websites",initTooltips);
}

function initReportHandlers(obj,all){	// to the webpages (reports to the
										// comments are tuned separately)
		// if all==true elements are serached through the whole page, othercase
		// - within current element
		var elems= all ? $('.btn_report') : obj.find('.btn_report');	
		elems.click(function(){		// report submenu
			var elem = $(this);
			var reportSubMenu = elem.parent(".buttons").nextAll(".report_submenu");
			reportSubMenu.toggle();
			reportSubMenu.css({left:elem.offset().left, top:elem.offset().top + elem.height()});
			elem.attr("href","javascript:void(0)");
		});
		obj.find('.report_submenu li a').bind('click',function(){		// website
																		// in
																		// reviews
			makeReport($(this),'website');
			return false;
		});
}

/**
 * Init ajax handlers for home.jsp
 * 
 * @return
 */
function initHomeAjaxActions() {	// ajax requests
	ajaxGet("/blog/ajaxBlogList","blogContent",function(){checkIfMinimized("blogContent");});   
	ajaxGet("/home/news","topNews",function(){checkIfMinimized("topNews");});
	ajaxGet("/home/events","eventsContent",function(){checkIfMinimized("eventsContent");});
	initRecommendPanel();
	initLikedUrlPanel();
	// $('#pagedisliked').remove();
	/*
	ajaxGet("/like/disliked?firstRowsCount=1","pagedisliked", function(){
		$("#pagedisliked").css("height",null);
		$("#pagedisliked div#loading").hide();
		//panelsHeight($('#pagedisliked'));
		initTooltips();
		checkIfMinimized("pagedisliked");
		initReportHandlers($('#pagedisliked'));
		if (isIE){
			$('#pagedisliked .tags').width($('#pagedisliked .site_info').width());
		} 
		$('.website_entry').each(function(){
			if ($(this).hasClass('clearfix'))
				$(this).removeClass('clearfix');
		});
	 });
	 */
}

function initRecommendPanel(){
	ajaxGet("/home/showRecommend?firstRowsCount=1","recommendURL", 
			function(){
				//console.log('recom loaded')
				tb_init('a.thickbox');
				$("#recommendURL").css("height",null);
				$("#recommendURL div#loading").hide();
				initTooltips();
				checkIfMinimized("recommendURL");
				initReportHandlers($('#recommendURL'));
				initLikeControls('#recommendURL');
				if (isIE){
					$('#recommendURL .tags').width($('#recommendURL .site_info').width());
				}
				$('.website_entry').each(function(){
					if ($(this).hasClass('clearfix'))
						$(this).removeClass('clearfix');
				});
			});
}
function initUrlPanel(url){
	ajaxGet(url,"pageliked",
			function(){
				tb_init('a.thickbox');
				$("#pageliked").css("height",null);
				$("#pageliked div#loading").hide();
				//panelsHeight($('#pageliked'));
				initTooltips();
				checkIfMinimized("pageliked");
				initReportHandlers($('#pageliked'));
				initLikeControls('#pageliked');
				if (isIE){
					$('#pageliked .tags').width($('#pageliked .site_info').width());
				}
				$('.website_entry').each(function(){
					if ($(this).hasClass('clearfix'))
						$(this).removeClass('clearfix');
				});
			});
}

function initDisLikedUrlPanel(){
	initUrlPanel("/like/disliked?firstRowsCount=1");
}

function initLikedUrlPanel(){
	initUrlPanel("/like/liked?firstRowsCount=1");
}

function initPeopleSearch(){
	$("#peopleSearch").submit(function() {
		   var dataEntered = false;	
		   if ($('#adv_search').css('display')!='none'){
			   var friendInteresting = isFormValueEntered('#peopleSearch select[name=peopleSearch.interesting]');// $.trim(($('#peopleSearch select[name=peopleSearch.interesting]').val()));
			   var friendCountry = isFormValueEntered('#peopleSearch select[name=peopleSearch.country]');//$.trim(($('#peopleSearch select[name=peopleSearch.country]').val()));
			   var friendGender = isFormValueEntered('#peopleSearch input:radio[name=peopleSearch.gender]:checked');//$.trim(($('#peopleSearch input:radio[name=peopleSearch.gender]:checked').val()));
			   var friendCity = isFormValueEntered('#peopleSearch input[name=peopleSearch.city]');//$.trim(($('#peopleSearch input[name=peopleSearch.city]').val()));	
			   var friendBeginAge = isDigitFormValueEntered('#peopleSearch input[name=peopleSearch.beginage]');//$.trim(($('#peopleSearch input[name=peopleSearch.beginage]').val()));
			   var friendEndAge = isDigitFormValueEntered('#peopleSearch input[name=peopleSearch.endage]');//$.trim(($('#peopleSearch input[name=peopleSearch.endage]').val()));
			   var friendName = isFormValueEntered('#peopleSearch input[name=userName]');
			   var result = friendInteresting || friendCountry || friendGender || friendCity || friendBeginAge || friendEndAge || friendName;
			   dataEntered = result;
		   } else {
			   dataEntered = isFormValueEntered('#peopleSearch input[name=userName]');
		   }
		   return dataEntered;

	    });
	
}
 
//need for initPeopleSearch
function isFormValueEntered(obj) {
	return ($.trim(($(obj).val())) != ''); 
}
//need for initPeopleSearch
function isDigitFormValueEntered(obj) {
	var b = isFormValueEntered(obj);
	if (b) {
		return !isNaN($.trim(($(obj).val())));
	} else {
		return b;
	}		
}	

// if ajax content is loaded into panel it needs extra checking if it's
// minimized
function checkIfMinimized(id){
	var parentRounded=$("#"+id).parents(".rounded");
	if (parentRounded.find(".btn_min").hasClass("btn_min_active")){
		parentRounded.children("div").hide();
	}
}

/* website entry and newsfeed entry init functions */
function initLikeControls(obj){	// obj are .website_entry and .newsfeedcontent
	obj=$(obj);
	obj.each(function(){
		var o=$(this);
		if (isIE && (o.hasClass('website_entry') || o.attr('id')=='recommended')){
			var t=0;
			if (o.attr('id')=='recommended') {o=o.find('.website_entry'); t=700;}	//overwrite other panel height fix for recommended
			setTimeout(function(){
				o.parent('div').css('height','auto');
				o.parent('div').css('minHeight','auto');
				o.parents('.rounded').css('height','auto');
				o.parents('.rounded').css('minHeight','auto');
			},t);
		}
	});
	var oo = obj.find('a.review');
	oo.unbind( "click" );
	oo.click(function(){
		var form1=$(this).parent().next('.form');
		var htmlcontent=$(this).html();
		if (form1.css('display') == 'none'){
			$(this).html('');	//htmlcontent.replace($(this).attr('rel'),'Hide')	
		}
		else{
			$(this).html($(this).attr('rel')+' your own Review');	//htmlcontent.replace('Hide',$(this).attr('rel'))
		}
		form1.toggle();
		// height fix
		var webEntry=$(this).parents('.website_entry,.newsfeedcontent');
		var h1=webEntry.find('.float_left').height();
		var h2=webEntry.find('.float_left').next('div').height();
		var hmax= h1>h2? h1 : h2;
		webEntry.height(hmax);
		if (isIE){
			webEntry.css('height',hmax);
			webEntry.parent('div').css('height','auto');
			webEntry.parents('.rounded').css('height','auto');
		}
		//$(this).trigger('blur');
		$("#newsFeedReview" + this.id.substr(10)).trigger("focus");
		
		return false;
	});
	obj.find('.form textarea').focus(function(){
					if ($(this).val()=="Write a review...")
						$(this).val("");
				}).blur(function(){
					if ($(this).val() == '' || $(this).val() == null){ 
						//$(this).val("Write a review...");
					}
	});
	obj.find('.form input:text').focus(function(){
					if ($(this).val()=="Add tags")
						$(this).val("");
				}).blur(function(){
					if ($(this).val() == '' || $(this).val() == null){ 
						$(this).val("Add tags");
					}
	});
	oo = obj.find('a.num_comments');
	oo.unbind( "click" );
	oo.click(function(){
		var div1=$(this).parent().next('div');
		var htmlcontent=$(this).html();
		if (div1.css('display')=='none'){
			$(this).html(htmlcontent.replace('Show','Hide'));
		}
		else{
			$(this).html(htmlcontent.replace('Hide','Show'));
		}
		div1.toggle();
		var webEntry=$(this).parents('.website_entry,.newsfeedcontent');
		var h1=webEntry.find('.float_left').height();
		var h2=webEntry.find('.float_left').next('div').height();
		var hmax= h1>h2? h1 : h2;
		webEntry.height(hmax);
		$(this).trigger('blur');
		reComputeHeight('#maincontent');
		return false;
	});
	oo= obj.find('.website_info a');
	oo.unbind( "click" );
	oo.click(function(){
		website_info_toggle($(this));
		return false;
	});
	obj.find('.website_entry,.newsfeedcontent').each(function(){	//,.newsfeedcontent
		if ($(this).hasClass('clearfix'))
			$(this).removeClass('clearfix');
		if (isIE6){
			var h1=$(this).find(".float_left").height();
			var h2=$(this).find(".float_left").next("div").height();
			var hmax= h1>h2? h1 : h2;
			$(this).height(hmax);
		}
		else{
			$(this).css('height','auto');
		}
	});
	if (!isIE6){
					obj.find("input[type='text'], input[type='password'], input.file").bind("focus",function(){
						$(this).css("backgroundImage","url("+webPattern+"/images/forms_input_bg_focus.png)"); 
					}).bind("blur",function(){
						$(this).css("backgroundImage","url("+webPattern+"/images/forms_input_bg.jpg)"); 
					});
					obj.find("textarea").bind("focus",function(){
						$(this).css("backgroundImage","url("+webPattern+"/images/forms_textarea_bg_focus.png)"); 
					}).bind("blur",function(){
						$(this).css("backgroundImage","url("+webPattern+"/images/forms_textarea_bg.png)"); 
					});
	}
	else{
					obj.find("input[type='text'], input[type='password'], input.file").bind("focus",function(){
						$(this).get(0).focus();
					});
	}
}

/**
 * Mark tag as checked/unchecked
 * 
 * @param a
 * @return
 */
function toggleTag(a) {
	var curObj=$(a);
	var curClone;
	var panel=$("#mytags p");
	if (!curObj.hasClass("checked_tag")){
		curClone=curObj.clone().unbind();
		curClone.bind('click',function(){deleteMyTag(this);});
		curClone.appendTo(panel);
		addMyCategory(curObj.clone().unbind());
	}	
	else{
		panel.children("a").each(function(){
			if ($(this).html()==curObj.html()){
				$(this).remove();
				removeMyCategory(curObj.clone());
			}
		});	
		
	}
	curObj.toggleClass("checked_tag");
	
}
 
function removeMyCategory(category) {

	$("#my_category").find("a").each(function() {
		
		if (category.html() == $(this).html()) {
			$(this).remove();
		}
	});
}
function addMyCategory(category) {
	var a=$("a.similar").eq(0);
	var href = a.attr("href");
	
	if (href) {
		// $(category).hide();
		category.appendTo($("#my_category"));
		category.toggleClass("more_tags");
		$(category).click(clickMoreTags);
		var path = href.split("?")[0];
		path = path + "?src=similar&maxElements=250&tag=" 
		+ escape(category.html().replace(/\s+/g,"")) 
		+ "&similarity=0.05&depth=3";
		category.attr("href", path);
		// $(category).show("slow");
	}	
}
// var lastRandom;
//
// function showSimilarToMeTagsDelayed() {
// lastRandom = Math.random()
// setTimeout("showSimilarToMeTags(" + lastRandom + ");", 3000)
// }
//
// function showSimilarToMeTags(r) {
// if (r == lastRandom) {
// $("#similar_tags p").html(r);
// }
// }

function deleteMyTag(a){
	var curObj=$(a);
	$('#tagcodecloud ul.tags').find("a").each(function(){
		if ($(this).html()==curObj.html()){
			$(this).toggleClass("checked_tag");
		}
	});
	removeMyCategory(curObj.clone().unbind());
	curObj.remove();
	
}



/**
 * List of checked tags
 * 
 * @return comma separated list of checked tags
 */
function getCheckedTags() {
	var result = null;
	var tags = $(".checked_tag").each(function(a){
		if (result != null) {
			result = result +" " + $(this).text().replace(/\s+/g,""); 
		} else {
			result = $(this).text().replace(/\s+/g,"");
		}
		});
	
	return result == null ? "" : result;
}

/**
 * 
 */
function tagCodeInit() {
	$('#tagcodecloud a.checked_tag').each(function(){
		addMyCategory($(this).clone().unbind().toggleClass('checked_tag'));
		var cClone=$(this).clone().unbind().toggleClass('checked_tag');
		cClone.bind('click',function() {deleteMyTag(this);});
		cClone.appendTo($('#mytags p'));
	});

	$('a.more_tags').each(function(){
		var params = $(this).attr('rel').split(/;/);
		var size = scaleTags( parseInt(params[0]), parseInt(params[1]), parseInt(params[2]));
		size=Math.round(size);
		if (size>0) 
			$(this).css('fontSize', size+'%');
	});
	$("#submit_tags").submit(function() {
		try {
		var tags = getCheckedTags();
		showMessage(common_savingtags);
		$.ajax({
			   type: "POST",
			   url: this.action,
			   data: {checkedTags: tags},
			   cache:false,
			   // async:false
				success: function(responseText){
				   showMessage(common_tagssaved);
				},
				error: function(){
					showMessage(common_tagsnotsaved);
				}
			});
		} catch (error) {
			alert(error);
		}
		return false;
		});

	$(".more_tags").click(clickMoreTags);
	}
 function clickMoreTags(){
		var thisTag=$(this).html();
		$('#tagcloud h1').html(common_tagcloudfor+thisTag);
		$.ajax({
			   type: "GET",
			   url: this.href,
			   data: {checkedTags: getCheckedTags()},
				success: function(responseText){
					$("#tagcodecloud").html(responseText);
					$('ul.tags a').each(function(){
						var params = $(this).attr('rel').split(/;/);
						var size = scaleTags( parseInt(params[0]), parseInt(params[1]), parseInt(params[2]));
						size=Math.round(size);
						if (size>0) 
							$(this).css('fontSize', size+'%');
						
					});
					$('#tagcodecloud a').click(function(){
						toggleTag(this);
						return false;
					});
				},
				error: function(){
					
				}
			});
		return false;
		}
/**
 * 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
 * 
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value == null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires
															// attribute,
															// max-age is not
															// supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain in
		// the following expressions, otherwise they evaluate to undefined in
		// the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/* setting the panels state in the homepage using cookie */
function initCookieState(){	// inits cookie. if not set use default panels
							// layout. refresh the panels
	var defaultPanelsStateLeft='profile_blog_friends_recentlyVisitor'; // _events_news
	var defaultPanelsStateRight='userTags_liked_disliked_recommended';
	if (!$.cookie('leftColumn') || !$.cookie('rightColumn')){
		$.cookie('leftColumn',defaultPanelsStateLeft,{expires:30});
		$.cookie('rightColumn',defaultPanelsStateRight,{expires:30});
	}
	refreshPanelsState();
// minimizing panels
	var minArr=[];
	if( $.cookie('panelsMin')!=null && $.cookie('panelsMin').indexOf("undefined")==-1 && $.cookie('panelsMin')!="")
		minArr=$.cookie('panelsMin').split("_");
	for (i=0; i<minArr.length; i++){
		if ($("#"+minArr[i]).length>0 && $("#"+minArr[i]).parents("#repository").length==0){	// exists
																								// and
																								// not
																								// in
																								// repository
			var btn=$("#"+minArr[i]).find(".btn_min");
			minimizingPanel(btn);
			if (!btn.hasClass("btn_min_active")) 
				btn.addClass("btn_min_active");
			}
	}
	
}

function updateCookieState(){	// checks the panels position and sets
								// appropriate cookie
	var lCookie=[];
	var rCookie=[];
	var leftChildren=$('#left_column').children(".rounded");
	var rightChildren=$('#right_column').children(".rounded");
	leftChildren.each(function(){
		lCookie.push($(this).attr("id"));
	});
	rightChildren.each(function(){
		rCookie.push($(this).attr("id"));
	});
	$.cookie('leftColumn',lCookie.join('_'),{expires:30});
	$.cookie('rightColumn',rCookie.join('_'),{expires:30});
}

function refreshPanelsState(){	// moves the panels from repository to the
								// columns according the cookie
	var repoChildren=$('#repository').children(".rounded");
	var lCookieArr=[];
	if ($.cookie('leftColumn')) lCookieArr=$.cookie('leftColumn').split("_");
	var rCookieArr=[];
	if ($.cookie('rightColumn')) rCookieArr=$.cookie('rightColumn').split("_");
	for (var i=0; i<lCookieArr.length; i++){
		repoChildren.each(function(){
			var el=$(this);
			if (el.attr("id")==lCookieArr[i]){
				el.appendTo("#left_column");
				if (el.attr("id")=="disliked")	el.hide();
				return false;
			}
		});
	}
	for (var i=0; i<rCookieArr.length; i++){
		repoChildren.each(function(){
			var el=$(this);
			if (el.attr("id")==rCookieArr[i]){
				el.appendTo("#right_column");
				if (el.attr("id")=="disliked")	el.hide();
				return false;
			}
		});
	}
}
function minimizingPanel(elem){
		var id=elem.parents(".rounded").attr("id");
		var cookieStr=($.cookie('panelsMin')==null || $.cookie('panelsMin').indexOf("undefined")>-1 || $.cookie('panelsMin')=="")?"":$.cookie('panelsMin');
		elem.parent().parent().nextAll("div").slideToggle();
		elem.toggleClass("btn_min_active");	 
		if (elem.hasClass("btn_min_active")){
			elem.attr("title",common_testoresize);
			var cookieArray = cookieStr.split('_');
			if(cookieStr == ''){
				cookieArray = [];
			}
			if ($.inArray(id, cookieArray)==-1)
				cookieArray.push(id);
				cookieStr = cookieArray.join('_');	// add cookie
		}
		else{
			elem.attr("title",common_minimize);
			if (cookieStr.length>0){		// remove cookie
				var n=cookieStr.indexOf(id);
				var strToDelete="";
				if (n>0)
					strToDelete="_"+id;
				else if (n==0)
					strToDelete=(cookieStr.length==id.length)?id:id+"_";
				cookieStr=cookieStr.replace(strToDelete,"");
			}
		}
		$.cookie('panelsMin', cookieStr,{expires:30});
}
/* mail */
function setWhatToDel(obj){
	obj=$(obj);
	$('#msgIdContainer').attr('href','#'+obj.parents('li').attr('id'));
}
function setWhatToDel_mail(obj){
	obj=$(obj);
	var msgId=obj.parents('li').attr('id');
	var page=$("#page").val();
	var count=$("#count").val();
	$('#msgId').attr('href','javascript:deleteMail("'+msgId+'","'+page+'","'+count+'")');
}
function setWhatToDel_mails(){
	clearErrorMessage();
	var msgId = "";
	 $("input[name='selectMessageID']").each(function(){
	 	if ($(this).attr("checked")==true){
			msgId = msgId+$(this).val()+",";
		}
     }); 
      if(msgId==""){
      	window.scroll(0, -65000);
      	showErrorMessage("Please choose what you want to delete.");
      	return;
    }
	var page=$("#page").val();
	var count=$("#count").val();
	$('#msgId').attr('href','javascript:deleteMail("'+msgId+'","'+page+'","'+count+'")');
	window.top.tb_show('Welcome','#TB_inline?&width=300&height=120&inlineId=confirmDialog',null); 
}
function deleteMail(msgId,page,count){
   var url=webPath+'/mail/deleteMessage?messageID='+msgId;
  	$.ajax({
	type: 'get',
	url: url,
	success: function(){
		showMessage(delete_mail_success);
		if ($("#forwardUrl").length>0){
			location.href=$("#forwardUrl").val();
		}else{
			url=webPath+"/mail/maillist?page="+page+"&count="+count;
			retrieveURL(url,"mail_list",function(){reComputeHeight("#maincontent");});   
		}
		refreshUnreadMessageCount();
	},
	error: function(){
	}
	});  
}
/* blog */
function setWhatToDel_Blog(blogID,commentID,page,count){

	$('#blogCommentId').attr('href','javascript:deleteBlogComment("'+blogID+'","'+commentID+'","'+page+'","'+count+'")');
}

function deleteBlogComment(blogID,commentID,page,count){
	var url=webPath+'/blog/deleteComment?commentID='+commentID;
	$.ajax({
		type: 'get',
		url: url,
		success: function(){
			showMessage(delete_blog_success);
			url=webPath+"/blog/blogComments?page="+page+"&count="+count+"&blogID="+blogID;
			retrieveURL(url,"blogComments",function(){reComputeHeight("#maincontent");});   
		},
		error: function(){
			
		}
	});

}


function setDelBlog(blogID,userName,page,count){
	$('#deleteBlogId').attr('href','javascript:deleteBlog("'+blogID+'","'+userName+'","'+page+'","'+count+'")');
}
/* group */
function setWhatToDel_topic(groupID,topicID,page,count){
	$('#deleteTopicId').attr('href','javascript:deleteTopic("'+groupID+'","'+topicID+'","'+page+'","'+count+'")');
}
function deleteTopic(groupID,topicID,page,count){
	var url=webPath+'/group/deleteTopic?topicID='+topicID+'&groupID='+groupID;
	
	$.ajax({
		type: 'get',
		url: url,
		success: function(){
			showMessage(delete_topic_success);
			if ($("#isGroupTopic").length>0){
				url=webPath+"/group/showTopic?page="+page+"&count="+count+"&group="+groupID;
				retrieveURL(url,"group_forum",function(){reComputeHeight("#maincontent");}); 
			}else{
				var groupTopicID=$("#groupTopicID").val(); 
				url=webPath+"/group/showSubTopic?page="+page+"&count="+count+"&group="+groupID+"&topicID="+groupTopicID;
				retrieveURL(url,"group_topic",function(){reComputeHeight("#maincontent");}); 
			} 
			
		},
		error: function(){
			
		}
	});
}
function saveGroupTopic(){
	var topicTitle = $("#topicTitle").val();
	if (topicTitle.length < 6 ){
		showErrorMessage(common_titleminimum);
		return false;
	}
	
	var url=webPath+'/group/saveTopic';
	var groupID=$('#groupID').val();
	$.ajax({
		type: 'post',
		url: url,
		data: $('#topicForm').serialize(),
		success: function(){
			window.parent.showMessage(save_topic_success);
			url=webPath+"/group/showTopic?page=1&group="+groupID;
			window.parent.retrieveURL(url,"group_forum",function(){reComputeHeight("#maincontent");});   
			window.parent.tb_remove();
		},
		error: function(){
			
		}
	});
}
function editTopic(){
	var topicTitle = $("#topicTitle").val();
	if (topicTitle.length < 6 ){
		showErrorMessage(common_titleminimum);
		return false;
	}
	var topicContent = $("#topicContent").val().replace('\n','<br/>');
	var topicID=$('#topicID').val();
	var url=webPath+'/group/editTopic';

	$.ajax({
		type: 'post',
		url: url,
		data: $('#topicForm').serialize(),
		success: function(){
			window.parent.showMessage(save_topic_success);
			window.parent.$('#topicTitle'+topicID).html(topicTitle);
			window.parent.$('#topicContent'+topicID).html(topicContent);
			window.parent.tb_remove();
		},
		error: function(){
			
		}
	});
}

function replyTopic(){
	var topicTitle = $("#topicTitle").val();
	if (topicTitle.length < 6 ){
		showErrorMessage(common_titleminimum);
		return false;
	}
	
	var url=webPath+'/group/reply';
	var groupID=$('#groupID').val();
	var topic=$('#topic').val();
	$.ajax({
		type: 'post',
		url: url,
		data: $('#topicForm').serialize(),
		success: function(){
			window.parent.showMessage(save_topic_success);
			url=webPath+"/group/showSubTopic?page=1&group="+groupID+"&topicID="+topic;
			window.parent.retrieveURL(url,"group_topic",function(){reComputeHeight("#maincontent");});   
			window.parent.tb_remove();
		},
		error: function(){
			
		}
	});
}

var website_info_toggle=function(obj){
		obj.next('div').toggle();
		obj.toggleClass('opened');
		obj.trigger('blur');
		return false;
};
/* functions for websiteReviews */
		function setLikeAndDislike(T) {
			likes = $(T).find('likes').text();
			dislikes = $(T).find('dislikes').text();
			// updating the amount of likes/dislikes everywhere except blue_form
			$('.vote').each(function(){
				if ($(this).parent('div') && $(this).parent('div').parent('div') && $(this).parent('div').parent('div').hasClass("blue_form"))
					{}
				else
					$(this).text(likes + ' likes');
			});
			$('.votebad').each(function(){
			if ($(this).parent('div') && $(this).parent('div').parent('div') && $(this).parent('div').parent('div').hasClass("blue_form"))
					{}
				else
					$(this).text(dislikes + ' dislikes');
			});
		}	
	
		function initPopularTags() {
			$.ajax({
				beforeSend: function(xhr){
					xhr.setRequestHeader("Location", locationURL);
					xhr.setRequestHeader("Accept", "text/xml");
					return true;
				},
				url: webPath + "/tags",
				type: "GET",
				error: function(){/* showMessage('Sorry, error occured'); */},
				success: callbackTag
			});
		}

		function callbackTag(xml){
			xml="<xml>"+xml+"</xml>";
			var tags = $('tag', xml); 
			var len = 0;
			var code = '';
			tags.each(function(){
				var tag = $(this).attr('tag');
				if(len + tag.length + 1 > maxTagLength){
					return false;
				}
				len += tag.length + 1;
				var tagID = $(this).attr('tagID');
				code += "<a href='javascript:void(0)' onclick='getTag(\""+tagID+"\")'><span id='tagsHTML"+tagID+"'>"+tag+"</span></a>&nbsp;";
			});
			if(code != ''){
				$("#tagsHTML").html(code);
				$("#popularTags").html(common_populartags);
			}
		}

		/**
		 * @param tagID
		 * @param inputId the id of <code>input</code> tag with tag list.
		 * default values <code>"add_tags"</code>, <code>"tags"</code> 
		 * @return
		 */
		function getTag(tagID, inputId){
			var t;
			if (inputId == undefined || inputId == null) {
				t = document.getElementById("add_tags") || document.getElementById("tags");
				inputId = "";
			} else {
				t = document.getElementById(inputId);
			}
			var tagsInput = t.value;
			var tagesHTML = document.getElementById("tagsHTML" + inputId + tagID).innerHTML;
			var tags = tagsInput.split(" ");

			if (tagsInput.length > 0){
				if (tagsInput == "Add tags") {
					tagsInput="";
				}
				
				tagsInput = tagsInput+" ";

			}

			var isExist=true;
			for(var i=0; i<tags.length; i++){
				if (tags[i]==tagesHTML){
					isExist=false;
					break;
				}
			}
			if (isExist){
				tagsInput = tagsInput+tagesHTML;
				t.value = tagsInput;
			}
		}
		
function websitereviewsrate(status){
	$(this).blur();
	status=parseInt(status);
	if (status==-1){
		websitedisableButton(-1);
	}
	else {
		websitedisableButton(1);
	}
	XHR = $.ajax({
	   type: "POST",
	   url: webPath+"/rating/"+status,
	   data: "url="+locationURL,
	   beforeSend: function(xhr){
	     xhr.setRequestHeader("Location", locationURL); // Handle the
														// beforeSend
														// event
	   },
	   success: function(T){
	   	countLikes = $(T).find('likes').text();
			countDislikes = $(T).find('dislikes').text();
			// setLikeAndDislike(T); // update likes/dislikes amount
			if (status==-1){
				showMessage(common_adddislikedwebsite);
			}else{
				showMessage(common_addlikedwebsite);
			}
			
			var id=$_GET('urlId');
			var _prefix = "";
			var value=status;
			var url=locationURL;
			var params = {
				getImgClass: function(){
					if(value == 1){
						return $('#' + _prefix + 'like' + id).attr('class');
					}else{
						return $('#' + _prefix + 'dislike' + id).attr('class');
					}
				},
				getLinkClass: function(){
					if(value == 1){
						return $('#' + _prefix + 'dislike' + id).attr('class');
					}else{
						return $('#' + _prefix + 'like' + id).attr('class');
					}		
				},
				getImgStyle: function(){
					if(value == 1){
						return $('#' + _prefix + 'like' + id).attr('style');
					}else{
						return $('#' + _prefix + 'dislike' + id).attr('style');
					}
				},
				getLinkStyle: function(){
					if(value == 1){
						return $('#' + _prefix + 'dislike' + id).attr('style');
					}else{ 
						return $('#' + _prefix + 'like' + id).attr('style');
					}
				}
			};
			
			var img = '<span class="{0}" id="{1}" src="' + webPath + '{2}" style="{3}">{4}</span>';
			var link = '<a onclick="rateURL(\'{0}\', \'{1}\', {2}, \'{3}\')" id="{4}" href="javascript:void(0)" style="{5}" class="{6}">{7}</a>';
			var changeHTML = function(imgType, linkType, imgCount, linkCount, imgPath, ratingValue){
				var imgText = ratingValue == 1 ? "dislikes" : "likes";
				var linkText = ratingValue == 1 ? "likes" : "dislikes";
				$('#' + imgType + id).replaceWith(img.template(params.getImgClass(), imgType + id, imgPath, params.getImgStyle(), imgCount + ' ' + imgText));
				$('#' + linkType + id).replaceWith(link.template(url, id, ratingValue, _prefix, linkType + id, params.getLinkStyle(), params.getLinkClass(), linkCount + ' ' + linkText));
			};
			
			switch(parseInt(value)){
			case 1: 
				showLikes($(this).parent().find('a.vote'),parseInt($(this).parent().find('a.vote').html()) + 1);
				break;
			case -1:
				showDislikes($(this).parent().find('a.votebad'),parseInt($(this).parent().find('a.votebad').html()) + 1);
				break;
			}

			if(status == 1){
				changeHTML(_prefix + 'like', _prefix + 'dislike', countLikes, countDislikes, webPattern+"/images/ico_thumbs_up_hover.png", -1);
			}else{
				changeHTML(_prefix + 'dislike', _prefix + 'like', countDislikes, countLikes, webPattern+"/images/ico_thumbs_down_hover.png", 1);
			}
			updateVoteTextInForm();

		}// end success
		
	});
	return false;	

}
function websitedisableButton(status){

	if (parseInt(status)==1){
			$('#your_reaction').addClass("liked");
			$('.likevote').unbind();
			$('.likevote').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_up_hover.png)");
			$('.likevote').css('cursor','default');
			$('.dislikevotebad').bind("click", function(){websitereviewsrate(-1);});
			$('.dislikevotebad').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_down.png)");
			$('.dislikevotebad').css('cursor','pointer');
			$('.dislikevotebad').attr('title',common_adddislikedsite);
			$('.likevote, .dislikevotebad').each(function(){
				if ($('#likevote').parent('div') && $('#likevote').parent('div').parent('div') && $('#likevote').parent('div').parent('div').hasClass('blue_form')){
					if ($('#likevote').attr('title') && $('#likevote').attr('title')!='')
						$('#likevote').removeAttr('title');
				}else{
					if ($('#likevote').hasClass('likevote')) 
						$('#likevote').attr('title',common_youlike);
					else  
						$('#likevote').attr('title',common_adddislikedsite);
					$('#likevote').ToolTip({className: 'tooltip',position: 'bottom',delay: 500});
				}
			});
			
	}
	else if (parseInt(status)==-1){
			$('#your_reaction').addClass("disliked");
			$('.dislikevotebad').unbind();
			$('.dislikevotebad').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_down_hover.png)");
			$('.dislikevotebad').css('cursor','default');
			$('.likevote').bind("click", function(){websitereviewsrate(1);});
			$('.likevote').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_up.png)");
			$('.likevote').css('cursor','pointer');
			$('.dislikevotebad, .likevote').each(function(){
				if ($('#dislikevotebad').parent('div') && $('#dislikevotebad').parent('div').parent('div') && $('#dislikevotebad').parent('div').parent('div').hasClass('blue_form')){
					if ($('#dislikevotebad').attr('title') && $('#dislikevotebad').attr('title')!='')
						$('#dislikevotebad').removeAttr('title');
				}else{
					if ($('#dislikevotebad').hasClass('dislikevotebad')) 
						$('#dislikevotebad').attr('title',common_youdislike);
					else  
						$('#dislikevotebad').attr('title',common_addlikedsite);
					$('#dislikevotebad').ToolTip({className: 'tooltip',position: 'bottom',delay: 500});
				}
			});	
	}
}
function websitereviewsrefreshStatus(xml){
	var status = $('status', xml).text();
	var bookmarked = $('bookmarked', xml).text() == "true";
	if (bookmarked){
		$('a.bookmark').html(common_editbookmark);
	}else{
		$('a.bookmark').html(common_bookmarkit);
	}
	if (parseInt(status)==1||parseInt(status)==-1){
		websitedisableButton(status);
	}else{
		$('.likevote').bind("click", function(){websitereviewsrate(1);});
		$('.dislikevotebad').bind("click", function(){websitereviewsrate(-1);});
	}
	updateVoteTextInForm();
}

function refreshStatus(xml){
	var status = $('status', xml).text();
	var bookmarked = $('bookmarked', xml).text() == "true";
	if (bookmarked)
		$('a.bookmark').html(common_editbookmark);
	else
		$('a.bookmark').html(common_bookmarkit);
	switch(parseInt(status)){

		case 1: {
			disableButton('like'); break;
			}
		case -1: {
			disableButton('dislike'); break;
			}
		default: 
			$('.vote').bind("click",rateLiked);
			$('.votebad').bind("click",rateDisliked);
			break;
	}
	updateVoteTextInForm();
}
function updateVoteTextInForm(){
	if ($('.blue_form').length>0){
		var voteBtn=$('.blue_form a.vote');
		if (voteBtn.css('backgroundImage').indexOf('hover')>-1)
			voteBtn.html(common_youlike);
		else
			voteBtn.html(common_addtoliked);
		var votebadBtn=$('.blue_form a.votebad');
		if (votebadBtn.css('backgroundImage').indexOf('hover')>-1)
			votebadBtn.html(common_youdislike);
		else
			votebadBtn.html(common_addtodisliked);
	}
	
}
function rateit(status) {
			status=parseInt(status);
			if (status==-1){
				disableButton('dislike');
			}
			else {
				disableButton('like');
			}
			XHR = $.ajax({
			   type: "PUT",
			   url: webPath+"/rating/"+status,
			   data: "url="+locationURL,
			   beforeSend: function(xhr){
			     xhr.setRequestHeader("Location", locationURL); // Handle the
																// beforeSend
																// event
			   },
			   success: function(T){
					setLikeAndDislike(T);   // update likes/dislikes amount
					if (status==-1)
						showMessage(common_adddislikedwebsite);
					else
						showMessage(common_addlikedwebsite);
					updateVoteTextInForm();
				}
				
			});
			return false;
}
function rateLiked(){
	$(this).blur();
	rateit(1);
}
function rateDisliked(){
	$(this).blur();
	rateit(-1);
}
function disableButton(type){
	if (type=='like'){
			$('.vote').unbind();
			$('.vote').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_up_hover.png)");
			$('.vote').css('cursor','default');
			$('.votebad').bind("click", rateDisliked);
			$('.votebad').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_down.png)");
			$('.votebad').css('cursor','pointer');
			$('.votebad').attr('title',common_adddislikedsite);
			$('.vote, .votebad').each(function(){
				if ($(this).parent('div') && $(this).parent('div').parent('div') && $(this).parent('div').parent('div').hasClass('blue_form')){
					if ($(this).attr('title') && $(this).attr('title')!='')
						$(this).removeAttr('title');
				}
				else{
					if ($(this).hasClass('vote')) 
						$(this).attr('title',common_youlike);
					else  
						$(this).attr('title',common_adddislikedsite);
					$(this).ToolTip({className: 'tooltip',position: 'bottom',delay: 500});
				}
			});
			
	}
	else if (type=='dislike'){
			$('.votebad').unbind();
			$('.votebad').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_down_hover.png)");
			$('.votebad').css('cursor','default');
			$('.vote').bind("click", rateLiked);
			$('.vote').css('backgroundImage',"url("+webPattern+"/images/ico_thumbs_up.png)");
			$('.vote').css('cursor','pointer');
			$('.votebad, .vote').each(function(){
				if ($(this).parent('div') && $(this).parent('div').parent('div') && $(this).parent('div').parent('div').hasClass('blue_form')){
					if ($(this).attr('title') && $(this).attr('title')!='')
						$(this).removeAttr('title');
				}
				else{
					if ($(this).hasClass('votebad')) 
						$(this).attr('title',common_youdislike);
					else  
						$(this).attr('title',common_addlikedsite);
					$(this).ToolTip({className: 'tooltip',position: 'bottom',delay: 500});
				}
			});	
	}
}

/* date selectboxes in personal information */
function set_option_selected(select_obj, value){
	day_options=select_obj.options;
	if (day_options.length>0) {
		for (i=0; i<day_options.length; i++) {
			(day_options[i].value==value) ? day_options[i].selected=true : '';
		}
	}
}
function extendDigitList(startIdx, endIdx, selIdx, object){
	if (object.val()==$("#birthday_year").val()){
		for (i = endIdx; i>startIdx ; i--){
			i=i<10?'0'+i:i;
			if (i == selIdx) {
				$(object).append("<option selected='selected' value='"+i+"'>"+i+"</option>");
			} else {
				$(object).append("<option value='"+i+"'>"+i+"</option>");
			}			
		}
	}else{
		for (i = startIdx; i<= endIdx; i++){
			i=i<10?'0'+i:i;
			if (i == selIdx) {
				$(object).append("<option selected='selected' value='"+i+"'>"+i+"</option>");
			} else {
				$(object).append("<option value='"+i+"'>"+i+"</option>");
			}			
		}
	}

}
function initDateSelects(){
	var startYear = (new Date().getFullYear() - 100);
	var endYear = (new Date().getFullYear() );
	var selectedYear = (new Date().getFullYear() - 38);
	var selectedDay = parseInt(0); 
	var date1 = $("#birthday_exchanger").attr("value");
	var dateArray = date1.split("-");
	if (dateArray.length == 3) {
		try {
			var y = parseInt(dateArray[0]);
			selectedYear = isNaN(y) || y == 0 ? selectedYear : y;
		} catch (error) {
			
		}
		try {
			var d = parseInt(dateArray[2]);
			selectedDay = isNaN(d)  ? selectedDay : d;
			 
		} catch (error) {
			
		}
	}
	extendDigitList(1, 31, selectedDay, $("#birthday_day"));	// days
	extendDigitList(startYear, endYear, '1000', $("#birthday_year"));	// years
	Calendar.setup({
				inputField	:	"birthday_exchanger",			// id of the
																// input field
				ifFormat	:	"%Y-%m-%d",													// format
																							// of
																							// the
																							// input
																							// field
				showsTime	:	false,																	// will
																										// display
																										// a
																										// time
																										// selector
				button		:	"birthday_calendar_button",	// trigger for the
															// calendar (button
															// ID)
				singleClick	:	true,																	// double-click
																										// mode
				step		:	1,																		// show
																										// all
																										// years
																										// in
																										// drop-down
																										// boxes
																										// (instead
																										// of
																										// every
																										// other
																										// year
																										// as
																										// default)
				range		:	[startYear,endYear],														// show
																											// all
																											// years
																											// in
																											// drop-down
																											// boxes
																											// (instead
																											// of
																											// every
																											// other
																											// year
																											// as
																											// default)
				firstDay	:	1																		// week
																										// start
																										// from
																										// Monday
	});
}

function updateEditMessage(id,message){
	$("#"+id).attr("title",message);
}

/*
 * News feed and addtionaInfo action support functions 
 */

function rateURLNewsFeed(url, id, value, prefix){
	var _prefix = prefix || "";
	var changeHTML = rateUrlNfUpdateControls(url, id, value, prefix);
	
	$.ajax({
		url: webPath + "/rating/" + value,
		type: "POST",
		beforeSend: function(xhr){
			xhr.setRequestHeader('Location', url);
		},
		error: function(){
			
		},
		success: function(xml){
			var count = setWebsiteCounters(xml, _prefix, id);
			if(value == 1){
				changeHTML(_prefix + 'like', _prefix + 'dislike', count.likes, count.dislikes, webPattern+"/images/ico_thumbs_up_hover.png", -1);
			}else{
				changeHTML(_prefix + 'dislike', _prefix + 'like', count.dislikes, count.likes, webPattern+"/images/ico_thumbs_down_hover.png", 1);
			}
			if ($('#profile_homepage').length>0){
			// if we in the profile page
				//console.log('refresh');
				$("#pageliked").empty();
				initLikedUrlPanel();
				// if we clicked recommendations
				initRecommendPanel();
			}
			
		}	
	});
}

function updateNfControlsState(url, id, value, prefix) {
	var _prefix = prefix || "";
	var changeHTML = rateUrlNfUpdateControls(url, id, value, prefix);
	if(value == 1){
		changeHTML(_prefix + 'like', _prefix + 'dislike', 0, 0, webPattern+"/images/ico_thumbs_up_hover.png", -1);
	}else{
		changeHTML(_prefix + 'dislike', _prefix + 'like', 0, 0, webPattern+"/images/ico_thumbs_down_hover.png", 1);
	}
}
/**
 * @param value
 * @param prefix
 * @return
 */
function rateUrlNfUpdateControls(url, id, value, prefix) {
	var _prefix = prefix || "";
	var params = {
		getImgClass: function(){
			if(value == 1){
				var c=$('.' + _prefix + 'like' + id).attr('class');
				c=c.replace('like ','like_pressed ');
				return c;
			}else{
				var c=$('.' + _prefix + 'dislike' + id).attr('class');
				c=c.replace('dislike ','dislike_pressed ');
				return c;
			}
		},
		getLinkClass: function(){
			if(value == 1){
				var c=$('.' + _prefix + 'dislike' + id).attr('class');
				c=c.replace('dislike_pressed ','dislike ');
				return c;
				
			}else{
				var c=$('.' + _prefix + 'like' + id).attr('class');
				c=c.replace('like_pressed ','like ');
				return c;
			}		
		},
		getImgStyle: function(){
			if(value == 1){
				return $('.' + _prefix + 'like' + id).attr('style');
			}else{
				return $('.' + _prefix + 'dislike' + id).attr('style');
			}
		},
		getLinkStyle: function(){
			if(value == 1){
				return $('.' + _prefix + 'dislike' + id).attr('style');
			}else{
				return $('.' + _prefix + 'like' + id).attr('style');
			}
		}
	};

	var img = '<span class="{0}" id="{1}" src="' + webPath + '{2}" style="{3}">{4}</span>';
	var link = '<a onclick="rateURLNewsFeed(\'{0}\', \'{1}\', {2}, \'{3}\')" id="{4}" href="javascript:void(0)" style="{5}" class="{6}">{7}</a>';
	var changeHTML = function(imgType, linkType, imgCount, linkCount, imgPath, ratingValue){
		var imgText = '';//ratingValue == 1 ? hopsurf_likedisliked_dislikes : hopsurf_likedisliked_likes;
		var linkText = '';//ratingValue == 1 ? hopsurf_likedisliked_likes : hopsurf_likedisliked_dislikes;
//current link
		$('.' + imgType + id).each(function(){
			$(this).replaceWith(img.template(params.getImgClass(), imgType + id, imgPath, params.getImgStyle(), /*imgCount + ' ' + imgText*/''));
		});

//other link		
		$('.' + linkType + id).each(function(){
			$(this).replaceWith(link.template(url, id, ratingValue, _prefix, linkType + id, params.getLinkStyle(), params.getLinkClass(), /*linkCount + ' ' + linkText*/''));
		});	
		
	};

	switch(parseInt(value)){
	case 1: 
		showLikes($(this).parent().find('a.'+_prefix+'like'),parseInt($(this).parent().find('a'+_prefix+'like').html()) + 1);
		break;
	case -1:
		showDislikes($(this).parent().find('a'+_prefix+'dislike'),parseInt($(this).parent().find('a'+_prefix+'dislike').html()) + 1);
		break;
	}
	return changeHTML;
}

function setWebsiteCounters(xml, _prefix, id){
	//parse response xml
	var countLikes = $('likes', xml).text();
	var countDislikes = $('dislikes', xml).text();
	var countReview = $('reviews', xml).text();
	//set counters	
	$('.count' + _prefix + 'like' + id).each(function (){
		$(this).html(countLikes);
	});
	$('.count' + _prefix + 'dislike' + id).each(function (){
		$(this).html(countDislikes);
	});
	$('.count' + _prefix + 'review' + id).each(function (){
		$(this).html(countReview);
	});
	var counters = {
		likes 	 : countLikes,
		dislikes : countDislikes,
		reviews  : countReview
		};	
	return counters;
}

function editNewsFeedCommentOnClick(urlid, url, prefix, status) { /* add/edit review form submit */
	var defMessage = "Write a review...";
	var defTags = "Add tags";
	var notes = $('#newsFeedReview'+urlid).val();
//	alert("!" + notes);
	if (defMessage == notes || notes.replace(/\s*/,"").length == 0) {
		showMessage('Review must be not empty!');//Review must be not empty!
		return false;
	}
	//var url = '${urlInfo.url}';
//	var tagName = $('.newsFeeddislike'+urlid)[0].tagName;
	var tags = $("#add_tags" + urlid).val();
	if (tags == defTags) {
		tags =" ";
	}
	$.ajax( {
		type : "POST",
		url : webPath + "/url/" + status,
		data : {
			url : url,
			notes : notes,
			tags : tags,
			asynchSave:"false"
		},
		cache : false,
		async : false,
		success : function() {
			/*$('p.yourReview'+urlid +' span').each(function(){
				$(this).text('Your review: ' + notes);
			});
			$('div.other_comments'+urlid).each(function(){
				$(this).attr('style','');
			});*/
			$.ajax({
				type : "POST",
				url  : webPath + "/ratingInfo",
				beforeSend : function(xhr){
								xhr.setRequestHeader('Location', url);
							},
				success : function (xml) {
								var counters = setWebsiteCounters(xml, prefix, urlid);
 								setWebsiteCounters(xml, prefix, urlid);
								if (counters.reviews==1){
									$(".countnewsFeedreviewUserText"+urlid).html(" user");
								}else{
									$(".countnewsFeedreviewUserText"+urlid).html(" users");
								}
							},
				error: function (){
							}													
			});	
			showMessage('Review for this site was saved');//Review for this site was changed
			tb_remove();
		},
		error : function() {
			alert('Sorry, server too busy');//Sorry, ajax error occured
			tb_remove();
		}
	});
	return true;
}

function deleteUserEvent(eventID) {
	$.ajax( {
		type : "POST",
		url : webPath + "/home/removeUserEvent",
		data : {
			eventID : eventID
		},
		cache : false,
		success : function() {
			$('div.userEvent'+eventID).each(function(){
				$(this).remove();
			});
			showMessage('User event successfully removed');
			tb_remove();
		},
		error : function() {
			alert('<s:text name="hopsurf.websites.sorry"/>');//Sorry, ajax error occured
			tb_remove();
		}
	});			
	return false;
}

/**
 * @param elementId
 * @param urlId
 * @return
 */
function updateAdditionalInfo(elementId, urlId, count) {
	$.ajax({
		type : "GET",
		url  : "/util/lastBookmarkStatus",
		success : function (html) {
			$.ajax({
				type : "GET",
				url  : "/web/additionalInfo",
				data : {urlId : urlId, additionalInfoCount: count},
		
				success : function (html) {
						$("#" + elementId).each(function(elem) {
							$(this).parent().html(html);
						});
						initLikeControls('.website_entry, .newsfeedcontent, .recommendURL');
						if (jsBreakWord){
							fnBreakWordAll({word:1,re:'[\\w]'});
						}
				}
															
			});	
		}
	
	});	
	
}	

/*
 * End of News feed and addtionaInfo action support functions 
 */
/* *************************************************************************************************** */

/**
 * string template eg:var result = 'my {0} is {1}'.template('name',
 * 'tom');result === 'my name is tom';
 */
String.prototype.template = function(){
	var args = arguments;
	return this.replace(/\{(\d+)\}/g, function(matchText, index){
		return args[index];
	});	
};


/**
 * This function is supplied to use ajax simple.
 */
function retrieveURL(url, id, callback) {
	var processStateChange = function(text) {	// text=responseText
		if ($("."+id).length>0){
			$("."+id).html(text);
		}else if($("#"+id).length>0){
			$("#"+id).html(text);
		}
		window.scroll(0, -65000);
		if(callback && callback.constructor == Function){
			callback();
		}
	};
	var failFunction = function(){
	};
	$.ajax({
		url: url,
		type: "POST",
		error: failFunction,
		success: processStateChange
	});
	
}

function previewBlog(){
	// alert(window.parent.document.getElementById("title").value);
	$("#header").html(window.parent.document.getElementById("title").value);
	$("#previewDiv").html("<div style='padding-top:10px;'>"+window.parent.RTE.getDoc()+"</div>");
	$("#previewDiv").find("ul").each(function(){
		$(this).css("padding-left","40px");
		$(this).find("li").each(function(){
			$(this).css("list-style-type","disc");
		});
	});
	$("#previewDiv").find("ol").each(function(){
		$(this).css("padding-left","40px");
		$(this).find("li").each(function(){
			$(this).css("list-style-type","decimal");
		});
	});
}
			
function checkblog(v,url){
	var contentText = RTE.getDoc();
	var title = $("#title").val();

	if (v=="savedraft"){
		$("#bstatus").val("draft");
	}
	
	if(!decideHasHtml()){
		return false;
	}
	if (title.length < 6 ){
		showErrorMessage(common_blogtitleminimum);
  		// $("#errorMessage").html();
		return false;
	}
	if (contentText.length<=0){
		showErrorMessage(common_enterblogcontent);
   	// $("#errorMessage").html("Please enter the blog content.");
		return false;
	}
	if (contentText.length>20000){
	// alert(contentText.length);
		showErrorMessage(common_blogcontentminimum);
   	// $("#errorMessage").html("Please enter the blog content.");
		return false;
	}
	if (contentText.length>180){
		$("#blogDescription").html(contentText.replace(/<.+?>/gim,'').substring(0,180)+"...");
	}else{
		$("#blogDescription").html(contentText.replace(/<.+?>/gim,''));
	}
	$('#blogContent').val(contentText);
	if (v=="publish"||v=="savedraft"){
		$("#submitForm").attr("disabled",true);
		$("#submitsavedraft").attr("disabled",true);
	}
	if (v=="cancel"){
		document.getElementById("blogForm").action=url;
	}
	$("#blogForm").submit();
	
}
function saveBlogcommon(blogID){
	var commonText = RTE.getDoc();
	clearErrorMessage();
	
	if (commonText.length<=0){//if (commonText.replace(/<.+?>/gim,'').length<=0){
		showErrorMessage(common_enterblogcommon);
		$("#errorMessage").css("display","block");
		return false;
	}
	if (commonText.length>2000){
		showErrorMessage(common_blogcommonminimum);
		$("#errorMessage").css("display","block");
 		return false;
	}
	
	$("#saveCommon").attr("disabled",true);
	$('#textarea_add_comment').val(RTE.getDoc());
	var url = webPath+'/blog/saveBlogCommon?blogID=' + blogID;
	$.ajax({
			type: 'post',
			url: url,
			data: $('#commentForm').serialize(),
			success: function(){
				$("#saveCommon").attr("disabled",false);
				showMessage(save_blog_comment_success);
				url=webPath+"/blog/blogComments?blogID="+blogID;
				retrieveURL(url,"blogComments",function(){reComputeHeight("#maincontent");}); 
				$("#textarea_add_comment").val("");
			},
			error: function(){
				
			}
		});
}

function checkmail(){
    var contentText=RTE.getDoc();
	
	var subject = $("#subject").val();
	var receives = $("#receives").val();

	if(!decideHasHtml()){
		return false;
	}
	
   if (receives.length<=0){
   	showErrorMessage(common_choosefriends);
   	// $("#errorMessage").html("Please choose your friends");
		return false;
   }
   if (subject.length<=0){
   	showErrorMessage(common_fillinsubject);
   	// $("#errorMessage").html("Please fill in subject");
		return false;
   }
   if (contentText.length<=0){
   	showErrorMessage(common_fillincontenttext);
   	// $("#errorMessage").html("Please fill in contentText");
		return false;
   }

    if (contentText.length>180){
    	$("#description").html(contentText.replace(/<.+?>/gim,'').substring(0,180)+"...");
    }else{
    	$("#description").html(contentText.replace(/<.+?>/gim,''));
    }
    
    $('#messageContent').val(contentText);
    
    if ($("#ajax").length>0){
    	if ($("#ajax").val()=="true"){
    		var url=webPath+"/mail/replyMessage";
    		$("#Send").attr("disabled",true);
	    	$.ajax({
				type: 'post',
				url: url,
				data: $('#form1').serialize(),
				success: function(){
					var msgId=$("#messageID").val();
					var page=$("#page").val();
					var count=$("#count").val();
					$("#Send").attr("disabled",false);
					showMessage(save_mail_sent_success);
					url=webPath+"/mail/maillist?page="+page+"&count="+count;
					retrieveURL(url,"mail_list",function(){reComputeHeight("#maincontent");}); 
				},
				error: function(){
					
				}
			});
    	}else{
    	return true;
    	}
    }else{
    return true;
    }

}

function chooesFriend(userName){

	var receives = $("#receives").val();
	var receivesHTML=$("#receivesHTML").html();
	// alert(receivesHTML);
	var r = receives.split(",");
	var isExist=true;
	for(var i=0; i<r.length; i++){
		if (r[i]==userName){
			isExist=false;
			break;
		}
	}
	if(isExist){
		if (receives.length!=0){
			receives = receives+","+userName;
			receivesHTML = receivesHTML+","+userName+"<a href=\"javascript:removeFriend('"+userName+"')\" title='"+common_remove+"' id='"+userName+"'>x</a>";
		}else{
			receives = userName;
			receivesHTML = userName+"<a href=\"javascript:removeFriend('"+userName+"')\" title='"+common_remove+"' id='"+userName+"'>x</a>";
		}
		$("#receives").val(receives);
		$("#receivesHTML").html(receivesHTML);
	}
}
function removeFriend(userName){
	var receives = $("#receives").val();
	var receivesHTML="";
	var r = receives.split(",");

	receives = "";
	
	for(var i=0; i<r.length; i++){
		if (r[i]!=userName){
			if (receives==""){
				receives = r[i];
				receivesHTML = r[i]+"<a href=\"javascript:removeFriend('"+r[i]+"')\" title='"+common_remove+"' id='"+r[i]+"'>x</a>";
			}else{
				receives = receives+","+r[i];
				receivesHTML = receivesHTML+","+r[i]+"<a href=\"javascript:removeFriend('"+r[i]+"')\" title='"+common_remove+"' id='"+r[i]+"'>x</a>";
			}
		}
	}

	$("#receives").val(receives);
	$("#receivesHTML").html(receivesHTML);
}

function report(id,username){
	RTE.setDoc("");
	$(".editor").hide();
	var replacedElement = $('#rtefield');
// var defaultValue = replacedElement.html();
	var subject=$("#subject" + id).html();
	$("#subject").val(subject);
	$("#receives").val(username);
	$("#messageID").val(id);
//	$('#' + id).append($('#fckEditor'));
//	replacedElement.load(webPath + '/rte.jsp', function(){
//	});

	var obj = $("#"+id);
	var offset = obj.offset();
	var right = offset.left;
	var down = offset.top+obj.height();
	$('#fckEditor').css({
		'font-size':'12px',
		'position':'absolute',
		'margin':'20px',
		'left':right,
		'top':down,
		'width':'70%',
		'z-index': '50',
		'padding':'10px'
	});

	$('#fckEditor').show();
}

function deleteBlog(blogID,userName,page,count){
	var url;
	if ($("#flag").val()=="home"){
		page=-1;
		count=-1;
	}

	if (page==-1&&count==-1){
		url = webPath+'/blog/deleteBlog?flag=home&blogID='+blogID+'&userName='+userName+'&page='+page+'&count='+count;
	}else{
		url = webPath+'/blog/deleteBlog?blogID='+blogID+'&userName='+userName+'&page='+page+'&count='+count;
	}

	if($("#deleteBlogId").hasClass("deleteBlog")){
		window.location.href=url;
	}else{
		$.ajax({
			type: 'get',
			url: url,
			success: function(){
				showMessage(delete_blog_success);
				if ($("#"+blogID).length){
					retrieveURL(webPath+"/blog/resultBlog?page="+page+"&count="+count,"blogContent",function(){reComputeHeight("#maincontent");});   
				}else{
					$("#blogContent").empty();
					if($("#blog").hasClass("maxWindow")){
						retrieveURL(webPath+"/blog/ajaxBlogList?page="+page+"&count="+count,"blogContent",function(){reComputeHeight("#maincontent");});   
					}else{
						ajaxGet("/blog/ajaxBlogList?page="+page+"&count="+count,"blogContent",function(){checkIfMinimized("blogContent");});   
					}
	
				}
				
			},
			error: function(){
				
			}
		});
	}

}


function deleteMessage(messageID){
	if(confirm(common_confirmdelete)){
		window.location.href = webPath + '/mail/deleteMessage?messageID=' + messageID;
	}
}

function deleteFriend(){
	
	$.ajax({
		   type: "POST",
		   url: $('#deleteFriendForm').attr('action'),
		   data: $('#deleteFriendForm').serialize(),
		   success: function(msg){
				showMessage(userName+' deleted from friends list.');
				location.reload();
		   },
		   error: function(msg) {
			   showMessage('Bad parameters!');
		   }	   
		 });
	
	return false;
}

function welcome(){
	try{
		$("#welcome").append($("#pageWelcome").html());
	}catch(e){
	
	}
}

function tabpage(id){
	var code = "";
	if (id=="Home"){
		code = '<ul id="navlist"><li id="active"><a href="javascript:void(0)" id="current">Home</a></li><li><a href="'+webPath+'/web/websitesDefault">Websites</a></li><li><a href="'+webPath+'/">People</a></li><li><a href="'+webPath+'/mail/mailDefault">Mail</a></li></ul>';
	}
	
	if (id=="Websites"){
		code = '<ul id="navlist"><li id="active"><a href="'+webPath+'/">Home</a></li><li><a href="javascript:void(0)" id="current">Websites</a></li><li><a href="'+webPath+'/people/peopleDefault">People</a></li><li><a href="'+webPath+'/mail/mailDefault">Mail</a></li></ul>';
	}
	if (id=="People"){
		code = '<ul id="navlist"><li id="active"><a href="'+webPath+'/">Home</a></li><li><a href="'+webPath+'/web/websitesDefault">Websites</a></li><li><a href="javascript:void(0)" id="current">People</a></li><li><a href="'+webPath+'/mail/mailDefault">Mail</a></li></ul>';
	}
	if (id=="Mail"){
		code = '<ul id="navlist"><li id="active"><a href="'+webPath+'/">Home</a></li><li><a href="'+webPath+'/web/websitesDefault">Websites</a></li><li><a href="'+webPath+'/people/peopleDefault">People</a></li><li><a href="javascript:void(0)" id="current">Mail</a></li></ul>';
	}
	

	try{
		$("#navcontainer").append(code);
	}catch(e){
	
	}
}


function showExtName(extName) {
	$("#csvDiv").hide();
	$("#manuDiv").hide();
	$("#mailDiv").show();
	
	var emailName;
	var addressName;
	var passwordName;
	if(extName == 'GMail'){
		emailName = common_gmailemailname;
		addressName = common_gmailaddressname;
		passwordName = common_gmailpasswordname;
	}else if(extName == 'Yahoo'){
		emailName = common_yahooemailname;
		addressName = common_yahooaddressname;
		passwordName = common_yahoopasswordname;
	}else if(extName == 'Hotmail'){
		emailName = common_hotmailemailname;
		addressName = common_hotmailaddressname;
		passwordName = common_hotmailpasswordname;
	}else if(extName == 'Aol'){
		emailName = common_aolemailname;
		addressName = common_aoladdressname;
		passwordName = common_aolpasswordname;
	}
	$("#addressName").html(addressName);
	$("#passwordName").html(passwordName);
	$("#extName").html(emailName);
	$("#providerType").val(extName);
	$("#password").val('');
	$("#address").val('');
	
}

function showCsvForm(){
	$("#csvDiv").show();
	$("#manuDiv").hide();
	$("#mailDiv").hide();
}


function showManuForm(){
	$("#csvDiv").hide();
	$("#manuDiv").show();
	$("#mailDiv").hide();
}
function  selectinterest(v){
	for(var i=0;i<old_list.length;i++){
		if (!isIE6){
			var inputradio = $('input', old_list[i]);
			var labelradio = $('label', old_list[i]);
			if (v=="select"){
				inputradio.attr("checked",true);
				labelradio.removeClass("checkbox_unchecked");
				labelradio.addClass("checkbox_checked");
			}else{
				inputradio.attr("checked",false);
				labelradio.removeClass("checkbox_checked");
				labelradio.addClass("checkbox_unchecked");
			}
		}
		else{
			var inputradio = $('input', old_list[i]);
			var labelradio = $('label', old_list[i]);
			if (v=="select"){
				inputradio.attr("checked",true);
			}else{
				inputradio.attr("checked",null);
			}
		}
	}
}

function open_folder(obj){
	$("#listCats li").each(function(){
		if($(this).hasClass('current')){
			$(this).attr('class', '');
			return false;
		}
	});
	$(obj).attr('class', 'current');
	var topicspan = $("#listTopics div");
	topicspan.each(function(){
		$(this).hide();
	});

	// var t = document.getElementsByName("span_"+$(obj).attr('id'));
// var t = $(".span_"+$(obj).attr('id'));
	if ($(obj).attr('id')=='All') {
		var t = $("#listTopics div");
	} else {	
		var t = $(".span_"+$(obj).attr('id'));
	}
	old_list = t;
	for(var i=0;i<t.length;i++){
		t[i].style.display="";
	}
}

function showDiv(divID){
	$("#" + divID).show();
}

function delDiv(divID){
	$("#" + divID).hide();
}

function savePersonalInfo(){
	$("#birthday").attr("value",$("#birthdayTmp").attr("value")) ;
	$('#hiddenEmailMessage').val($('#emailMessage').attr('checked') ? '1' : '2');
	$('#hiddenSendUpdateMessage').val($('#sendUpdateMessage').attr('checked') ? '1' : '2');
	$('#hiddenFindByEmail').val($('#findByEmail').attr('checked') ? '1' : '2');
	$('#hiddenAnonySendMessage').val($('#anonySendMessage').attr('checked') ? '1' : '2');
	$('#hiddenLeaveMyFootprint').val($('#leaveMyFootprint').attr('checked') ? '1' : '2');	
	$('#hiddenUpdateblogMessage').val($('#updateblogMessage').attr('checked') ? '1' : '0');	
	$('#hiddenLikesMessage').val($('#likesMessage').attr('checked') ? '1' : '0');	
	$('#hiddenDislikesMessage').val($('#dislikesMessage').attr('checked') ? '1' : '0');	
	$('#hiddenMakecommentMessage').val($('#makecommentMessage').attr('checked') ? '1' : '0');	
	$('#hiddenSaveStickyNote').val($('#saveStickyNote').attr('checked') ? '1' : '0');	
	$('#hiddenLanguages').val($('#firstLanguages').val()+', '+$('#secondLanguages').val());
	var email=$('#userEmail').val();
	var p = /^([\w\.-]+)@([a-zA-Z0-9-]+)(\.[a-zA-Z\.]+)$/;
    if(email.search(p) == -1){
    	showErrorMessage(hopsurf_personal_decideemail);
      return false;  
    }
	
	
	var birthday_exchanger = $("#birthday_exchanger").val();
	var b = birthday_exchanger.split('-');
	for(var i=0;i<b.length;i++){
		if(b[i]=='1000'||b[i]=='00'){
			$("#birthday_exchanger").val("");
		}
	}

	return decideHasHtml();

}

/**
 * limit textarea size for publicprofile.jsp
 */
function profile(){
	
	if(!decideHasHtml()){
		return false;
	}
	if($('#personalSummary').val().length>200){
		showErrorMessage(common_personalsummaryminimum);
		return false;
	}
	if($('#caption').val().length>200){
		showErrorMessage(common_captionminimum);
		return false;
	}
	if($('#quote').val().length>200){
		showErrorMessage(common_quoteminimum);
		return false;
	}
	if($('#mySign').val().length>200){
		showErrorMessage(common_mysignminimum);
		return false;
	}

	
	
	var url = webPath + "/user/saveProfile";
	$.ajax({
		type: 'POST',
		url: url,
		data: $('#profileForm').serialize(),
		success: function(){
			showMessage(common_publicprofilesaved);
		},
		error: function(){
			showErrorMessage(common_decidehashtmlaction);
		}
	});
	
}

/**
 * accept friend authenticatioin request
 */
function acceptAuthRequest(){
	if($('#reasonStr').val().length>200){
		alert(common_messageminimum);
		return false;
	}
	$('#acceptMessage').val($('#reasonStr').val()); 
	$('#sform').submit();
}

/**
 * refuse friend authenticatioin request
 */
function refuseAuthRequest(){
	if($('#reasonStr').val().length>200){
		alert(common_messageminimum);
		return false;
	}
	$('#refuseMessage').val($('#reasonStr').val()); 
	$('#rform').submit();
}

function showErrorMessage(msg) {
	$("#errorMessage").html(msg);
	$("#errorMessage").fadeIn("normal");
}

function clearErrorMessage() {
	$("#errorMessage").hide();
	$("#errorMessage").html("");
}


/**
 * Convert url to HTTPS.
 * 
 * @param url
 * @return
 */
function urlInHttps(url) {
	if (url.substr(0, 8) == "https://") {
		return url;
	}
	if (url.substr(0, 7) == "http://") {
		return "https://" + url.substr(7);
	}
		
	return "https://" + url;	
}
// sign up page check

/**
 * Validate user name field for Sign Up form
 */
function validateUserName() {
	var username = $('#userName').val();
	if(username != "") {
		if (username.length < 4) {
			return createValidationObject(false, common_logintooshort,"userName");
		}
		if (username.length > 64) {
			
			return createValidationObject(false, common_logintoolong,"userName");
			
		}
		var validator = new RegExp("^[a-zA-Z_]([0-9a-zA-Z_]{3,63})$");
		if (validator.test(username)) {
			return createValidationObject(true, "", "userName");
		} else {
			return createValidationObject(false, common_loginletter,"userName");
		}
	} 
		return createValidationObject(false, "", "userName");

}

/**
 * Validate email
 */
function validateEmail() {
	var email = $('#userEmail').val();
	if(email == "") {
			return createValidationObject(false, common_emailempty, "userEmail");
	} else {
			return createValidationObject(true,"", "userEmail");
			
	}
}

function checkSpecialChar(str){
	
	var regularStr = /<.*?>/g;
	if(regularStr.test(str)){
		return true;
	}
	return false;
}


function validateFirstName(){	
	var fristName = $('#firstName').val();
	if(checkSpecialChar(fristName)){
		return createValidationObject(false, common_firstname_wrong, "firstName");
	}else{
		return createValidationObject(true, "", "firstName");
	}
}

function validateLastName(){
	var lastName = $('#lastName').val();
	if(checkSpecialChar(lastName)) {
		return createValidationObject(false, common_lastname_wrong, "lastName");
	}else{
		return createValidationObject(true, "", "lastName");
	}
}

function validateCity(){	
	var city = $('#city').val();
	if(checkSpecialChar(city)) {
		return createValidationObject(false, common_city_wrong, "city");
	}else{
		return createValidationObject(true, "", "city");
	}
}
	
function validateState(){
	var state = $('#state').val();
	if(checkSpecialChar(state)) {
		return createValidationObject(false, common_state_wrong, "state");
	}else{
		return createValidationObject(true, "", "state");
	}
}

function createValidationObject(success, message, id) {
	return {success:success, message:message, id:id};
}

function markElementAsIncorrect(id) {
	$("#" + id).css("border","1px solid #a00");
}

function markElementAsCorrect(id) {
	$("#" + id).css("border", "1px solid #D0DED5");
}

function markElement(id, correct) {
	if (correct) {
		markElementAsCorrect(id);
	} else {
		markElementAsIncorrect(id);
	}
}

/**
 * Clear validation info on sign up form.
 * 
 */
function clearValidation() {
	
	clearErrorMessage();
	markElementAsCorrect("userName");
	markElementAsCorrect("userEmail");
	markElementAsCorrect("pass1");
	markElementAsCorrect("pass2");
	markElementAsCorrect("checkCode");
	markElementAsCorrect("firstName");
	markElementAsCorrect("lastName");
	markElementAsCorrect("city");
	markElementAsCorrect("state");
	
} 

/**
 * Function validates sign up form and writes error messages if any.
 * 
 * @return false
 */
function validateSignUpForm() {
	var showOkButton = false;
	var errorMessages = new Array();
	var validationResult = validateUserName();
	
	markElement(validationResult.id, validationResult.success);
	if (validationResult.success) {
		showOkButton = true;
		
	} else {
		if (validationResult.message.length > 0) {
			errorMessages[errorMessages.length] = validationResult.message;
		}
	}
	
	validationResult = validateEmail();
	markElement(validationResult.id, validationResult.success);
	if ( !validationResult.success ) {
		showOkButton = false;
		if (validationResult.message.length > 0) {
			errorMessages[errorMessages.length] = validationResult.message;
		}
	}
	
	validationResult = validatePassword1 ();
	markElement(validationResult.id, validationResult.success);
	if ( !validationResult.success ) {
		showOkButton = false;
		if (validationResult.message.length > 0) {
			errorMessages[errorMessages.length] = validationResult.message;
		}
	}
	
	validationResult = validatePassword2();
	markElement(validationResult.id, validationResult.success);
	if ( !validationResult.success ) {
		showOkButton = false;
		if (validationResult.message.length > 0) {
			errorMessages[errorMessages.length] = validationResult.message;
		}
	}
	
	validationResult = validateFirstName();
	if(validationResult != null){
		markElement(validationResult.id, validationResult.success);
		if ( !validationResult.success ) {
			showOkButton = false;
			if (validationResult.message.length > 0) {
				errorMessages[errorMessages.length] = validationResult.message;
			}
		}
	}
	
	validationResult = validateLastName();
	if(validationResult != null){
		markElement(validationResult.id, validationResult.success);
		if ( !validationResult.success ) {
			showOkButton = false;
			if (validationResult.message.length > 0) {
				errorMessages[errorMessages.length] = validationResult.message;
			}
		}
	}
	
	validationResult = validateCity();
	if(validationResult != null){
		markElement(validationResult.id, validationResult.success);
		if ( !validationResult.success ) {
			showOkButton = false;
			if (validationResult.message.length > 0) {
				errorMessages[errorMessages.length] = validationResult.message;
			}
		}
	}
	
	validationResult = validateState();
	if(validationResult != null){
		markElement(validationResult.id, validationResult.success);
		if ( !validationResult.success ) {
			showOkButton = false;
			if (validationResult.message.length > 0) {
				errorMessages[errorMessages.length] = validationResult.message;
			}
		}
	}
	
	if (errorMessages.length > 0) {
		var html = errorMessages[0];
		for(i=1 ; i<errorMessages.length; i++) {
			html +="<br/>" + errorMessages[i];
		}
		showErrorMessage(html);
	} else {
		clearErrorMessage();
	}
	
	return showOkButton;
}


function validatePassword1() {
	var pass1 = $('#pass1').val(); 
	
	if (pass1 !=""){
		if(pass1.length >= 6) {
			return createValidationObject(true, "","pass1");
		} else {
			return createValidationObject(false, common_passwordlength, "pass1");	
		}
	} else {
		return createValidationObject(false, common_emptypassword,"pass1");
		
	}

}


function validatePassword2 () {
	if ($('#confirmPassword').css("display") =="none") {
		return createValidationObject(true, "", "pass2");
	}
		
	var pass1 = $('#pass1').val();
	var pass2 = $('#pass2').val();

	if (pass2 != pass1){
		if (pass2.length != 0) {
			return createValidationObject(false, common_passwordsnotequal, "pass2");
		} else {
			return createValidationObject(false, common_emptyconfirmpassword, "pass2");
		}
	} else {
		if (pass2.length != 0) {
			return createValidationObject(true, "", "pass2");
		} else {
			return createValidationObject(false, "");
		}
	}
}

function validateEmail() {
	var email = $('#userEmail').val(); 
	if (isValidEmailAddress(email)){
		return createValidationObject(true, "","userEmail");
	} else {
		return createValidationObject(false, common_invalidemail, "userEmail");	
	}
	
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}
function signUpCheck(){
	
	var username = $('#userName').val();
	
	$.ajax({
		url: "/user/checkUserName?userName="+username,
		type: "GET",
		success: function(html){
			if(html == 'false'){
				var html = 'User name in use.';
				showErrorMessage(html);
			}else{
				validateUserEmail();
			}
		}
	});
}

function validateUserEmail(){
	
	var userEmail = $('#userEmail').val();
		
	$.ajax({
		url: "/user/checkUserEmail?userEmail="+userEmail,
		type: "GET",
		success: function(html){
			if(html == 'false'){
				var html = 'User email in use.';
				showErrorMessage(html);
			}else{
				if (validateSignUpForm()) {
					submitIfValidCheckCode();
				}
			}
		}
	});

}

function submitIfValidCheckCode(){
	if($('#checkCode').val() != ""){
		var url = /* urlInHttps(webPath + */"/captcha/"+$('#checkCode').val()/* ) */;
		$.ajax({
			url: url,
			type: "GET",
			success: function(html){
				markElement("checkCode",true);
				$('#signupForm').submit();
			},
			error: function(html){
				markElement("checkCode",false);
				showErrorMessage(common_checkcodewrong);
				
				$('#ccode').attr('src',webPath+'/captcha?'+Math.random());
			}
		});
	} else {
		markElement("checkCode", false);
		showErrorMessage(common_inputvalidationcode);
	}

}

function flushValidateCode(){
	// set timeout is workaroud for update captcha in IE
	setTimeout(function()
			{									
				$('#ccode').attr('src', '/captcha?_=' + parseInt(Math.random()*1000+1));
			}, 100);
}

function setSignUpMethod(method) {
	$("#signUpMethod").val(method);
	$("#" + method).show();
	var other;
	if (method=="signup") {
		$("#confirmPassword").css("display","");
		other = common_subscribe;
		$("#continueButton img").attr("src",webPattern+"/images/forms_btn_signup.gif");
	} else {
		$("#confirmPassword").hide();
		other = common_signup;
		$("#continueButton img").attr("src",webPattern+"/images/forms_btn_subscribe.gif");
			
	}
	$("#" + other).hide();
	clearValidation();
}

function groupManage(action){

	if(action == "Ban"){
		$('#manageForm').attr('action',webPath+'/group/ban');
	}else if(action == "Remove"){
		$('#manageForm').attr('action',webPath+'/group/remove');
	}else if(action == "SetAsAdmin"){
		$('#manageForm').attr('action',webPath+'/group/setAsAdmin');
	}else if(action == "SetAsMember"){
		$('#manageForm').attr('action',webPath+'/group/setAsMember');
	}else if(action == "Accept"){
		$('#manageForm').attr('action',webPath+'/group/acceptRequest');
	}else if(action == "Restore"){
		$('#manageForm').attr('action',webPath+'/group/restore');
	}
	$('#manageForm').submit();
}

function moveOption(e1, e2){
	try{
		for(var i = 0; i < e1.options.length; i++){
			if(e1.options[i].selected){
				var e = e1.options[i];
				e2.options.add(new Option(e.text, e.value));
				e1.remove(i);
				i = i - 1;
			}
		}
		$("#friendNames").value=getvalue($('#friend2'));
	}catch(e){}
}
function getvalue(geto){
	var allvalue = "";
	for(var i = 0; i < geto.options.length; i++){
		allvalue += geto.options[i].value + ",";
	}
	return allvalue;
}
function moveAllOption(e1, e2){
	try{
		for(var i = 0;i < e1.options.length; i++){
			var e = e1.options[i];
			e2.options.add(new Option(e.text, e.value));
			e1.remove(i);
			i = i - 1;
		}
		$("#friendNames").value=getvalue($('#friend2'));
	}
	catch(e){
	
	}
}
function choosefriend(){
	if ($("#choosefriend").css("display") == "none"){
		$("#choosefriend").show();
	}else{
		$("#choosefriend").hide();
	}
}
function inviteSubmit(){
	$("#topicForm").submit();
}

function checkword(){
	var v = $("#recInput").val();
	var recInput = document.getElementById("recInput");
	var width=parseInt(30)+v.length*8;
	recInput.style.width = width+"px";
}
function inputFriend(){
	var v = $("#recInput").val();
	var recInput = document.getElementById("recInput");
	if ($.trim(v).length>0){
		chooesFriend(v);
	}
	
	$("#recInput").val("");
	recInput.style.width = "30px";
}

function mybirthday(){
	var birthday_year = $('#birthday_year').val();
	var birthday_mon = $('#birthday_mon').val();
	var birthday_day = $('#birthday_day').val();
	$('#birthday_exchanger').val(birthday_year+'-'+birthday_mon+'-'+birthday_day);
	setbirthday();
}
function doRegister(){
	top.location.href = webPath + "/signup";
}
function bookmarkCallback(id){
	var img = '<span style="margin:0;"><img class="with_tooltip" src="'+webPattern+'/images/ico_thumbs_up_hover.png" title="'+common_youhavesaved+'"></img></span>';
	$('#' + id).replaceWith(img);
	initTooltips();
}

function recommendCallback(id){
	bookmarkCallback(id);
}

function showLikes(object, countLikes) {
	$(object).html(countLikes + ' likes');
}

function showDislikes(object, countDislikes) {
	$(object).html(countDislikes + ' dislikes');
}

function rateURL(url, id, value, prefix){
	var _prefix = prefix || "";
	var params = {
		getImgClass: function(){
			if(value == 1){
				return $('#' + _prefix + 'like' + id).attr('class');
			}else{
				return $('#' + _prefix + 'dislike' + id).attr('class');
			}
		},
		getLinkClass: function(){
			if(value == 1){
				return $('#' + _prefix + 'dislike' + id).attr('class');
			}else{
				return $('#' + _prefix + 'like' + id).attr('class');
			}		
		},
		getImgStyle: function(){
			if(value == 1){
				return $('#' + _prefix + 'like' + id).attr('style');
			}else{
				return $('#' + _prefix + 'dislike' + id).attr('style');
			}
		},
		getLinkStyle: function(){
			if(value == 1){
				return $('#' + _prefix + 'dislike' + id).attr('style');
			}else{
				return $('#' + _prefix + 'like' + id).attr('style');
			}
		}
	};

	var img = '<span class="{0}" id="{1}" src="' + webPath + '{2}" style="{3}">{4}</span>';
	var link = '<a onclick="rateURL(\'{0}\', \'{1}\', {2}, \'{3}\')" id="{4}" href="javascript:void(0)" style="{5}" class="{6}">{7}</a>';
	var changeHTML = function(imgType, linkType, imgCount, linkCount, imgPath, ratingValue){
		var imgText = ratingValue == 1 ? hopsurf_likedisliked_dislikes : hopsurf_likedisliked_likes;
		var linkText = ratingValue == 1 ? hopsurf_likedisliked_likes : hopsurf_likedisliked_dislikes;
		$('#' + imgType + id).replaceWith(img.template(params.getImgClass(), imgType + id, imgPath, params.getImgStyle(), imgCount + ' ' + imgText));
		$('#' + linkType + id).replaceWith(link.template(url, id, ratingValue, _prefix, linkType + id, params.getLinkStyle(), params.getLinkClass(), linkCount + ' ' + linkText));
	};

	switch(parseInt(value)){
	case 1: 
		showLikes($(this).parent().find('a.vote'),parseInt($(this).parent().find('a.vote').html()) + 1);
		break;
	case -1:
		showDislikes($(this).parent().find('a.votebad'),parseInt($(this).parent().find('a.votebad').html()) + 1);
		break;
	}

	
	$.ajax({
		url: webPath + "/rating/" + value,
		type: "POST",
		beforeSend: function(xhr){
			xhr.setRequestHeader('Location', url);
		},
		error: function(){
			
		},
		success: function(xml){
			var countLikes = $('likes', xml).text();
			var countDislikes = $('dislikes', xml).text();
			if(value == 1){
				changeHTML(_prefix + 'like', _prefix + 'dislike', countLikes, countDislikes, webPattern+"/images/ico_thumbs_up_hover.png", -1);
			}else{
				changeHTML(_prefix + 'dislike', _prefix + 'like', countDislikes, countLikes, webPattern+"/images/ico_thumbs_down_hover.png", 1);
			}
		}	
	});
}
function userRateURL(user,url, id, value, prefix){
	var _prefix = prefix || "";
	var params = {
		getImgClass: function(){
			if(value == 1){
				return $('#' + _prefix +user+ 'like' + id).attr('class');
			}else{
				return $('#' + _prefix +user+'dislike' + id).attr('class');
			}
		},
		getLinkClass: function(){
			if(value == 1){
				return $('#' + _prefix +user+ 'dislike' + id).attr('class');
			}else{
				return $('#' + _prefix +user+ 'like' + id).attr('class');
			}		
		},
		getImgStyle: function(){
			if(value == 1){
				return $('#' + _prefix +user+ 'like' + id).attr('style');
			}else{
				return $('#' + _prefix +user+ 'dislike' + id).attr('style');
			}
		},
		getLinkStyle: function(){
			if(value == 1){
				return $('#' + _prefix +user+ 'dislike' + id).attr('style');
			}else{
				return $('#' + _prefix +user+ 'like' + id).attr('style');
			}
		}
	};
	
	var img = '<span class="{0}" id="{1}" src="' + webPath + '{2}" style="{3}">{4}</span>';
	var link = '<a onclick="userRateURL(\'{0}\', \'{1}\',  \'{2} \', {3}, \'{4}\')" id="{5}" href="javascript:void(0)" style="{6}" class="{7}">{8}</a>';
	var changeHTML = function(imgType, linkType, imgCount, linkCount, imgPath, ratingValue){
		var imgText = ratingValue == 1 ? hopsurf_likedisliked_dislikes : hopsurf_likedisliked_likes;
		var linkText = ratingValue == 1 ? hopsurf_likedisliked_likes : hopsurf_likedisliked_dislikes;
// alert(link.template(user,url, id, ratingValue, _prefix, linkType + id,
// params.getLinkStyle(), params.getLinkClass(), linkCount + ' ' + linkText));
		$('#' + imgType + id).replaceWith(img.template(params.getImgClass(), imgType + id, imgPath, params.getImgStyle(), imgCount + ' ' + imgText));
		$('#' + linkType + id).replaceWith(link.template(user,url, id, ratingValue, _prefix, linkType + id, params.getLinkStyle(), params.getLinkClass(), linkCount + ' ' + linkText));
	};

	switch(parseInt(value)){
	case 1: 
		showLikes($(this).parent().find('a.vote'),parseInt($(this).parent().find('a.vote').html()) + 1);
		break;
	case -1:
		showDislikes($(this).parent().find('a.votebad'),parseInt($(this).parent().find('a.votebad').html()) + 1);
		break;
	}

	
	$.ajax({
		url: webPath + "/rating/" + value,
		type: "POST",
		beforeSend: function(xhr){
			xhr.setRequestHeader('Location', url);
		},
		error: function(){
			
		},
		success: function(xml){
			var countLikes = $('likes', xml).text();
			var countDislikes = $('dislikes', xml).text();
			if(value == 1){
				changeHTML(_prefix+user+'like', _prefix+user+'dislike', countLikes, countDislikes, webPattern+"/images/ico_thumbs_up_hover.png", -1);
			}else{
				changeHTML(_prefix+user+'dislike', _prefix+user+'like', countDislikes, countLikes, webPattern+"/images/ico_thumbs_down_hover.png", 1);
			}
		}	
	});
}

function ftSearch(searchquery,page,contentRating){
	var action = {
			tags: ftPath + '/search/searchByTag?page='+page+'&contentRating='+contentRating+'&search=',
			keywords: ftPath + '/search/searchByKeyword?page='+page+'&contentRating='+contentRating+'&search='
		};
		var query=$.trim(searchquery);

		if(query != ""){
			var where=$("#search_area").val();
			var searchStr = action[where] + encodeURI(encodeURI(query));
			searchStr = searchStr+"&callback=?";		
			
			$.getJSON(searchStr,function(json){
				var code='<div class="websites">';
				var tags="";
				var likeordislike="";
				var urlIDs="";
				var siteinfo="";
				var contentRating="";
				if(json!=null){
					if(json.urls.records.length>0){
						$('.arr_div').show();
						$('.empty_message').hide();
						
						for(var i=0; i<json.urls.records.length; i++ ){
							for(var j=0; j<json.urls.records[i].urlTags.length; j++ ){
								tags+='<a href="'+webPath+'/web/getURLs?searchTag='+json.urls.records[i].urlTags[j].urlTagId.tag.tag+'">'+json.urls.records[i].urlTags[j].urlTagId.tag.tag+'</a>';
							}
							likeordislike='<span id="like'+json.urls.records[i].urlid+'" class="vote">  '+json.urls.records[i].countLikes+' likes </span><span id="dislike'+json.urls.records[i].urlid+'" class="votebad"> '+json.urls.records[i].countDislikes+' dislikes </span>';
							siteinfo='<p class="site_info">';
							if (contextUserName==""){
								siteinfo='<p class="site_info disable_hover">';
							}
							if (json.urls.records[i].contentRating=="GENERAL"){
								contentRating='';
							}else if (json.urls.records[i].contentRating=="RESTRICTED"){
								contentRating='<img class="rating_watermark" src="'+webPattern+'/images/watermark_rrated.png"/>';
							}else if (json.urls.records[i].contentRating=="XXX"){
								contentRating='<img class="rating_watermark" src="'+webPattern+'/images/watermark_xrated.png"/>';
							}else{
								contentRating='<img class="rating_watermark" src="'+webPattern+'/images/watermark_malicious.png"/>';
							}
							code+='<div class="clearfix"><p class="buttons"><a class="btn_report" href="#">Report</a></p><ul class="report_submenu"></ul><a style="position: relative;" href="'+webPath+'/web/websiteReviews?urlId='+json.urls.records[i].urlid+'" title="'+json.urls.records[i].urlTitle+'" target="_blank" class="screenshot"><img height="90" border="0" width="120" src="http://70.87.178.26:8090/image/img?url='+json.urls.records[i].url+'"/>'+contentRating+'</a><h3 class="with_tooltip"><span class="with_tooltip" title="'+json.urls.records[i].urlTitle+'">'+json.urls.records[i].urlTitle+'</span></h3><h4><a href="'+webPath+'/toolbar-api/toolbar?url='+json.urls.records[i].url+'" id="url'+json.urls.records[i].urlid+'">'+json.urls.records[i].url+'</a></h4>'+siteinfo+'<a class="discoverer with_tooltip" title="Discovered by '+json.urls.records[i].url+'" href="'+webPath+'/people/showSummary?userName='+json.urls.records[i].discoverer.userName+'"> <img  id="photo'+json.urls.records[i].urlid+'" height="20" border="0" width="20" src=""/> <span style="color: rgb(36, 72, 0); padding-right: 0px; display: inline; float: none; position: relative; top: -8px;" class="discoverer_name">'+json.urls.records[i].discoverer.userName+' </span></a><span style="color: rgb(194, 194, 194); font-size: 10px;">'+json.urls.records[i].lastModifiedTime+' </span>	<span id="likeordislike'+json.urls.records[i].urlid+'">'+likeordislike+'</span><a class="num_comments" href="'+webPath+'/web/websiteReviews?urlId='+json.urls.records[i].urlid+'">'+json.urls.records[i].countReviews+' reviews</a><span class="tags">'+tags+'</span></p></div>';
							tags="";
							urlIDs+=json.urls.records[i].urlid+",";
							
						}
					}else{
						$('.arr_div').hide();
						$('.empty_message').show();
					}

				}
				code += '</div>';
				$("#jswebsites").html(code);
				if(urlIDs!=""){
					loadBookmarkStatus(urlIDs);
				}
				
			});
		}
		
}
function loadBookmarkStatus(urlIDs){
	var action=webPath+'/search/bookmarkStatus?urlIDs='+urlIDs+'&callback=?';
	$.getJSON(action,function(json){
		var url;
		var countLikes;
		var countDislikes;
		var likeordislike;
		for(var i=0; i<json.bookmarkStatus.length; i++ ){
			url=$("#url"+json.bookmarkStatus[i].urlID).html();
			countLikes=$("#like"+json.bookmarkStatus[i].urlID).html();
			countDislikes=$("#dislike"+json.bookmarkStatus[i].urlID).html();
			if(json.bookmarkStatus[i].status==1){
				likeordislike='<span id="like'+json.bookmarkStatus[i].urlID+'" class="vote likdislike">'+countLikes+' </span><a title="Add to Disliked" class="votebad likdislike" href="javascript:void(0)" id="dislike'+json.bookmarkStatus[i].urlID+'" onclick="rateURL(\''+url+'\', \''+json.bookmarkStatus[i].urlID+'\', -1, \'\')">'+countDislikes+' </a>';
			}else	if(json.bookmarkStatus[i].status==-1){
				likeordislike='<a id="like'+json.bookmarkStatus[i].urlID+'" class="vote likdislike" title="Add to Liked" href="javascript:void(0)" onclick="rateURL(\''+url+'\', \''+json.bookmarkStatus[i].urlID+'\', 1, \'\')">'+countLikes+'</a><span id="dislike'+json.bookmarkStatus[i].urlID+'" class="votebad likdislike"> '+countDislikes+' </span>';
			}else{
				likeordislike='<a id="like'+json.bookmarkStatus[i].urlID+'" class="vote likdislike" title="Add to Liked" href="javascript:void(0)" onclick="rateURL(\''+url+'\', \''+json.bookmarkStatus[i].urlID+'\', 1, \'\')">'+countLikes+'</a><a title="Add to Disliked" class="votebad likdislike" href="javascript:void(0)" id="dislike'+json.bookmarkStatus[i].urlID+'" onclick="rateURL(\''+url+'\', \''+json.bookmarkStatus[i].urlID+'\', -1, \'\')">'+countDislikes+' </a>';
			}
			$("#likeordislike"+json.bookmarkStatus[i].urlID).html(likeordislike);
			$("#photo"+json.bookmarkStatus[i].urlID).attr("src",json.bookmarkStatus[i].photo);
		}
	});
}

function decideHasHtml(){
	clearErrorMessage();
	var inputStr=$(".decideHasHtml");
	if(typeof decideHasHtmlSize!='undefined'){
		if (inputStr.length != decideHasHtmlSize){
			showErrorMessage(common_decidehashtmlsize);
			return false;
		}
	}
	
	for (var i=0; i<inputStr.length;i++){
		if (/<.*?>/g.test($(inputStr.get(i)).val())){
			showErrorMessage(common_decidehashtml);
			$("#"+$(inputStr.get(i)).attr("id")).val($(inputStr.get(i)).val().replace(/<.*?>/g,""));
			$("#"+$(inputStr.get(i)).attr("id")).focus();
			return false;
			break;
		}
	}
	return true;
}

function ajaxFileUpload(url, isSecure){ //upload photo
	if($("#fileToUpload").val().length<=0){
		showErrorMessage(hopsurf_regstarted_selectyourpicture);//Please select your picture.
		return false;
	}
	if(!/[^\\]+(\.)(gif|jpg|jpeg|png|bmp|jpe|JPG|GIF|JPEG|PNG|BMP|JPE)$/.test($("#fileToUpload").val())){
        showErrorMessage(common_pictypeerror);//File types can be .png, .bmp, .gif, .jpeg only.
		return false;
	}
	$("#picture").ajaxStart(function(){
		$(this).attr('src',webPattern+'/images/ajax-loader.gif');
	});
	var path = "";
	if (isSecure) {
		path = webPathSecure + url;
	} else {
		path = webPath +url;
	}	
	$.ajaxFileUpload({
			url:path,
			secureuri:isSecure,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data, status){
				//alert("xxx"+data.error);
				$("#picture").attr('src',data.src+'?'+parseInt(Math.random()*1000+1));
				if(typeof(data.error) != 'undefined'){
					if(data.error != '' && data.error != 'null'){
						showErrorMessage(data.error);
					}else{
						showErrorMessage(data.msg);
					}
				}
			},
			error: function (data, status, e){
				alert(e);
			}
		}
	);
	return false;
}

function userSuccess(){ // reg step Confirmed And Saved
				$("#success_name").html($("#firstName").val()+" "+$("#lastName").val());
				$("#success_email").html($("#userEmail").val());
				$("#success_birthday").html($("#birthday_exchanger").val());
				$("#success_gender").html($("#gender").val());
				$("#success_city").html($("#city").val());
				$("#success_state").html($("#state").val());
				$("#success_country").html($("#country").val());
				$("#success_timezone").html($("#timeZone").val());
				document.getElementById("success_picture").src=document.getElementById("picture").src;
				var gender=document.getElementsByName("userInfo.personalInfo.gender");
				for(var i=0;i<gender.length;i++){
					if (gender[i].checked){
						if (gender[i].value==1){
							$("#success_gender").html("Male");
						}else{
							$("#success_gender").html("Female");
						}
					}
				}
				$("#success_interests").html("<h2>"+hopsurf_people_interests+"</h2>");
				var interests=document.getElementsByName("interest.interestName");
				var noChecked=true;
				var categoryName="";
				var id;
				for(var i=0;i<interests.length;i++){
					if (interests[i].checked){
						noChecked=false;
						id="success_"+$.trim(interests[i].value.replace("/","").replace(" ",""));
						if(categoryName!=document.getElementById(id).value){
							categoryName=document.getElementById(id).value;
							if ($("#success_interests_"+categoryName).length == 0){
								$("#success_interests").append('<p id="success_interests_'+categoryName+'" class="fieldLabel clearfix"><b>'+categoryName+'</b><br></p>');
							}
						}
						$("#success_interests_"+categoryName).append("<span>"+interests[i].value+"</span>");
					}
				}
				if (noChecked){
					$("#success_interests").append('<p class="fieldLabel clearfix">'+common_notchooseinterested+'</p>');
				}
				
		}
		
		function regstep(v){ // reg step wizard
			if(!decideHasHtml()){
				return false;
			}
			$("#"+v).css("display","");
			
			for(var i=1;i<5;i++){
				$("#s"+i).removeClass("current");
				$("#s"+i).removeClass("lastDone");
				$("#s"+i).removeClass("done");
				if (i!=v){
					$("#"+i).css("display","none");
				}else{
					$("#s"+v).addClass("current");
				}
				if (i<v){
					$("#s"+i).removeClass("current");
					$("#s"+i).removeClass("lastDone");
					$("#s"+i).addClass("done");
				}
				if (i==v-1){
					$("#s"+i).removeClass("current");
					$("#s"+i).removeClass("done");
					$("#s"+i).addClass("lastDone");					
				}

			}
			if (v==4){
				$("#s"+v).css("background-image","none");
			}
			
		}
function setbirthday(){
	var today=new Date();
	var birthday = $("#birthday_exchanger").val();
	birthday = birthday.replace(/-/g, "/");
	birthday = new Date(birthday);

	var years= today.getFullYear() - birthday.getFullYear();
	if ($('#personal_information').length>0){
		if (years<18||$("#birthday_year").val()=="1000"||$("#birthday_day").val()=="00"||$("#birthday_mon").val()=="00"){

			$("#myContentRatingXXX").attr("disabled",true);
			$("#myContentRatingRESTRICTED").attr("disabled",true);
			$("#ico_rating_x").attr("src",webPattern+"/images/ico_rating_x_disabled.png");
			$("#ico_rating_r").attr("src",webPattern+"/images/ico_rating_r_disabled.png");
			$("label[for='myContentRatingXXX'] span").css({position:"relative", top:"-5px", color:"#cccccc"});
			$("label[for='myContentRatingRESTRICTED'] span").css({position:"relative", top:"-5px", color:"#cccccc"});
			var a = document.getElementsByName("preferredContentRating");
		
			a[0].checked;

			$("label[for='myContentRatingXXX']").removeClass("radio_checked");
			$("label[for='myContentRatingXXX']").addClass("radio_unchecked");

			$("label[for='myContentRatingRESTRICTED']").removeClass("radio_checked");
			$("label[for='myContentRatingRESTRICTED']").addClass("radio_unchecked");
			
			$("label[for='myContentRatingGENERAL']").removeClass("radio_unchecked");
			$("label[for='myContentRatingGENERAL']").addClass("radio_checked");
			
		}else{
			$("#myContentRatingXXX").attr("disabled",false);
			$("#myContentRatingRESTRICTED").attr("disabled",false);
			$("#ico_rating_x").attr("src",webPattern+"/images/ico_rating_x.png");
			$("#ico_rating_r").attr("src",webPattern+"/images/ico_rating_r.png");
			$("label[for='myContentRatingXXX'] span").css({position:"relative", top:"-5px", color:"#333333"});
			$("label[for='myContentRatingRESTRICTED'] span").css({position:"relative", top:"-5px", color:"#333333"});
		}
	}

}		

function setRemoveBookmark(url, title, tags, status,last){
	$('#deletemybookmark').attr('href','javascript:OfflineBookmark.removeBookmark("'+url+'","'+title+'","'+tags+'","'+status+'",'+last+')');
}

function showMoreReviews(urlID, count){
	count += 5;		
	updateAdditionalInfo('site_info'+urlID, urlID,count);	
//	updateNfControlsState('${urlInfo.url}', '${urlInfo.urlID}', 1, 'newsFeed');
//	updateEditMessage(urlID,'Edit your own Review'); 
//	$('#reviewLink'+urlID).trigger('click');
	return false;
}	

function appendNewReviewComment(urlID,url,prefix, status, count){
	if (editNewsFeedCommentOnClick(urlID,url,prefix, status) == true){
		updateAdditionalInfo('site_info' + urlID, urlID,count);
		var digitState = 1;
		if (status == 'dislike'){
			digitState = -1;
		}		
		updateNfControlsState(url, urlID, digitState, prefix);
		updateEditMessage(urlID,'Add your own Review '); //Edit your own Review
//		$('#reviewLink'+urlID).trigger('click');
		
	}
	return false;
}	
function  selectmail(v){
	 $("input[name='selectMessageID']").each(function(){
	 	if (v=="select"){
			$(this).attr("checked",true);
		}else{
			$(this).attr("checked",false);
		}
     }); 

}

//word break;
function fnBreakWordAll(o){
	var o = o || {},
	iWord = o.word || 13,
	sRe = o.re || '[a-zA-Z0-9]',
	bAll = o.all || false,
	sClassName = o.className || 'wordwrap',
	aEls = o.els || (function(){
		var aEls = [],
		aAllEls = document.getElementsByTagName('*'),
		re = new RegExp('(?:^|\\s+)' + sClassName + '(?:\\s+|$)');
		for(var i =0,iLen = aAllEls.length; i < iLen ; ++i){
			if(re.test(aAllEls[i].className)){
				aEls[aEls.length] = aAllEls[i]; 
			}
		}
		return aEls;
	})() || [],
	fnBreakWord = function(oEl){ 
	
		if(!oEl || oEl.nodeType !== 1){
			return false;
//		} else if(oEl.currentStyle && typeof oEl.currentStyle.wordWrap === 'string'){
//			breakWord = function(oEl){
//				oEl.runtimeStyle.wordWrap = 'break-word';
//				return true;
//			}
//			return breakWord(oEl);
		}else if(document.createTreeWalker){
			var trim = function  (str) {
				str = str.replace(/^\s\s*/, '');
				var ws = /\s/,
				i = str.length;
				while (ws.test(str.charAt(--i)));
				return str.slice(0, i + 1);
			};
		
			breakWord = function(oEl){
				var dWalker = document.createTreeWalker(oEl, NodeFilter.SHOW_TEXT, null, false);
				var node,s,c = String.fromCharCode('8203'),
				//re = /([a-zA-Z0-9]{0,13})/;
				re = new RegExp('('+ sRe +'{0,' + iWord + '})');
				while (dWalker.nextNode()){
					node = dWalker.currentNode;
					s = trim(node.nodeValue).split(re).join(c);
					node.nodeValue = s;
				}
				return true;
			};
		
			return breakWord(oEl);
		}
	};
	
	for(var i=0,n=aEls.length; i<n; ++i){
		var sUa = navigator.userAgent,
		sTn = aEls[i].tagName.toLowerCase() ;
		if((/Opera/).test(sUa) || (/Firefox/).test(sUa) || ((/KHTML/).test(sUa) && (sTn === 'td' || sTn === 'th')) || bAll){
			fnBreakWord(aEls[i]);
		}
	}
	
}


var dateSelection = {
	writeYears:function writeYears(obj, date){
		var years = date.getFullYear()+100;
		for (var i=1949; i<2010; i++)
		{
			var opt = document.createElement("option");
			opt.text = i;
			opt.value = i;
			obj.options.add(opt);
		}
	},
	writeMonths:function (obj){
		for (var i=1; i<13; i++){
			var opt = document.createElement("option");
			opt.text = opt.value = Math.floor(i/10) ? i : "0"+i;
			obj.options.add(opt);
		}
	},
	writeDate:function (obj, year, month){
		if (year=="00"){
			year="2000";
		}
		var date = new Date(""+year+"/"+(parseInt(month)+1)+"/"+0).getDate();
		var selectedIndex = date<=obj.selectedIndex ? date: obj.selectedIndex;
		var len = obj.options.length-1;
		if (date>len){
			for (var i=len+1; i<=date; i++){
				var opt = document.createElement("option");
				opt.text = opt.value = Math.floor(i/10) ? i : "0"+i;
				obj.options.add(opt);
			}
		}else{
			for (var i=date; i<len; i++) {
				obj.remove(obj.length-1);
			}
		}
		
		obj.selectedIndex = selectedIndex;
	},
	changeDate:function() {
		var c_year = eval('document.getElementById("birthday_year")');
		var c_month = eval('document.getElementById("birthday_mon")');
		var c_day = eval('document.getElementById("birthday_day")');
		if (c_year!="00"&&c_month!="00")
		dateSelection.writeDate(c_day, c_year.value, c_month.value);
	},
	initDate:function(){
		var now = new Date();
		dateSelection.writeYears(document.getElementById("birthday_year"), now);
		$("#birthday_year").val(now.getFullYear());
		dateSelection.writeMonths(document.getElementById("birthday_mon"));
		var this_month = now.getMonth()+1;
		if (this_month<10){this_month = "0"+this_month;}
		$("#birthday_mon").val(this_month);
		dateSelection.writeDate(document.getElementById("birthday_day"), now.getFullYear(), now.getMonth()+1);
		nowday = now.getDate();
		if (nowday<10){nowday="0"+(now.getDate())*1;}
		$("#birthday_day").val(nowday);
	}
};

var nfocusName;
function displayFocus(focusName){

	if(typeof(focusName)=="object"){
		var id = $(focusName).attr("id");
		var nid = $(nfocusName).attr("id");
		$("label[for='"+nid+"'] span").removeClass("focus_bg");
		$("label[for='"+id+"'] span").addClass("focus_bg");
	}else{
		$("#focus_"+nfocusName).removeClass("focus_bg");
		$("#focus_"+focusName).addClass("focus_bg");
	}
	
	nfocusName = focusName;
}





