$.fn.editable = function(url, options) {
	// Options
	options = arrayMerge({
		"url": url,
		"paramName": "q",
		"callback": null,
		"saving": "saving ...",
		"type": "text",
		"submitButton": 0,
		"delayOnBlur": 0,
		"extraParams": {},
		"editClass": null,
		"favoId": 0
	}, options);
	// Set up
	this.click(function(e) {
			if (this.editing) return;
			if (!this.editable) this.editable = function() {
				var me = this;
				me.editing = true;
				me.orgHTML = $(me).html();
				me.innerHTML = "";
				var tempId = $(this).attr("id").split('|');
				options.favoId = tempId[1];
				if (options.editClass) $(me).addClass(options.editClass);
				var f = document.createElement("form");
				var i = createInputElement(me.orgHTML);
				var t = 0;
				f.appendChild(i);
				if (options.submitButton) {
					var b = document.createElement("input");
					b.type = "submit";
					b.value = "OK";

					f.appendChild(b);
				}
				me.appendChild(f);
				$("input[type=submit]").addClass("submit");
				i.focus();
				$(i).blur(
						options.delayOnBlur ? function() { t = setTimeout(reset, options.delayOnBlur) } : reset
					)
					.keydown(function(e) {
						if (e.keyCode == 27) { // ESC
							e.preventDefault;
							reset
						}
					});
				$(f).submit(function(e) {
					if (t) clearTimeout(t);
					e.preventDefault();
					var p = {};
					p[i.name] = $(i).val();
					$(me).html(options.saving).load(options.url+'?favoId='+options.favoId, arrayMerge(options.extraParams, p), function() {
						// Remove script tags
						me.innerHTML = me.innerHTML.replace(/<\s*script\s*.*>.*<\/\s*script\s*.*>/gi, "");
						// Callback if necessary
						if (options.callback) options.callback(me);
						// Release
						me.editing = false;
					});
				});
				function reset() {
					me.innerHTML = me.orgHTML;
					if (options.editClass) $(me).removeClass(options.editClass);
					me.editing = false;
				}
			};
			this.editable();
		})
	;
	// Don't break the chain
	return this;
	// Helper functions
	function arrayMerge(a, b) {
		if (a) {
			if (b) for(var i in b) a[i] = b[i];
			return a;
		} else {
			return b;
		}
	};
	function createInputElement(v) {
		if (options.type == "textarea") {
			var i = document.createElement("textarea");
			options.submitButton = true;
			options.delayOnBlur = 100; // delay onBlur so we can click the button
		} else {
			var i = document.createElement("input");
			i.type = "text";
		}
		$(i).val(v);
		i.name = options.paramName;
		return i;
	}
};

function stristr( haystack, needle, bool ) {

    var pos = 0;

    haystack += '';
    pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() );
    if( pos == -1 ){
        return false;
    } else{
        if( bool ){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}



//$(document).ready(function()	{
	//controle op activatie van favosystem
//	checkActiveFavo();
//})

function checkActiveFavo()	{
	$.ajax({
		url: "/modules/favoSystem/ajaxRequests/checkActive.php",
		type: "GET",
		dataType: "html",
		//cache: false,
		success: function(data) {
			if (data == 'use')	{
				//start favoSystem
				useFavoSystem();
			}
		}
	});
}

function useFavoSystem()
{
	if ($("div.favoriteDetail").length > 0)	{
		//first get the class(id) for showing
		var curPageFav = '';
		$("div[title^=favo_]").each(function()	{
			curPageFav = curPageFav + "/" + $(this).attr("title");
		})

		if (curPageFav != '')	{
			//handel de inhoud af
			loadFavosPerPage(curPageFav);

			$("div.favoriteDetail").each(function()	{
				//bestaat
				var divRel = $(this).attr("title").split("_");
				if (divRel[1] != '')	{
					//handel de inhoud af
					//updateFavoOptions(divRel[1]);

					//toevoegen opvangen
					$("div.favoriteDetail[title=favo_"+divRel[1]+"] span.makeFavo").live("click",function()	{
						$("div.favoriteDetail[title=favo_"+divRel[1]+"] span.makeFavo img").attr('src','/grafix/loader.gif');
						//request voor het toevoegen
						$.ajax({
							url: "/modules/favoSystem/ajaxRequests/addFavorite.php",
							type: "GET",
							data: "strId="+divRel[1],
							dataType: "html",
							//cache: false,
							success: function(data) {
								if (data != 'add')	{
									//show error
									$("div.favoriteDetail[title=favo_"+divRel[1]+"]").append(data);
								}else	{
									updateFavoOptions(divRel[1]);
									//$("div#favoriteDetail[class=favo_"+divRel[1]+"] img.favoLoad").hide();
								}
							}
						});

					})
				}
			});
		}

	}
}

function updateFavoOptions(workStrId)
{
	//request voor status van veld
	$.ajax({
		url: "/modules/favoSystem/ajaxRequests/handleField.php",
		type: "GET",
		data: "strId="+workStrId,
		dataType: "html",
		//cache: false,
		success: function(data) {
			//data vullen
			$("div.favoriteDetail[title=favo_"+workStrId+"]").html(data).show();
		}
	});
}


function loadFavosPerPage(classRow)
{
	//request voor status van veld
	$.ajax({
		url: "/modules/favoSystem/ajaxRequests/handleFavPage.php",
		type: "GET",
		data: "clRow="+classRow,
		dataType: "html",
		//cache: false,
		success: function(data) {
			//data vullen
			if (data != '0')	{
				var $holder = $('<div/>').html(data);
				var $children = $holder.children('div');
				$.each($children, function(val, i) {

					$("div[title=favo_"+i.id+"]").html(i.innerHTML).show();

				});
				$holder.remove();
			}
		}
	});
}

function showFavoOverview(page,searchVal)	{
	//request voor vullen van de div
	//page addon
	if (page !== false)	{
		var pageAddOn = '?page='+page;
	}else	{
		var pageAddOn = '?page=1';
	}
	//handle search val
	if (searchVal != '' && searchVal != undefined)	{
		pageAddOn = pageAddOn+'&searchVal='+searchVal;
	}

	//show loader
	$("#whileLoad").ajaxStart(function()	{
		$(this).show();
	});
	$("#whileLoad").ajaxStop(function()	{
		$(this).hide();
	});


	$(".favoOverview").load("/modules/favoSystem/ajaxRequests/showFavoOverview.php"+pageAddOn," ", function()	{
		handleLoginActions();
		handleOverviewActions();
		if (searchVal != '' && searchVal != undefined)	{
			$(".favoShowAll").show();
			$("input.favoSearchVal").val(searchVal);
		}else	{
			$(".favoShowAll").hide();
		}
	});



}

//verwijderen opvangen
function handleOverviewActions()
{
	$("table.favoTable tr:nth-child(even)").removeClass("product_oneven").addClass("product_even");
	//add the focus
	$("input.favoSearchVal").focus();

	$("img.delFavo").live("click",function()	{
		//verwijderen
		var favoIdAndPage = $(this).attr("id").split('|');
		var favoId = favoIdAndPage[1];
		//if (favoIdAndPage[2] == 0)	{
//			var goPage = false;
//		}else	{
//			var goPage = favoIdAndPage[2];
//		}
		//zoeken
		if (stristr(favoIdAndPage[2],','))	{
			var sZoek = favoIdAndPage[2].split(',');
			var goPage = sZoek[0];
			var sQuery = sZoek[1];
		}else	{
			var goPage = favoIdAndPage[2];
			var sQuery = '';
		}

		 $.ajax({
			url: "/modules/favoSystem/ajaxRequests/delFavorite.php",
			type: "GET",
			data: "favoId="+favoId,
			dataType: "html",
			//cache: false,
			complete: function(XMLHttpRequest, textStatus) {
				//data bijwerken
				if (sQuery != '')	{
					showFavoOverview(goPage,sQuery);
				}else	{
					showFavoOverview(goPage);
				}
			}
		});
	}).mouseover(function()	{
		$(this).attr("src","/grafix/verwijder_hover.gif");
	}).mouseout(function()	{
		$(this).attr("src","/grafix/verwijder.gif");
	})

	$(".shop_button").mouseover(function()	{
		$(this).attr("src","/grafix/toevoegen_hover.gif");
	}).mouseout(function()	{
		$(this).attr("src","/grafix/toevoegen.gif");
	});

	//commentaar verwerken
	$(".editComment").editable("/modules/favoSystem/ajaxRequests/handleComment.php",
								{paramName : "comment",
								 saving: "<img src='/grafix/loader.gif'>",
								 submitButton: 1,
								 delayOnBlur: 100
								});

	$(".pageNr a").click( function()	{
		var pageNum = $(this).attr("rel");

		if (pageNum == '' || pageNum == 'undefined')
			return

		//zoeken
		if (stristr(pageNum,'|'))	{
			sRel = pageNum.split('|');
			showFavoOverview(sRel[0],sRel[1]);
		}else	{
			//pagina inladen
			showFavoOverview(pageNum);
		}
	})

	//dubbele activatie van afbeelding vergroting
	$("a[rel^='prettyPhoto']").prettyPhoto({
		showTitle:false,
		//animationSpeed: 'normal', /* fast/slow/normal */
		//padding: 40, /* padding for each side of the picture */
		//opacity: 0.35, /* Value betwee 0 and 1 */
		//showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
		counter_separator_label: '/' /* The separator for the gallery counter 1 "of" 2 */
	});

	//zoekform
	$("form.searchFavo").submit(function()	{
		//get the value
		var inputVal = $("input.favoSearchVal").val();
		if (inputVal != '' && inputVal != undefined)	{
			//call the favooverview with the seachval
			showFavoOverview(false,inputVal);
		}

		return false;
	})

	$(".favoShowAll").click(function()	{

		showFavoOverview(1);
	})
}

