var regex_alphanumeric = /^[a-zA-Z0-9\-\_\s]{2,}$/;
var templateImageDir = "templates/standard/images/";

function print_r(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

//var functions

function checkboxState(trueFalse) {
	//converts the data received from JS to data ready for the DB
	if (trueFalse) {
		return '1';
	} else {
		return '0';
	}
}

function getUrlVars(link) {
	var vars = [], hash;
	var hashes = link.slice(link.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

function numericOnly(obj) { //removes some characters from a string
	string = $(obj).val();
	changed = true;
	while (changed) {
		oldString = string;
		string = string.replace("-","");
		if (oldString == string) {
			changed = false;
		}
	}
	
	$(obj).val(string);
}

//var functions ******************************************************************************************

//make content strings
function genericJsPopup(titleString, contentString) {
	return '<div class="listcleanblock"><div class="title"><a href="javascript:void(0);" class="button" id="closeButton" style="float: right; margin: -2px 5px 0 0;"><img src="./images/icon_close_16_black.png" alt="X" /></a>' + titleString + '</div><div class="item">' + contentString + '</div></div>';
}

function workingJsPopup(titleString) {
	return genericJsPopup(titleString, showWorking());
}

function showWorking() {
	return '<img src="./images/loading.gif" alt="loading" /> Working...';
}

//jQuery code ********************************************************************************************

function openJsPopup($popup, $background, positionfromTop) {
	$background.insertAfter($('body')).fadeIn('fast');
	$popup.css('top', positionfromTop);
	$popup.insertAfter($('body')).show('fast');
	//jumpToTopOfPopup('jsPopup2'); 
	//$('#jsPopup2').scrollTop(600);
	//$('#jsPopup2').center({horizontal: false});
}

function closeJsPopup($popup, $background) {
	$('#jsDisableOverlay2').remove();
	$('#jsPopup2').remove();
}

function enableJsPopupClosing() {
	$('#closeButton').click(function() {
		closeJsPopup($('#jsPopup2'), $('#jsDisableOverlay2'));
		return false;
	});
	$('#jsDisableOverlay2').click(function() {
		closeJsPopup($('#jsPopup2'), $('#jsDisableOverlay2'));
	});
}

function jumpToTopOfPopup (elementId) {
	window.location.hash = elementId;
}

function strToNum($string) {
	return $string.replace(/[^\d\.]/g, '');
}

//visual stuff
$(document).ready(function() {
	$('.hiddenByDefault').hide();
	$('.editBlock').hover(function() {
		var id = strToNum($(this).attr('id'));
		$('#hiddenByDefault-' + id).show('fast');
	}, function() {
		//$('.hiddenByDefault').hide('fast');
	});
});

//tag create and vote block*******************************************************************************

//save tags to the reeks
$(document).ready(function() {
	$('#tagAddSubmit').click(function() {
		
		var userId = $('#footer > #userId').val();
		var sessionId = $('#footer > #sessionId').val();
		
		//get the reeksId
		var reeksId = $('#generalReeksId').val();
		
		//get the tag
		var tag = $('#tagAddField').val();
		
		if (tag != "") {
			$('#reeksTags').append('<div id="newtag"></div>');
			//$('#newtag').html(tag);
			
			//show working
			htmlContent = showWorking();
			$('#newtag').html(htmlContent);
			
			//submit the vote
			$.post('ajax_save_tag.php', {'u': userId, 's': sessionId, 't': tag, 'r': reeksId}, function(data) {
				//hide working
				$('#newtag').remove();
				
				//remove the message that says there are no tags yet
				$('#noTags').remove();
				
				//insert the tag
				$('#reeksTags').append(data);
				
				//bind
				bindVoteButtons();
				
				//empty the input field
				$('#tagAddField').val('').focus();
			}, "html");
		}
	});
});

function submitTagVote (tagId, vote, $insertSpot, voteType, block) { //submit the vote for a tag for a reeks
	
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	var reeksId = $('#generalReeksId').val();
	
	 if (block == null){
	   block = false;
	 }
	
	htmlContent = showWorking();
	if (voteType == 'reeks_tag') {
		$container = $('#reeksTagIdDiv-'+tagId);
	} else if (voteType == 'recensie') {
		$container = $('.recensieVoteBlock');
		$block = $('#bigvoteblock');
	} else if (voteType == 'interview') {
		$container = $('.interviewVoteBlock');
		$block = $('#bigvoteblock');
	}
	$container.html(htmlContent);
	if (block) {
		$block.html('<div>' + htmlContent + '</div>');
	}
	
	$.post('ajax_save_tag_vote.php', {'u': userId, 's': sessionId, 'v': vote, 't': tagId, 'r': reeksId, 'voteType': voteType}, function(data) {
		$container.html(data);
		bindVoteButtons();
		$('#tagAddField').focus();
	}, "html");
	
	if (block) {
		$.post('ajax_show_voteblock.php', {'u': userId, 's': sessionId, 'id': tagId, 'mode': voteType}, function(data) {
			$block.html(data);
		}, "html");
	} else {
	}
}

//tag vote code
function bindVoteButtons() {
	$('.voteForTagUp').click(function() {
		//get the id of the clicked element
		var tagId = strToNum($(this).attr('id'));
		vote = '1';
		submitTagVote(tagId, vote, this, 'reeks_tag');
	});
	$('.voteForTagCancel').click(function() {
		//get the id of the clicked element
		var tagId = strToNum($(this).attr('id'));
		vote = '0';
		submitTagVote(tagId, vote, this, 'reeks_tag');
	});
	$('.voteForRecensieUp').click(function() {
		//get the id of the clicked element
		var recensieId = strToNum($(this).attr('id'));
		vote = '1';
		submitTagVote(recensieId, vote, this, 'recensie', true);
	});
	$('.voteForRecensieCancel').click(function() {
		//get the id of the clicked element
		var recensieId = strToNum($(this).attr('id'));
		vote = '0';
		submitTagVote(recensieId, vote, this, 'recensie', true);
	});
	$('.voteForInterviewUp').click(function() {
		//get the id of the clicked element
		var interviewId = strToNum($(this).attr('id'));
		vote = '1';
		submitTagVote(interviewId, vote, this, 'interview', true);
	});
	$('.voteForInterviewCancel').click(function() {
		//get the id of the clicked element
		var interviewId = strToNum($(this).attr('id'));
		vote = '0';
		submitTagVote(interviewId, vote, this, 'interview', true);
	});
}

$(document).ready(function() {
	bindVoteButtons();
});

//end tag create and vote block***************************************************************************

//begin aanbieden part************************************************************************************

$(document).ready(function() {
	bindAanbiedingButtons();
});

function bindAanbiedingButtons() {
	$('.showAanbiedenBit').click(function() {
		var stripId = strToNum($(this).attr('id'));
		
		$('#showAanbiedenBit-' + stripId).parent().remove();
		
		$('#aanbiedenBit-' + stripId).html(showWorking());
		
		$.post('ajax_aanbieden.php', {'st': stripId, 'mode': 'initialShow'}, function(data) {
			$('#aanbiedenBit-' + stripId).html(data);
			bindAanbiedingButtons();
		}, "html");
	});
	$('.saveAanbieding').click(function() {
		var stripId = strToNum($(this).attr('id'));
		
		var prijs = $('#prijs-' + stripId).val();
		var opmerking = $('#opmerking-' + stripId).val();
		var inJsPopup = $('#inJsPopup-' + stripId).val();
		if (inJsPopup != 'true') inJsPopup = '';
		//var status = checkboxState($('#status').attr("checked"));
		var status = 1;
		
		$('#aanbiedenBit-' + stripId).html(showWorking());
		
		$.post('ajax_aanbieden.php', {'st': stripId, 'prijs': prijs, 'opmerking': opmerking, 'status': status, 'mode': 'save', 'inJsPopup': inJsPopup}, function(data) {
			if (inJsPopup == 'true') {
				$('#aanbiedenBit-' + stripId).replaceWith(data);
				closeJsPopup('x', 'y');
			} else {
				$('#aanbiedenBit-' + stripId).html(data);
			}
			bindAanbiedingButtons(); //in case we are in strip.php
			marktplaatsCatchClick(); //in case we are in markplaats.php
		}, "html");
		
		return false;
	});
	$('.stripNietMeerAanbieden').click(function() {
		stripNietMeerAanbieden($(this));
	});
}

function stripNietMeerAanbieden($element, marktplaats) {
	var stripId = strToNum($element.attr('id'));
	
	$('#aanbiedenBit-' + stripId).html(showWorking());
	
	$.post('ajax_aanbieden.php', {'st': stripId, 'mode': 'delete', 'marktplaats': marktplaats}, function(data) {
		if (data == 'Verwijderen succesvol') {
			$('#aanbiedenBit-' + stripId).html(data);
		} else {
			$('#aanbiedenBit-' + stripId).html('');
			$('#stripButtons-' + stripId).append('<div class="fancy button"><a id="showAanbiedenBit-' + stripId + '" class="markup showAanbiedenBit" href="javascript:void(0);">Aanbieden<img style="position: absolute; margin: -7px 0 0 7px;" alt="Aanbieden" src="images/icon_market_place_32_black.png"></a></div>');
			bindAanbiedingButtons();
		}
	}, "html");
	
	return false;
}

//begin marktplaats part *********************************************************************************
$(document).ready(function() {
	bindMarktplaatsElements();
});

function bindMarktplaatsElements() {
	$marktplaatsContainer = $('#marktplaatsContainer');
	
	$('#marktNieuw').click(function() {
		htmlContent = '<div id="marktplaatsNieuweAanbiedingen"></div>';
		$marktplaatsContainer.html(htmlContent);
		bindMarktplaatsElements();
	});
	$('#marktZoek').click(function() {
		htmlContent = '<div id="marktplaatsGezochteStrips">Strips die ik zoek</div>';
		$marktplaatsContainer.html(htmlContent);
		bindMarktplaatsElements();
	});
	$('#marktLopend').click(function() {
		htmlContent = '<div id="marktplaatsLopendeDeals">Lopende deals</div>';
		$marktplaatsContainer.html(htmlContent);
		bindMarktplaatsElements();
	});
	$('#marktAanbiedingen').click(function() {
		htmlContent = '<div id="marktplaatsAangebodenStrips">Mijn aanbiedingen</div>';
		$marktplaatsContainer.html(htmlContent);
		bindMarktplaatsElements();
	});
	$('#marktZoeken').click(function() {
		htmlContent = '<div id="marktplaatsZoeken">Zoeken</div>';
		$marktplaatsContainer.html(htmlContent);
		bindMarktplaatsElements();
	});
	
	$marktplaatsNieuweAanbiedingen = $('#marktplaatsNieuweAanbiedingen');
	if ($marktplaatsNieuweAanbiedingen.length != 0) {
		$marktplaatsNieuweAanbiedingen.html(showWorking());
		$.post('marktplaats.php', {'mode': 'marktNieuw'}, function(data) {
			$marktplaatsNieuweAanbiedingen.html(data);
			marktplaatsCatchClick($marktplaatsNieuweAanbiedingen);
		});
	}
	
	$marktplaatsGezochteStrips = $('#marktplaatsGezochteStrips');
	if ($marktplaatsGezochteStrips.length != 0) {
		$marktplaatsGezochteStrips.html(showWorking());
		$.post('marktplaats.php', {'mode': 'marktZoek'}, function(data) {
			$marktplaatsGezochteStrips.html(data);
			marktplaatsCatchClick($marktplaatsGezochteStrips);
		});
	}
	
	$marktplaatsLopendeDeals = $('#marktplaatsLopendeDeals');
	if ($marktplaatsLopendeDeals.length != 0) {
		$marktplaatsLopendeDeals.html(showWorking());
		$.post('marktplaats.php', {'mode': 'marktLopend'}, function(data) {
			$marktplaatsLopendeDeals.html(data);
			marktplaatsCatchClick($marktplaatsLopendeDeals);
		});
	}
	
	$marktplaatsAangebodenStrips = $('#marktplaatsAangebodenStrips');
	if ($marktplaatsAangebodenStrips.length != 0) {
		$marktplaatsAangebodenStrips.html(showWorking());
		$.post('marktplaats.php', {'mode': 'marktAanbiedingen'}, function(data) {
			$marktplaatsAangebodenStrips.html(data);
			marktplaatsCatchClick($marktplaatsAangebodenStrips);
		});
	}
	
	$marktplaatsZoeken = $('#marktplaatsZoeken');
	if ($marktplaatsZoeken.length != 0) {
		$marktplaatsZoeken.html(showWorking());
		$.post('marktplaats.php', {'mode': 'marktZoeken'}, function(data) {
			$marktplaatsZoeken.html(data);
			marktplaatsCatchClick($marktplaatsZoeken);
		});
	}
}

function marktplaatsCatchClick($element) {
	$('.ajaxLink').click(function() {
		var url = $(this).attr("href");
		
		$.get(url, function(data) {
			$element.html(data);
			marktplaatsCatchClick($element);
		});
		return false;
	});
	$('#marktZoekterm').keypress(function(e) {
		if (e.keyCode == '13') {
			marktplaatsZoekResultaten();
		}
	});
	$('#marktZoekButton').click(function() {
		marktplaatsZoekResultaten()
	});
	$('.marktplaatsStripAanbiedingAanpassen').click(function() {
		var stripId = strToNum($(this).attr('id'));
		
		var $popup = $('<div id="jsPopup2"></div>').hide();
		var $background = $('<div id="jsDisableOverlay2"></div>').hide();
			
		//get the id of the clicked element
		var stripId = strToNum($(this).attr('id'));
		
		positionFromTop = parseInt($(this).offset().top);
		//show the popup and block the rest
		openJsPopup($popup, $background, positionFromTop)
		
		titel = 'Aangeboden strip aanpassen';
		
		htmlContent = workingJsPopup(titel);
		$popup.html(htmlContent);
		
		$.post('ajax_aanbieden.php', {'st': stripId, 'mode': 'initialShow', 'inJsPopup': 'true'}, function(data) {
			$popup.html(genericJsPopup(titel, data));
			bindAanbiedingButtons();
		
			//when to close the popup					
			enableJsPopupClosing();
		}, "html");
		
		//when to close the popup					
		enableJsPopupClosing();
	});
	$('.marktplaatsStripNietMeerAanbieden').click(function() {
		//alert('marktplaatsStripNietMeerAanbieden');
		stripNietMeerAanbieden($(this), 'marktplaats');
	});
}

function marktplaatsZoekResultaten() {
	var zoekTerm = $('#marktZoekterm').val();
	
	$results = $('#marktZoekResultaten');
	
	$results.html(showWorking());
	
	$.get('?mode=marktZoeken&zoekterm=' + zoekTerm, function(data) {
		$results.html(data);
	});
}

//begin collection part***********************************************************************************

//show collectionbit
$(document).ready(function() {
	$('.showCollectionBit').click(function() {
		var stripId = strToNum($(this).attr('id'));
		
		htmlContent = showWorking();
		$('#collectieBit-' + stripId).html(htmlContent);
		
		$.post('ajax_strip_collection.php', {'st': stripId, 'mode': 'save'}, function(data) {
			$('#collectieBit-' + stripId).html(data);
		}, "html");
	});
	bindDeleteFromCollectionButtons();
});

function bindDeleteFromCollectionButtons() {
	$('.stripCollectieDelete').click(function() {
		stripCollectionId = strToNum($(this).attr('id'));
		
		$('#stripCollectieBitId-' + stripCollectionId).html(showWorking());
		
		$.post('ajax_strip_collection.php', {'id': stripCollectionId, 'mode': 'delete'}, function(data) {
			$('#stripCollectieBitId-' + stripCollectionId).html(data);
			$('.stripCollectieUndoDelete').click(function() {
				var st = $('#TABLE_MEMBER_COLLECTION_STRIP_ID').val();
				var bezit = $('#TABLE_MEMBER_COLLECTION_BEZIT').val();
				var datum = $('#TABLE_MEMBER_COLLECTION_DATUM').val();
				var prijs = $('#TABLE_MEMBER_COLLECTION_PRIJS').val();
				var wishlist = $('#TABLE_MEMBER_COLLECTION_WISHLIST').val();
				var gelezen = $('#TABLE_MEMBER_COLLECTION_GELEZEN').val();
				var opmerking = $('#TABLE_MEMBER_COLLECTION_OPMERKING').val();
				var score = $('#TABLE_MEMBER_COLLECTION_SCORE').val();
				var druk = $('#TABLE_MEMBER_COLLECTION_DRUK').val();
				var aantal = $('#TABLE_MEMBER_COLLECTION_AANTAL').val();
				var locatie = $('#TABLE_MEMBER_COLLECTION_LOCATIE').val();
				var aanbieding = $('#TABLE_MEMBER_COLLECTION_AANBIEDING').val();
				var aanbiedingDatum = $('#TABLE_MEMBER_COLLECTION_AANBIEDING_DATUM').val();
				
				$('#stripCollectieBitId-' + stripCollectionId).html(showWorking());
				
				$.post('ajax_strip_collection.php', {'st': st, 'bezit': bezit, 'datum': datum, 'prijs': prijs, 'wishlist': wishlist, 'gelezen': gelezen, 'opmerking': opmerking, 'score': score, 'druk': druk, 'aantal': aantal, 'locatie': locatie, 'aanbieding': aanbieding, 'aanbiedingDatum': aanbiedingDatum, 'mode': 'reSave'}, function(data) {
					$('#collectieBit-' + st).html(data);
					bindDeleteFromCollectionButtons();
				}, "html");
			});
		}, "html");
	});
}

//end collection part*************************************************************************************

//begin covertekst part***********************************************************************************

//show covertekst strips
$(document).ready(function() {
	$('.showcovertekst').click(function() {
		//get the id of the clicked element
		var stripId = strToNum($(this).attr('id'));
		
		//show working
		htmlContent = showWorking();
		
		var $contentField = $('<div id="covertekst-'+stripId+'"></div>').hide();
		var $parentDiv = $(this).parent().parent();
		
		$contentField.html(htmlContent);
		$contentField.insertAfter($(this).parent().parent()).show('fast');
		$(this).parent().hide();
		
		//get the covertekst html
		$.post('ajax_strip_get_covertekst.php', {'st': stripId}, function(data) {
			//show the covertekst
			$contentField.hide;
			$contentField.html(data);
			$contentField.show('fast');
		});
		
		return false;
	});
});

//end covertekst part*************************************************************************************

//********************************************************************************************************

//story arc edit (add + edit)
$(document).ready(function() {
	if ($('#cycliManageInterfaceStripId').length != 0) {
		var checkId = $('#cycliManageInterfaceStripId').val();
		
		if (checkId.substr(0,8) == 'stripId-') {
			$('#cycliManageInterface').html(showWorking());
			
			var stripId = strToNum(checkId);
			
			$.post('ajax_manage_strip_story_arcs.php', {'st': stripId}, function(data) {
				showCycliManageInterface(data, false);
			});
		}
	}
});

function showCycliManageInterface(htmlData, popup) {
	if (popup) {
		var $popup = $('#jsPopup2');
		var $container = $('#jsPopup2');
		var $background = $('#jsDisableOverlay2');
	
		//show the interface
		$popup.html(genericJsPopup('Cycli beheren voor deze strip', htmlData));
		embedded = 0;
		approve = 0;
	} else {
		$container = $('#cycliManageInterface');
		$container.html(htmlData);
		embedded = 1;
		approve = 1;
	}
	
	$('#storyArcAddField').focus();
	
	//bind the autocomplete field
	autoCompleteFunction('storyArcAddField', 'autocompleteStoryArc.php');
	
	$('#storyArcAddButton').click(function() {
		var storyArc = $('#storyArcAddField').val();
		var stripId = $('#id-storyArcAddStripId').val();
		//alert(stripId);
		
		if (storyArc.length) {
			nr = $('#storyArcNr').val();
			$container.html(showWorking());
			$.post('ajax_manage_strip_story_arcs.php', {'st': stripId, 'storyArc': storyArc, 'nr': nr, 'mode': 'add', 'approve': approve}, function(data) {
				//we have submitted data, show the interface again
				showCycliManageInterface(data, popup);
			});
		}
		return false;
	});
	
	$('.stripStoryArcDel').click(function() {
		var stripStoryArcId = strToNum($(this).attr('id'));
		var stripId = $('#id-storyArcAddStripId').val();
		
		$(this).replaceWith('<span id="tmpWorking-' + stripStoryArcId + '">' + showWorking() + '</span>');
		
		$.post('ajax_manage_strip_story_arcs.php', {'st': stripId, 'stripStoryArcId': stripStoryArcId, 'mode': 'del', 'approve': approve}, function(data) {
			if (approve == 0) {
				$('#tmpWorking-' + stripStoryArcId).html(data); //.remove();
				$('#stripStoryArcName-' + stripStoryArcId).css("text-decoration", "line-through");
			} else {
				showCycliManageInterface(data, popup);
			}
		});
	});
	
	//activate the close button
	$('#closeButton').click(function() {
		closeJsPopup($popup, $background);
		return false;
	});
}

function manageCycli(element) {
	var $popup = $('<div id="jsPopup2"></div>').hide();
	var $background = $('<div id="jsDisableOverlay2"></div>').hide();
		
	//get the id of the clicked element
	var stripId = strToNum($(element).attr('id'));
	
	positionFromTop = parseInt($(element).offset().top);
	//show the popup and block the rest
	openJsPopup($popup, $background, positionFromTop)
	
	htmlContent = workingJsPopup('Cycli beheren voor deze strip');
	$popup.html(htmlContent);
	
	$.post('ajax_manage_strip_story_arcs.php', {'st': stripId}, function(data) {
		showCycliManageInterface(data, true);
	});
	
	//when to close the popup
	$background.click(function() {
		closeJsPopup($popup, $background);
	});
}

//********************************************************************************************************

//link strips to trivia

$(document).ready(function() {
	if ($('#triviaToStripInterfaceTriviaId').length != 0) {
		var checkId = $('#triviaToStripInterfaceTriviaId').val();
		if (checkId.substr(0,9) == 'triviaId-') {
			$('#triviaToStripInterface').html(showWorking());
			
			var userId = $('#footer > #userId').val();
			var sessionId = $('#footer > #sessionId').val();
			var reeksId = strToNum($('#triviaToStripInterfaceReeksId').val());
			var triviaId = strToNum($('#triviaToStripInterfaceTriviaId').val());
			
			$.post('ajax_manage_trivia_reeks.php', {'u': userId, 's': sessionId, 'reeksId': reeksId, 'triviaId': triviaId}, function(data) {
				showTriviaStripManageInterface(data, true);
			});
		}
	}
});

function showTriviaStripManageInterface(htmlData) {
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	
	//show the interface
	$('#triviaToStripInterface').html(htmlData);
	
	$('#triviaStripAddField').focus();
	
	var reeksId = strToNum($('#reeksId').val());
	
	//bind the autocomplete field
	autoCompleteFunction('triviaStripAddField', 'autocompleteStripsForReeks.php', 'bindId', 0, reeksId);
	
	$('#triviaStripAddButton').click(function() {
		var triviaId = strToNum($('#triviaId').val());
		var stripsId = strToNum($('#id-triviaStripAddField').val());
		
		if (reeksId.length && triviaId.length && stripsId.length && reeksId > 0 && triviaId > 0 && stripsId > 0) {
			$('#triviaToStripInterface').html(showWorking());
			
			$.post('ajax_manage_trivia_reeks.php', {'u': userId, 's': sessionId, 'stripsId': stripsId, 'reeksId': reeksId, 'triviaId': triviaId, 'mode': 'add'}, function(data) {
				//we have submitted data, show the interface again
				showTriviaStripManageInterface(data);
			});
		} else {
			alert('Geen geldige strip geselecteerd');
		}
		return false;
	});
	$('.stripsTriviaDel').click(function() {
		var stripsTriviaId = strToNum($(this).attr('id'));
		var triviaId = strToNum($('#triviaId').val());
		var reeksId = strToNum($('#reeksId').val());
		
		$('#auteurManageInterface').html(showWorking());
		
		$.post('ajax_manage_trivia_reeks.php', {'u': userId, 's': sessionId, 'triviaId': triviaId, 'reeksId': reeksId, 'stripsTriviaId': stripsTriviaId, 'mode': 'del'}, function(data) {
			//we have submitted data, show the interface again
			showTriviaStripManageInterface(data);
		});
	});
}

//********************************************************************************************************

//auteur edit (add + edit)

$(document).ready(function() {
	if ($('#auteurManageInterfaceStripId').length != 0) {
		var checkId = $('#auteurManageInterfaceStripId').val();
		if (checkId.substr(0,8) == 'stripId-') {
			$('#auteurManageInterface').html(showWorking());
			
			var userId = $('#footer > #userId').val();
			var sessionId = $('#footer > #sessionId').val();
			var stripId = strToNum($('#auteurManageInterfaceStripId').val());
			
			$.post('ajax_manage_strip_auteurs.php', {'u': userId, 's': sessionId, 'st': stripId}, function(data) {
				showAuteurManageInterface(data, true);
			});
		}
	}
});

function showAuteurManageInterface(htmlData) {
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	
	//show the interface
	$('#auteurManageInterface').html(htmlData);
	
	$('#stripAuteurAddField').focus();
	
	//bind the autocomplete field
	autoCompleteFunction('stripAuteurAddField', 'autocompleteAuteur.php', 'bindId');
	autoCompleteFunction('stripAuteurFunctie', 'autocompleteFunctie.php', 'bindId');
	
	$('#stripAuteurAddButton').click(function() {
		var auteur = $('#id-stripAuteurAddField').val();
		var functie = $('#id-stripAuteurFunctie').val();
		var stripId = $('#id-stripAuteurStrip').val();
		
		if (auteur.length && functie.length && stripId.length && auteur > 0 && functie > 0 && stripId > 0) {
			$('#auteurManageInterface').html(showWorking());
			
			$.post('ajax_manage_strip_auteurs.php', {'u': userId, 's': sessionId, 'st': stripId, 'auteur': auteur, 'functie': functie, 'mode': 'add', 'approve': '1'}, function(data) {
				//we have submitted data, show the interface again
				showAuteurManageInterface(data);
			});
		} else {
			alert('Geen geldige auteur en functie geselecteerd');
		}
		return false;
	});
	
	$('.stripAuteurDel').click(function() {
		var stripAuteurId = strToNum($(this).attr('id'));
		var stripId = $('#id-stripAuteurStrip').val();
		
		$('#auteurManageInterface').html(showWorking());
		
		$.post('ajax_manage_strip_auteurs.php', {'u': userId, 's': sessionId, 'st': stripId, 'stripAuteurId': stripAuteurId, 'mode': 'del', 'approve': '1'}, function(data) {
			//we have submitted data, show the interface again
			showAuteurManageInterface(data);
		});
	});
}

function manageAuteur(element) {
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	
	var $popup = $('<div id="jsPopup2"></div>').hide();
	var $background = $('<div id="jsDisableOverlay2"></div>').hide();
		
	//get the id of the clicked element
	var stripId = strToNum($(element).attr('id'));
	
	positionFromTop = parseInt($(element).offset().top);
	//show the popup and block the rest
	openJsPopup($popup, $background, positionFromTop)
	
	var htmlContent = workingJsPopup('Auteurs beheren voor deze strip');
	$popup.html(htmlContent);
	
	$.post('ajax_manage_strip_auteurs.php', {'u': userId, 's': sessionId, 'st': stripId}, function(data) {
		showAuteurManageInterfacePopup(data);
	});
	
	//when to close the popup
	$background.click(function() {
		closeJsPopup($popup, $background);
	});
}

function showAuteurManageInterfacePopup(htmlData) {
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	
	//show the interface
	var $popup = $('#jsPopup2');
	var $background = $('#jsDisableOverlay2');
	
	$popup.html(genericJsPopup('Auteurs beheren voor deze strip', htmlData));
	
	$('#stripAuteurAddField').focus();
	
	//bind the autocomplete field
	autoCompleteFunction('stripAuteurAddField', 'autocompleteAuteur.php', 'bindId');
	autoCompleteFunction('stripAuteurFunctie', 'autocompleteFunctie.php', 'bindId');
	
	$('#stripAuteurAddButton').click(function() {
		var auteur = $('#id-stripAuteurAddField').val();
		var functie = $('#id-stripAuteurFunctie').val();
		var stripId = $('#id-stripAuteurStrip').val();
		if (auteur.length && functie.length && auteur > 0 && functie > 0) {
			$.post('ajax_manage_strip_auteurs.php', {'u': userId, 's': sessionId, 'st': stripId, 'auteur': auteur, 'functie': functie, 'mode': 'add'}, function(data) {
				//we have submitted data, show the interface again
				showAuteurManageInterfacePopup(data);
			});
		} else {
			alert('Geen geldige auteur en functie geselecteerd');
		}
		return false;
	});
	
	$('.stripAuteurDel').click(function() {
		var stripAuteurId = strToNum($(this).attr('id'));
		var stripId = $('#id-stripAuteurStrip').val();
		
		$(this).replaceWith('<span id="tmpWorking-' + stripAuteurId + '">' + showWorking() + '</span>');
		$.post('ajax_manage_strip_auteurs.php', {'u': userId, 's': sessionId, 'st': stripId, 'stripAuteurId': stripAuteurId, 'mode': 'del'}, function(data) {
			$('#tmpWorking-' + stripAuteurId).html(data); //.remove();
			$('#stripAuteurName-' + stripAuteurId).css("text-decoration", "line-through");
		});
	});
	
	//activate the close button
	$('#closeButton').click(function() {
		closeJsPopup($popup, $background);
		return false;
	});
}

//********************************************************************************************************

//karakter edit (add + edit)
$(document).ready(function() {
	if ($('#personageManageInterfaceStripId').length != 0) {
		var checkId = $('#personageManageInterfaceStripId').val();
		
		if (checkId.substr(0,8) == 'stripId-') {
			$('#personageManageInterface').html(showWorking());
			
			var stripId = strToNum(checkId);
			
			$.post('ajax_manage_strip_karakters.php', {'st': stripId}, function(data) {
				showKarakterManageInterface(data, false);
			});
		}
	}
	
	$('.manageStripsVoorPersonage').click(function() {
		var $popup = $('<div id="jsPopup2"></div>').hide();
		var $background = $('<div id="jsDisableOverlay2"></div>').hide();
			
		//get the id of the clicked element
		var personageId = strToNum($(this).attr('id'));
		//alert(personageId);
		
		positionFromTop = parseInt($(this).offset().top);
		//show the popup and block the rest
		openJsPopup($popup, $background, positionFromTop);
		
		var htmlContent = workingJsPopup('Strips beheren voor dit personage');
		$popup.html(htmlContent);
		
		$.post('ajax_manage_personage_strips.php', {'p': personageId}, function(data) {
			showStripPersonageManageInterface(data, true);
		});
		
		//when to close the popup
		$background.click(function() {
			closeJsPopup($popup, $background);
		});
		return false;
	});
});

function showStripPersonageManageInterface(htmlData) {
	var $popup = $('#jsPopup2');
	var $background = $('#jsDisableOverlay2');
		
	$popup.html(genericJsPopup('Personages beheren voor deze strip', htmlData));
	
	$('#personageStripsAddField').focus();

	//bind the autocomplete field
	autoCompleteFunction('personageStripsAddField', 'autocompleteStrips.php', 'bindId');
	
	$('#personageStripsAddButton').click(function() {
		var personage = $('#id-personageStrips').val();
		var stripsId = $('#id-personageStripsAddField').val();
		if (stripsId.length && stripsId > 0) {
			$.post('ajax_manage_personage_strips.php', {'s': stripsId, 'p': personage, 'mode': 'add'}, function(data) {
				//we have submitted data, show the interface again
				showStripPersonageManageInterface(data);
			});
		} else {
			alert('Geen geldige strip geselecteerd');
		}
		return false;
	});
	
	$('.personageStripsDel').click(function() {
		var personageStripsId = strToNum($(this).attr('id'));
		var personage = $('#id-personageStrips').val();
		
		//$(this).replaceWith('<span id="tmpWorking-' + personageStripsId + '">' + showWorking() + '</span>');
		$.post('ajax_manage_personage_strips.php', {'p': personage, 'personageStripsId': personageStripsId, 'mode': 'del'}, function(data) {
			//$('#tmpWorking-' + personageStripsId).html(data); //.remove();
			alert(data);
			$('#personageStripsName-' + personageStripsId).css("text-decoration", "line-through");
		});
	});
	
	//when to close the popup
	$background.click(function() {
		closeJsPopup($popup, $background);
	});
	return false;
}

function manageKarakter(element) {
	var $popup = $('<div id="jsPopup2"></div>').hide();
	var $background = $('<div id="jsDisableOverlay2"></div>').hide();
		
	//get the id of the clicked element
	var stripsId = strToNum($(element).attr('id'));
	
	positionFromTop = parseInt($(element).offset().top);
	//show the popup and block the rest
	openJsPopup($popup, $background, positionFromTop);
	
	var htmlContent = workingJsPopup('Personages beheren voor deze strip');
	$popup.html(htmlContent);
	
	$.post('ajax_manage_strip_karakters.php', {'st': stripsId}, function(data) {
		showKarakterManageInterface(data, true);
	});
	
	//when to close the popup
	$background.click(function() {
		closeJsPopup($popup, $background);
	});
}

function showKarakterManageInterface(htmlData, popup) {
	if (popup) {
		//show the interface
		var $popup = $('#jsPopup2');
		var $background = $('#jsDisableOverlay2');
		
		$popup.html(genericJsPopup('Personages beheren voor deze strip', htmlData));
		embedded = false;
		approve = 0;
	} else {
		$container = $('#personageManageInterface');
		$container.html(htmlData);
		embedded = true;
		approve = 1;
	}
	
	$('#stripKarakterAddField').focus();
	
	//bind the autocomplete field
	autoCompleteFunction('stripKarakterAddField', 'autocompleteKarakter.php', 'bindId');
	
	$('#stripKarakterAddButton').click(function() {
		var karakter = $('#id-stripKarakterAddField').val();
		var stripsId = $('#id-stripKarakterStrip').val();
		if (karakter.length && karakter > 0) {
			$.post('ajax_manage_strip_karakters.php', {'st': stripsId, 'karakter': karakter, 'mode': 'add', 'approve': approve}, function(data) {
				//we have submitted data, show the interface again
				showKarakterManageInterface(data, popup);
			});
		} else {
			alert('Geen geldig personage geselecteerd');
		}
		return false;
	});
	
	$('.stripKarakterDel').click(function() {
		var stripKarakterId = strToNum($(this).attr('id'));
		var stripsId = $('#id-stripKarakterStrip').val();
		
		$(this).replaceWith('<span id="tmpWorking-' + stripKarakterId + '">' + showWorking() + '</span>');
		$.post('ajax_manage_strip_karakters.php', {'st': stripsId, 'stripKarakterId': stripKarakterId, 'mode': 'del', 'approve': approve}, function(data) {
			if (approve == 0) {
				$('#tmpWorking-' + stripKarakterId).html(data); //.remove();
				$('#stripKarakterName-' + stripKarakterId).css("text-decoration", "line-through");
			} else {
				showKarakterManageInterface(data, popup);
			}
		});
	});
	
	$('#stripKarakterMakeButton').click(function() {
		var karName = $('#stripKarakterMakeField').val();
		var stripsId = $('#id-stripKarakterStrip').val();
		if (karName.length) {
			$.post('ajax_manage_strip_karakters.php', {'st': stripsId, 'name': karName, 'mode': 'make'}, function(data) {
				//we have submitted data, show the interface again
				showKarakterManageInterface(data, popup);
			});
		}
	});
	
	//activate the close button
	$('#closeButton').click(function() {
		closeJsPopup($popup, $background);
		return false;
	});
}

//********************************************************************************************************

//strip_edit_dialogue
$(document).ready(function() {
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	
	var $popup = $('<div id="jsPopup2"></div>').hide();
	var $background = $('<div id="jsDisableOverlay2"></div>').hide();
	
	doubleupZwarwitMetSteunkleurCheckbox();
	cleanIsbnBarcodeFields();
	generateBarcodeFromIsbn();
	
	autoCompleteFunction('taalAddField', 'autocompleteLang.php', 'bindId');
	autoCompleteFunction('reeksAddField', 'autocompleteReeks.php', 'bindId');
	autoCompleteFunction('collectieAddField', 'autocompleteCollectie.php', 'bindId');
	
	$('.manageCycli').click(function () {
		manageCycli(this);
	});
	
	$('.manageAuteur').click(function () {
		manageAuteur(this);
	});
	
	$('.manageKarakter').click(function () {
		manageKarakter(this);
	});
	
	$('.gegevensAanpassen').click(function() {
		
		//get the id of the clicked element
		var stripId = strToNum($(this).attr('id'));
		
		positionFromTop = parseInt($(this).offset().top);
		//show the popup and block the rest
		openJsPopup($popup, $background, positionFromTop);
		
		//generate the content
		htmlContent = workingJsPopup('Strip aanpassen');
		$popup.html(htmlContent);
		$.post('ajax_edit_strip_get_data.php', {'u': userId, 's': sessionId, 'st': stripId}, function(data) {
			$popup.html(genericJsPopup('Strip aanpassen', data));
			
			doubleupZwarwitMetSteunkleurCheckbox();
			cleanIsbnBarcodeFields();
			generateBarcodeFromIsbn();
			
			autoCompleteFunction('taalAddField', 'autocompleteLang.php', 'bindId');
			autoCompleteFunction('reeksAddField', 'autocompleteReeks.php', 'bindId');
			autoCompleteFunction('collectieAddField', 'autocompleteCollectie.php', 'bindId');
			
			$('#closeButton').click(function() {
				closeJsPopup($popup, $background);
				return false;
			});
			$('#submitButton').click(function() {
				//fetch the data
				nrVoor = $('#nrVoor').val();
				nr = $('#nr').val();
				nrAchter = $('#nrAchter').val();
				integraal = checkboxState($('#intCheckbox').attr("checked"));
				titel = $('#titel').val();
				jaar = $('#jaar').val();
				paginas = $('#paginas').val();
				isbn = $('#isbn').val();
				barcode = $('#barcode').val();
				hcsc = $('#hcscOption').val();
				luxe = checkboxState($('#luxeCheckbox').attr("checked"));
				kleur = checkboxState($('#kleurCheckbox').attr("checked"));
				zw = checkboxState($('#zwCheckbox').attr("checked"));
				steunkleur = checkboxState($('#steunkleurCheckbox').attr("checked"));
				taal = $('#id-taalAddField').val();
				reeks = $('#id-reeksAddField').val();
				ncollectie = $('#id-collectieAddField').val();
				collectieNr = $('#collectieNr').val();
				covertekst = $('#covertekst').val();
				opmUitgave = $('#opmUitgave').val();
				opmInhoud = $('#opmInhoud').val();
				opmAdmin = $('#opmAdmin').val();
				
				//we have the data, show working
				htmlContent = workingJsPopup('Strip aanpassen');
				$popup.html(htmlContent);
				//jumpToTopOfPopup('jsPopup2'); 
				
				//submit the data
				$.post('ajax_edit_strip_save_data.php', {'u': userId, 's': sessionId, 'st': stripId, 'nrVoor': nrVoor, 'nr': nr, 'nrAchter': nrAchter, 'integraal': integraal, 'titel': titel, 'jaar': jaar, 'paginas': paginas, 'isbn': isbn, 'barcode': barcode, 'hcsc': hcsc, 'luxe': luxe, 'kleur': kleur, 'zw': zw, 'steunkleur': steunkleur, 'taal': taal, 'reeks': reeks, 'ncollectie': ncollectie, 'collectieNr': collectieNr, 'covertekst': covertekst, 'opmUitgave': opmUitgave, 'opmInhoud': opmInhoud, 'opmAdmin': opmAdmin}, function(data) {
					$popup.html(genericJsPopup('Strip aanpassen', data));
					//jumpToTopOfPopup('jsPopup2');
					$('#closeButton').click(function() {
						closeJsPopup($popup, $background);
						return false;
					});
				});
				
				return false;
			});
		});
		
		//when to close the popup
		$background.click(function() {
			closeJsPopup($popup, $background);
		});
	});
	
	$('.verschenenButton').click(function() {
		
		//get the id of the clicked element
		var stripId = strToNum($(this).attr('id'));
		
		positionFromTop = parseInt($(this).offset().top);
		//show the popup and block the rest
		openJsPopup($popup, $background, positionFromTop);
		
		htmlContent = workingJsPopup('Strip is verschenen');
		
		$.post('ajax_strip_verschenen.php', {'u': userId, 's': sessionId, 'st': stripId}, function(data) {
			$popup.html(genericJsPopup('Strip is verchenen', data));					
			$('#closeButton').click(function() {
				closeJsPopup($popup, $background);
				return false;
			});
		});
		
		//when to close the popup
		$background.click(function() {
			closeJsPopup($popup, $background);
		});
		return false;
	});
});

function doubleupZwarwitMetSteunkleurCheckbox() {
	$('#steunkleurCheckbox').click(function() {
		if ($('#steunkleurCheckbox').is(':checked')) {
			$('#zwCheckbox').attr('checked','checked');
		}
	});
	$('#zwCheckbox').click(function() {
		if (!$('#zwCheckbox').is(':checked')) {
			$('#steunkleurCheckbox').removeAttr("checked");
		}
	});
}

function cleanIsbnBarcodeFields() {
	$('#isbn').keyup(function() {
		numericOnly('#isbn');
	});
	$('#barcode').keyup(function() {
		numericOnly('#barcode');
	});
}

function generateBarcodeFromIsbn() {
	/*$('#isbn').keyup(function() {*/
	$('#calculateBarcode').click(function() {
		isbn = $('#isbn').val();
		oldIsbn = $('#oldIsbn').val();
		if (isbn.length != 10 & isbn.length != 13) isbn = oldIsbn;
		if (isbn.length == 10) {
			isbn = isbn.substr(0,9);
			
			barcode = '978' + isbn;
			
			check = 0;
			for (i = 0; i < 12; i += 2) {
				check += parseInt(barcode.substr(i, 1));
			}
			
			for (i = 1; i < 12; i += 2) {
				check += parseInt(parseInt(barcode.substr(i, 1)) * 3);
			}
			
			controle = 10- (check % 10);
			
			if (controle == 10) controle = 0;
			
			barcode = barcode + controle;
			$('#barcode').val(barcode);
		} else if (isbn.length == 13) {
			//isbn = $('#isbn').val();
			$('#barcode').val(isbn);
		} else {
			alert('Geen geldige ISBN gevonden');
		}
	});
}

//********************************************************************************************************

$(document).ready(function() {
	//mark external links as being just that
	/*$('a[@href^="http://"]').not('a[@href*="stripinfo.be"').addClass('external-link').attr({'target': '_blank'});*/
	
	//enable tag autocompletion
	autoCompleteFunction('tagAddField', 'autocompleteTag.php');
	
	//enable hover images
	//alert('yes');
	$('.hoverImage').mouseenter(function() {
		var prodId = strToNum($(this).attr('id'));
		var imageLink = $('#imgUrl-' + prodId).val();
		//alert(prodId);
		$(this).prepend('<div id="genImg-' + prodId + '" class="hoverImageImg" style="margin: 0 0 0 -180px;"><div style="display: table; #position: relative; overflow: hidden; height: 200px; width: 150px;"><div style="display: table-cell; #position: absolute; #top: 50%; vertical-align: middle;"><div style="display: block; #position: relative; #top: -50%; text-align: center;"><img src="' + imageLink + '" /></div></div></div>');
	}).mouseleave(function() {
		var prodId = $(this).attr('id');
		$('.hoverImageImg').remove();
	});
	
	//enable hover extension of abbreviated lists
	$('.liHiddenByDefault').hide();
	//var parent = $('.liHiddenByDefault').parent().attr('id');
	$('ul').mouseenter(function() {
		var parentId = $(this).attr('id');
		$('#' + parentId + ' > .liHiddenByDefault').show('fast');
	}).mouseleave(function() {
		var parentId = $(this).attr('id');
		$('#' + parentId + ' > .liHiddenByDefault').hide('fast');
	});
	$('.hiddenChildren').mouseenter(function() {
		var parentId = $(this).attr('id');
		$('#' + parentId + ' > .liHiddenByDefault').show('fast');
	}).mouseleave(function() {
		var parentId = $(this).attr('id');
		$('#' + parentId + ' > .liHiddenByDefault').hide('fast');
	});
	
	//add strip double check
	$('#addNewStrip').click(function() {
		var error = "";
		if ($('#id-taalAddField').val() < 1 | $('#id-taalAddField').val() == null) {
			error += 'Er is geen geldige taal ingevuld. ';
		}
		if ($('#id-reeksAddField').val() < 1 | $('#id-reeksAddField').val() == null) {
			error += 'Er is geen geldige reeks ingevuld. ';
		}
		if ($('#id-collectieAddField').val() < 1 | $('#id-collectieAddField').val() == null) {
			error += 'Er is geen geldige uitgever ingevuld.';
		}
		if (error.length > 0) {
			alert('Fout: ' + error);
			return false;
		}
	});
});

//********************************************************************************************************

$(function() {
	$('.imageThumbMax').lightBox();
});

//********************************************************************************************************

//tabmenu funcitons **************************************************************************************
$(document).ready(function() {
	$('.tabMenu a').click(function() {
		id = $(this).attr('id');
		
		$('.tabMenu a').removeClass('active');
		
		$('#' + id).addClass('active');
		
		return false;
	});
});

//forum functions

$(document).ready(function() {
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	
	var $popup = $('<div id="jsPopup2"></div>').hide();
	var $background = $('<div id="jsDisableOverlay2"></div>').hide();
	
	$('.forumquote').click(function() {
		//get the id of the clicked element
		var postId = strToNum($(this).attr('id'));
		
		positionFromTop = parseInt($(this).offset().top);
		//show the popup and block the rest
		openJsPopup($popup, $background, positionFromTop);
		
		//generate the content
		htmlContent = workingJsPopup('Antwoord plaatsen');
		
		$.post('ajax_forum_reply.php', {'u': userId, 's': sessionId, 'post': postId, 'quote' : 'true'}, function(data) {
			$popup.html(genericJsPopup('Antwoord plaatsen', data));	

			forumBindPostButton();
			
			$('#forumPostMessage').focus();
			
			$.getScript('js/jquery.putCursorAtEnd.js', function() {
				$('#forumPostMessage').putCursorAtEnd();
			});
			
			$('#closeButton').click(function() {
				closeJsPopup($popup, $background);
				return false;
			});
		});
		
		//when to close the popup
		$background.click(function() {
			closeJsPopup($popup, $background);
		});
		
		return false;
	});
	$('.forumreply').click(function() {
		//get the id of the clicked element
		var postId = strToNum($(this).attr('id'));
		
		positionFromTop = parseInt($(this).offset().top);
		//show the popup and block the rest
		openJsPopup($popup, $background, positionFromTop);
		
		//generate the content
		htmlContent = workingJsPopup('Antwoord plaatsen');
		
		$.post('ajax_forum_reply.php', {'u': userId, 's': sessionId, 'post': postId, 'quote' : 'false'}, function(data) {
			$popup.html(genericJsPopup('Antwoord plaatsen', data));					
			
			forumBindPostButton();
			
			$('#forumPostMessage').focus();
			
			$.getScript('js/jquery.putCursorAtEnd.js', function() {
				$('#forumPostMessage').putCursorAtEnd();
			});
			
			$('#closeButton').click(function() {
				closeJsPopup($popup, $background);
				return false;
			});
		});
		
		//when to close the popup
		$background.click(function() {
			closeJsPopup($popup, $background);
		});
		
		return false;
	});
	
	if ($('.showForumReplies').length != 0) {
		var checkId = strToNum($('.showForumReplies').attr('id'));
		
		$('#forumRepliesThreadId-' + checkId).html(showWorking());
			
		$.post('ajax_forum_threadview.php', {'thread': checkId, 'hideFirstPost': 'true'}, function(data) {
			$('#forumRepliesThreadId-' + checkId).html(data);
			bindForumButtons();
		});
	}
});

function bindForumButtons() {
	
	$('.ajaxEmbeddedControls').click(function() {
		var link = $(this).attr('href');
		var linkVars = getUrlVars(link);
		thread = linkVars[linkVars[0]];
		page = linkVars[linkVars[1]];
		
		$('#forumRepliesThreadId-' + thread).html(showWorking());
		
		$.post('ajax_forum_threadview.php', {'thread': thread, 'page': page}, function(data) {
			$('#forumRepliesThreadId-' + thread).html(data);
			bindForumButtons();
		});
		
		return false;
	});
}

function forumBindPostButton() {
	$('#forumpost').click(function() {
		//get the form data
		var forumPostMessage = $('#forumPostMessage').val();
		var postId = $('#post').val();
		var userId = $('#userId').val();
		var sessionId = $('#sessionId').val();
		
		alert(forumPostMessage);
		alert(postId);
		alert(userId);
		alert(sessionId);
		
		return false;
	});
}

//****************************************************************************************************************

//ajax image upload with progress bar

//$(function() {
//    $('.formWithProgress').uploadProgress({
		/* scripts locations for safari */
		//jqueryPath: "../lib/jquery.js",
		//uploadProgressPath: "../jquery.uploadProgress.js",
    /* function called each time bar is updated */
//		uploading: function(upload) {$('#percents').html(upload.percents+'%');},
		/* selector or element that will be updated */
//		progressBar: "#progressbar",
		/* progress reports url */
//		progressUrl: "/progress",
    /* how often will bar be updated */
//		interval: 2000
//    });
//});


/***************************************
   Autocomplete search field
-------------------------------------- */

function autoCompleteFunction(tagInQuestion, ajaxFile, bindId, minLenght, extraId) {
  	var $autocomplete = $('<ul class="autocomplete"></ul>').hide().insertAfter('#' + tagInQuestion);
  	var selectedItem = null;
  	
  	if (minLenght == null) {
	  	minLenght = 3;
  	}
  	
  	if (extraId == null) {
	  	extraId = 0;
  	}

  	var setSelectedItem = function(item, mouse) {
    	
	  	selectedItem = item;

    	if (selectedItem === null) {
      		$autocomplete.hide();
      		return;
    	}
    	
    	if (mouse) {
    		firstelement = $autocomplete.find('li:first');
			firstElementIndex = $('ul.autocomplete > li').index(firstelement);
	    	selectedItem = selectedItem - firstElementIndex;
    	}

    	if (selectedItem < 0) {
      		selectedItem = 0;
    	}
    	
    	if (selectedItem >= $autocomplete.find('li').length) {
      		selectedItem = $autocomplete.find('li').length - 1;
    	}
    	
    	$autocomplete.find('li').removeClass('selected').eq(selectedItem).addClass('selected');
    	$autocomplete.show();
  	};

  	var populateSearchField = function() {
    	$('#' + tagInQuestion).val($autocomplete.find('li').eq(selectedItem).text());
    	if (bindId == 'bindId') {
	    	$('#id-' + tagInQuestion).val(strToNum($autocomplete.find('li').eq(selectedItem).attr('id')));
    	}
    	setSelectedItem(null);
  	};

  	$('#' + tagInQuestion).attr('autocomplete', 'off').keyup(function(event) {
	    if (event.which > 40 || event.which == 8) {
		    
			//check if the input string is at least minLenght characters
			var stringValue = $('#' + tagInQuestion).val();
			stringLength = stringValue.length;
			if (stringLength >= minLenght) {
				
				$.post('ajax_' + ajaxFile, {'search-text': encodeURIComponent(stringValue), 'extraId': extraId}, function(data) { //new ajax code, uses html
				  	if (data.length) {
						$autocomplete.html(data.replace('&amp;', '&'));
						$('ul.autocomplete > li').mouseover(function() {
							element = $('ul.autocomplete > li').index(this);
							setSelectedItem(element, true);
						}).click(populateSearchField);
						setSelectedItem(0);
					} else {
						setSelectedItem(null);
						$autocomplete.hide();
					}
				}, "html");
			} else {
				$autocomplete.hide();
			}
		}
		else if (event.which == 38 && selectedItem !== null) {
			// User pressed up arrow.
			setSelectedItem(selectedItem - 1);
			event.preventDefault();
		}
		else if (event.which == 40 && selectedItem !== null) {
			// User pressed down arrow.
			setSelectedItem(selectedItem + 1);
			event.preventDefault();
		}
		else if (event.which == 27 && selectedItem !== null) {
			// User pressed escape key.
			setSelectedItem(null);
		}
	}).keypress(function(event) {
		if (event.which == 13 && selectedItem !== null) {
			// User pressed enter key.
			populateSearchField();
			event.preventDefault();
		}
	}).blur(function(event) {
		setTimeout(function() {
			setSelectedItem(null);
		}, 250);
	});
};
