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

var ajaxRequest = ajaxCheck();

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;
}

function ajaxReceive() {
	if(ajaxRequest.readyState == 4){
		result = jsonParse(ajaxRequest.responseText);
		if (result['result'] == 'succesfull') {
			if (result['mode'] == 'verschenen') {
				makeJsAlertPopup('Bedankt voor de inbreng. Deze strip zal nu door een moderator gecontroleerd worden.', 'Strip is verschenen');
				stripId = result['stripid'];
				document.getElementById('verschenenwrapper_' + stripId).innerHTML = '<span class="verschenen">Verschenen</span>';
			}
		} else if (result['mode'] != '') {
			makeJsAlertPopup(result['reason'], 'Fout');
		}
	}
}

function ajaxCheck() {
	//Browser Support Code
	try {
		// Opera 8.0+, Firefox, Safari
		return new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer Browsers
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				// Something went wrong
				makeJsAlertPopup('Uw browser ondersteunt geen Ajax :(', 'Grote fout');
				return false;
			}
		}
	}
}

//ajaxRequests

//var functions
function checkbox10(binaryVar) {
	//converts the DB value of a checkbox to HTML code
	if (binaryVar == 1) {
		return 'checked';
	} else {
		return '';
	}
}

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

//ajax calls

function notLoggedIn() {
	makeJsAlertPopup('Deze functie is niet beschikbaar voor gebruikers die niet zijn ingelogd. Gelieve eerst in te loggen of je te registreren indien je dat nog niet bent.', 'Je bent niet ingelogd.');
}

//make content strings

function makeJsAlertPopup(messageString, titleString) {
	showOverlay('visible');
	document.getElementById('jsPopup').style.visibility  = "visible";
	document.getElementById('jsPopup').innerHTML = '<div class="listcleanblock"><div class="title">' + titleString + '</div><div class="item">' + messageString + '<br/><br/><a href="javascript:void(0);" onclick="closeJsPopup();">Sluiten</a></div>';
}

function makeJsAlertPopupWorking(titleString) {
	showOverlay('visible');
	document.getElementById('jsPopup').style.visibility  = "visible";
	document.getElementById('jsPopup').innerHTML = '<div class="listcleanblock"><div class="title">' + titleString + '</div><div class="item" style="text-align:center;"><img src="./images/loading.gif" alt="loading" /> Working...</div>';
}

function closeJsPopup() {
	showOverlay('hidden');
	document.getElementById('jsPopup').style.visibility  = 'hidden';
}

function showOverlay(mode) {
	document.getElementById('jsDisableOverlay').style.visibility = mode;
}

function genericJsPopup(titleString, contentString) {
	return '<div class="listcleanblock"><div class="title">' + titleString + '</div><div class="item">' + contentString + '</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, $insertSpot) {
	$popup.insertAfter($insertSpot).show('fast');
	$background.insertAfter($insertSpot).fadeIn('fast');
	jumpToTopOfPopup('jsPopup2'); 
}

function closeJsPopup($popup, $background) {
	//$background.fadeOut('fast');
	//$popup.hide('fast');
	$background.remove();
	$popup.remove();
}

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 = $('#tagReeksId').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 = $('#tagReeksId').val();
	
	 if (block == null){
	   block = false;
	 }
	
	htmlContent = showWorking();
	if (voteType == 'reeks_tag') {
		$container = $('#reeksTagIdDiv-'+tagId);
	} else if (voteType == 'recensie') {
		$container = $('#recensieVoteBlock');
		$block = $('#bigvoteblock');
	}
	$container.html(htmlContent);
	if (block) {
		$block.html('<div class="tabletitle">Score</div><div class="tablebody">' + htmlContent + '</div>');
	}
	
	$.post('ajax_save_tag_vote.php', {'u': userId, 's': sessionId, 'v': vote, 't': tagId, 'r': reeksId, 'voteType': voteType}, function(data) {
		//$('#reeksTags').html(data).fadeIn('slow');
		$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 {
		//alert('no');
	}
}

//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');
	});
	$('.voteForTagDown').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);
	});
	$('.voteForRecensieDown').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);
	});
}

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

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

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

//show collectionbit
$(document).ready(function() {
	$('.showCollectionBit').click(function() {
		var userId = $('#footer > #userId').val();
		var sessionId = $('#footer > #sessionId').val();
		
		var stripId = strToNum($(this).attr('id'));
		
		htmlContent = showWorking();
		$('#collectieBit-' + stripId).html(htmlContent);
		
		$.post('ajax_strip_collection.php', {'u': userId, 's': sessionId, 'st': stripId}, function(data) {
			$('#collectieBit-' + stripId).html(data);
			//bindCollectionButtons();
		}, "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)
function manageCycli(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'));
	
	//show the popup and block the rest
	openJsPopup($popup, $background, element)
	
	htmlContent = workingJsPopup('Cycli beheren voor deze strip');
	$popup.html(htmlContent);
	
	$.post('ajax_manage_strip_story_arcs.php', {'u': userId, 's': sessionId, 'st': stripId}, function(data) {
		showCycliManageInterface(data);
	});
	
	//when to close the popup
	$background.click(function() {
		closeJsPopup($popup, $background);
	});
}

function showCycliManageInterface(htmlData) {
	var userId = $('#footer > #userId').val();
	var sessionId = $('#footer > #sessionId').val();
	
	var $popup = $('#jsPopup2');
	var $background = $('#jsDisableOverlay2');
	
	//show the interface
	$popup.html(genericJsPopup('Cycli beheren voor deze strip', htmlData));
	$('#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();
			$popup.html(htmlContent);
			$.post('ajax_manage_strip_story_arcs.php', {'u': userId, 's': sessionId, 'st': stripId, 'storyArc': storyArc, 'nr': nr, 'mode': 'add'}, function(data) {
				//we have submitted data, show the interface again
				showCycliManageInterface(data);
			});
		}
		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', {'u': userId, 's': sessionId, 'st': stripId, 'stripStoryArcId': stripStoryArcId, 'mode': 'del'}, function(data) {
			
			$('#tmpWorking-' + stripStoryArcId).html(data); //.remove();
			$('#stripStoryArcName-' + stripStoryArcId).css("text-decoration", "line-through");
		});
	});
	
	//activate the close button
	$('#closeButton').click(function() {
		closeJsPopup($popup, $background);
		return false;
	});
}

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

//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'));
		
		$('#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'));
	
	//show the popup and block the rest
	openJsPopup($popup, $background, element)
	
	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'));
		
		$(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;
	});
}

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

//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();
			
	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);
	});
	
	$('.gegevensAanpassen').click(function() {
		
		//get the id of the clicked element
		var stripId = strToNum($(this).attr('id'));
		
		//show the popup and block the rest
		openJsPopup($popup, $background, this);
		
		//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));
			
			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();
				hcsc = $('#hcscOption').val();
				luxe = checkboxState($('#luxeCheckbox').attr("checked"));
				kleur = checkboxState($('#kleurCheckbox').attr("checked"));
				zw = checkboxState($('#zwCheckbox').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, 'hcsc': hcsc, 'luxe': luxe, 'kleur': kleur, 'zw': zw, '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'));
		
		//show the popup and block the rest
		openJsPopup($popup, $background, this);
		
		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;
	});
});

$(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'));
		//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%;"><img src="images/strip/strip_' + prodId + '.jpg" /></div></div></div>');
	}).mouseleave(function() {
		var prodId = $(this).attr('id');
		$('.hoverImageImg').remove();
	});
	
	//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;
		}
	});
});


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

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

  	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);
			//elementCount = $autocomplete.find('li').length - 1;
	    	//$autocomplete.append('f: ' + firstElementIndex + ' l: ' + (elementCount + firstElementIndex) + ' s: ' + selectedItem + '<br />')
	    	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());
    	//$('#' + tagInQuestion).val($autocomplete.find('li.selected').text());
    	if (bindId == 'bindId') {
	    	$('#id-' + tagInQuestion).val(strToNum($autocomplete.find('li').eq(selectedItem).attr('id')));
    	}
    	setSelectedItem(null);
  	};

  	$('#' + tagInQuestion).attr('autocomplete', 'off').keyup(function(event) {
  	//$('#' + tagInQuestion).attr('autocomplete', 'off').bind('keydown', function(event) {
	    if (event.which > 40 || event.which == 8) {
			//check if the input string is at least 3 characters
			var stringValue = $('#' + tagInQuestion).val();
			stringLength = stringValue.length;
			if (stringLength >= 3) {
				// Keys with codes 40 and below are special (enter, arrow keys, escape, etc.).
				// Key code 8 is backspace.
				/*$.ajax({ //old ajax code, uses json
					'url': 'http://www.stripinfo.be/ajax/' + ajaxFile,
					'data': {'search-text': stringValue},
					'dataType': 'json',
					'type': 'POST',
					'success': function(data) {
					  	if (data.length) {
							$autocomplete.empty();
							$.each(data, function(index, term) {
								term = term.replace('&amp;', '&');
								term = term.replace('&amp;', '&');
								$('<li></li>').text(term).appendTo($autocomplete).mouseover(function() {
									setSelectedItem(index);
								}).click(populateSearchField);
							});
							
							setSelectedItem(0);
						} else {
						  setSelectedItem(null);
						}
					},
					'error': function(data) {
						alert(data);
					}
				});*/
				$.post('ajax/' + ajaxFile, {'search-text': stringValue}, function(data) { //new ajax code, uses html
				  	if (data.length) {
						$autocomplete.html(data.replace('&amp;', '&'));
						/*$('ul.autocomplete > li').each(function(i) {
							$(this).append(i);
						});*/
						$('ul.autocomplete > li').mouseover(function() {
							element = $('ul.autocomplete > li').index(this);
							//element = $(this).attr('id');
							//$autocomplete.prepend(element + ' - ');
							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);
	});
};