/*********** delete photo buttons ***********/
jQuery.fn.createForm = function(options) {
	var settings = jQuery.extend({
     	// put more defaults here
   	}, options);
	
	// Get page sizes
	var arrPageSizes = ___getPageSize();
	
	// Get page scroll
	var arrPageScroll = ___getPageScroll();
	
	var form = '#create_form';
	var headertxt = '';
	
	if (!settings.parentname)
		headertxt = 'New Section';
	else
		headertxt = settings.parentname;
	
	// ... the code start here ...
	if (!$(form).length) {
   		$('body').append('<div id="create_form" style="display: block; opacity: 1;" class="dialog"><div class="body"><div class="content"><div id="stylized" class="newitemform" style="display:block"><form id="post_form" name="post_form"><input type="hidden" name="post_tid" id="post_tid" value="'+settings.tid+'" /><h1>'+headertxt+'</h1><p></p><label>Title</label><input type="text" name="post_title" id="post_title" maxlength="35" /><label>Content</label><textarea name="post_description" id="post_description"></textarea><center><button class="submit-button" id="create_button">Add</button> or <a href="#" id="cancel_create">cancel</a></center><div class="spacer"></div></form></div></div></div><div class="foot"><a class="cancel close" href="#">close</a></div></div>');
	} else {
		$(form).show();
	}
	
	//<div id="create_form" style="display: block; opacity: 1;" class="dialog"><div class="body"><div class="content"><div id="stylized" class="newitemform" style="display:block"><form id="post_form" name="post_form"><input type="hidden" name="post_tid" id="post_tid" value="'+settings.tid+'" /><h1>Create form</h1><p>You can create your own section/list here.</p><label>Title</label><input type="text" name="post_title" id="post_title" maxlength="35" /><label>Content</label><textarea name="post_description" id="post_description"></textarea><center><button class="submit-button" id="create_button">Add</button> or <a href="#" id="cancel_create">cancel</a></center><div class="spacer"></div></form></div></div></div><div class="foot"><a class="cancel close" href="#">close</a></div></div>
	
	//$('#post_description').autogrow();
	
	if (settings.type == 'child')
		//$('#post_description').after('<label>This will be placed under</label><select name="post_parent" id="post_parent"><option value="'+settings.parent+'">'+settings.parentname+'</option></select><br><br>');
		$('#post_description').after('<input type="hidden" name="post_parent" id="post_parent" value="'+settings.parent+'" />');
		//$("#post_parent").prev().remove().end().remove();
	
	$('#cancel_create').click(function(e){
		e.preventDefault();
		$('.dialog').fadeOut(function() { $('.dialog').remove(); });
	});
	
	/*********** add new item form ***********/
	//$("#create_button").click(function() { 
	$('#create_button').click(function(){
		if ($('#post_title').attr('value') == '') {
			alert('Opps.. You forgot to fill in something?');
			return false;
		}
		$(this).showOverlay();
		$('.dialog').fadeOut('fast');
		$.ajax({
			type: "POST",
			url: "ajax/ajax.add-post.php",
			data: $('#post_form').serialize(), //+ "&post_level=" + post_level,
			complete: function(){
				$(this).removeOverlay()
			},
			success: function(response){
				//location.reload(); // refresh page
				var response_array = response.split('||'); 
				//var new_pid = response_array[1];
				//var new_title = 'aaa';
				//var new_description = 'testse';
				$.cookie('tripdj[settings][gotosection]', response_array[1], { expires: 30 });
				//location.reload(); // refresh page				
				window.location.reload();
				//window.location = ''
				
				//$('#column-left h1').after('<div class="first-level-container" id="postid_'+new_pid+'"><h2 class="first-level"><font style="background:#fff; padding-right:5px;">'+new_title+'</font><span class="title-line"></span></h2><p class="item-date"><font color="#ff0000">New added!</font> | <a href="#" class="options" onclick="return false;">options</a></p><p><div id="photoid_'+new_pid+'" class="item-photo"><ul class="thumbs"><li class="upload-handler"><a onclick="showUploadPanel(\''+new_pid+'\')">Upload Photo</a></li></ul>					<div id="uploadid_'+new_pid+'" class="uploadPanel"><h3>Upload from Computer</h3><p><span>Allowed file format [ jpg, jpeg, png ] & file size [ &lt; 2MB ]</span><span><button id="uploadbtn_'+new_pid+'" class="browse"></button></span>						</p><h3>Upload from URL</h3><p><span>image URL &nbsp;</span><span><input type="text" name="imgurl_<?=$level1_pid?>" id="imgurl_<?=$level1_pid?>"></span><span><button id="copybtn_'+new_pid+'" class="upload" onclick="javascript:inputImageURL(\''+new_pid+'\')"></button></span></p></div></div></p><div style="height:5px"></div><div class="q" id="qcontainer_'+new_pid+'"></div><div class="ask"><p class="gq"><a href="javascript:void(0)">Got question?</a></p><div style="display:none;width:533px"><p>Enter your question:</p><input id="q_'+new_pid+'" type="text"></div></div><div style="height:20px"></div><p id="postdesc_'+new_pid+'" class="desc autogrow" title="Double click to edit">'+new_description+'</p><p id="edit_'+new_pid+'" class="edit-blank">[<a href="#" onclick="editDescription(\'+tid+\',\''+new_pid+'\');return false;">edit</a>]</p><div style="height:30px"></div></div>');
				
				//$('.ask div').askQuestion();
				//$('a.options').optionControl({tid:tid});
			}
		});
		return false;
	});
		
	$(form).css({
		position: 'absolute',
		top:	arrPageScroll[1] + (20),
		left:	arrPageScroll[0] + ((arrPageSizes[2] - $(form).width()) / 2)
	}).show();
	
	$(window)
		.scroll(function(){ // If scroll, calculate the new position
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			$(form).css({
				//top:	arrPageScroll[1] + (50),
				//top: 50,
				left:	arrPageScroll[0] + ((arrPageSizes[2] - $(form).width()) / 2)
			});
		})
		.resize(function() { // If window was resized, calculate the new position
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			$(form).css({
				//top:	arrPageScroll[1] + (50),
				//top: 50,
				left:	arrPageScroll[0] + ((arrPageSizes[2] - $(form).width()) / 2)
			});
		});
		
	/**
	 / THIRD FUNCTION
	 * getPageSize() by quirksmode.com
	 *
	 * @return Array Return an array with page width, height and window width, height
	 */
	function ___getPageSize() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};
	
	/**
	 / THIRD FUNCTION
	 * getPageScroll() by quirksmode.com
	 *
	 * @return Array Return an array with x,y page scroll values.
	 */
	function ___getPageScroll() {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}
		arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};
};

jQuery.fn.copyImg = function(options) {
   	// instead of selecting a static container with 
   	var container = this;
   
   	var settings = jQuery.extend({
     	postid: 0
		// put more defaults here
   	}, options);
   	
   	// ... the code start here ...	
	$.ajax({
		type: "POST",
		url: "ajax/ajax.copy-url-image.php",
		data: "postid=" + settings.postid + "&imgurl=" + settings.imgurl + "&title=" + $('#imgtitle_'+settings.postid).attr('value'),
		beforeSend: function(){
			$(this).showOverlay();
		},
		complete: function(){},
		success: function(response){
			if(response.match('success') == 'success') {
				var response_array = response.split('||'); 
				var id = jQuery.trim(response_array[1]);;	
			} else {
				alert('Opps.. There is error while copying the photo from URL.');
				location.reload();
				return false;
			}
			/*
			$('#postid_'+settings.postid+' .thumbs li.upload-handler').before('<li id="imgid_'+id+'" class="imgset"><a href="php-bin/phpthumb/phpthumb.php?src=../../img/photo/'+id+'.jpg&ws=300&hs=300" class="preview" title="" onclick="javascript:location.href=\'download-photo.php?imageid='+id+'\';return false;"><img src="php-bin/phpthumb/phpthumb.php?src=../../img/photo/'+id+'.jpg&ws=75&hs=75&zc=1" border="0" alt=""></a><span class="delete-img" onclick="confirmDeletePhoto(\''+id+'\',\''+settings.postid+'\')"></span></li>');	
			if( $('#postid_'+settings.postid+' .thumbs > li.imgset').length > 5) {
				$('#postid_'+settings.postid+' .thumbs > li.upload-handler').remove();
				$('#uploadid_'+settings.postid).hide();
			}*/
			
			if ($('#photoid_'+settings.postid+' .thumbs > li.imgset').length) {
				$('#photoid_'+settings.postid+' .thumbs li.upload-handler').siblings(':first').before('<li id="imgid_'+id+'" class="imgset"><a href="php-bin/phpthumb/phpthumb.php?src=../../img/photo/'+id+'.jpg&ws=300&hs=300" class="preview" title="" onclick="javascript:location.href=\'download-photo.php?imageid='+id+'\';return false;"><img src="php-bin/phpthumb/phpthumb.php?src=../../img/photo/'+id+'.jpg&ws=75&hs=75&zc=1" border="0" alt=""></a><span class="delete-img" onclick="confirmDeletePhoto(\''+id+'\',\''+settings.postid+'\')"></span></li>');	
			} else {
				$('#photoid_'+settings.postid+' .thumbs li.upload-handler').before('<li id="imgid_'+id+'" class="imgset"><a href="php-bin/phpthumb/phpthumb.php?src=../../img/photo/'+id+'.jpg&ws=300&hs=300" class="preview" title="" onclick="javascript:location.href=\'download-photo.php?imageid='+id+'\';return false;"><img src="php-bin/phpthumb/phpthumb.php?src=../../img/photo/'+id+'.jpg&ws=75&hs=75&zc=1" border="0" alt=""></a><span class="delete-img" onclick="confirmDeletePhoto(\''+id+'\',\''+settings.postid+'\')"></span></li>');	
			}
			
			if( $('#photoid_'+settings.postid+' .thumbs > li.imgset').length > 5) {
				$('#photoid_'+settings.postid+' .thumbs > li.imgset:last').remove();
			}
			$('#uploadid_'+settings.postid).hide();
			
			imagePreview();
			//$(this).deleteImgButton();
			$(this).removeOverlay();
		}
	}); 
	
   	// if possible, return "this" to not break the chain
   	return this;
};

/*********** delete photo buttons ***********/
jQuery.fn.deleteImgButton = function() {
	$('ul.thumbs li').hover(function() {
		$(this).find('.delete-img').show().end().find('.source-img').show();
    },function(){
    	$(this).find('.delete-img').hide().end().find('.source-img').hide();
   	});	
}

/*********** photo info ***********/
function getSourceInfo(imageid) {
	alert(imageid);
}

var intStartSearch;
function startSearch(value,e) {	
	clearTimeout(intStartSearch);
	if (value != '') {
		intStartSearch = setTimeout("searchKeywords('"+value+"')",1000);
	}
}

function searchKeywords(q) {
	$.ajax({
			url: "ajax/ajax.search.php",
			type: "POST",
			data: 'keywords='+q+'&tid='+tid,
			beforeSend: function(){
				$('#search-form .loading').show();
			},
			success: function(result){
				$('#search-form .loading').hide();
				$('#search-result').html(result);
			}
		});
	return false;
}

/*********** delete photo confirmation prompt ***********/
function confirmDeletePhoto(imageid,parentid) {
	if (!confirm("Are you sure you want to delete this photo?"))
		return false;
	else
		$(this).deleteImg({imgid:imageid,postid:parentid});
}

/*********** delete post confirmation prompt ***********/
function confirmDeleteItem(postid) {
	if (!confirm("Are you sure you want to delete this post?"))
		return false;
	else
		$(this).deletePost({postid:postid});
}

/*********** create post function ***********/
function createPost(tid, postid) {
	$(this).createForm({tid:tid,type:'child',parent:postid,parentname:$('#postid_'+postid).find('h2').html()});
}

/*********** sort post function ***********/
function sortItem(postid) {
	var oldsortno = ($('#sortno_'+postid).val()) ? $('#sortno_'+postid).val() : 0 ;
	if (newsortno = prompt ("Current sort number is "+oldsortno+"\nEnter sort number here","")) {
		$.ajax({
				url: "ajax/ajax.sortpost.php",
				type: "POST",
				data: 'postid='+postid+'&sortno='+newsortno,
				success: function(feedback){}
			});
		return false;
	}
}

/*********** add new item link ***********/
$("#addpost").click(function() {
	$('.newitemform').fadeIn();
	return false;
});	

/*********** create post function ***********/
function editDescription(tid, postid) {
	$('#tempedit_'+postid).remove();
	$('#edit_'+postid).hide();
	var textarea = $('<textarea class="editable" />');
	var content = $('#postdesc_'+postid).html()
						.replace(/<br[\s\/]?>/gi, '\n')
						.replace(/&amp;/gi, '&')
						.replace(/&lt;/gi, '<')
						.replace(/&gt;/gi, '>');

	textarea.width('508px');
	textarea.attr('value', content);
	textarea.css('line-height', '18px');
	$('#postdesc_'+postid).before('<p id="tempedit_'+postid+'" class="autogrow desc"></p>');
	$('#tempedit_'+postid).append(textarea);
	textarea.wrap('<form style="border:1px dotted #C5C5C5"></form>')
			.after('<button class="submit-button" type="submit">Done</button><button class="submit-button cancel" type="cancel">Cancel</button>');
	$('#tempedit_'+postid).find('button[type=submit]')
						  .bind('click', function(e){ 
						  		e.preventDefault();
								var content = $(this).prev().attr('value')
														.replace(/\n/g, '<br>')
														.replace(/&amp;/gi, '&')
														.replace(/&lt;/gi, '<')
														.replace(/&gt;/gi, '>');
								$.ajax({
									type: "POST",
									url: "ajax/ajax.editable.php",
									data: "id=" + postid + "&post_type=desc&value=" + encodeURIComponent(content),
									beforeSend: function(){
										$('#tempedit_'+postid).html('<span><img src="img/indicator.gif" width="16" height="16" border="0" alt="Processing..."></span>').end();
									},
									success: function(del){
										$('#postdesc_'+postid).html(content);
										$('#tempedit_'+postid).remove(); 
										$('#postdesc_'+postid).show();
										$('#edit_'+postid).show();
									}
								});
								return false;
						  });
						  
	$('#tempedit_'+postid).find('button.cancel')
							.bind('click', function(e){ 
								e.preventDefault(); 
								$('#tempedit_'+postid).remove(); 
								$('#postdesc_'+postid).show(); 
								$('#edit_'+postid).show();
							});
	
	textarea.autogrow();	
	$('#postdesc_'+postid).hide();
}

/*********** show Upload Panel ***********/
function showUploadPanel(postid) {
	if($('#uploadid_'+postid).is(':visible')) {
		$('#uploadid_'+postid).slideUp('fast');
		return false;
	}
	
	$(document).click(function(event){ 		
		var target = $(event.target);
		if (target.parents("#photoid_"+postid).length == 0) {				
			$('#uploadid_'+postid).slideUp('fast');
		}
	});	
	
	$('#uploadid_'+postid).slideDown('slow');
	//$('#postdesc_'+postid).before('<div class="uploadPanel"><p class="title">Upload from Computer</p><div class="clear"></div><p>Allowed file format [ jpg, jpeg, png ] & file size [ < 2MB ] </p><button id="uploadbtn_'+postid+'" style="background:url(img/browse.png) no-repeat;"></button><div id="spacer" style="height:10px"></div><p style="margin-left:150px"><b>OR</b></p><div id="spacer" style="height:10px"></div><p class="title">Upload from URL</p><div class="clear"></div><p>image URL &nbsp;</p><input type="text" name="imgurl_'+postid+'" id="imgurl_'+postid+'"><button id="copybtn_'+postid+'" style="background:url(img/upload.png) no-repeat;" onclick="javascript:inputImageURL(\''+postid+'\')"></button><div id="spacer"></div></div>');
}

/*********** validate copy url alert ***********/
function inputImageURL(postid) {
	if ($('#imgurl_'+postid).attr('value') == '') {
		alert('You forgot to enter image URL');
		$('#imgurl_'+postid).focus();
	} else {
		var imgurl = $('#imgurl_'+postid).attr('value');
		$(this).copyImg({postid:postid, imgurl:imgurl});
	}	
	//if (!(imgurl = prompt ("Enter the image URL\nExample:http://www.example.com/images/sample.jpg","http://")))
	//	return false;
	//else			
}

/*********** menu navigation hovering (add to $(document).ready to use this)***********/
$(".options").hover(function(){
	$(this).stop().animate({
		paddingLeft: "20px"
	}, 300);
}, function(){
	$(this).stop().animate({
		paddingLeft: "0px"
	}, 300);
});

this.smartPosition = function(){
	$("#smartnav").before('<div id="smartnav-hook"></div>');
	
	$(window).scroll(function(){
		$(".parent-title").each(function(i) { 
			if ($(window).scrollTop() > $(this).offset({ scroll: false }).top-$(this).height()) {
				$("#smartnav").html($(this).html());
			}
		});
	
		//if  ($(window).scrollTop() > $("#smartnav-hook").offset({ scroll: false }).top){
		if  ($(window).scrollTop() > $('.parent-title:nth-child(1)').offset({ scroll: false }).top+$('.parent-title:nth-child(1)').height()){
			$("#smartnav")
				.show()
				.css("position", "fixed")
				.css("top", "0");
				//.html($(window).scrollTop());	
							
		} else {
			$("#smartnav")
				.hide()
				.css("position", "relative");
  				//.css("top", $("#smartnav-hook").offset);
		}
	}); 
};

jQuery.fn.inputAutoTitles = function(options) {
    // stick all the titles
	this.find('textarea').each(function(i) {
		var title=$(this).attr('title');
			$(this).val(title).addClass('waiting')
                   .blur(function(){
            	       $(this).removeClass('active');
                       if ($(this).val()=='' || $(this).val()==title) $(this).addClass('waiting').val(title);
					   if ($(this).val()=='' || $(this).val()==title) $(this).parent().find('button').remove().end().parent().find('span').remove().end();
				   })
                   .focus(function(){ 
						$(this).removeClass('waiting').addClass('active');
                        if ($(this).val()==title) $(this).val('');
						$(this).parent().find('button').remove().end().parent().find('span').remove().end();
						$(this).before("<span>Q:"+title+"<br></span>");
						$(this).after("<button>Confirm my answer</button>")
							   .bind('click', function(){ 
							   		$(".q button").click(function() {
								    	var answer = $(this).parent().find('textarea').val();
										var qid = $(this).parent().find('textarea').attr('id').replace('ans_','');
										
										$('.q span').remove();$(this).after('<span><img src="img/indicator.gif" width="16" height="16" border="0" alt="Processing..."></span>');
										var self_container = $(this).parent();
										var postid = self_container.parent().attr('id').replace('qcontainer_','')
										var self_content = $('#postdesc_'+postid).html();
										
										$.ajax({
											type: "POST",
											url: "ajax/ajax.edit-answer.php",
											data: "qid=" + qid + "&answer=" + answer,
											complete: function(){
												
											},
											success: function(del){
												$('.q span').remove();
												self_container.hide();												
												var postid = self_container.parent().attr('id').replace('qcontainer_','')
												$('#postdesc_'+postid).html(answer + '<br><br>' + self_content)
												//location.reload(true); // refresh page
											}
										});
										return false;
								   });	
							   });
                   });		
    });
	
	
	
	this.submit(function(e){
		e.preventDefault();
	});
};

jQuery.fn.searchInput = function() {
	var container = this;
	
	this.each(function(i) {
		var title=$(this).attr('title');
			$(this).val(title).addClass('waiting')
                   .blur(function(){
            	       $(this).removeClass('active');
                       if ($(this).val()=='' || $(this).val()==title) $(this).addClass('waiting').val(title);
				   })
                   .focus(function(){ 
						$(this).removeClass('waiting').addClass('active');
                        if ($(this).val()==title) $(this).val('');
                   });		
    });
};

jQuery.fn.askQuestion = function() {
	$('.ask a').click(function(e){
		e.preventDefault();
		$(this).parent().next().fadeIn().end(); //show the input field
		$(this).parent().hide();
	});
	
	$(document).click(function(event){ 		
		var target = $(event.target);
		if (target.parents(".ask").length == 0) {				
			$(".ask p.gq").show();
			$(".ask div").hide();
		}
	});		
	
	this.find('input').each(function(i) {
		if ($(this).val()=='') {
			$(this)//.addClass('waiting')
							.blur(function(){
		            	       $(this).removeClass('active');
		                       if ($(this).val()=='') { 
							   		//$(this).addClass('waiting'); 
									$(this).next().remove();
							   }
		                   })
						    .focus(function(){ 
								$(this).removeClass('waiting').addClass('active');
								$(this).next().remove(); $(this).after("<button>Ask now</button>").next().
									bind('click', function(){ 
										var question = $(this).prev().val();
										var postid = $(this).prev().attr('id').replace('q_','');
										
										var self_container = $(this).parent().parent();
										
										if (question=='') {
											return false;
										} else {
											$(this).after('<span><img src="img/indicator.gif" width="16" height="16" border="0" alt="Processing..."></span>').end();
											$.ajax({
												type: "POST",
												url: "ajax/ajax.add-question.php",
												data: "postid=" + postid + "&question=" + question,
												complete: function(){
												},
												success: function(response){
													self_container.find('div').hide().end().find('div span').remove().end().find('div input').attr('value','');
													self_container.find('p.gq').show();
													var response_array = response.split('||'); 
													$('#qcontainer_'+postid).append('<div class="field"><textarea id="ans_'+response_array[1]+'" class="question" title="'+question+'"></textarea></div>')
													$('.ask div').askQuestion();
													$('.q div.field').inputAutoTitles();
													//location.reload(true); // refresh page
													//window.location.reload(true);
												}
											});
											return false;
										}										
									});
							});
		} else {
			$(this).unbind('click');
        }
			
	});
};

/*********** options menu control ***********/
(function($){
	$.fn.optionControl = function(options){
	
		var defaults = {
			padding: 10,
			bgColor: '#fff',
			borderColor: '#DADADA',
			inline: false,
			overlay: true
		};
		
		var options = $.extend(defaults, options);

		//var linky = '';
		var currentText = '';

		var element = this;
		
		return this.each(function(){
			if(options.overlay === true){
				$(this).hover(
					function(over){
						//linky = $(this).attr('href');
						//currentText = $(this).text();
						currentText = 'options';
						//$(this).removeAttr('href');
						var w = $(this).width();
						
						var postid = $(this).parent().parent().attr('id').replace('postid_','');
						if (isadm) {
							var del_option = '&nbsp;|&nbsp;<a href="#" onclick="confirmDeleteItem(\''+postid+'\');return false;">Delete</a>';
						} else {
							var del_option = '';
						}
						$(this).css('position','relative');
						$(this).html(currentText + '<div id="link-text" style="position:absolute; display:block; border-right:none; z-index:1000; background:' + options.bgColor + '; border:' + options.borderColor + ' 1px solid; border-right:none;">' + currentText + '&raquo;</div><span style="width:auto; position:absolute; top:-' + (options.padding+1) + 'px; left:' + (w+options.padding*2) + 'px; padding:' + options.padding + 'px; background:' + options.bgColor + '; border:' + options.borderColor + ' 1px solid; padding-left:0; z-index:999;"><a alt="Add Listing" href="#" onclick="createPost(\''+options.tid+'\',\''+postid+'\');return false;">Add&nbsp;Listing</a>'+del_option+'&nbsp;|&nbsp;<a href="#" onclick="editDescription(\''+options.tid+'\',\''+postid+'\');return false;">Edit</a>&nbsp;|&nbsp;<a href="#" onclick="toggleRevision(\''+postid+'\');return false;">Revision</a>&nbsp;|&nbsp;<a href="#" onclick="sortItem(\''+postid+'\');return false;">Sort</a></span>');
						
						$('#link-text').css({
							top: '-' + (options.padding+1) + 'px',
							left: '-' + (options.padding+1) + 'px',
							padding: options.padding,
							paddingRight: options.padding+1,
							width: (w+options.padding)
						});
					},
								   
					function(out){
						$(this).html(currentText);
					}
				);
			} // options.overlay
			
		}); // end this.each
	
	}; // end fn.linkControl
	
})(jQuery);

jQuery.fn.expander = function(options) {
   	// instead of selecting a static container with 
   	var container = this;
	
	this.click(function() {
		var checkElement = $(this).parent().parent().next();
		
		if ($.browser.msie) {
			var checkElement = $(this).parent().next();
		}
		
		if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
			$(this).parent().parent().find('span a').html('-');
			checkElement.slideDown('200');
			return false;
		} else {
			$(this).parent().parent().find('span a').html('+');
			checkElement.slideUp('200');
			return false;
		}
	});	
}

//Login Module
function loginAsUser() {
	var login_email=$('#login_email').val(), login_password=$('#login_password').val();
	if ($('#login_email').val()==$('#login_email').attr('title')) login_email = '';
	if ($('#login_password').val()==$('#login_password').attr('title')) login_password = '';
	if (!login_email && !login_password) return false;
	
	var params = 'username='+login_email+'&password='+login_password;
	
	$.ajax({
			url: "ajax/ajax.login.php",
			type: "POST",
			data: params,
			beforeSend: function(){
				$('#login-err').remove();
				$('#login-form .loading').show();
			},
			success: function(result){
				$('#login-form .loading').hide();
				if (result == 'fail') {
					$('#login-form .loading').before('<span id="login-err" style="color:#FF0000">login fail!</span>');
					return false;
				}
				$('#login-form').hide();
				location.reload(); // refresh page
			}
		});
	return false;
}

function logout() {
	$.ajax({
			url: "ajax/ajax.logout.php",
			type: "POST",
			success: function(result){
				location.reload(); // refresh page
			}
		});
	return false;
}

function showRegisterForm(){
	$('#login-form').hide();
	$('#register-form').show();
	return false;
}

//register Module
function registerAsUser() {
	var register_name=$('#register_name').val(),register_email=$('#register_email').val(),register_password=$('#register_password').val();
	if ($('#register_name').val()==$('#register_name').attr('title')) register_name = '';
	if ($('#register_email').val()==$('#register_email').attr('title')) register_email = '';
	if ($('#register_password').val()==$('#register_password').attr('title')) register_password = '';
	if (!register_name && !register_email && !register_password) return false;
	
	var params = 'name='+register_name+'&email='+register_email+'&password='+register_password;
	
	$.ajax({
			url: "ajax/ajax.register.php",
			type: "POST",
			data: params,
			beforeSend: function(){
				$('#register-err').remove();
				$('#register-form .loading').show();
			},
			success: function(result){
				$('#register-form .loading').hide();
				if (result == 'fail') {
					$('#register-form .loading').before('<span id="register-err" style="color:#FF0000">register fail!</span>');
					return false;
				}
				$('#register-form').hide();
				location.reload(); // refresh page
			}
		});
	return false;
}

// toggle latest update
function toggleLastestUpdate() {
	$('.upt-more').toggle();
	if ($('.upt-more:first').is(':visible')) {
		$('#upt-control a').html('show less');
	} else {
		$('#upt-control a').html('show all');
	}
}

this.smartMenu = function(){
	$("#table-content").before('<div id="smartnav-hook"></div>');
	$(window).scroll(function(){
		if  ($(window).scrollTop() > $("#smartnav-hook").offset({ scroll: false }).top+10){
			$("#table-content")
				.css("position", "fixed")
				.css("top", "10px")
				.css("width", "232px");
				//.html($(window).scrollTop());	
							
		} else {
			$("#table-content")
				.css("position", "relative")
				.css("top", "0");
  				//.css("top", $("#smartnav-hook").offset);
		}
	}); 
};

// toggleStickyFeature
function toggleStickyFeature() {
	if (disabled_smartmenu == 1) {
		disabled_smartmenu = 0;
		$('#sticky-control a').html('[sticky <font color="#008000">ON</font>]');
	} else {
		disabled_smartmenu = 1;
		$('#sticky-control a').html('[sticky <font color="#ff0000">OFF</font>]');
	}
	
	if (!$('#smartnav-hook').length) { $("#table-content").before('<div id="smartnav-hook"></div>'); }
	
	$(window).scroll(function(){
		if  ($(window).scrollTop() > $("#smartnav-hook").offset({ scroll: false }).top+10 && disabled_smartmenu == 0){
			$("#table-content")
				.css("position", "fixed")
				.css("top", "10px")
				.css("width", "232px");
		} else {
			$("#table-content")
				.css("position", "relative")
				.css("top", "0");
		}
	}); 
}

/*********** show Revision Panel ***********/
function toggleRevision(postid) {
	$('#revision_'+postid).slideToggle();
	return false;
}

// toggle Revision Detail
function toggleRevisionDescription(revid) {
	$('#revision_'+revid).find('ul').slideToggle();
	$(document).click(function(event){ 		
		var target = $(event.target);
		if (target.parents("#revision_"+revid).length == 0) {				
			$('#revision_'+revid).find('ul').slideUp('fast');
		}
	});	
	return false;
}

// revert Revision
function revertRevision(revid) {
	if (!confirm("Are you sure you want to revert this revision?")) {
		return false;
	} else {
		$.ajax({
			type: "POST",
			url: "ajax/ajax.revert-revision.php",
			data: "revid=" + revid,
			beforeSend: function(){
				//$('#tempedit_'+postid).html('<span><img src="img/indicator.gif" width="16" height="16" border="0" alt="Processing..."></span>').end();
			},
			success: function(response){
				// replace reverted content to existing, desc or title?
				// remove reverted revision
				
				var response_array = response.split('||'); 
				var postid = response_array[0];
				var type = response_array[1];
				var content = $('#revision_'+revid).find('ul li').html();
				
				if (type == 'desc') {
					$('#postdesc_'+postid).html(content);
				} else if (type == 'title') {
					$('#posttitle_'+postid).html(content);
				}
				
				$('#revision_'+revid).remove();
				
				//$('#postdesc_'+postid).html(content);
				//$('#tempedit_'+postid).remove(); 
				//$('#postdesc_'+postid).show();
				//$('#edit_'+postid).show();
			}
		});
	}
	
	return false;
}

// delete Revision
function deleteRevision(revid) {
	if (!confirm("Are you sure you want to delete this revision?")) {
		return false;
	} else {
		$.ajax({
			type: "POST",
			url: "ajax/ajax.delete-revision.php",
			data: "revid=" + revid,
			success: function(response){
				if (response != 'success') {
					return false;
				}
				$('#revision_'+revid).remove();
				
				
			}
		});
	}
	
	return false;
}

// put script to load here
$(document).ready(function(){
	$('.ask div').askQuestion();
	$('.q div.field').inputAutoTitles();
	$('#search-form input,#login-form input,#register-form input').searchInput();
	//smartPosition();
	//smartMenu();
	//$('#table-content .level2expand a,#table-content .level3expand a').expander();
	$('a.options').optionControl({tid:tid});
	
	/*********** question field ***********/
	$('.question').autogrow();
	/*********** editable title ***********/
   	$("#column-left h2:not(.first-level)").editable("ajax/ajax.editable.php", {
		type 	   : "text",
		submit 	   : 'Done',
		submitdata : { post_type:'title' },
		cancel     : 'Cancel',
		tooltip    : "Double click to edit",
		onblur 	   : "ignore",
		width	   : 'auto',
		height     : "16px"
	});
	
	/*********** editable description ***********/
  	$(".autogrow").editable("ajax/ajax.editable.php", {
		type : "autogrow",
		submit : 'Done',
		data: function(value, settings) {
	    	var retval = value
							.replace(/<br[\s\/]?>/gi, '\n')
							.replace(/&amp;/gi, '&')
							.replace(/&lt;/gi, '<')
							.replace(/&gt;/gi, '>');
			return retval;
	    },
		submitdata : {
			post_type : 'desc'
		},
		cancel    : 'Cancel',
		tooltip : "Double click to edit",
		onblur : "ignore",
		width: '508px',
		style: 'border:1px dotted #C5C5C5;',
		autogrow : {
			lineHeight : 16,
			minHeight : 32
		}
	});
	/*********** sort image ***********/
	$('ul.thumbs').sortable({
		accept: 'imgset',
		opacity: '0.5',
		cursor: "move",
		update: function(e, ui){
			serial = $(this).sortable("serialize");	
			$.ajax({
				url: "ajax/ajax.sortdata.php",
				type: "POST",
				data: serial,
				success: function(feedback){}
			});
		}
	});
});

