var fan_wall_max_length = 750;
var fan_avatar_default_width = 80;
var fan_avatar_default_height = 80;
var fan_avatar_small_width = 50;
var fan_avatar_small_height = 50;
var built_wall_comment_forms = Array();
var fan_wall_scraps = Array();
var fan_users = Array();
var fan_logged_user_session = null;
var fan_available_transliterations = {
//	en:'English',
	ar:'Arabic',
	bn:'Bengali',
	gu:'Gujarati',
	hi:'Hindi',
	kn:'Kannada',
	ml:'Malayalam',
	mr:'Marathi',
	ne:'Nepali',
	fa:'Persian',
	pa:'Punjabi',
	ta:'Tamil',
	te:'Telugu',
	ur:'Urdu'
};

var fan_wall_availability_dictionary = {
	public:'Public',
	idols_fans:'Friends & Fans',
	idols:'Friends',
	private:'Private'
};

var fan_transliterationControl = false;


fanDeleteCookie('fan_client_op');
fanDeleteCookie('fan_client_user_id');
fanDeleteCookie('fan_msg_id');
fanDeleteCookie('fan_save_draft');
fanDeleteCookie('fan_refresh_wall');

$(document).ready(function()	{
	$('.fan_wall_textarea').markItUp(fan_markitup_bb_settings);
});

function fanSetCookie(name,value,expires,path,domain,secure) {
	if(!expires){
		expires = 315360000000; // 10 years
	}
	
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
	
    var cookieString = name + "=" +escape(value) + 
       ( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
       ( (path) ? ";path=" + path : "") + 
       ( (domain) ? ";domain=" + domain : "") + 
       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
}

function fanGetCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

function fanDeleteCookie(name, path, domain) {
	if (fanGetCookie(name)){
		document.cookie = name + "=" +
		((path)?";path="+path:"") +
		((domain)?";domain="+domain:"") +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

function fan_center_avatar(img_element){
	var required_width = fan_avatar_default_width;
	var required_height = fan_avatar_default_height;
	if(typeof(img_element.avatar_size)=='string' && img_element.avatar_size=='small'){
		required_width = fan_avatar_small_width;
		required_height = fan_avatar_small_height;
	}
	
	if(img_element.width>0 && img_element.height>0){
		var width_index = required_width / img_element.width;
		var height_index = required_height / img_element.height;
	
		var resize_index = Math.max(width_index, height_index);
		
		if(resize_index!=1){
			//use buffer values to avoid deforming the image
			var new_width = img_element.width * resize_index;
			var new_height = img_element.height * resize_index;
				
			if(resize_index<1){
				img_element.style.width = ''+new_width+'px';
				img_element.style.height = ''+new_height+'px';
			}
		}
	}
	else{
		setTimeout(function(){fan_center_avatar(img_element)}, 100);
		return;
		img_element.style.maxWidth = ''+required_width+'px';
		img_element.style.maxHeight = ''+required_height+'px';
	}
			
	//center the picture
	if(img_element.width!=required_width && (required_width - img_element.width)<0){
		img_element.style.left = '' + Math.round((required_width - img_element.width)/2) + 'px';
	}
	if(img_element.height!=required_height){
		img_element.style.top = '' + Math.round((required_height - img_element.height)/2) + 'px';
	}
}

function fan_go_to_page(page_param, page_value){
	fanSetCookie(page_param,page_value);
	window.location.reload();
}

var fan_wall_post_initiated_img_fields = Array();
function fan_init_wall_image_input(btn_elem, container_id, display){
	var container = document.getElementById(container_id);
	
	if(typeof(fan_wall_post_initiated_img_fields[container_id])!='object'){
		
		var image_container = document.createElement('table');
		image_container.className = 'fan_wall_extra_input_table';
		image_container.style.display = 'none';
		var temp_tbody = document.createElement('tbody');
		image_container.appendChild(temp_tbody);
		var temp_tr = document.createElement('tr');
		temp_tbody.appendChild(temp_tr);
		
		var label_td = document.createElement('td');
		label_td.className = 'fan_wall_extra_input_label';
		label_td.innerHTML = 'Image';
		
		var input_td = document.createElement('td');
		var file_input = document.createElement('input');
		file_input.type = 'file';
		file_input.name = 'scrap_image';
		input_td.appendChild(file_input);
		
		var text_input = document.createElement('input');
		text_input.type = 'text';
		text_input.name = 'scrap_image_url';
		fan_setFieldTempValue(text_input, 'image URL', true);
		input_td.innerHTML += '<br />or<br />';
		input_td.appendChild(text_input);
		
		temp_tr.appendChild(label_td);
		temp_tr.appendChild(input_td);
		
		fan_wall_appeant_as_first_extra_input(container, image_container);
		
		fan_wall_post_initiated_img_fields[container_id] = image_container;
	}
	
	if(!display || display=='toggle'){
		if(!fan_wall_post_initiated_img_fields[container_id].style.display){
			display = 'none';
			container.image_active = false;
			if((typeof(container.video_active)!='boolean' || !container.video_active) && (typeof(container.link_active)!='boolean' || !container.link_active)){
				fan_hide_submit_btn2extra_container(container);
			}
		}
		else{
			display = '';
			container.image_active = true;
			fan_show_submit_btn2extra_container(container);
		}
	}
	
	fan_wall_post_initiated_img_fields[container_id].style.display = display;
}

var fan_wall_share_msg_style = {
	color:'#336B30',
	fontSize:'16px',
	fontFamily:'arial'
}

function fan_fieldTempValue(fieldElem, caption, restore, style_attributes){ 
	if(restore){
		var current_val = $.trim(fieldElem.value);
		if(!current_val){
			fieldElem.old_styles = Array();
			if(typeof(style_attributes)=='object'){
				for(var attr_name in style_attributes){
					try{
						eval ('fieldElem.old_styles.'+attr_name+'=fieldElem.style.'+attr_name);
					}
					catch(E){
						eval ('fieldElem.old_styles.'+attr_name+'=""');
					}
					eval ('fieldElem.style.'+attr_name+'=style_attributes.'+attr_name);
				}
			}
			fieldElem.value = caption;
		}
	}
	else{
		if(fieldElem.value == caption){
			for(var attr_name in fieldElem.old_styles){
				eval ('fieldElem.style.'+attr_name+'=fieldElem.old_styles.'+attr_name);
			}
			fieldElem.value = '';
		}
	}
}

function fan_setFieldTempValue(fieldElem, caption, set_now, style_attributes){
    
	if(set_now){
		fan_fieldTempValue(fieldElem,caption,true, style_attributes);
	}
	
	var old_onfocus = fieldElem.onfocus;
	fieldElem.onfocus = function(){
		if(typeof(old_onfocus)=='function'){
			old_onfocus();
		}
		fan_fieldTempValue(fieldElem,caption,false, style_attributes);
	}
	
	var old_onblur = fieldElem.onblur;
	fieldElem.onblur = function(){
		if(typeof(old_onblur)=='function'){
			try{
				old_onblur()
			}catch(E){}
		}
		fan_fieldTempValue(fieldElem,caption,true, style_attributes);
	}
}

function fan_setFieldPermValue(fieldElem, caption, set_now, style_attributes){
     
	if(set_now){
		fan_fieldTempValue(fieldElem,caption,true, style_attributes);
	}

//	var old_onfocus = fieldElem.onfocus;
//	fieldElem.onfocus = function(){
//		if(typeof(old_onfocus)=='function'){
//			old_onfocus();
//		}
//		fan_fieldTempValue(fieldElem,caption,false, style_attributes);
//	}
//
//	var old_onblur = fieldElem.onblur;
//	fieldElem.onblur = function(){
//		if(typeof(old_onblur)=='function'){
//			try{
//				old_onblur()
//			}catch(E){}
//		}
//		fan_fieldTempValue(fieldElem,caption,true, style_attributes);
//	}
}

var fan_wall_post_initiated_video_fields = Array();
function fan_init_wall_video_input(container_id, input_value, display){
	var container = document.getElementById(container_id);
	
	if(typeof(fan_wall_post_initiated_video_fields[container_id])!='object'){
		var video_container = document.createElement('table');
		video_container.className = 'fan_wall_extra_input_table';
		video_container.style.display = 'none';
		var temp_tbody = document.createElement('tbody');
		video_container.appendChild(temp_tbody);
		var temp_tr = document.createElement('tr');
		temp_tbody.appendChild(temp_tr);
		
		var label_td = document.createElement('td');
		label_td.className = 'fan_wall_extra_input_label';
		label_td.innerHTML = 'Video';
		
		var input_td = document.createElement('td');
		var textarea_input = document.createElement('textarea');
		textarea_input.name = 'scrap_embed_video';
		input_td.appendChild(textarea_input);
		
		temp_tr.appendChild(label_td);
		temp_tr.appendChild(input_td);
		
		fan_wall_appeant_as_first_extra_input(container, video_container)
		
		video_container.video_input = textarea_input;
		
		fan_wall_post_initiated_video_fields[container_id] = video_container;
		
		fan_setFieldTempValue(textarea_input, fan_default_wall_vid_embed_value, true);
		
		textarea_input.onkeyup = function(evt){
			evt = evt || window.event;
			fan_watch_video_input_content(evt, textarea_input, container_id);
		}
	}
	
	if(typeof(input_value)=='string'){
		fan_wall_post_initiated_video_fields[container_id].video_input.value = input_value;
	}
	
	if(typeof(display)!='string' || display=='toggle'){
		if(!fan_wall_post_initiated_video_fields[container_id].style.display){
			display = 'none';
			container.video_active = false;
			if((typeof(container.image_active)!='boolean' || !container.image_active) && (typeof(container.link_active)!='boolean' || !container.link_active)){
				fan_hide_submit_btn2extra_container(container);
			}
		}
		else{
			display = '';
			container.video_active = true;
			fan_show_submit_btn2extra_container(container);
		}
	}
	
	fan_wall_post_initiated_video_fields[container_id].style.display = display;
}

function fan_watch_video_input_content(e, html_textarea, extra_container_id){
	if(html_textarea && typeof(html_textarea)=='object'){
		
		var keynum = fan_get_keynym(e);
		
		var extra_container = document.getElementById(extra_container_id);
		var input_val = html_textarea.value;
		var link_url = null;
		
		var no_video_callback = function(){
			alert ('We did not find any video at the given URL!');
			html_textarea.value = '';
		}
		
		if(keynum==86){ // it there was a paste
			for(var i in fan_link_only_regexps){
				var link_rexexp = fan_link_only_regexps[i];
				while(link_url = input_val.match(link_rexexp)){
					input_val = input_val.replace(link_rexexp, ' ');
					
					var found_link = fan_link_prefixes[i] + link_url[1];
					if(link_url){
						fan_get_link_details(found_link, extra_container, true, true, no_video_callback);
					}
				}
			}
		}
	}
}

var fan_wall_post_extra_submit_btn = Array();
function fan_show_submit_btn2extra_container(extra_container){
	if(typeof(fan_wall_post_extra_submit_btn[extra_container.id])!='object'){
		var submit_btn = document.createElement('input');
		submit_btn.type = 'submit';
		submit_btn.name = 'fan_wall_posted';
		submit_btn.value = 'Submit';
		submit_btn.className = 'fan_default_but';
		
		if(typeof(extra_container.is_draft)=='boolean'){
			submit_btn.value = 'Save';
			submit_btn.onclick = function(){return fan_set_save_draft()};
		}
		
		$(extra_container).find('.fan_wall_extra_but_container').append(submit_btn);
		fan_wall_post_extra_submit_btn[extra_container.id] = submit_btn;
	}
	else{
		fan_wall_post_extra_submit_btn[extra_container.id].style.display = '';
	}
}

function fan_hide_submit_btn2extra_container(extra_container){
	if(typeof(fan_wall_post_extra_submit_btn[extra_container.id])=='object'){
		fan_wall_post_extra_submit_btn[extra_container.id].style.display = 'none';
	}
}

function fan_wall_appeant_as_first_extra_input(extra_container, child_element){
	$(extra_container).find(".fan_wall_extra_but_container").after(child_element);
}

function fan_reload_window(){
	window.location.href = window.location.href;
}

function fan_create_wall_comment_form(msg_id, wall_owner_remote_id, parent_id){
	var placeholder_id = 'fan_comment_plh_wall_'+wall_owner_remote_id+'-'+msg_id;
	var placeholder = document.getElementById(placeholder_id);
	
	if(placeholder){
		if(!built_wall_comment_forms[placeholder_id]){
			fan_create_wall_scrap_form(placeholder, wall_owner_remote_id, parent_id, 'Comment');
			built_wall_comment_forms[placeholder_id] = true;
		}
		
		animatedcollapse.toggle(placeholder_id);
	}
}



function fan_get_user_name(user_name){
	var user_name = '';
	if (typeof(user_details.user_name)=='string' && user_details.user_name) {
		user_name = user_details.user_name;
	}
	else if (typeof(user_details.extra.username)=='string' && user_details.extra.username) {
		user_name = user_details.extra.username;
	}
	else{
		user_name = user_details.name;
	}
	
	return user_name;
}



function fan_print_users(users, container, cat_index, displayed_type){
	if (typeof(users)=='object' && users.length>0) {
		var users_container = document.createElement('div');
		container.appendChild(users_container);
		users_container.className = 'fan_users_container';
				
		for( var i in users) {
			user_details = users[i];
			icons_exist = false;
			user_name = fan_get_user_name(user_details);
			var user_elem_container = document.createElement('div');
			user_elem_container.className = 'fan_user_item_container';
			users_container.appendChild(user_elem_container);
			
			
			var user_item = document.createElement('a');
			user_elem_container.appendChild(user_item);
			user_item.className = 'fan_user_item';
			
			if (typeof(user_details.url)=='string' && user_details.url) {
				user_item.href = user_details.url;
			}
			
			if (typeof(user_details.extra.avatar)=='string' && user_details.extra.avatar) {
				var img_container1 = document.createElement('div');
				img_container1.className = 'fan_user_avatar_container1';
				var img_container2 = document.createElement('div');
				img_container2.className = 'fan_user_avatar_container2';
				img_container2.align = 'center';
				
				var img = document.createElement('img');
				img_container1.appendChild(img);
				img_container2.appendChild(img_container1);
				user_item.appendChild(img_container2);
				img.className = 'fan_user_avatar';
				img.src = user_details.extra.avatar;
				img.onload = function(){ fan_center_avatar(img)};
			}
			
			var username_label = document.createElement('div');
			username_label.innerHTML = user_name;
			username_label.className = 'fan_client_username_label';
			user_item.appendChild(username_label);
			
			var fan_user_item_btn_container = document.createElement('div');
			fan_user_item_btn_container.className = 'fan_user_item_btn_container';
			var but_set_id = 'fan_but_set_'+user_details.remote_id+'~'+Math.random();
			fan_user_item_btn_container.id = but_set_id;
			
			
			// show the email icon
			if (typeof(user_details.extra.public_email)=='string' && user_details.extra.public_email) {
				var email_btn = document.createElement('a');
				fan_user_item_btn_container.appendChild(email_btn);
				email_btn.href = 'mailto:'+user_details.extra.public_email;
				email_btn.className = 'fan_mailto_user_btn';
				email_btn.title = fan_html_entity_decode('email to '+user_name);
				icons_exist = true;
			}
			
			if (fan_logged_user && fan_logged_user!=user_details.user_id){
				var logged_user_details = fan_users[fan_logged_user];
				
				if(typeof(logged_user_details.idols_ids)=='object' && logged_user_details.idols_ids){
					// show not a fan icon
					if (typeof(logged_user_details.idols_ids[user_details.user_id])=='boolean') {
						var remove_fan_btn = document.createElement('a');
						fan_user_item_btn_container.appendChild(remove_fan_btn);
						
						var link_url = 'javascript: ';
						link_url += " fanSetCookie('fan_client_op','not_a_fan');";
						link_url += " fanSetCookie('fan_client_fan_id', '"+fan_logged_user+"');";
						link_url += " fanSetCookie('fan_client_user_id','"+user_details.user_id+"');";
						link_url += ' fan_reload_window();';
				
						remove_fan_btn.href = link_url;
						remove_fan_btn.onclick = function(){
							return confirm('Are you sure you want to remove '+user_name+' as a fan?');
						}
						remove_fan_btn.className = 'fan_not_a_fan_16_ico';
						remove_fan_btn.title = 'Stop Following';
						icons_exist = true;
					}
					
					// show follow icon
					if (typeof(logged_user_details.idols_ids[user_details.user_id])=='undefined') {
						email_btn = document.createElement('a');
						fan_user_item_btn_container.appendChild(email_btn);
						
						var link_url = 'javascript: ';
						link_url += " fanSetCookie('fan_client_op','become_a_fan');";
						link_url += " fanSetCookie('fan_client_fan_id', '"+fan_logged_user+"');";
						link_url += " fanSetCookie('fan_client_user_id','"+user_details.user_id+"');";
						link_url += ' fan_reload_window();';
				
						email_btn.href = link_url;
						email_btn.className = 'fan_become_a_fan_16_ico';
						email_btn.title = 'Follow';
						icons_exist = true;
					}
				}
				
				// show trust user icon
				var trust_btn = document.createElement('a');
				fan_user_item_btn_container.appendChild(trust_btn);
				
				var link_url = 'javascript: ';
				
				if(
					typeof(logged_user_details.extra.trusted_users)!='object' ||
					typeof(logged_user_details.extra.trusted_users[user_details.user_id])!='boolean' ||
					!logged_user_details.extra.trusted_users[user_details.user_id]
				){
					link_url += " fanSetCookie('fan_client_op','trust_user');";
					trust_btn.className = 'fan_trust_16_ico';
					trust_btn.title = 'trust';
				}
				else {
					link_url += " fanSetCookie('fan_client_op','remove_trusted_user');";
					trust_btn.className = 'fan_trust_off_16_ico';
					trust_btn.title = 'do not trust';
				}
				
				link_url += " fanSetCookie('fan_client_user_id', '"+fan_logged_user+"');";
				link_url += " fanSetCookie('fan_client_trusted_id','"+user_details.user_id+"');";
				link_url += ' fan_reload_window();';
		
				trust_btn.href = link_url;
				icons_exist = true;
			}
			
			if (icons_exist) {
				user_elem_container.appendChild(fan_user_item_btn_container);
				user_elem_container.onmouseover = function(){document.getElementById(but_set_id).style.display='block'};
				user_elem_container.onmouseout = function(){document.getElementById(but_set_id).style.display='none'};
			}
			
			user_item.title = fan_html_entity_decode(user_name);
		}
		var clear_float = document.createElement('div');
		clear_float.className = 'fan_clear_both';
		users_container.appendChild(clear_float);
	}
}

var fan_jquery_theme_loaded = false;
function fan_load_jquery_theme(){
	if(!fan_jquery_theme_loaded){
		var style_elem = document.createElement('link');
		style_elem.rel = 'stylesheet';
		style_elem.type = 'text/css';
		style_elem.href = fan_server_url+"/3rd_party/jquery_theme/jquery.ui.all.css";
		
		var fan_doc_head_elem = document.getElementsByTagName('head')[0];
		fan_doc_head_elem.appendChild(style_elem);
		
		fan_jquery_theme_loaded = true;
	}
}

function fan_show_datepicker(input_elem, container){
	var onselect_callback = function(dateText, inst) {
		fan_datepicker_select(dateText, inst, input_elem, container)
	}
	datepicker = $(container).datepicker({onSelect:onselect_callback , dateFormat: 'mm/dd/yy'});
	
	var matches = input_elem.value.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/)
	if(input_elem.value && matches){
		var selected_date = new Date(matches[3],matches[1]-1,matches[2]); 
		datepicker = $(container).datepicker('setDate', selected_date);
	}
}

function fan_datepicker_select(dateText, inst, input_elem, container){
	input_elem.value = dateText;
	
	$(container).datepicker('destroy');
}

function fan_validate_time_input(input_elem, am_pm_format){
	var retVal = false;
	if(typeof(am_pm_format)!='boolean'){
		am_pm_format = false;
	}
	
	if(am_pm_format){
		var matches = input_elem.value.match(/^([0-9]{1,2})\:([0-9]{2})[\s]*(am|pm)$/i);
	}
	else{
		var matches = input_elem.value.match(/^([0-9]{1,2})\:([0-9]{2})$/);
	}

	if(matches){
		var hour = parseInt(matches[1], 10);
		var minute = parseInt(matches[2], 10);
		
		if(am_pm_format){
			var am_pm = matches[3].toLowerCase();
			if(am_pm=='pm' && hour!=12){
				hour += 12;
			}
			else if(am_pm=='am' && hour==12){
				hour = 0;
			}
		}
		
		if(hour>=0 && hour<24 && minute>=0 && minute<60){
			retVal = true;
			$(input_elem).removeClass('fan_fill_error');
		}
	}
	
	if(!retVal){
		$(input_elem).addClass('fan_fill_error');
		input_elem.focus();
	}
	
	return retVal;
}

function fan_iso_time2am_pm(iso_hour){
	var matches = iso_hour.match(/([0-9]{2}):([0-9]{2})/i);
	var new_time = '';
	
	var hour = parseInt(matches[1], 10);
	var minute = parseInt(matches[2], 10);
	var am_pm = '';

        am_pm = 'am'; //add
	if(hour==0){
		hour = 12;
		am_pm = 'am';
	}
	else if(hour==12){
		am_pm = 'pm';
	}
	else if(hour>12){
		am_pm = 'pm';
		hour = hour - 12;
	}

//        if (minute == 0){
//                minute = '00';
//        }

        if (minute < 10){
                minute = '0' + minute;
        }
	
	new_time = '' + hour + ':' + minute + am_pm;
	
	return new_time;
}

function fan_validate_date_input(input_elem, return_time_array){
	var retVal = false;
	var matches = input_elem.value.match(/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/);

	if(matches){
		var month = parseInt(matches[1], 10);
		var day = parseInt(matches[2], 10);
		var year = parseInt(matches[3], 10);

		if(month>0 && month<13 && day>0 && day<32 && year>1900 && year<2100){
			retVal = true;
			if(return_time_array){
				retVal = Array();
				retVal['year'] = matches[3];
				retVal['month'] = matches[1];
				retVal['day'] = matches[2];
			}
			$(input_elem).removeClass('fan_fill_error');
		}
	}
	
	if(!retVal){
		$(input_elem).addClass('fan_fill_error');
		input_elem.focus();
	}
	
	return retVal;
}

function fan_wall_scrap_category_change(cat_id, extra_container_id, period_start, period_end, title){
	var category_details = false;

	if(typeof(fan_wall_categories[cat_id])=='object'){
		category_details = fan_wall_categories[cat_id];
	}
	else{
		for (var i in fan_wall_categories){
			var parent_cat = fan_wall_categories[i];
			
			if(typeof(parent_cat.children)=='object' && typeof(parent_cat.children[cat_id])=='object'){
				category_details = parent_cat.children[cat_id];
				break;
			}
		}
	}
	
	if(typeof(category_details)=='object'){
		var extra_container = document.getElementById(extra_container_id);
		
		var new_max_length = fan_wall_max_length;
		if(parseInt(category_details.max_post_length)>0){
			new_max_length = parseInt(category_details.max_post_length);
		}
		var textarea_input = $(extra_container.parentNode.parentNode).find('.fan_wall_textarea').get(0);
		fan_set_max_input_length(textarea_input, new_max_length);
		
		var requires_period = false;
		var requires_title = false;
		
		if(category_details.requires_period=='y'){
			requires_period = true;
		}
		if(category_details.requires_title=='y'){
			requires_title = true;
		}

		if(requires_title && typeof(extra_container.title_container)!='object'){
			var title_container = document.createElement('div');
			
			var title_input = document.createElement('input');
			title_input.type = 'text';
			title_input.className = 'fan_wall_title_input';
			title_input.name = 'fan_title';

                        //fan_setFieldTempValue(title_input, fan_default_wall_title_value, true);
                        if (fan_default_wall_title_value != 'title'){
                                fan_setFieldPermValue(title_input, fan_default_wall_title_value, true);
                                fan_default_wall_title_value = 'title';
                        }else{
                                fan_setFieldTempValue(title_input, fan_default_wall_title_value, true);
                        }
			

                        title_container.appendChild(title_input);
			
			if(title){
				title_input.value = title;
			}
			
			$(extra_container).prepend(title_container);
			extra_container.title_container = title_container;
		}
		else if(!requires_title && typeof(extra_container.title_container)=='object'){
			extra_container.removeChild(extra_container.title_container);
			extra_container.title_container = false;
		}
		
		if(requires_period && typeof(extra_container.period_container)!='object'){
			fan_load_jquery_theme();
			
			var period_container = document.createElement('div');
			
			var start_container = document.createElement('div');
			start_container.className = 'fan_from_to_container';
			
			var start_datepicker_plh = document.createElement('div');
			start_container.appendChild(start_datepicker_plh);
			start_datepicker_plh.className = 'fan_datepicker_plh';
			
			var start_label = document.createElement('label');
			start_label.innerHTML = 'From';
			start_label.className = 'fan_from_to_label';
			start_container.appendChild(start_label);
			
			var start_date_input = document.createElement('input');
			start_date_input.type = 'text';
			start_date_input.name = 'fan_start_date';
			start_date_input.size = '10';
                        //start_date_input.value = fan_default_wall_start_date_value;
			start_date_input.onclick = function(){
				fan_show_datepicker(this, start_datepicker_plh);
			}
			start_container.appendChild(start_date_input);
			
			var start_time_input = document.createElement('input');
			start_time_input.type = 'text';
			start_time_input.name = 'fan_start_time';
			start_time_input.size = '7';
                      //  start_time_input.value = default_wall_start_date_value;
			start_container.appendChild(start_time_input);
			
			// set start values
                        if (!period_start && typeof(fan_default_wall_period_start_value) != 'undefined'){
                                period_start = fan_default_wall_period_start_value;
                        }

			if(period_start){
				period_start_array = fan_parse_iso_datetime(period_start);
				if(period_start_array){
					start_date_input.value = period_start_array['month']+'/'+period_start_array['day']+'/'+period_start_array['year'];
					start_time_input.value = fan_iso_time2am_pm(period_start_array['hour']+':'+period_start_array['minute']);
				}
			}
			
			var end_container = document.createElement('div');
			end_container.className = 'fan_from_to_container';
			
			var end_datepicker_plh = document.createElement('div');
			end_container.appendChild(end_datepicker_plh);
			end_datepicker_plh.className = 'fan_datepicker_plh';
			
			var end_label = document.createElement('label');
			end_label.innerHTML = 'To';
			end_label.className = 'fan_from_to_label';
			end_container.appendChild(end_label);
			
			var end_date_input = document.createElement('input');
			end_date_input.type = 'text';
			end_date_input.name = 'fan_end_date';
			end_date_input.size = '10';
			end_date_input.onclick = function(){
				fan_show_datepicker(this, end_datepicker_plh);
			}
			end_container.appendChild(end_date_input);
			
			var end_time_input = document.createElement('input');
			end_time_input.type = 'text';
			end_time_input.name = 'fan_end_time';
			end_time_input.size = '7';
			end_container.appendChild(end_time_input);
			
			// set end values
                        if (!period_end  && typeof(fan_default_wall_period_end_value) != 'undefined'){
                                period_end = fan_default_wall_period_end_value;
                        }
			if(period_end){
				period_end_array = fan_parse_iso_datetime(period_end);
				if(period_end_array){
					end_date_input.value = period_end_array['month']+'/'+period_end_array['day']+'/'+period_end_array['year'];
					end_time_input.value = fan_iso_time2am_pm(period_end_array['hour']+':'+period_end_array['minute']);
				}
			}
			
			period_container.appendChild(start_container);
			period_container.appendChild(end_container);
			extra_container.appendChild(period_container);
			extra_container.period_container = period_container;
		}
		else if(!requires_period && typeof(extra_container.period_container)=='object'){
			extra_container.removeChild(extra_container.period_container);
			extra_container.period_container = false;
		}
	}
}


function fan_parse_iso_datetime(time_string){
	var retVal = false;
	
	var matches = time_string.match(/^([0-9]{4})[\-\/]([0-9]{2})[\-\/]([0-9]{2}) ([0-9]{2}):([0-9]{2})(:([0-9]{2}))?$/);
	
	if(matches){
		retVal = Array();
		retVal['year'] = matches[1];
		retVal['month'] = matches[2];
		retVal['day'] = matches[3];
		retVal['hour'] = matches[4];
		retVal['minute'] = matches[5];
		retVal['second'] = matches[7];
	}
	
	return retVal;
}


function fan_create_wall_scrap_form(placeholder, wall_owner_remote_id, parent_id, form_label, scrap_edit_id, comment_msg, embed_video, links_details, cat_id, scrap_status, availability, tags, cat_id_l2, period_start, period_end, title){
	if(typeof(form_label)!='string'){
		form_label = 'Post on wall';
	}
	
	var scrap_form_container = document.createElement('div');
	scrap_form_container.className = 'fan_wall_scrap_form';
	placeholder.appendChild(scrap_form_container);
	scrap_form_container.style.margin = '10px 0px';
	
	var post_label = document.createElement('div');
	post_label.className = 'fan_wall_post_label';
	scrap_form_container.appendChild(post_label);
	post_label.innerHTML = form_label;
	
	var form_elem = document.createElement('form');
	form_elem.onsubmit = function(){
		return fan_validate_wall_posting(form_elem)
	};
	form_elem.enctype = 'multipart/form-data';
	form_elem.method = 'post';
	form_elem.style.margin = '0px';
	scrap_form_container.appendChild(form_elem);
	
	var avatar_layout_table = document.createElement('table');
	avatar_layout_table.width = '100%';
	form_elem.appendChild(avatar_layout_table);
	var tbody = document.createElement('tbody');
	avatar_layout_table.appendChild(tbody);
	var temp_tr = document.createElement('tr');
	tbody.appendChild(temp_tr);
	
	var avatar_td = document.createElement('td');
	avatar_td.width = 88;
	temp_tr.appendChild(avatar_td);
	if(typeof(fan_logged_user)!='undefined' && typeof(fan_users[fan_logged_user])=='object'){
		var temp_user = Array(fan_users[fan_logged_user]);
		fan_print_users(temp_user, avatar_td);
	}
	
	
	var textarea_td = document.createElement('td');
	temp_tr.appendChild(textarea_td);
	
	// textarea
	var textarea_input = document.createElement('textarea');
	textarea_td.appendChild(textarea_input);
	textarea_input.name = 'fan_wall_message';
	textarea_input.className = 'fan_wall_textarea';
	if(typeof(comment_msg)=='string'){
		textarea_input.innerHTML = comment_msg;
	}
	textarea_input.id = 'fan_textarea_'+Math.random();
	textarea_input.onfocus = function(){
		fan_wall_body_input_focus(textarea_input, form_elem);
	}
	fan_setFieldTempValue(textarea_input, fan_default_wall_textarea_value, true, fan_wall_share_msg_style);
	$(textarea_input).markItUp(fan_markitup_bb_settings);
	
	var hidden_form_container = document.createElement('div');
	hidden_form_container.className = 'fan_hidden_form_container';
	form_elem.appendChild(hidden_form_container);
	
	var extra_container = document.createElement('div');
	extra_container.className = 'fan_wall_post_extra_container';
	
	extra_container_id = 'fan_wall_post_extra_container-'+wall_owner_remote_id+'-'+parent_id;
	if(scrap_edit_id){
		extra_container_id += '-edit-'+scrap_edit_id;
	}
	
	extra_container.id = extra_container_id;
	hidden_form_container.appendChild(extra_container);
	
	textarea_input.onkeyup = function(evt){
		evt = evt || window.event;
		fan_watch_scrap_content(evt, textarea_input, extra_container.id);
	}
//	fan_set_max_input_length(textarea_input, fan_wall_max_length);
	
	var extra_but_container = document.createElement('div');
	extra_container.appendChild(extra_but_container);
	extra_but_container.className = 'fan_wall_extra_but_container';
	
	//category
	if (typeof(fan_wall_categories)=='object'){
		if(typeof(cat_id)=='string'){
			cat_id = Number(cat_id);
		}
		if(typeof(cat_id)!='number'){
			cat_id = 0;
		}
		if(typeof(cat_id_l2)=='string'){
			cat_id_l2 = Number(cat_id_l2);
		}
		if(typeof(cat_id_l2)!='number'){
			cat_id_l2 = 0;
		}
		
		var categories = fan_wall_categories;
		var selected_cat_id = cat_id;
		if(cat_id && cat_id_l2){
			categories = fan_wall_categories[cat_id].children[cat_id_l2];
		}
		
		cat_select = document.createElement('select');
		cat_select.className = 'fan_wall_cat_id_select';
		
		
		var categories = fan_wall_categories;
		var selected_cat_id = cat_id;
		if(cat_id && cat_id_l2){
			categories = fan_wall_categories[cat_id].children;
			selected_cat_id = cat_id_l2;
			cat_select.name = 'fan_cat_id_l2';
			
			var cat_input_l1 = document.createElement('input');
			cat_input_l1.type = 'hidden';
			cat_input_l1.name = 'fan_cat_id';
			cat_input_l1.value = cat_id;
			extra_but_container.appendChild(cat_input_l1);
		}
		else{
			cat_select.name = 'fan_cat_id';
		}
		
		cat_select.onchange = function(){
			fan_wall_scrap_category_change($(this).val(), extra_container_id);
		}
		
		default_option = document.createElement('option');
		default_option.value = '';
		default_option.innerHTML = 'category';
		cat_select.appendChild(default_option);
		for(var i in categories) {
			var cat_item = categories[i];
			if(cat_item.is_hidden=='y'){
				continue;
			}
			option_elem = document.createElement('option');
			option_elem.value = cat_item.cat_id;
			option_elem.innerHTML = cat_item.name;
			cat_select.appendChild(option_elem);
			
			if(selected_cat_id==cat_item.cat_id){
				option_elem.selected = true;
			}
		}
		extra_but_container.appendChild(cat_select);
	}
	
	// availability
	availability_select = document.createElement('select');
	availability_select.className = 'fan_wall_availability_select';
	availability_select.name = 'fan_availability';

	for(var item_key in fan_wall_availability_dictionary){
		var item = eval('fan_wall_availability_dictionary.'+item_key);
		var option_elem = document.createElement('option');
		option_elem.value = item_key;
		option_elem.innerHTML = item;
		if(availability==item_key){
			option_elem.selected = true;
		}
		availability_select.appendChild(option_elem);
	}
		
	extra_but_container.appendChild(availability_select);

	fan_wall_post_init_tags_field(extra_container, tags);
	
	// upload img link
	var img_anchor = document.createElement('a');
	img_anchor.className = 'fan_wall_post_extra_link';
	img_anchor.title = 'attach image';
	img_anchor.onclick = function(){
		fan_init_wall_image_input(image_but, extra_container.id);
	}
	extra_but_container.appendChild(img_anchor);
	var image_but = document.createElement('img');
	img_anchor.appendChild(image_but);
	image_but.src = fan_server_url+'/images/icon/22/image.png';
	image_but.align = 'absmiddle';
	img_caption = document.createElement('span');
	img_caption.innerHTML = 'Add Image';
	img_anchor.appendChild(img_caption);
	
	//embed video link
	var embed_anchor = document.createElement('a');
	embed_anchor.className = 'fan_wall_post_extra_link';
	embed_anchor.title = 'embed video';
	embed_anchor.onclick = function(){
		fan_init_wall_video_input(extra_container.id, null, 'toggle');
	}
	if(embed_video){
		fan_init_wall_video_input(extra_container.id, embed_video, '');
	}
	extra_but_container.appendChild(embed_anchor);
	var embed_video_but = document.createElement('img');
	embed_anchor.appendChild(embed_video_but);
	embed_video_but.src = fan_server_url+'/images/icon/22/video.png';
	embed_video_but.align = 'absmiddle';
	embed_caption = document.createElement('span');
	embed_caption.innerHTML = 'Embed Video';
	embed_anchor.appendChild(embed_caption);
	
	var submit_btn = document.createElement('input');
	submit_btn.type = 'submit';
	hidden_form_container.appendChild(submit_btn);
	submit_btn.name = 'fan_wall_posted';
	submit_btn.className = 'fan_default_but';
	
	if(scrap_status=='draft'){
		submit_btn.value = 'Publish';
		
		var draft_btn = document.createElement('input');
		draft_btn.type = 'submit';
		$(submit_btn).before(draft_btn);
		draft_btn.name = 'fan_wall_posted';
		draft_btn.value = 'Save';
		draft_btn.className = 'fan_default_but';
		draft_btn.onclick = fan_set_save_draft;
		draft_btn.style.marginRight = '10px';
		extra_container.is_draft = true;
	}
	else if(Number(scrap_edit_id)){
		submit_btn.value = 'Save';
	}
	else{
		submit_btn.value = 'Submit';
	}
	
	var op_hidden = document.createElement('input');
	op_hidden.type = 'hidden';
	form_elem.appendChild(op_hidden);
	op_hidden.name = 'wall_owner_remote_id';
	op_hidden.value = wall_owner_remote_id;
	
	var parent_hidden = document.createElement('input');
	parent_hidden.type = 'hidden';
	form_elem.appendChild(parent_hidden);
	parent_hidden.name = 'fan_parent_msg_id';
	parent_hidden.value = parent_id;
	
	if(typeof(scrap_edit_id)=='number'){
		var edit_hidden = document.createElement('input');
		edit_hidden.type = 'hidden';
		form_elem.appendChild(edit_hidden);
		edit_hidden.name = 'fan_msg_id';
		edit_hidden.value = scrap_edit_id;
	}
	
	//initiate links
	if(typeof(links_details)=='object' && typeof(links_details.title)=='object' && links_details.title.length>0){
		for(var i in links_details.title){
			var temp_link_details = {};
			temp_link_details.successfull = true;
			temp_link_details.title = links_details.title[i];
			temp_link_details.heading = links_details.heading[i];
			temp_link_details.images = Array();
			if(links_details.image[i]){
				temp_link_details.images[0] = links_details.image[i];
			}
			
			fan_retrieved_link_details[links_details.url[i]] = temp_link_details;
			fan_get_link_details(links_details.url[i], extra_container, true);
		}
	}
	
	if(cat_id){
		fan_wall_scrap_category_change(cat_id, extra_container_id, period_start, period_end, title);
	}
}

var fan_link_regexps = Array();
var fan_link_only_regexps = Array();
var fan_link_regexps_4paste = Array();
var fan_link_prefixes = Array();

fan_link_regexps[0] = /(http[s]{0,1}:\/\/(([a-z0-9\-]+\.)+[a-z]{2,4})(\/[^\s\n\t\r]*)?)[\s\n\t\r]/i;
fan_link_regexps[1] = /(www\.(([a-z0-9\-]+\.)+[a-z]{2,4})(\/[^\s\n\t\r]*)?)[\s\n\t\r]/i;

fan_link_only_regexps[0] = /(http[s]{0,1}:\/\/(([a-z0-9\-]+\.)+[a-z]{2,4})(\/[^\s\n\t\r]*)?)$/i;
fan_link_only_regexps[1] = /(www\.(([a-z0-9\-]+\.)+[a-z]{2,4})(\/[^\s\n\t\r]*)?)$/i;

fan_link_regexps_4paste[0] = /(http[s]{0,1}:\/\/(([a-z0-9\-]+\.)+[a-z]{2,4})(\/[^\s\n\t\r]*)?)([\s\n\t\r]|$)/i;
fan_link_regexps_4paste[1] = /(www\.(([a-z0-9\-]+\.)+[a-z]{2,4})(\/[^\s\n\t\r]*)?)([\s\n\t\r]|$)/i;

fan_link_prefixes[0] = '';
fan_link_prefixes[1] = 'http://';

var fan_embed_responses = Array();
var fan_embed_regexps = Array();
fan_embed_regexps[0] = /<object [^>]*?(\/>|>).*?(<\/object>)/i;
fan_embed_regexps[1] = /<embed [^>]*?(\/>|><\/embed>)/i;


var fan_watch_scrap_content_additional_parsers = Array();
/**
 * Adds a parser for the wall txtarea input
 * @param function parser_function - function(e, html_textarea, container_id) if return=='stop_parsing' - the current parsing process will be stopped
 */
function fan_add_scrap_content_parser(parser_function){
	if(typeof(parser_function)=='function'){
		fan_watch_scrap_content_additional_parsers.push(parser_function);
	}
}

function fan_watch_scrap_content(e, html_textarea, container_id){
	fan_wall_body_input_focus(html_textarea, false, container_id);
	
	if(html_textarea && typeof(html_textarea)=='object'){
		//run additional parsers
		if(fan_watch_scrap_content_additional_parsers.length>0){
			for(var parser_idex in fan_watch_scrap_content_additional_parsers){
				var current_parser = fan_watch_scrap_content_additional_parsers[parser_idex];
				var parser_response = current_parser(e, html_textarea, container_id);
				
				if(parser_response=='stop_parsing'){
					return;
				}
			}
		}
		
		var keynum = fan_get_keynym(e);
		
		var extra_container = document.getElementById(container_id);
		var input_val = html_textarea.value;
		var link_url = null;
		
		// detect if embed code has been used
		for(var i in fan_embed_regexps){
			var embed_rexexp = fan_embed_regexps[i];
			while(embed_ = input_val.match(embed_rexexp)){
				input_val = input_val.replace(embed_rexexp, ' ');
				
				if(typeof(fan_embed_responses[embed_[0]])!='boolean'){
					var embed_video = confirm('Do you want to embed this?');
					fan_embed_responses[embed_[0]] = embed_video;
					
					if(embed_video){
						html_textarea.value = input_val.replace(embed_[0], '');
						fan_init_wall_video_input(extra_container.id, embed_[0], '');
					}
				}
			}
		}
		
		if(keynum==86){ // it there was a paste
			var link_regexps = fan_link_regexps_4paste;
		}
		else{
			var link_regexps = fan_link_regexps;
		}
		
		for(var i in link_regexps){
			var link_rexexp = link_regexps[i];
			while(link_url = input_val.match(link_rexexp)){
				input_val = input_val.replace(link_rexexp, ' ');
				
				var found_link = fan_link_prefixes[i] + link_url[1];
				if(link_url){
					fan_get_link_details(found_link, extra_container);
				}
			}
		}
	}
}

function fan_wall_body_input_focus(html_textarea, form_elem, extra_container_id){
	if(typeof(extra_container_id)=='string' && extra_container_id){
		var html_element = document.getElementById(extra_container_id).parentNode;
		form_elem = html_element.parentNode;
	}
	
	if(typeof(form_elem.extra_container_expanded)!='boolean' || !form_elem.extra_container_expanded){
		
		if(typeof(extra_container_id)=='string' && extra_container_id){
			$(html_element).show('blind');
			var show_backup = function(){
				if(html_element.style.dosplay=='none'){
					html_element.style.dosplay = 'block';
				}
			}
		}
		else{
			$(form_elem).find('.fan_hidden_form_container').show('blind');
			var show_backup = function(){
				if($(form_elem).find('.fan_hidden_form_container').css('dosplay')=='none'){
					$(form_elem).find('.fan_hidden_form_container').css('dosplay', 'block');
				}
			}
		}
		
		setTimeout(show_backup,500);
		form_elem.extra_container_expanded = true;
	}
}

function fan_wall_post_init_tags_field(extra_container, value){
	var tags_container = document.createElement('div');
	tags_container.className = 'fan_tags_input_container';
	extra_container.appendChild(tags_container);
	
	var tags_input = document.createElement('input');
	tags_input.type = 'text';
	tags_input.className = 'fan_tags_input';
	tags_input.name = 'fan_tags';
	if(typeof(value)=='string'){
		tags_input.value = value;
	}
	
	fan_setFieldTempValue(tags_input, fan_default_wall_tags_value, true);
	
	tags_container.appendChild(tags_input);
}

function fan_get_keynym(e){
	var keynum;
	if(window.event){ // IE
		e = window.event;
		keynum = e.keyCode;
	}
	else if(e.which){ // Netscape/Firefox/Opera
		keynum = e.which;
	}
	
	return keynum;
}

var fan_built_link_containers = Array();
var fan_retrieved_link_details = Array();
var fan_active_link_calls = Array();

/**
 * gets the link details from the server
 */

function fan_get_link_details(link_url, container, init_link, require_video, no_video_callback){
	if(!container.id){
		container.id = 'fan_'+Math.random();
	}
	
	if(typeof(require_video)!='boolean'){
		require_video = false;
	}
	
	
	container.link_active = true;
	fan_show_submit_btn2extra_container(container);
	
	if(
	   	typeof(fan_built_link_containers[container.id])=='object' &&
	   	typeof(fan_built_link_containers[container.id][link_url])=='object' &&
		fan_built_link_containers[container.id][link_url]
	){
		var link_container = fan_built_link_containers[container.id][link_url];
	}
	else{
		//build container div
		var link_container = document.createElement('div');
		container.appendChild(link_container);
		link_container.className = 'fan_found_link_container';
		link_container.align = 'center';
		
		if(	typeof(fan_built_link_containers[container.id])!='object'){
			fan_built_link_containers[container.id] = Array();
		}
		fan_built_link_containers[container.id][link_url] = link_container;
		init_link = true;
	}
	
	if(typeof(fan_retrieved_link_details[link_url])=='object' && fan_retrieved_link_details[link_url]){
		// reinit the link details only if requested
		if(typeof(init_link)=='boolean' && init_link){
			data = fan_retrieved_link_details[link_url];
			fan_link_details_callback(data, link_url, link_container, container, require_video, no_video_callback);
		}
	}
	else if(typeof(fan_active_link_calls[link_url])!='boolean' || !fan_active_link_calls[link_url]){
		link_container.innerHTML = '';
		
		var fan_found_link_container_table = document.createElement('table');
		link_container.appendChild(fan_found_link_container_table);
		fan_found_link_container_table.className = 'fan_found_link_container_table';
	
		var tbody_elem = document.createElement('tbody');
		fan_found_link_container_table.appendChild(tbody_elem);
		
		var tr_elem = document.createElement('tr');
		tbody_elem.appendChild(tr_elem);
		
		var td_elem = document.createElement('td');
		tr_elem.appendChild(td_elem);
		td_elem.style.textAlign = "center";
		td_elem.style.verticalAlign = "middle";
		
		var wait_img = document.createElement('img');
		td_elem.appendChild(wait_img);
		wait_img.src = fan_server_url+"/images/loading/bar_220.gif";
		
		// make the request
		var request = fan_server_url+"/index.php?what=link";
		request += '&link_url='+encodeURIComponent(link_url);
		request += '&output=jquery&callback=?';
		
		fan_active_link_calls[link_url] = true;
		
		jQuery.ajax({
			type: "GET",
			url: request,
			data: {},
			success: function(data){fan_link_details_callback(data, link_url, link_container, container, require_video, no_video_callback)},
			dataType: 'json'
		});
	}
}

function fan_link_details_callback(data, link_url, container, extra_container, require_video, no_video_callback){
	if(typeof(data.successfull)!='boolean' || !data.successfull){
		container.parentNode.removeChild(container);
	}
	
	fan_active_link_calls[link_url] = false;
	fan_retrieved_link_details[link_url] = data;
	
	if(typeof(require_video)=='boolean' && require_video && (typeof(data.embeds)!='object' || data.embeds.length==0)){
		if(typeof(no_video_callback)=='function'){
			no_video_callback();
		}
		container.parentNode.removeChild(container);
		return false;
	}
	
	container.innerHTML = '';
	
	//header
	
	var found_link_header = document.createElement('div');
	container.appendChild(found_link_header);
	found_link_header.align = 'left';
	found_link_header.className = 'fan_found_link_header';
	
	var header_remove_but = document.createElement('img');
	header_remove_but.src = fan_server_url+'/images/cancel.png';
	header_remove_but.className = 'fan_remove_ico_16';
	header_remove_but.title = 'remove link';
	header_remove_but.align = 'right';
	header_remove_but.onclick = function(){
		container.parentNode.removeChild(container);
	}
	found_link_header.appendChild(header_remove_but);
	
	var header_caption = document.createElement('span');
	header_caption.innerHTML = 'Found Link';
	header_caption.className = 'fan_found_link_header_caption';
	found_link_header.appendChild(header_caption);
	
	
	
	
	var fan_found_link_container_table = document.createElement('table');
	container.appendChild(fan_found_link_container_table);
	fan_found_link_container_table.className = 'fan_found_link_container_table';
	
	var tbody_elem = document.createElement('tbody');
	fan_found_link_container_table.appendChild(tbody_elem);
	
	var tr_elem = document.createElement('tr');
	tbody_elem.appendChild(tr_elem);
	
	var img_td_elem = document.createElement('td');
	tr_elem.appendChild(img_td_elem);
	img_td_elem.width = 1;
	
	if(typeof(data.images)=='object' && data.images.length>0){
		data.current_img = 0;
		
		var image_wrapper = document.createElement('div');
		image_wrapper.className = 'fan_wall_input_link_image_wrapper';
		img_td_elem.appendChild(image_wrapper);
		
		var img_elem = document.createElement('img');
		img_elem.className = 'fan_wall_input_link_image';
		image_wrapper.appendChild(img_elem);
		img_elem.src = data.images[0];
		img_elem.id = link_url+'-image';
		
		var img_input = document.createElement('input');
		img_input.type = 'hidden';
		img_td_elem.appendChild(img_input);
		img_input.value = data.images[0];
		img_input.id = link_url+'-image-input';
		img_input.name = 'fan_link_image[]';
		
		var tr_elem2 = document.createElement('tr');
		tbody_elem.appendChild(tr_elem2);
		
		var img_nav_td = document.createElement('td');
		tr_elem2.appendChild(img_nav_td);
		
		var left_arrow = document.createElement('a');
		img_nav_td.appendChild(left_arrow);
		left_arrow.className = 'fan_nav_left_16';
		left_arrow.onclick = function(){
			fan_scroll_link_images(link_url, -1)
		}
		
		var right_arrow = document.createElement('a');
		img_nav_td.appendChild(right_arrow);
		right_arrow.className = 'fan_nav_right_16';
		right_arrow.onclick = function(){
			fan_scroll_link_images(link_url, 1)
		}
		
		var img_count = document.createElement('div');
		img_nav_td.appendChild(img_count);
		img_count.className = 'fan_link_img_nav';
		
		var current_img_span = document.createElement('span');
		img_count.appendChild(current_img_span);
		current_img_span.innerHTML = 1;
		current_img_span.id = link_url+'-image-current';
		
		var img_count_val = document.createElement('span');
		img_count.appendChild(img_count_val);
		img_count_val.innerHTML = ' of '+ data.images.length;
		
		// no icon
		var td_2_2 = document.createElement('td');
		tr_elem2.appendChild(td_2_2);
		
		var no_icon_label = document.createElement('label');
		td_2_2.appendChild(no_icon_label);
		
		var no_icon_input = document.createElement('input');
		no_icon_input.type = 'checkbox';
		no_icon_input.name = 'fan_no_image[]';
		no_icon_input.id = link_url+'-image-none';
		no_icon_input.align = 'absmiddle';
		no_icon_input.onchange = function(){
			if(no_icon_input.checked){
				img_input.value = '';
			}
			else{
				var selected_image = 0;
				if(typeof(fan_retrieved_link_details[link_url].current_img)=='number'){
					selected_image = fan_retrieved_link_details[link_url].current_img;
				}
				img_input.value = fan_retrieved_link_details[link_url].images[selected_image];
			}
		}
		no_icon_label.appendChild(no_icon_input);
		
		var no_icon_caption = document.createElement('span');
		no_icon_caption.innerHTML = ' use no icon';
		no_icon_label.appendChild(no_icon_caption);
	}
	else{
		
		var img_input = document.createElement('input');
		img_input.type = 'hidden';
		img_td_elem.appendChild(img_input);
		img_input.value = '';
		img_input.id = link_url+'-image-input';
		img_input.name = 'fan_link_image[]';
//		img_td_elem.innerHTML = 'no image found';
	}
	
	
	// video
	if(typeof(data.embeds)=='object' && data.embeds.length>0){
		var tr_elem3 = document.createElement('tr');
		tbody_elem.appendChild(tr_elem3);
		
		var embed_td = document.createElement('td');
		embed_td.setAttribute('colspan','2');
		tr_elem3.appendChild(embed_td);
		
		var embed_caption = document.createElement('div');
		embed_caption.innerHTML = 'Video';
		embed_caption.className = 'fan_link_embed_title';
		embed_td.appendChild(embed_caption);
		
		var embed_container = document.createElement('div');
		embed_container.className = 'fan_embed_video_container';
		embed_td.appendChild(embed_container);
		
		var embed_item = document.createElement('div');
		embed_item.innerHTML = data.embeds[0];
		embed_item.className = 'fan_embed_video_item';
		embed_container.appendChild(embed_item);
				
		var use_input = document.createElement('input');
		use_input.type = 'checkbox';
		use_input.onchange = function(){
			if(!use_input.checked){
				fan_init_wall_video_input(extra_container.id, data.embeds[fan_retrieved_link_details[link_url].current_embed], '');
			}
			else{
				fan_init_wall_video_input(extra_container.id, '', 'none');
			}
		}
		
		// navigation
		var nav_container = document.createElement('div');
		nav_container.className = 'fan_embed_nav_container';
		embed_td.appendChild(nav_container);
		
		var left_arrow = document.createElement('a');
		nav_container.appendChild(left_arrow);
		left_arrow.className = 'fan_nav_left_16';
		left_arrow.onclick = function(){
			fan_scroll_link_embeds(link_url, embed_item, -1, use_input, extra_container);
		}
		
		var right_arrow = document.createElement('a');
		nav_container.appendChild(right_arrow);
		right_arrow.className = 'fan_nav_right_16';
		right_arrow.onclick = function(){
			fan_scroll_link_embeds(link_url, embed_item, 1, use_input, extra_container);
		}
		
		var img_count = document.createElement('div');
		nav_container.appendChild(img_count);
		img_count.className = 'fan_link_img_nav';
		
		var current_embed_span = document.createElement('span');
		nav_container.appendChild(current_embed_span);
		current_embed_span.innerHTML = 1;
		current_embed_span.id = link_url+'-embed-current';
		
		var embed_count_val = document.createElement('span');
		nav_container.appendChild(embed_count_val);
		embed_count_val.innerHTML = ' of '+ data.embeds.length;
		
		fan_retrieved_link_details[link_url].current_embed = 0;
		
		// use
		var use_container = document.createElement('div');
		use_container.className = 'fan_embed_use_container';
		embed_td.appendChild(use_container);
		
		var use_label = document.createElement('label');
		use_container.appendChild(use_label);
		use_label.appendChild(use_input);
		fan_init_wall_video_input(extra_container.id, data.embeds[fan_retrieved_link_details[link_url].current_embed], '');
		
		var use_caption = document.createElement('span');
		use_caption.innerHTML = 'do not embed';
		use_label.appendChild(use_caption);
	}
	
	var details_td = document.createElement('td');
	details_td.rowspan = 2;
	tr_elem.appendChild(details_td);
	details_td.style.verticalAlign = 'top';
	
/*	var link_title = document.createElement('div');
	details_td.appendChild(link_title);
	link_title.innerHTML = data.title;*/
	
	var title_input = document.createElement('input');
	title_input.type = 'text';
	title_input.className = 'fan_link_title_input';
	details_td.appendChild(title_input);
	title_input.value = fan_html_entity_decode(data.title);
	title_input.onblur = function(){
		return fan_input_enpty_chech(title_input, 'You must enter a title for the link');
	}
	title_input.name = 'fan_link_title[]';
	
	var url_input = document.createElement('input');
	url_input.type = 'hidden';
	details_td.appendChild(url_input);
	url_input.value = link_url;
	url_input.name = 'fan_link_url[]';
	
	var heading_input = document.createElement('textarea');
	heading_input.className = 'fan_link_heading_input';
	details_td.appendChild(heading_input);
	heading_input.value = fan_html_entity_decode(data.heading?data.heading:'');
	heading_input.name = 'fan_link_heading[]';
	fan_set_max_input_length(heading_input, 300);
}

function fan_scroll_link_embeds(link_url, embed_item_container, shift_position, use_input, extra_container){
	var link_details = fan_retrieved_link_details[link_url];
	
	if(typeof(link_details.embeds)!='object' || link_details.embeds.length==0){
		return;
	}
	
	var new_imdex = link_details.current_embed+shift_position;
	
	if(new_imdex<0){
		new_imdex = 0;
	}
	else if(new_imdex>=link_details.embeds.length){
		new_imdex = link_details.embeds.length-1;
	}
	
	embed_item_container.innerHTML = link_details.embeds[new_imdex];
	
	
	if(!use_input.checked){
		fan_init_wall_video_input(extra_container.id, link_details.embeds[new_imdex], '');
	}
	
	var current_label = document.getElementById(link_url+'-embed-current');
	current_label.innerHTML = new_imdex + 1;
	
	link_details.current_embed = new_imdex;
}

function fan_scroll_link_images(link_url, shift_position){
	var link_details = fan_retrieved_link_details[link_url];
	
	if(typeof(link_details.images)!='object' || link_details.images.length==0){
		return;
	}
	
	var new_img_imdex = link_details.current_img+shift_position;
	
	if(new_img_imdex<0){
		new_img_imdex = 0;
	}
	else if(new_img_imdex>=link_details.images.length){
		new_img_imdex = link_details.images.length-1;
	}
	
	var no_icon_input = document.getElementById(link_url+'-image-none');
	
	img_elem = document.getElementById(link_url+'-image');
	img_elem.src = link_details.images[new_img_imdex];
	
	var img_input = document.getElementById(link_url+'-image-input');
	if(no_icon_input.checked){
		img_input.value = '';
	}
	else{
		img_input.value = link_details.images[new_img_imdex];
	}
	
	var img_current = document.getElementById(link_url+'-image-current');
	img_current.innerHTML = new_img_imdex + 1;
	
	link_details.current_img = new_img_imdex;
}

function fan_edit_scrap(wall_id, msg_id, parent_id, message_container_id){
	if(
		typeof(fan_wall_scraps[wall_id])=='object' &&
		(
			(parent_id && (typeof(fan_wall_scraps[wall_id][parent_id])=='object' && typeof(fan_wall_scraps[wall_id][parent_id].comments[msg_id])=='object')) ||
			typeof(fan_wall_scraps[wall_id][msg_id])=='object'
		)
	){
		if(typeof(message_container_id)!='string'){
			message_container_id = "fan_scrap_message_td-"+wall_id+"-"+msg_id;
		}
		
		var container = document.getElementById(message_container_id);
		container.innerHTML = "";
		
		if(typeof(fan_wall_scraps[wall_id][msg_id])=='object'){
			var scrap_details = fan_wall_scraps[wall_id][msg_id];
		}
		else if(parent_id && typeof(fan_wall_scraps[wall_id][parent_id].comments[msg_id])=='object'){
			var scrap_details = fan_wall_scraps[wall_id][parent_id].comments[msg_id];
		}
		
		var embed_video = '';
		if(typeof(scrap_details.extra)=='object' && typeof(scrap_details.extra.embed_video)=='object' && scrap_details.extra.embed_video.length>0){
			embed_video = scrap_details.extra.embed_video[0];
		}
		
		fan_create_wall_scrap_form(container, wall_id, 0, 'Edit entry', msg_id, scrap_details.message_body, embed_video, scrap_details.extra.link, scrap_details.cat_id, scrap_details.status, scrap_details.availability, scrap_details.tags, scrap_details.cat_id_l2, scrap_details.period_start, scrap_details.period_end, scrap_details.title);
	}
}

document.write('<div id="fan_htmlconverter_plh" style="display:none"></div>');
var fan_htmlconverter_plh = document.getElementById('fan_htmlconverter_plh');

function fan_html_entity_decode(str){
	fan_htmlconverter_plh.innerHTML = '<textarea id="fan_innerConverter">' + str + '</textarea>';
	var content = document.getElementById("fan_innerConverter").value;
	fan_htmlconverter_plh.innerHTML = "";
	return content;
}

	

function fan_htmlentities (string, quote_style) {
	// Convert all applicable characters to HTML entities  
	// 
	// version: 909.322
	// discuss at: http://phpjs.org/functions/htmlentities    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: nobbler
	// +    tweaked by: Jack
	// +   bugfixed by: Onno Marsman    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +    bugfixed by: Brett Zamir (http://brett-zamir.me)
	// +      input by: Ratheous
	// -    depends on: get_html_translation_table
	// *     example 1: htmlentities('Kevin & van Zonneveld');    // *     returns 1: 'Kevin &amp; van Zonneveld'
	// *     example 2: htmlentities("foo'bar","ENT_QUOTES");
	// *     returns 2: 'foo&#039;bar'
	
	this.get_html_translation_table = function(table, quote_style) {
		// http://kevin.vanzonneveld.net
		// +   original by: Philip Peterson
		// +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   bugfixed by: noname
		// +   bugfixed by: Alex
		// +   bugfixed by: Marco
		// +   bugfixed by: madipta
		// +   improved by: KELAN
		// +   improved by: Brett Zamir (http://brett-zamir.me)nput by: Frank Forte
		// +   bugfixed by: T.Wild
		// +      input by: Ratheous
		// %          note: It has been decided that we're not going to add global
		// %          note: dependencies to php.js, meaning the constants are not
		// %          note: real constants, but strings instead. Integers are also supported if someone
		// %          note: chooses to create the constants themselves.
		// *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
		// *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
		
		var entities = {}, hash_map = {}, decimal = 0, symbol = '';
		var constMappingTable = {}, constMappingQuoteStyle = {};
		var useTable = {}, useQuoteStyle = {};
		
		// Translate arguments
		constMappingTable[0]      = 'HTML_SPECIALCHARS';
		constMappingTable[1]      = 'HTML_ENTITIES';
		constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
		constMappingQuoteStyle[2] = 'ENT_COMPAT';
		constMappingQuoteStyle[3] = 'ENT_QUOTES';
		
		useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
		useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
		
		if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
		    throw new Error("Table: "+useTable+' not supported');
		    // return false;
		}
		
		entities['38'] = '&amp;';
		if (useTable === 'HTML_ENTITIES') {
		    entities['160'] = '&nbsp;';
		    entities['161'] = '&iexcl;';
		    entities['162'] = '&cent;';
		    entities['163'] = '&pound;';
		    entities['164'] = '&curren;';
		    entities['165'] = '&yen;';
		    entities['166'] = '&brvbar;';
		    entities['167'] = '&sect;';
		    entities['168'] = '&uml;';
		    entities['169'] = '&copy;';
		    entities['170'] = '&ordf;';
		    entities['171'] = '&laquo;';
		    entities['172'] = '&not;';
		    entities['173'] = '&shy;';
		    entities['174'] = '&reg;';
		    entities['175'] = '&macr;';
		    entities['176'] = '&deg;';
		    entities['177'] = '&plusmn;';
		    entities['178'] = '&sup2;';
		    entities['179'] = '&sup3;';
		    entities['180'] = '&acute;';
		    entities['181'] = '&micro;';
		    entities['182'] = '&para;';
		    entities['183'] = '&middot;';
		    entities['184'] = '&cedil;';
		    entities['185'] = '&sup1;';
		    entities['186'] = '&ordm;';
		    entities['187'] = '&raquo;';
		    entities['188'] = '&frac14;';
		    entities['189'] = '&frac12;';
		    entities['190'] = '&frac34;';
		    entities['191'] = '&iquest;';
		    entities['192'] = '&Agrave;';
		    entities['193'] = '&Aacute;';
		    entities['194'] = '&Acirc;';
		    entities['195'] = '&Atilde;';
		    entities['196'] = '&Auml;';
		    entities['197'] = '&Aring;';
		    entities['198'] = '&AElig;';
		    entities['199'] = '&Ccedil;';
		    entities['200'] = '&Egrave;';
		    entities['201'] = '&Eacute;';
		    entities['202'] = '&Ecirc;';
		    entities['203'] = '&Euml;';
		    entities['204'] = '&Igrave;';
		    entities['205'] = '&Iacute;';
		    entities['206'] = '&Icirc;';
		    entities['207'] = '&Iuml;';
		    entities['208'] = '&ETH;';
		    entities['209'] = '&Ntilde;';
		    entities['210'] = '&Ograve;';
		    entities['211'] = '&Oacute;';
		    entities['212'] = '&Ocirc;';
		    entities['213'] = '&Otilde;';
		    entities['214'] = '&Ouml;';
		    entities['215'] = '&times;';
		    entities['216'] = '&Oslash;';
		    entities['217'] = '&Ugrave;';
		    entities['218'] = '&Uacute;';
		    entities['219'] = '&Ucirc;';
		    entities['220'] = '&Uuml;';
		    entities['221'] = '&Yacute;';
		    entities['222'] = '&THORN;';
		    entities['223'] = '&szlig;';
		    entities['224'] = '&agrave;';
		    entities['225'] = '&aacute;';
		    entities['226'] = '&acirc;';
		    entities['227'] = '&atilde;';
		    entities['228'] = '&auml;';
		    entities['229'] = '&aring;';
		    entities['230'] = '&aelig;';
		    entities['231'] = '&ccedil;';
		    entities['232'] = '&egrave;';
		    entities['233'] = '&eacute;';
		    entities['234'] = '&ecirc;';
		    entities['235'] = '&euml;';
		    entities['236'] = '&igrave;';
		    entities['237'] = '&iacute;';
		    entities['238'] = '&icirc;';
		    entities['239'] = '&iuml;';
		    entities['240'] = '&eth;';
		    entities['241'] = '&ntilde;';
		    entities['242'] = '&ograve;';
		    entities['243'] = '&oacute;';
		    entities['244'] = '&ocirc;';
		    entities['245'] = '&otilde;';
		    entities['246'] = '&ouml;';
		    entities['247'] = '&divide;';
		    entities['248'] = '&oslash;';
		    entities['249'] = '&ugrave;';
		    entities['250'] = '&uacute;';
		    entities['251'] = '&ucirc;';
		    entities['252'] = '&uuml;';
		    entities['253'] = '&yacute;';
		    entities['254'] = '&thorn;';
		    entities['255'] = '&yuml;';
			entities['8226'] = '&bull;';
		}
		
		if (useQuoteStyle !== 'ENT_NOQUOTES') {
		    entities['34'] = '&quot;';
		}
		if (useQuoteStyle === 'ENT_QUOTES') {
		    entities['39'] = '&#39;';
		}
		entities['60'] = '&lt;';
		entities['62'] = '&gt;';
		
		
		// ascii decimals to real symbols
		for (decimal in entities) {
		    symbol = String.fromCharCode(decimal);
		    hash_map[symbol] = entities[decimal];
		}
		
		return hash_map;
	}
	
	
	var hash_map = {}, symbol = '', tmp_str = '', entity = '';
	tmp_str = string.toString();    
	if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
		return false;
	}
	hash_map["'"] = '&#039;';
	
	for (symbol in hash_map) {
		entity = hash_map[symbol];
		tmp_str = tmp_str.split(symbol).join(entity);
	}
	
	return tmp_str;
}


function fan_input_enpty_chech(input_elem, on_empty_message){
	if(typeof(on_empty_message)!='string' || !on_empty_message){
		on_empty_message = 'This field can not be enpty';
	}
	
	if(!input_elem.value){
		alert(on_empty_message);
		setTimeout(function(){input_elem.focus();},10);
		return false;
	}
	
	return true;
}

function fan_set_max_input_length(input_elem, max_length){
	if(typeof(input_elem.fan_max_length)!='number'){
		input_elem.onkeyup = fan_append_code2function(input_elem.onkeyup, function(){fan_trim_input_value(input_elem)});
		input_elem.onchange = fan_append_code2function(input_elem.onchange, function(){fan_trim_input_value(input_elem)});
	}
	input_elem.fan_max_length = max_length;
	
	fan_trim_input_value(input_elem);
}

function fan_trim_input_value(input_elem, max_length){
	if(typeof(max_length)!='number' && typeof(input_elem.fan_max_length)=='number'){
		max_length = input_elem.fan_max_length;
	}

	if(input_elem.value.length > max_length){
		input_elem.value = input_elem.value.substring(0, max_length);
//		alert('Maximum length reached');
//		input_elem.focus();
	}
}

function fan_append_code2function(old_func, function2append){
	var reurn_function = function(evt){
		if(typeof(old_func)=='function'){
			try{
				old_func(evt);
			}catch(E){}
		}
		
		function2append(evt);
	}
	
	return reurn_function;
}

function fan_preppend_code2function(old_func, function2preppend){
	var reurn_function = function(evt){
		function2preppend(evt);
		
		if(typeof(old_func)=='function'){
			try{
				old_func(evt);
			}
			catch(E){}
		}
	}
	
	return reurn_function;
}

function fan_prependChild(parentElement, childElement) {
	var firstChild = parentElement.firstChild;
	if(firstChild){
		parentElement.insertBefore(childElement, firstChild);
	}
	else{
		parentElement.appendChild(childElement);
	}
}

/**
 * displays a menu
 * 
 * @param Element menu_btn clicked button
 * @param String menu_container_id
 * @param boolean keep_btn_intact if set no change will be made to the button
 * @param boolean no_hide disables menu hide if shown
 */

function fan_menu(menu_btn, menu_container_id, xOffset, yOffset, keep_btn_intact, no_hide){
	var _self = this;
	
	this.menu_container = document.getElementById(menu_container_id);
	
	if(typeof(keep_btn_intact)!='boolean'){
		keep_btn_intact = false;
	}
	
	/**
	 * hides this menu
	 */
	this.hide = function(){
		if(!keep_btn_intact){
			menu_btn.className = 'fan_menu_caption';
		}
		_self.menu_container.style.display = 'none';
	}
	
	menu_btn.hide_menu = this.hide;
	
	if(typeof(fan_menu.active_menu)=='object' && fan_menu.active_menu){
		try{
			fan_menu.active_menu.hide();
		}
		catch(E){}
	}
	fan_menu.active_menu = this;
	
	if(typeof(this.menu_container.style.display)!='string' || this.menu_container.style.display=='' || this.menu_container.style.display=='none'){
		if(!keep_btn_intact){
			menu_btn.className = 'fan_menu_caption_active';
		}
		
		if(typeof(xOffset)!='number'){
			xOffset = menu_btn.offsetLeft;
		}
		if(typeof(yOffset)!='number'){
			yOffset = menu_btn.offsetTop + menu_btn.offsetHeight;
		}
		
		this.menu_container.style.top = ''+yOffset+'px';
		this.menu_container.style.left = ''+xOffset+'px';
		this.menu_container.style.display = 'block';
	}
	else if(typeof(no_hide)!='boolean' || !no_hide){
		menu_btn.hide_menu();
	}
	
	this.distroy_timeout = null;
	this.menu_container.onmouseout = function(){
		_self.distroy_timeout = setTimeout(menu_btn.hide_menu, 1000);
	}
	this.menu_container.onmouseover = function(){
		try{
			clearTimeout(_self.distroy_timeout);
		}
		catch(E){}
	}
	_self.distroy_timeout = setTimeout(menu_btn.hide_menu, 5000);
}

function fan_display_flag_tool(container, msg_id, buton_element){
	if(typeof(container.flagContainerCreated)=='boolean' && container.flagContainerCreated){
		return;
	}
	
	var xOffset = buton_element.offsetLeft;
	var yOffset = buton_element.offsetTop + 19;
	
	var flags_container = document.createElement('div');
	flags_container.className = 'fan_flags_container';
	flags_container.style.top = ''+yOffset+'px';
	flags_container.style.left = ''+xOffset+'px';
	
	var distroy_timeout;
	flags_container.onmouseout = function(){
		distroy_timeout = setTimeout(function(){
			container.removeChild(flags_container);
			container.flagContainerCreated = false;
		}, 1000);
	}
	flags_container.onmouseover = function(){
		try{
			clearTimeout(distroy_timeout);
		}
		catch(E){}
	}
	distroy_timeout = setTimeout(function(){
		container.removeChild(flags_container);
		container.flagContainerCreated = false;
	}, 5000);
	
	var spam_flag = document.createElement('a');
	spam_flag.innerHTML = 'Spam/Scam';
	flags_container.appendChild(spam_flag);
	spam_flag.onclick = function(){
		fan_flag_wall_post(flags_container, msg_id, 'spam');
	}
	
	var vulgarity_flag = document.createElement('a');
	vulgarity_flag.innerHTML = 'Vulgarity';
	flags_container.appendChild(vulgarity_flag);
	vulgarity_flag.onclick = function(){
		fan_flag_wall_post(flags_container, msg_id, 'vulgarity');
	}
	
	var not_appropriate_flag = document.createElement('a');
	not_appropriate_flag.innerHTML = 'Not Appropriate';
	flags_container.appendChild(not_appropriate_flag);
	not_appropriate_flag.onclick = function(){
		fan_flag_wall_post(flags_container, msg_id, 'not_appropriate');
	}
	
	var nudity_flag = document.createElement('a');
	nudity_flag.innerHTML = 'Nudity';
	flags_container.appendChild(nudity_flag);
	nudity_flag.onclick = function(){
		fan_flag_wall_post(flags_container, msg_id, 'nudity');
	}
	
	var harassment_flag = document.createElement('a');
	harassment_flag.innerHTML = 'Harassment';
	flags_container.appendChild(harassment_flag);
	harassment_flag.onclick = function(){
		fan_flag_wall_post(flags_container, msg_id, 'harassment');
	}
	
	container.appendChild(flags_container);
	container.flagContainerCreated = true;
}

function fan_flag_wall_post(flags_container, msg_id, flag_type){
	flags_container.parentNode.removeChild(flags_container);
	
	alert('Your flag has been posted.\nThank you for helping make the wall nicer!');
	
	fanSetCookie('fan_client_op', 'flag_wall_posting');
	fanSetCookie('fan_msg_id', msg_id);
	fanSetCookie('fan_flag_type', flag_type);
	fan_reload_window();
}

function fan_show_settings_window(user_id){
	var container = document.createElement('div');
	
	var user_settings = Array();
	if(typeof(fan_users[user_id].extra.settings)=='object'){
		user_settings = fan_users[user_id].extra.settings;
	}
	
	var form_elem = document.createElement('form');
	form_elem.method = 'post';
	container.appendChild(form_elem);
	
	var layout_table = document.createElement('table');
	form_elem.appendChild(layout_table);
	layout_table.width = '660';
	layout_table.border = 0;
	var layout_tbody = document.createElement('tbody');
	layout_table.appendChild(layout_tbody);
	
	
	for(var key in fan_user_settings_dictionary){
		var details = fan_user_settings_dictionary[key];
		
		var value = null;
		if(typeof(user_settings[key])=='undefined'){
			value = details['default'];
		}
		else{
			value = user_settings[key];
		}
		
		var line = document.createElement('tr');
		layout_tbody.appendChild(line);
		var caption = document.createElement('td');
		caption.className = 'fan_form_caption';
		caption.width = 300;
		var input_container = document.createElement('td');
		input_container.className = 'fan_form_input_container';
		var input_elem = document.createElement('input');
		input_elem.type = details.type;
		input_elem.name = 'fan_'+key;
		
		if(details.type=='checkbox'){
			input_elem.value = 'y';
			if(value){
				input_elem.checked = true;
			}
		}
		else{
			if(value){
				input_elem.value = value;
			}
			else{
				input_elem.value = '';
			}
		}
		
		if(typeof(details.onchange)=='string'){
			var onchange_fc = eval(details.onchange);
			input_elem.onchange = function(e){onchange_fc(e, this)};
		}
		
		input_container.appendChild(input_elem);
		caption.innerHTML = details.caption;
		if(typeof(details.tip)=='string' && details.tip){
			var comment_container = document.createElement('span');
			comment_container.className = 'fan_form_comment';
			comment_container.innerHTML = details.tip;
			input_container.appendChild(comment_container);
		}
		line.appendChild(caption);
		line.appendChild(input_container);
	}
	
	
//	//auto facebook
//	var line = document.createElement('tr');
//	layout_tbody.appendChild(line);
//	var caption = document.createElement('td');
//	caption.className = 'fan_form_caption';
//	var input_container = document.createElement('td');
//	input_container.className = 'fan_form_input_container';
//	var input_elem = document.createElement('input');
//	input_elem.type = 'checkbox';
//	input_elem.name = 'fan_wall_auto_facebook';
//	input_elem.value = 'y';
//	if(typeof(user_settings.wall_auto_facebook)!='boolean' || user_settings.wall_auto_facebook){
//		input_elem.checked = true;
//	}
//	input_container.appendChild(input_elem);
//	caption.innerHTML = 'auto posting on Facebook';
//	caption.width = 180;
//	line.appendChild(caption);
//	line.appendChild(input_container);
//	
//	//auto twitter
//	var line = document.createElement('tr');
//	layout_tbody.appendChild(line);
//	var caption = document.createElement('td');
//	caption.className = 'fan_form_caption';
//	var input_container = document.createElement('td');
//	input_container.className = 'fan_form_input_container';
//	var input_elem = document.createElement('input');
//	input_elem.type = 'checkbox';
//	input_elem.name = 'fan_wall_auto_twitter';
//	input_elem.value = 'y';
//	if(typeof(user_settings.wall_auto_twitter)!='boolean' || user_settings.wall_auto_twitter){
//		input_elem.checked = true;
//	}
//	input_container.appendChild(input_elem);
//	caption.innerHTML = 'auto posting on Twitter';
//	line.appendChild(caption);
//	line.appendChild(input_container);
//	
//	//transliteration
//	var line = document.createElement('tr');
//	layout_tbody.appendChild(line);
//	var caption = document.createElement('td');
//	caption.className = 'fan_form_caption';
//	var input_container = document.createElement('td');
//	input_container.className = 'fan_form_input_container';
//	var input_elem = document.createElement('input');
//	input_elem.type = 'checkbox';
//	input_elem.name = 'fan_disable_transliteration';
//	input_elem.value = 'y';
//	if(typeof(user_settings.disable_transliteration)=='boolean' && user_settings.disable_transliteration){
//		input_elem.checked = true;
//	}
//	input_container.appendChild(input_elem);
//	caption.innerHTML = 'disable transliteration';
//	line.appendChild(caption);
//	line.appendChild(input_container);
//	
//	//public wall
//	var line = document.createElement('tr');
//	layout_tbody.appendChild(line);
//	var caption = document.createElement('td');
//	caption.className = 'fan_form_caption';
//	var input_container = document.createElement('td');
//	input_container.className = 'fan_form_input_container';
//	var input_elem = document.createElement('input');
//	input_elem.type = 'checkbox';
//	input_elem.name = 'fan_public_wall';
//	input_elem.value = 'y';
//	if(typeof(user_settings.public_wall)=='boolean' && user_settings.public_wall){
//		input_elem.checked = true;
//	}
//	input_container.appendChild(input_elem);
//	caption.innerHTML = 'make my wall public';
//	var comment_container = document.createElement('span');
//	comment_container.className = 'fan_form_comment';
//	comment_container.innerHTML = '(anybody can post)';
//	input_container.appendChild(comment_container);
//	line.appendChild(caption);
//	line.appendChild(input_container);
	
	
	var bottom_tr = document.createElement('tr');
	layout_tbody.appendChild(bottom_tr);
	
	var submit_container = document.createElement('td');
	bottom_tr.appendChild(submit_container);
	submit_container.colSpan = 2;
	submit_container.className = 'fan_submit_container';
	
	var input_elem = document.createElement('input');
	input_elem.type = 'hidden';
	input_elem.name = 'fan_client_op';
	input_elem.value = 'update_settings';
	form_elem.appendChild(input_elem);
	
	var input_elem = document.createElement('input');
	input_elem.type = 'hidden';
	input_elem.name = 'fan_client_user_id';
	input_elem.value = user_id;
	form_elem.appendChild(input_elem);
	
	var submit_btn = document.createElement('input');
	submit_btn.type = 'submit';
	submit_btn.value = 'OK';
	submit_btn.className = 'fan_default_but';
	submit_container.appendChild(submit_btn);
	
	
	fan_show_transparent_bg();
	new fan_window(document.body, 'Settings', container, {onclose:function(){fan_hide_transparent_bg()}});
}

function fan_wall_auto_twitter_notice_confirm(e, input_elem, user_response){
	if(input_elem.checked){
		if(typeof(user_response)=='string'){
			if(user_response=='cancel'){
				input_elem.checked = false;
			}
		}
		else{
			var content = 'A message @yourtwittername will be sent each time somebody posts on your wall<br />In order to receive these messages you must follow SocialPulse on Twitter';
			var answers = {ok:'ok',cancel:'cancel'};
			var callback = function(response){fan_wall_auto_twitter_notice_confirm(e,input_elem, response)};
			fan_window.confirm(content, answers, callback)
		}
	}
}

function fan_display_settings_info(buton_element){
	var container = document.createElement('div');
	var xOffset = buton_element.offsetLeft + 20;
	var yOffset = buton_element.offsetTop + 20;
	
	var text_elem = document.createElement('span');
	text_elem.innerHTML = 'Manage ';
	container.appendChild(text_elem);
	
	var img_elem = document.createElement('img');
	img_elem.src = fan_server_url+'/images/icon/16/facebook.png';
	img_elem.align = 'absmiddle';
	container.appendChild(img_elem);
	
	var text_elem = document.createElement('span');
	text_elem.innerHTML = ' and ';
	container.appendChild(text_elem);
	
	var img_elem = document.createElement('img');
	img_elem.src = fan_server_url+'/images/icon/16/twitter.png';
	img_elem.align = 'absmiddle';
	container.appendChild(img_elem);
	
	var text_elem = document.createElement('span');
	text_elem.innerHTML = ' auto posting and wall posting permissions';
	container.appendChild(text_elem);
	
	
	buton_element.info_window = new fan_window(buton_element.parentNode, 'Settings Info', container, {nobar:true, xOffset:xOffset, yOffset:yOffset,width:'220px'});
}

function fan_validate_wall_posting(form_elem){
	
	if(typeof(form_elem.fan_title)=='object'){
		if(!form_elem.fan_title.value || form_elem.fan_title.value==fan_default_wall_title_value){
			alert('Please enter the title');
			form_elem.fan_title.focus();
			return false;
		}
	}
	
	if(typeof(form_elem.fan_start_date)=='object'){
		if(!fan_validate_date_input(form_elem.fan_start_date)){
			alert('Please select the start date');
			return false;
		}
	}
	
	if(typeof(form_elem.fan_start_time)=='object'){
		if(!fan_validate_time_input(form_elem.fan_start_time, true)){
			alert('Please enter the start time like 6:32pm');
			return false;
		}
	}
	
	if(typeof(form_elem.fan_end_date)=='object'){
		if(!fan_validate_date_input(form_elem.fan_end_date)){
			alert('Please select the end date');
			return false;
		}
	}
	
	if(typeof(form_elem.fan_end_time)=='object'){
		if(!fan_validate_time_input(form_elem.fan_end_time, true)){
			alert('Please enter the end time like 6:32pm');
			return false;
		}
	}
	
	if(
		typeof(form_elem.fan_start_date)=='object' &&
		typeof(form_elem.fan_start_time)=='object' &&
		typeof(form_elem.fan_end_date)=='object' &&
		typeof(form_elem.fan_end_time)=='object'
	){

                

		var temp = fan_validate_date_input(form_elem.fan_start_date, true);
		var start_date_time = temp['year']+temp['month']+temp['day']+fan_am_pm2time(form_elem.fan_start_time.value);
		var temp = fan_validate_date_input(form_elem.fan_end_date, true);
		var end_date_time = temp['year']+temp['month']+temp['day']+fan_am_pm2time(form_elem.fan_end_time.value);
		
		start_date_time = start_date_time.replace(/[^0-9]/, ''); 
		end_date_time = end_date_time.replace(/[^0-9]/, ''); 
		
		start_date_time = parseInt(start_date_time, 10);  
		end_date_time = parseInt(end_date_time, 10);   
		if(end_date_time<=start_date_time){
			alert('The end must be after the start');
			return false;
		}
	}
	
	form_elem.fan_wall_message.value = form_elem.fan_wall_message.value.replace(/^\s+|\s+$/g,"");
	if(!form_elem.fan_wall_message.value || form_elem.fan_wall_message.value==fan_default_wall_textarea_value){
		alert('Please enter the message body');
		form_elem.fan_wall_message.focus();
		return false;
	}
	
	fanSetCookie('fan_client_op','post_on_wall');
	return true;
}

function fan_am_pm2time(time){
        var ret_hour = time.match(/([0-9]+):/);
        ret_hour = ret_hour[1];
        var ret_minutes = time.match(/:([0-9]+)/);
        ret_minutes = ret_minutes[1];
        var ret_meridian = time.match(/[a-zA-Z]+$/);
        if (ret_meridian == 'pm'){
                ret_hour = parseInt(ret_hour) + 12;
        }
        if (ret_hour < 10){
                ret_hour = '0' + ret_hour;
        }
        var ret_value = ret_hour + ret_minutes;
        return ret_value;
}


function fan_xlc_login_successful(){
	var xlc_user_id = XLC.get_user_id();
	if(fan_xlc_logged_user != xlc_user_id && !fan_logged_user){// if the current login center user is not logged
		fanSetCookie('fan_client_op','login_via_logincenter');
		fanSetCookie('fan_xlc_key',XLC.lcjs_user_data);
		fan_reload_window();
	}
}

function fan_xlc_logout_successful(){
	if(fan_xlc_logged_user){ // if a login center user was logged
		fanSetCookie('fan_client_op','logout_logincenter_user');
		fan_reload_window();
	}
}

function fan_show_help_window(){
	var content = document.createElement('iframe');
	content.src = fan_server_url+'/help/';
	content.className = 'fan_help_iframe';
	content.setAttribute('frameborder', 0);
	
	fan_show_transparent_bg();
	new fan_window(document.body, 'Help', content, {onclose:function(){fan_hide_transparent_bg()}});
}

function fan_show_tooltip_window(tooltip_url_id){
	var content = document.createElement('iframe');
	content.src = fan_server_url+'/tooltip/'+tooltip_url_id;
	content.className = 'fan_tooltip_iframe';
	content.setAttribute('frameborder', 0);
	
	fan_show_transparent_bg();
	new fan_window(document.body, 'Tooltip', content, {onclose:function(){fan_hide_transparent_bg()}});
}

function fan_display_wall_search_form(wall_owner_user_id){
	var form_elem = document.createElement('form');
	form_elem.method = 'post';
	
	var layout_table = document.createElement('table');
	form_elem.appendChild(layout_table);
	layout_table.style.marginTop = '10px';
	layout_table.width = '350';
	layout_table.border = 0;
	
	var layout_tbody = document.createElement('tbody');
	layout_table.appendChild(layout_tbody);
	
	
	//keyword
	var line = document.createElement('tr');
	layout_tbody.appendChild(line);
	var caption = document.createElement('td');
	caption.className = 'fan_form_caption';
	var input_container = document.createElement('td');
	input_container.className = 'fan_form_input_container';
	var keyword_input_elem = document.createElement('input');
	keyword_input_elem.type = 'text';
	keyword_input_elem.name = 'fan_wall_search_keyword-'+wall_owner_user_id;
	input_container.appendChild(keyword_input_elem);
	caption.innerHTML = 'Search for:';
	caption.width = 180;
	line.appendChild(caption);
	line.appendChild(input_container);
	
	
	//category
	var line = document.createElement('tr');
	layout_tbody.appendChild(line);
	var caption = document.createElement('td');
	caption.className = 'fan_form_caption';
	var input_container = document.createElement('td');
	input_container.className = 'fan_form_input_container';
	
	cat_id = 0;
	
	cat_select = document.createElement('select');
	cat_select.calssName = 'fan_wall_cat_id_select';
	cat_select.name = 'fan_wall_search_category_id-'+wall_owner_user_id;
	default_option = document.createElement('option');
	default_option.value = '';
	default_option.innerHTML = 'all';
	cat_select.appendChild(default_option);
	for(var i in fan_wall_categories) {
		var cat_item = fan_wall_categories[i];
		option_elem = document.createElement('option');
		option_elem.value = cat_item.cat_id;
		option_elem.innerHTML = cat_item.name;
		cat_select.appendChild(option_elem);
		
		if(cat_id==cat_item.cat_id){
			option_elem.selected = true;
		}
	}
	input_container.appendChild(cat_select);
	caption.innerHTML = 'In Category:';
	caption.width = 180;
	line.appendChild(caption);
	line.appendChild(input_container);
	
	
	var bottom_tr = document.createElement('tr');
	layout_tbody.appendChild(bottom_tr);
	
	var submit_container = document.createElement('td');
	bottom_tr.appendChild(submit_container);
	submit_container.colSpan = 2;
	submit_container.className = 'fan_submit_container';
	
	form_elem.onsubmit = function(){
		fanSetCookie(cat_select.name,$(cat_select).val());
		fanSetCookie(keyword_input_elem.name,keyword_input_elem.value);
		fan_reload_window();
		return false;
	}
	
	var submit_btn = document.createElement('input');
	submit_btn.type = 'submit';
	submit_btn.value = 'GO';
	submit_btn.className = 'fan_default_but';
	submit_container.appendChild(submit_btn);
	
	fan_show_transparent_bg();
	new fan_window(document.body, 'Search The wall', form_elem, {onclose:function(){fan_hide_transparent_bg()}});
}

function fan_set_refresh_wall(){
	fanSetCookie('fan_refresh_wall','y');
}

function fan_set_save_draft(){
	fanSetCookie('fan_save_draft','y');
	return true;
}

function fan_display_wall_drafts(wall_owner_user_id){
	fan_set_refresh_wall();
	fanSetCookie('fan_display_wall_drafts-'+wall_owner_user_id,'y');
	fan_reload_window();
}

function fan_hide_wall_drafts(wall_owner_user_id){
	fan_set_refresh_wall();
	fanDeleteCookie('fan_display_wall_drafts-'+wall_owner_user_id);
	fan_reload_window();
}

function fan_publish_draft(msg_id){
	fanSetCookie('fan_client_op','publish_draft');
	fanSetCookie('msg_id',msg_id);
	fan_reload_window();
}

function fan_init_transliteration(){
	// initiate control
	if(typeof(fan_transliterationControl)!='object'){
		var available_langs = Array();
		for ( var i in fan_available_transliterations){
			available_langs.push(i);
		}
		
		var options = {
			sourceLanguage: 'en',
			destinationLanguage: available_langs,
			shortcutKey: 'ctrl+g',
			transliterationEnabled: true
		};
		
		fan_transliterationControl = new google.elements.transliteration.TransliterationControl(options);
	}
}

function fan_disable_transliteration(){
	if(typeof(fan_transliterationControl)=='object' && fan_transliterationControl){
		fan_transliterationControl.disableTransliteration();
	}
}

function fan_set_transliteration(language_abr){
	fan_init_transliteration();

	// get ids
	var textareas = $('.fan_wall_textarea');
	var ids = Array();
	if(typeof(textareas)=='object'){
		if(typeof(textareas.id)=='string'){
			if(typeof(textareas.transliterated_initiated)!='boolean' || !textareas.transliterated_initiated){
				ids.push(textareas.id);
				textareas.transliterated_initiated = true;
			}
		}
		else{
			for(var i in textareas){
				if(typeof(textareas[i].id)=='string'){
					if(typeof(textareas[i].transliterated_initiated)!='boolean' || !textareas[i].transliterated_initiated){
						ids.push(textareas[i].id);
						textareas[i].transliterated_initiated = true;
					}
				}
			}
		}
	}
	
	if(ids.length>0){
		// Enable transliteration in the textfields with the given ids.
		fan_transliterationControl.makeTransliteratable(ids);
	}
	
	fan_transliterationControl.setLanguagePair('en', language_abr);
	fan_transliterationControl.enableTransliteration();
	$("input[name='fan_wall_language']").val(language_abr);
}

function fan_display_transliteration_menu(click_elem){
	if(typeof(click_elem.menu_container)!='object' || !click_elem.menu_container){
		var menu_container = document.createElement('div');
		var menu_container_id = 'fan_pop_menu_container-'+Math.random();
		menu_container.id = menu_container_id;
		menu_container.className = 'fan_menu_container';
		click_elem.parentNode.appendChild(menu_container);


		var lang_opt = document.createElement('a');
		lang_opt.innerHTML = '--default--';
		menu_container.appendChild(lang_opt);
		lang_opt.onclick = fan_disable_transliteration;
		
		//language buttons
		for(var lang_abbr in fan_available_transliterations){
			var lang_name = eval('fan_available_transliterations.'+lang_abbr);
			
			var lang_btn = document.createElement('a');
			lang_btn.className = 'fan_lang_'+lang_abbr+'_16_btn';
			lang_btn.innerHTML = lang_name;
			menu_container.appendChild(lang_btn);
			lang_btn.title = lang_name;
			lang_btn.lang_abbr = lang_abbr;
			lang_btn.onclick = function(){
				fan_set_transliteration(this.lang_abbr);
			}
		}
		
		click_elem.menu_container = menu_container;
	}
	
	click_elem.menu_obj = new fan_menu(click_elem, click_elem.menu_container.id);
}

function fan_make_service_call(parameters, callback_func){
	var request = fan_server_url+"/index.php";

	// set the user session id
	request += "?session_id="+encodeURIComponent(fan_logged_user_session);
	request += '&output=jquery&callback=?';
	
	if (typeof(parameters)=='object') {
		for(var key in parameters) {
			var value = parameters[key];
			request += "&"+key+"="+encodeURIComponent(value);
		}
	}
	
	jQuery.ajax({
		type: "GET",
		url: request,
		data: {},
		success: callback_func,
		dataType: 'json'
	});
}

function fan_display_private_messages(){
	var container = document.createElement('div');
	container.className = 'fan_private_message_main_container';
	
	var wait_img = document.createElement('img');
	container.appendChild(wait_img);
	wait_img.src = fan_server_url+"/images/loading/bar_220.gif";
	wait_img.style.margin = '50px 20px';

	new fan_window(document.body, 'Private Messages', container);
	
	var callback_func = function(data){
		fan_display_private_messages_callback(data, container);
	}
	var call_params = {
		what:'wall',
		op:'get_private',
		user_id:fan_logged_user
	};
	fan_make_service_call(call_params, callback_func);	
}

function fan_display_private_messages_callback(data, container){
	if(typeof(data)=='object' && typeof(data.successfull)=='boolean' && data.successfull){
		container.innerHTML = '';
		container.style.display = 'none';
		
		// dummy div to avoid FF display bug
		var dummy_div = document.createElement('div');
		dummy_div.innerHTML = '&nbsp';
		container.appendChild(dummy_div);
		
		var first_scrap = true;
		var mesages_displayed = 0;
		for(var i in data.wall){
			var scrap_details = data.wall[i];
			var poster_details = data.users[scrap_details.poster_id];
			
			fan_display_private_message_collapsed(scrap_details, poster_details, container, first_scrap);
			first_scrap = false;
			mesages_displayed++;
		}
		
		if(mesages_displayed==0){
			var no_mes_msg = document.createElement('div');
			no_mes_msg.innerHTML = 'You have no private message';
			container.appendChild(no_mes_msg);
		}
		
		$(container).show('blind');
	}
	else{
		container.innerHTML = 'Could not retrieve the private messages!';
	}
}

function fan_display_private_message_collapsed(scrap_details, poster_details, container, first_scrap){
	var scrap_item = document.createElement('div');
	scrap_item.className = 'fan_private_mesage_item';
	if(first_scrap){
		scrap_item.style.marginTop = '0px';
	}
	
	var scrap_item_collapsed = document.createElement('div');
	scrap_item_collapsed.className = 'fan_private_mesage_item_collapsed';
	scrap_item.appendChild(scrap_item_collapsed);
	
	// poster
	var poster_elem = document.createElement('span');
	poster_elem.className = 'fan_private_mes_list_poster';
	poster_elem.innerHTML = poster_details.user_name + ': ';
	scrap_item.appendChild(poster_elem);
	
	
	// message body
	var message_body = fan_strip_tags(scrap_details.message_body);
	message_body = message_body.substring(0, 50);
	var message_body_elem = document.createElement('span');
	message_body_elem.innerHTML = message_body;
	scrap_item.appendChild(message_body_elem);
	if(scrap_details.is_read=='n'){
		message_body_elem.className = 'fan_unread_msg_head';
	}
	else{
		message_body_elem.className = 'fan_read_msg_head';
	}
	
	//collapse button
	var collapse_btn = document.createElement('a');
	collapse_btn.style.display = 'none';
	collapse_btn.title = 'close message';
	collapse_btn.className = 'fan_close_message_16_btn';
	scrap_item.appendChild(collapse_btn);
	
	// full poster icon
	var full_poster_details = document.createElement('div');
	full_poster_details.style.display = 'none';
	var temp = Array();
	temp.push(poster_details);
	fan_print_users(temp, full_poster_details);
	scrap_item.appendChild(full_poster_details);
	
	// full message body
	var full_message_body_elem = document.createElement('div');
	full_message_body_elem.style.display = 'none';
	full_message_body_elem.innerHTML = scrap_details.message_body;
	scrap_item.appendChild(full_message_body_elem);
	
	scrap_item.expand = function(){
		message_body_elem.style.display = 'none';
		poster_elem.style.display = 'none';
		collapse_btn.style.display = '';
		
		full_poster_details.style.display = '';
		$(full_message_body_elem).show('blind');
		
		
		if(scrap_details.is_read=='n'){
			fan_mark_scrap_as_read(scrap_details.msg_id);
			message_body_elem.className = 'fan_read_msg_head';
		}
	}
	
	scrap_item.collapse = function(){
		message_body_elem.style.display = '';
		poster_elem.style.display = '';
		collapse_btn.style.display = 'none';
		
		$(full_message_body_elem).hide('blind');
		full_poster_details.style.display = 'none';
	}
	
	collapse_btn.onclick = scrap_item.collapse;
	
	message_body_elem.onclick = scrap_item.expand;
	
	container.appendChild(scrap_item);
}

function fan_mark_scrap_as_read(msg_id){
	var call_params = {
		what:'wall',
		op:'mark_as_read',
		msg_id:msg_id,
		user_id:fan_logged_user
	};
	fan_make_service_call(call_params, function(){});	
}

function fan_strip_tags(str){
	str = str.replace(/(<br(\s\/)?>)/ig," ");
	str = str.replace(/(<([^>]+)>)/ig,"");
	return str; 
}

/**
 * how many login queries got a login status != successfull, failed, pending
 */
var fan_no_status_login_requests = 0;
var fan_pending_login_requests = 0;
function fan_login_watch(data, watchInterval){
	fanSetCookie('fan_login_watch_active','1');

	if(typeof(watchInterval)!='number'){
		watchInterval = 500;
	}
	
//	var alert_ = ''+data
//	if(typeof(data)=='object' && data){
//		alert_ = 'object - ';
//		for(var i in data){
//			eval ("alert_ +='\\n"+i+":"+data[i]+"'");
//		}
//	}
//	alert(alert_);
	
	if(typeof(data)=='object' && typeof(data.login_status)=='string'){
		if(data.login_status=='successfull'){
			fanSetCookie('fan_client_op','login');
			fanSetCookie('fan_logged_user_id', data.user_id);
			fanDeleteCookie('fan_login_watch_active');
			fan_reload_window();
			return;
		}
		else if(data.login_status=='failed'){
			fanDeleteCookie('fan_login_watch_active');
			var alert_msg = 'Login Failed';
			if(typeof(data.login_error)=='string' && data.login_error){
				alert_msg = data.login_error;
			}
			else{
				alert('no reason');
			}
			alert(alert_msg);
			return;
		}
		else if(data.login_status=='pending'){
			fan_pending_login_requests = fan_pending_login_requests + 1;
			if(fan_pending_login_requests>120){ // about 2 minutes
				fanDeleteCookie('fan_login_watch_active');
				return;
			}
		}
		else{
			fan_no_status_login_requests = fan_no_status_login_requests + 1;
			if(fan_no_status_login_requests>10){
				fanDeleteCookie('fan_login_watch_active');
				return;
			}
		}
	}
	
	var parameters = Array();
	parameters['what'] = 'user';
	parameters['op'] = 'get_login_status';
	parameters['session_id'] = fan_user_session;
	
	setTimeout(function(){fan_make_service_call(parameters, function(callback_data){fan_login_watch(callback_data, watchInterval)})}, watchInterval);
}

function fan_init_twitter_login(){
	var user_browser = fan_browser_detect();
	var watchInterval = 1000;
	
	var iframe_src = fan_server_url+'/index.php?what=twitter&op=authentificate';
	iframe_src += "&session_id="+fan_user_session;
	iframe_src += "&return_url="+encodeURIComponent(window.location.href);
	
	if(user_browser=='Safari' || user_browser=='Internet Explorer'){
		iframe_src += "&close_window_on_finish=y";
		login_window_handler = fan_centeredPopUp(iframe_src, 600, 400);
	}
	else{
		var iframe_elem = document.createElement('iframe');
		iframe_elem.src = 'about:blank';
		iframe_elem.marginheight = 0;
		iframe_elem.marginwidth = 0;
		iframe_elem.allowtransparency = "on";
		iframe_elem.frameborder = "0";
		iframe_elem.className = "fan_share_working_frame";
		iframe_elem.style.width = '0px';
		iframe_elem.style.height = '0px';
		
		document.body.appendChild(iframe_elem);
		iframe_elem.src = iframe_src;
	}
	
	setTimeout(function(){fan_login_watch(false, watchInterval)}, watchInterval);
}

function fan_init_facebook_login(){
	var user_browser = fan_browser_detect();
	var watchInterval = 1000;
	
	var iframe_src = fan_server_url+'/index.php?what=facebook&op=authenticate';
	iframe_src += "&session_id="+fan_user_session;
	iframe_src += "&return_url="+encodeURIComponent(window.location.href);
	
	if(user_browser=='Safari' || user_browser=='Internet Explorer'){
		iframe_src += "&close_window_on_finish=y";
		login_window_handler = fan_centeredPopUp(iframe_src, 600, 400);
	}
	else{
		var iframe_elem = document.createElement('iframe');
		iframe_elem.src = 'about:blank';
		iframe_elem.marginheight = 0;
		iframe_elem.marginwidth = 0;
		iframe_elem.allowtransparency = "on";
		iframe_elem.frameborder = "0";
		iframe_elem.className = "fan_share_working_frame";
		iframe_elem.style.width = '0px';
		iframe_elem.style.height = '0px';
		
		document.body.appendChild(iframe_elem);
		iframe_elem.src = iframe_src;
	}

	setTimeout(function(){fan_login_watch(false, watchInterval)}, watchInterval);
}

function fan_init_orkut_login(){
	var user_browser = fan_browser_detect();
	var watchInterval = 1000;
	
	var iframe_src = fan_server_url+'/index.php?what=orkut&op=authenticate';
	iframe_src += "&session_id="+fan_user_session;
	iframe_src += "&return_url="+encodeURIComponent(window.location.href);
	alert(iframe_src)
	return;
	
	if(user_browser=='Safari' || user_browser=='Internet Explorer'){
		iframe_src += "&close_window_on_finish=y";
		login_window_handler = fan_centeredPopUp(iframe_src, 600, 400);
	}
	else{
		var iframe_elem = document.createElement('iframe');
		iframe_elem.src = 'about:blank';
		iframe_elem.marginheight = 0;
		iframe_elem.marginwidth = 0;
		iframe_elem.allowtransparency = "on";
		iframe_elem.frameborder = "0";
		iframe_elem.className = "fan_share_working_frame";
		iframe_elem.style.width = '0px';
		iframe_elem.style.height = '0px';
		
		document.body.appendChild(iframe_elem);
		iframe_elem.src = iframe_src;
	}

	setTimeout(function(){fan_login_watch(false, watchInterval)}, watchInterval);
}

function fan_build_wall_share_text(scrap_details){
	var share_text = '';
	if(scrap_details.tag_free_message_body){
		share_text = scrap_details.tag_free_message_body;
	}
	else if(
		typeof(scrap_details.extra.link)=='object' &&
		typeof(scrap_details.extra.link.title)=='object' &&
		scrap_details.extra.link.title[0]
	){
		share_text = fan_htmlentities(scrap_details.extra.link.title[0]);
	}
	
	return share_text;
}

function fan_expand_container(container_id){
	var container = document.getElementById(container_id);
	container.style.display = 'none';
	container.style.height = 'auto';
	container.style.maxHeight = 'none';
	var dlg = $(container).show('blind');
}

function fan_show_more_link(){
	$('.fan_scrap_message_collapsed').attr('id',
		function(arr){
			if(this.scrollHeight>$('#'+this.id).innerHeight()){
				$('#'+this.id+' ~ .fan_expand_btn_container').show('blind');
			}
		}
	);
}

function fan_display_login_options(login_btn_id, container_id){
	var login_btn = document.getElementById(login_btn_id);
	new fan_menu(login_btn, container_id, false, false, true);
}


function fan_browser_detect() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
			return navigator.userAgent.substr(0,agt.indexOf('\/'));
		}
		else return 'Netscape';
	}
	else if (agt.indexOf(' ') != -1){
		return navigator.userAgent.substr(0,agt.indexOf(' '));
	}
	else {
		return navigator.userAgent;
	}
}


function fan_centeredPopUp(theURL, myWidth, myHeight) {
	var winName = 'feedback';
	var features='toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0';
	var isCenter = 'true';
	if(window.screen)if(isCenter)if(isCenter=="true"){
		var myLeft = (screen.width-myWidth)/2;
		var myTop = (screen.height-myHeight)/2;
		features+=(features!='')?',':'';
		features+=',left='+myLeft+',top='+myTop;
	}
	var handle = window.open(theURL,winName,features+((features!='')?',':'')+'width='+myWidth+',height='+myHeight);
	handle.opener = window;
	handle.focus();
	return handle;
}

function fan_set_url_param($param, $value, $link, $unset){
	if (!$link){
		$link = window.location.href;
	}
	
	var patern = new RegExp("([\&\?])"+$param+"=[^\&]*(\&|$)");
	$link = $link.replace(patern, "$1");
	$last_char = $link.substr(-1);
	
	if (!$unset){
		if ($last_char!='&' && $last_char!='?'){
			if ($link.indexOf('?')!=-1){
				$link += '&';
			}
			else {
				$link += '?';
			}
		}
		$link += $param+"="+encodeURIComponent($value);
	}
	
	return $link;
}

function fan_wall_filter_comments(cat_dropdown){
	var cat_id = parseInt($(cat_dropdown).val());
	if(cat_id>0){
		$(cat_dropdown.parentNode.parentNode).find(".fan_comment_item_container").hide();
		$(cat_dropdown.parentNode.parentNode).find(".cat_id_"+cat_id).show();
	}
	else{
		$(cat_dropdown.parentNode.parentNode).find(".fan_comment_item_container").show();
	}
}

function fan_cancel_bubble(e){
	if (e && e.stopPropagation){ //if stopPropagation method supported
		e.stopPropagation();
	}
	else{
		event.cancelBubble=true;
	}
}

function fan_delete_scrap_image(wall_id, msg_id, parent_id, image_index){
	var scrap_details = false;
	if(typeof(fan_wall_scraps[wall_id][msg_id])=='object'){
		scrap_details = fan_wall_scraps[wall_id][msg_id];
	}
	else if(parent_id && typeof(fan_wall_scraps[wall_id][parent_id].comments[msg_id])=='object'){
		scrap_details = fan_wall_scraps[wall_id][parent_id].comments[msg_id];
	}
	
	if(typeof(scrap_details)=='object'){
		if(!confirm('Delete image?')){
			return false;
		}
		
		var parameters = {
			what:'wall',
			op:'delete_image',
			msg_id:msg_id,
			image_index:image_index
		}
		fan_make_service_call(parameters, fan_delete_scrap_image_callback);
	}
	
	return false;
}

function fan_delete_scrap_image_callback(data){
	if(typeof(data)=='object' && data.successfull){
		fan_set_refresh_wall();
		fan_reload_window();
	}
	else{
		var error_message = 'An error occured while deleting the image';
		if(typeof(data)=='object' && typeof(data.error)=='string' && data.error){
			error_message = data.error;
		}
		alert(error_message);
	}
}

function fan_add_scrap_image(wall_id, msg_id, parent_id){
	var scrap_details = false;
	if(typeof(fan_wall_scraps[wall_id][msg_id])=='object'){
		scrap_details = fan_wall_scraps[wall_id][msg_id];
	}
	else if(parent_id && typeof(fan_wall_scraps[wall_id][parent_id].comments[msg_id])=='object'){
		scrap_details = fan_wall_scraps[wall_id][parent_id].comments[msg_id];
	}
	
	if(typeof(scrap_details)=='object'){
		var content = document.createElement('iframe');
		var frame_src = fan_server_url+'/index.php?session_id='+fan_logged_user_session;
		frame_src += "&what=wall";
		frame_src += "&op=add_image";
		frame_src += "&msg_id="+msg_id;
		
		content.src = frame_src;
		content.style.border = '0px';
		content.style.height = '130px';
		content.style.width = '250px';
		content.setAttribute('frameborder', 0);
		
		fan_show_transparent_bg();
		
		var on_close_callback = function(){
			fan_set_refresh_wall();
			fan_reload_window();
			fan_hide_transparent_bg();
		}
		new fan_window(document.body, 'Add image', content, {onclose:on_close_callback});
	}
	
	return false;
}

function fan_get_scrap_details(wall_id, msg_id, parent_id){
	var scrap_details = false;
	if(typeof(fan_wall_scraps[wall_id][msg_id])=='object'){
		scrap_details = fan_wall_scraps[wall_id][msg_id];
	}
	else if(parent_id && typeof(fan_wall_scraps[wall_id][parent_id].comments[msg_id])=='object'){
		scrap_details = fan_wall_scraps[wall_id][parent_id].comments[msg_id];
	}
	return scrap_details;
}

function fan_display_big_thumb(main_placeholder, wall_id, msg_id, parent_id, image_index){
	scrap_details = fan_get_scrap_details(wall_id, msg_id, parent_id);
	
	if(
		typeof(scrap_details)=='object' &&
		typeof(scrap_details.extra.external_images)=='object' &&
		typeof(scrap_details.extra.external_images[image_index])=='object'
	){
		if(typeof(main_placeholder.img_plh)!='object'){
			var layout_table = document.createElement('table');
			var layout_tbody = document.createElement('tbody');
			var tr = document.createElement('tr');
			var td = document.createElement('td');
			
			main_placeholder.appendChild(layout_table);
			layout_table.appendChild(layout_tbody);
			layout_tbody.appendChild(tr);
			tr.appendChild(td);
			
			main_placeholder.img_plh = td;
			placeholder = td;
		}
		else{
			placeholder = main_placeholder.img_plh;
		}
		
		placeholder.innerHTML = '';
		
		var image_details = scrap_details.extra.external_images[image_index];
		var gallery_array = Array();
		for(var i in scrap_details.extra.external_images){
			var temp_img = scrap_details.extra.external_images[i];
			if(temp_img.uploaded){
				gallery_array[i] = temp_img.original;
			}
		}
		
		var wait_img = document.createElement('img');
		wait_img.src = fan_server_url + '/images/loading/bar_220.gif';
		placeholder.appendChild(wait_img);
		
		var img_obj = document.createElement('img');
		img_obj.src = image_details.thumb_320;
		img_obj.className = 'fan_scrap_big_thumb';
		img_obj.onload = function(){
			placeholder.innerHTML = '';
			placeholder.appendChild(this);
		}
		
		if(image_details.uploaded){
			img_obj.onclick = function(){
				var gallery = new fanPicGallery();
				gallery.set_gallery_pics(gallery_array);
				gallery.show_gallery_pic(image_index);
			}
		}
		
		if(typeof(main_placeholder.is_shown)!='boolean' || !main_placeholder.is_shown){
			$(main_placeholder).show(500);
			main_placeholder.is_shown = true;
		}
	}
}

function fan_mark_user_as_spammer(user_id){
	var user_details = fan_users[user_id];
	if(
		typeof(user_details)=='object' &&
		confirm('Mark '+user_details.name+' as a spammer?\nAll his posts will be deleted!') &&
		prompt('Mark '+user_details.name+' as a spammer?\nAll his posts will be deleted!\nEnter 1234 to continue')=='1234'
	){
		fanSetCookie('fan_client_op', 'mark_user_as_spammer');
		fanSetCookie('fan_client_user_id', user_id);
		fan_set_refresh_wall();

		fan_reload_window();
	}
}