
var dosIterator = 0;
function setLoader()
{
	var dosCoolness = new Array('Een ogenblik..<b>.</b>', '<b>Een</b> ogenblik...', 'Een <b>og</b>enblik...', 'Een og<b>en</b>blik...', 'Een ogen<b>blik</b>...');
	
	$("#progressBar").html(dosCoolness[(dosIterator%5)]);
	dosIterator++;
}

function str_repeat ( input, multiplier ) {
    return new Array(multiplier+1).join(input); 
}

function resetLoader()
{
	// $("#progressBar div").width(0);
	$("#progressBar").html('Een ogenblik..<b>.</b>');
	dosIterator = 0;
}

// Initialize jquery history plugin
function loadHistory()
{

    $.historyInit(pageload);
    // If ajax isn't loaded, do filterize()
    if(ajaxLoaded === false) {
		if(arrResult == '') {
			setTimeout("reset()", timeout_mid);
			return;
		} else {
			setTimeout("filterize()", timeout_mid);
            print_r('filterizerer', 'w00t')
			return;
		}
    }
}

// Initialize the result page
function init()
{
    // Load history also loads filterize
    loadHistory();

    $("#filter_title h1").text('Verfijn uw zoekopdracht');
    
    // Add click event to the sort header links
    $("a")
       .filter(".sortoption_items")
         .click(function(event) {
            blnSetHistory = true;
            showAlert("#TB_inline?height=50&width=450&inlineId=loader_div", $(this));
            setTimeout("sortBy('"+event.target.title+"', '"+event.target.title+"_img', false);" , timeout_fast);
            bClick = true;
			return false;
         })
       .end();
}


// Split request and load them into an array
function handleRequest(hash)
{
	var realRequest = [];
	var tmpArr = [];
	var tmpArr2 = [];
	var tmpArr3 = [];
	var tmpVal = [];
	var newVal = [];
	
	realRequest = document.location.href.split("?");
	
	if(realRequest.length > 1) {
		tmpArr = realRequest[1].split("#");
		if(tmpArr[0].split("&").length > 1) {
			tmpArr3 = tmpArr[0].split("&");
		} else {
			tmpArr3 = tmpArr;
		}
		
		for(var key in tmpArr3) {
			tmpArr2 = tmpArr3[key].split("=");
			realParams[tmpArr2[0]] = tmpArr2[1];
			arrRequest[tmpArr2[0]] = tmpArr2[1];
		}
	}
	
    $.each(hash.split("&"), function(i, value) {
        tmpVal = value.split("_");
        if(tmpVal[0] == 'sort') {
            value = 'srt='+getOrdername(tmpVal[1]);
        }
        newVal = value.split("=");

		if(newVal[0]) {
			arrRequest[newVal[0]] = newVal[1];
		}
		if(newVal[1]) {
			noload = 0;
		}
    });

    print_r("requests!",arrRequest);
}

// Get specific request by key
function getRequest(key)
{
    if(requestsLoaded == false) return "";
    if(arrRequest[key]) {
        return arrRequest[key];
    }
    return "";
}

// History implementation
function pageload(hash) {
    bBackbutton = false;
    if(bClick == true) {
        bClick = false;
        if(blnStopPageLoad == true) {
            return;
        }
    } else {
        bBackbutton = true;
    }
    
    // If form is posted don't load history (because it's not needed)
    if (getCookie('form_posted') == '1') {
        setCookie('form_posted', 0);
        return;
    }

    // If page is loaded, load history
    if((pageLoaded == true || bBackbutton == true)) {
        handleRequest(hash);
        loadMain(getOrdername(getRequest('srt')), getRequest('rev'));
        var arrOptions = getRequest("options");
        arrActive = [];
        print_r("options", arrOptions);
        if(arrOptions != null) {
            $.each(arrOptions.split(","), function(i, value) {
                var newVal = value.split("_");
                if(!arrActive[newVal[0]]) {
                    arrActive[newVal[0]] = [];
                }
                arrActive[newVal[0]][newVal[1]] = true;
            });
        }
    }

    if(bBackbutton == true && ajaxLoaded == true) {
        // filterize();
    }
}

// When an action is performed on the result page this function is called
function setHistory(hash)
{
    if(blnSetHistory == false) return;
    blnStopPageLoad = true;
    blnSetHistory = false;
    // var hash = document.location.href;
    if(hash && initnourl != true) {
        hash = hash.replace(/^.*#/, '');
        $.historyLoad(hash);
    }
    print_r("set history 2", hash);
    initnourl = false;
}

// set sort parameters
function loadMain(sort, sortOrder)
{
    if(sort != undefined && sort != '') {
        if(sortOrder == undefined) {
            currentOrderType = 'desc';
        }

        print_r("test", sort);
        sortBy(sort, sort+"_img", null, true);
    }
}

// Show alert to user
function showAlert(string, object, closeWindow) {
	if(noalert == 1) return false;
	
    if(closeWindow == undefined) closeWindow = false;
    if(object) object.addClass("clicked");
    
    if(total_result_count >= 5 && blnPopupStay == false) {
        tb_show(null,string,null, closeWindow);
        setCookie('form_posted', 0);
    }

    closeWindow = false;
}

// Remove alert
function removeAlert()
{
    tb_remove();
	setTimeout("resetLoader()", 1);
	$("a").filter(".pages").css('cursor', 'hand');
	$('#body').css('cursor', '');
}

// Remove spacer that shows the seperation between normal results and alternatives
function showSpacer(object)
{
    if(showAlternative == false) return;
    $(object).prepend(spacer_html);
	setLoader();
}

// Get backend-ordername from frontend-ordername and visa versa
function getOrdername(currentOrder)
{
	switch(currentOrder) {
        case "Plaats": ordername = "city"; break;
        case "Hotelnaam": ordername = "name"; break;
        case "Prijs": ordername = "price"; break;
        case "Sterren": ordername = "stars"; break;
        case "Beoordeling": ordername = "score"; break;
        case "Afstand": ordername = "distance"; break;

        case "city": ordername = "Plaats"; break;
        case "name": ordername = "Hotelnaam"; break;
        case "price": ordername = "Prijs"; break;
        case "stars": ordername = "Sterren"; break;
        case "score": ordername = "Beoordeling"; break;
        case "distance": ordername = "Afstand"; break;

        default: ordername = currentOrder; break;
    }

	return ordername;
}

// Highlight pagenumber
function hilitepage(object)
{
    $(".other .pages").removeClass('active_page');
    $(".page_span").removeClass('hilite');
    $(object).removeClass('clicked');
    $(object).addClass('active_page');
    $(object).parent().addClass('hilite');
    $(object).blur();
}

// This method will handle all pagination related tasks
function paginator(page, object, noscroll, noanalytics, nourl, timeout)
{
    if(timeout == undefined) {
        timeout = null;
    }
	
    // If ajax request hasn't finished we will wait untill it is
    if((ajaxLoaded == false && page <= 1) || timeout == true) {
        setTimeout("paginator('"+page+"', '"+object+"', '"+noscroll+"', '"+noanalytics+"', '"+nourl+"')", 400);
        return;
    }
	
    timeout = null;

    if(blnSetHistory == false && bBackbutton == false) {
        return;
    }

    // Paginator vars
	var iMaxPerPage = 15;
	var iCurrentPage = parseInt(page);
	if (iCurrentPage < 1) iCurrentPage = 1;

	var html = '';
	var showAll = false;
	if (arrIndexer && arrIndexer.length == 0) {
		showAll = true;
    }

	var arrShowHotels = [];
	var iCounterShow = 0;
    // Loop through hotels that should be shown and create an array
	for (iCounter = 0, iMax = $(arrJson).length; iCounter < iMax; iCounter++) {
        // Get id's of hotel
		var id = $(arrJson).get(iCounter).id;
        
		if(showAll == true) {
			arrShowHotels[iCounterShow] = id;
	        iCounterShow++
            if($(arrJson).get(iCounter).distance > 0 && alternativeID == 0) {
                alternativeID = id;
            }
		} else if (arrIndexer && arrIndexer[id] && arrIndexer[id] == true) {
			arrShowHotels[iCounterShow] = id;
			iCounterShow++
            if($(arrJson).get(iCounter).distance > 0 && alternativeID == 0) {
                alternativeID = id;
            }
		}
	}
	
    // Loop through hotels
    arrRealShowHotels = [];
	for (iCounter = (iMaxPerPage * (iCurrentPage - 1)), iMax = (iMaxPerPage * iCurrentPage); iCounter < iMax; iCounter++) {
		var id = arrShowHotels[iCounter];
		if(arrShowHotels.length <= iCounter) break;

        if (id) {
            arrRealShowHotels.push(id);
		}
	}
	
    getHotelData(arrRealShowHotels);
    fillResult(page, object, noscroll, noanalytics, nourl, true);
    setTimeout('repager("'+intShowHotelCounter+'", "'+page+'"); hilitepage("'+object+'");', 1);

    if(alternativeID > 0) {
        setTimeout('showSpacer("#h_'+alternativeID+'")', timeout_slow);
        alternativeID = 0;
    }

	noalert = 0;
}

function fillResult(page, object, noscroll, noanalytics, nourl, timeout)
{
    if(timeout == undefined) {
        timeout = null;
    }
	
    // If ajax request hasn't finished we will wait untill it is
    if(hotelDataLoaded == false || timeout == true) {
        setTimeout("fillResult('"+page+"', '"+object+"', '"+noscroll+"', '"+noanalytics+"', '"+nourl+"')", timeout_slow);
        return;
    }
	setLoader();
	
    hotelDataLoaded = false;

    var html = '';
    $.each($(arrRealShowHotels), function(i, n) {
        html += arrHotels[n];
    });

    // Set html to content
	$('.pi_result .content').html(html);
    
	if (blnPopupStay != true) {
        removeAlert();
    }

	var url = base_url;

	if (url.split("?").length > 1) url += "&";
	else url += "?";

    var hist_url = '';

    // Generate url from current vars
    arrActiveOptions = [];

    if(arrActive) {
        $(arrActive).each(function(key, value) {

            for( var item in arrActive[key]) {
                if(arrActive[key][item]) {
                    arrActiveOptions.push(key+"_"+item);
                }
            }
        });
    }

    if(blnSetHistory == false && bBackbutton == true) {
        bBackbutton = false;
        return;
    } else {
        if(arrActiveOptions != undefined) {
            hist_url = "srt=" + ordername + "&rev=" + (currentOrderType == 'asc' ? 0 : 1) + "&pg="+page+"&options="+arrActiveOptions.join(",");
            url += hist_url;
        } else {
            hist_url = "srt=" + ordername + "&rev=" + (currentOrderType == 'asc' ? 0 : 1) + "&pg="+page;
            url += hist_url;
        }

        if (!nourl) {
            var newUrl = url.split("?");
            if(newUrl.length > 0) {
                document.location.href = '#' + newUrl[1];
            } else {
                document.location.href = '#' + newUrl[0];
            }
        }
        print_r("set history", hist_url);
        setHistory(hist_url);
    }

    // Check if analytics exists and generate a call
	if (noanalytics != true) {
        //setTimeout('GA_call("'+base_url+'", "'+ordername+'", "'+(currentOrderType == "asc" ? 0 : 1)+'","'+page+'")', 20);
        GA_call(base_url, ordername, (currentOrderType == "asc" ? 0 : 1),page);
	}
}

// Sort results
function sortBy(name, id, nourl, nopage)
{
    // If ajax request hasn't finished we will wait untill it is
    if(ajaxLoaded == false) {
        setTimeout("sortBy('"+name+"', '"+id+"', '"+nourl+"', '"+nopage+"')", timeout_slow);
        return;
    }

	setLoader();
	if(currentOrder != name) {
        if(name == 'Beoordeling') currentOrderType = 'desc';
		else currentOrderType = 'asc';
    } else {
        currentOrderType = currentOrderType == 'asc' ? 'desc' : 'asc';
    }

    $(".sortoptions span a img").hide();
    $("#"+id).attr({src: (currentOrderType == 'desc' ? imageOrderUp : imageOrderDown)});
    $("#"+id).show();
    $("#"+id).parent().blur();
    $(".sortoptions span a").removeClass('clicked');
    $(".sortoptions span a").removeClass('hilite');
    $("#"+id).parent().addClass('hilite');

    currentOrder = name;
    ordername = getOrdername(currentOrder);

	if((realParams && realParams['srt'] != ordername || noload == 0)) {
		arrJson = $(arrJson).sort(ordername, currentOrderType);
	}
	
    if(!nopage) {
        paginator(0, ".page_1", null, null, nourl, true);
    }

    showAlternative = false;
}

// Will generate the pagebar on top of result
function repager(intHotelCount, intCurrentPage)
{
	if(noload == 0) {
		if(intCurrentPage < 1) {
			intCurrentPage = 1;
		}
		$("div.paginator .other").html("");

		var intItemsPerPage = 15;
		var intTotalResult = Math.ceil(intHotelCount/intItemsPerPage);
		var intMaxPages = 2;
		var strClass = "";

		if(intTotalResult > 1) {
			if(intCurrentPage > 1) {
				var prev_page = parseInt(intCurrentPage) - 1;
				$("div.paginator .other").append('<span class="page_span">&laquo; <a rel="nofollow" class="page_'+prev_page+' pages" href="' + base_url + '?pg='+prev_page+'" title="'+prev_page+'">Vorige</a>&nbsp;</span>');
			} else {
				$("div.paginator .other").append('<span class="page_span disabled">&laquo; Vorige&nbsp;</span>');
			}

			$("div.paginator .other").append('<span class="page_span"><a rel="nofollow" class="page_1 pages" href="' + base_url + '?pg=1" title="1">1 - '+intItemsPerPage+'</a>&nbsp;</span>');

			var intOffsetLeft = parseInt(intCurrentPage) - Math.ceil(intMaxPages/2);
			var intOffsetRight = parseInt(intCurrentPage) + Math.ceil(intMaxPages/2);
			if(intCurrentPage < intMaxPages) {
				intOffsetRight = intMaxPages + 1;
				intOffsetLeft = 1;
			}

			if(intCurrentPage > (intTotalResult - intMaxPages)) {
				intOffsetLeft = intTotalResult - intMaxPages - 1;
				intOffsetRight = intTotalResult + 1;
			}

			if(intOffsetLeft > 2) {
				$("div.paginator .other").append('<span class="page_span">...&nbsp;&nbsp;</span>');
			}

			for (i = 1; i <= intTotalResult; i++) {
				if(i == 1 || i == intTotalResult) continue;
				
				// Show some of the pages
				if(intTotalResult > intMaxPages + 1) {

					if(i >= intOffsetLeft && i <= intOffsetRight) {
						$("div.paginator .other").append('<span class="page_span"><a rel="nofollow" class="page_' + i + ' pages" href="' + base_url + '?pg=' + i + '" title="' + i + '">' + ((i * intItemsPerPage) - (intItemsPerPage-1)) + '-' + (intHotelCount < (i * intItemsPerPage) ? intHotelCount : (i * intItemsPerPage)) + '</a>&nbsp;</span>');
					}
				} else {
					// Show all of the pages
					$("div.paginator .other").append('<span class="page_span"><a rel="nofollow" class="page_' + i + ' pages" href="' + base_url + '?pg=' + i + '" title="' + i + '">' + ((i * intItemsPerPage) - (intItemsPerPage-1)) + '-' + (intHotelCount < (i * intItemsPerPage) ? intHotelCount : (i * intItemsPerPage)) + '</a>&nbsp;</span>');
				}
			}
		}

		if(intOffsetRight < intTotalResult - 1) {
			$("div.paginator .other").append('<span class="page_span">...&nbsp;&nbsp;</span>');
		}

		$("div.paginator .other").append('<span class="page_span"><a rel="nofollow" class="page_' + intTotalResult + ' pages" href="' + base_url + '?pg=' + intTotalResult + '" title="' + intTotalResult + '">' + ((intTotalResult * intItemsPerPage) - (intItemsPerPage-1)) + '-' + (intHotelCount < (intTotalResult * intItemsPerPage) ? intHotelCount : (intTotalResult * intItemsPerPage)) + '</a>&nbsp;</span>');

		if(intCurrentPage < intTotalResult) {
			var next_page = parseInt(intCurrentPage) + 1;
			$("div.paginator .other").append('<span class="page_span"><a rel="nofollow" class="page_'+next_page+' pages" href="' + base_url + '?pg='+next_page+'" title="'+next_page+'">Volgende</a>&nbsp;&raquo;</span>');
		} else {
			$("div.paginator .other").append('<span class="page_span disabled">Volgende&nbsp;&raquo;</span>');
		}
	}
	
	noload = 0;
    
    $("div.paginator .other").append('<div style="clear: both;"></div>');
    $("a").filter(".pages")
         .unbind('click').click(function(event) {
            blnSetHistory = true;
			$(this).css('cursor', 'wait');
			$('#body').css('cursor', 'wait');
            // showAlert("#TB_inline?height=50&width=450&inlineId=loader_div", $(this));
            setTimeout("paginator('"+event.target.title+"', '.page_"+event.target.title+"', null, null, null, true);", 1);
            // Scroll page to top
            $('html, body').animate({scrollTop: 0}, 300);
            bClick = true;
			return false;
         })
       .end();
}

// Initialize filter options
function filterize(object)
{	
	setLoader();
    print_r("filterize start", "1");
    showAlert("#TB_inline?height=50&width=450&inlineId=loader_div", null);
	$(object).children().blur();
	$(object).toggleClass('active');
	var object_filterid = $(object).attr('filterid');
	var object_optionid = $(object).attr('optionid');

    if(object_filterid != undefined) {
        // removeSpacer();
        if(!arrActive[object_filterid]) {
            arrActive[object_filterid] = [];
        }

        arrActive[object_filterid][object_optionid] = !arrActive[object_filterid][object_optionid];

        checkActiveCat();

        print_r("active state", arrActive[object_filterid][object_optionid]);
    }
    
    filter();
    print_r("filterize end", "1");
}

// Generate all links per category
function more_links(catid)
{
    print_r("more_links start", "1");
	$(catid+"_more.filter_item_more ul li").unbind('click').click(function(event) {
		return false;
	});

	$(catid+".filter_item ul li").each(function(i, n) {
        if(!$(n).hasClass('clickedobject')) {
            $(n).unbind('click').click(function(event) {
                if(!$(n).hasClass('no_link')) {
                    if(noinit == '1') {
                        arrActiveOptions = [];
                        GA_call(base_url, '', 0, 1, true);
                        return false;
                    }
                    blnSetHistory = true;
                    intActiveCat = $(n).attr('filterid');
                    filterize($(n));
                    bClick = true;
                }
                return false;
            });
            $(n).addClass('clickedobject');
        }
    });
	
	$(catid+".filter_item .more").unbind('click').click(function(e) {
		var moreObject = $("#"+$(this).parent().parent().attr('id')+"_more");
    	var y = e.pageY;
        var t;

		moreObject.css("left", 120);
		moreObject.css("top", y - 8);
		moreObject.show();
        
        moreObject.hover(function(){
            clearTimeout(t);
        },function(){
            t = setTimeout(function(){
                moreObject.hide();
            }, 1000);
        });
	});

	$(catid+"_more.filter_item_more a.close_more").unbind('click').click(function(event) {
		$(this).parent().parent().hide();
	});

	$(catid+"_more.filter_item_more ul li").unbind('click').click(function(event) {
        if(noinit == '1') {
            arrActiveOptions = [];
            activateOption($(this).attr('filterid')+"_"+$(this).attr('optionid'));
            GA_call(base_url, '', 0, 1, true);
            return false;
        }
        blnSetHistory = true;
        $(this).parent().parent().hide();
        intActiveCat = $(this).attr('filterid');
        $(catid+".filter_item ul").append($(this));
		filterize($(this));
        bClick = true;
		return false;
	});

    print_r("more_links end", "1");

}

// Check if specific filter is active
function checkActive(filterid, optionid)
{
	if(arrActive[filterid] == undefined || optionid == undefined) return false;

	if(arrActive[filterid][optionid] && arrActive[filterid][optionid] == true) {
		return true;
	}

	return false;
}

// Check if category is active and has child, if it doesn't, reset activecat var.
function checkActiveCat()
{
    if(arrActive[intActiveCat] == undefined) {
        intActiveCat = false;
        return;
    }

    var resetActiveCat = true;
    for ( var i in arrActive[intActiveCat] ) {
        if(arrActive[intActiveCat][i] == true) {
            resetActiveCat = false;
        }
    }

    if(resetActiveCat) {
        intActiveCat = false;
    }
}

// Check if specific filter is displayed
function checkShow(filterid, optionid) {
	if(arrData[filterid] == undefined) return true;

	if(arrData[filterid][optionid] == undefined || arrData[filterid][optionid] == '') return true;
	if(arrData[filterid][optionid] == 0) return false;

    if(arrStayOpen[filterid] == true && intActiveCat != filterid && arrData[filterid][optionid] < 1) return false;
	return true;
}

// Get statistics of specific filter
function getStats(filterid, filterObject)
{
    if(!arrData[filterid]) arrData[filterid] = [];

    if(!arrData[filterid][filterObject['id']]) {
        return 0;
    }

    if(arrData[filterid][filterObject['id']] > 0) {
        return arrData[filterid][filterObject['id']];
    }

	if(filterObject != undefined) {
		return filterObject['stats'];
	}

	return 0;
}

// Organize filter menu items
function reorganize(div_id)
{
	setLoader();
    print_r("reorganize start", "1");
    showAlert("#TB_inline?height=50&width=450&inlineId=loader_div", null);
    arrActiveOptions = [];
	var show_more = false;

	if(div_id != undefined) {
        var object = $('div#'+div_id+'.filter_item');
	} else {
		var object = $('div.filter_item');
	}

	dots = '';

    // Loop through all categories
	$.each(object, function(i, n) {
		var iterator = $("#"+$(n).attr('id')+" span.filter_id").text();

        if(noinit == '1' || noload == '1') {
            html = '';
            html2 = '';
            var counter = 0;
            $.each(arrFilter[iterator], function(j, m) {
                if(checkShow(iterator, m['id'])) {
                    var count_stats = parseInt(getStats(iterator, m));
                    if(count_stats > 0) {
                        var addToHTML2 = false;
                        if(arrStayOpen[iterator] == true && count_stats == 0) {
                            addToHTML2 = true;
                        } else {
                            var html_tmp = '<li class="" filterid="'+iterator+'" optionid="'+m['id']+'">';
                            html_tmp += '<a href="javascript://">';
                            html_tmp += m['name']+dots;
                            html_tmp += '<span id="value_'+iterator+'_'+m['id']+'">&nbsp;'+(count_stats > 0 ? '<span>('+count_stats+')</span>' : '<span>(0)</span>')+'</span></a>';
                            html_tmp += '</li>';
                        }

                        // Put items in category
                        if(counter <= 5 && addToHTML2 == false) {
                            // html += html_tmp;
                        } else {
                            // Put items in "more" space
                            if(html_tmp != undefined && html_tmp != '') {
                                html2 += html_tmp;
                            } else {
                                counter--;
                            }
                        }
                        counter++;
                    }
                }
            });
            
            $("#"+$(n).attr('id')+" .more").hide();
            if(html2 != '') {
                $("#"+$(n).attr('id')+"_more ul").html(html2);
                $("#"+$(n).attr('id')+" .more").show();
            }
            more_links("#"+$(n).attr('id'));
        } else {
        
            html = '';
            html2 = '';
            var counter = 0;

            if(arrFilter[iterator] && (intActiveCat != iterator || intActiveCat == false || arrStayOpen[iterator] == false)) {
                $("#"+$(n).attr('id')+'.filter_item .more').hide();
                $("#"+$(n).attr('id')+'.filter_item .all').hide();
                // Loop through items
                $.each(arrFilter[iterator], function(j, m) {
                    if(checkShow(iterator, m['id'])) {
                        var count_stats = parseInt(getStats(iterator, m));

                        var is_active = checkActive(iterator, m['id']);
                        if(count_stats > 0 || arrStayOpen[iterator]) {
                            if(is_active) {
                                if(count_stats == 0 && arrStayOpen[iterator]) {
                                    deactivateOption(iterator+"_"+m['id']);
                                } else {
                                    activateOption(iterator+"_"+m['id']);
                                }
                            }
                            
                            var addToHTML2 = false;
                            if(arrStayOpen[iterator] == true && count_stats == 0) {
                                addToHTML2 = true;
                            } else {
                                var html_tmp = '<li class="'+(is_active != "" ? 'active' : '')+'" filterid="'+iterator+'" optionid="'+m['id']+'">';
                                html_tmp += '<a href="javascript://">';
                                html_tmp += m['name']+dots;
                                html_tmp += '<span id="value_'+iterator+'_'+m['id']+'">&nbsp;'+(count_stats > 0 ? '<span>('+count_stats+')</span>' : '<span>(0)</span>')+'</span></a>';
                                html_tmp += '</li>';
                            }

                            // Put items in category
                            if((counter <= 5 || is_active != "") && addToHTML2 == false) {
                                html += html_tmp;
                            } else {
                                // Put items in "more" space
                                if(html_tmp != undefined) {
                                    html2 += html_tmp;
                                } else {
                                    counter--;
                                }
                            }
                            counter++;
                        }
                    }
                });

                $("#"+$(n).attr('id')+" ul").html(html);

                if(html2 != '') {
                    $("#"+$(n).attr('id')+"_more ul").html(html2);
                    $("#"+$(n).attr('id')+" .more").show();
                } else {
                    // $("#"+$(n).attr('id')+" .all").show();
                }
            } else {
                $.each(arrFilter[iterator], function(j, m) {
                    if(checkShow(iterator, m['id'])) {
                        var count_stats = parseInt(getStats(iterator, m));

                        var is_active = checkActive(iterator, m['id']);
                        if(count_stats > 0 || arrStayOpen[iterator]) {
                            if(is_active) {
                                activateOption(iterator+"_"+m['id']);
                            }
                        }
                    }
                });
            }
            setTimeout("more_links('#"+$(n).attr('id')+"')", timeout_fast);
        }
	});
	
	print_r("reorganize end", "1");
}

function activateOption(id)
{
    var arrTmp = handleID(id);
}

function deactivateOption(id)
{
    var arrTmp = handleID(id);
    arrActive[arrTmp['cat']][arrTmp['id']] = null;
    return;
}

function activateParent(id)
{
    if(arrFilter[intActiveCat] && arrFilter[intActiveCat][id] && arrFilter[intActiveCat][id]['parent_id'] && arrFilter[intActiveCat][id]['parent_id'] > 0) {
        $(intActiveCat+".filter_item ul li").each(function(i, n) {
            if($(n).attr('optionid') == id) {
                activateParent(arrFilter[intActiveCat][id]['parent_id']);
                filterize($(n));
                return;
            }
        });
    }
}



// Filter results
function filter()
{
    print_r("filter start", "1");
	var arrCategories = [];
    var iterator = 0;
    var blnShowAllHotels = true;
    var intHotelCounter = 0;
    var intShowHotel = 0;

	arrMatch = [];
	
    // Loop though filters
	$.each(arrFilter, function(i, n) {
		$.each(n, function(j, k) {

			if(!arrMatch[k['cat_id']]) {
				arrMatch[k['cat_id']] = [];
				arrCategories.push(k['cat_id']);
			}

			if (checkActive(k['cat_id'], k['id'])) {
				arrMatch[k['cat_id']].push(k['id']);
			}
		});
	});
   
    var arrDataActive = [];
	var intCategoryCheck = 0;

    arrData = [];
	arrNewResult = [];

	// Loop through all hotel data
	$.each(arrJson, function(i, n) {

		intShowHotel = 0;
		arrDataActive = [];

		// Loop through categories
		$.each(arrCategories, function(iterator_test, iterator) {
			// Check if array exists
			if (arrMatch[iterator]) {
				// intShowHotelCounter = 0; 
				intCategoryCheck = 0;
				intCategoryCheckIterator = 0;
				// Loop through the options
				$.each(arrMatch[iterator], function(j, m) {
					if (arrResult[n['id']][iterator]) {
						// Check if the (resultset) array contains the optionid
						if ($.inArray(m, arrResult[n['id']][iterator]) != -1) {
							intCategoryCheck++;
						}
					}
					intCategoryCheckIterator++;
				});

				// if andOrArray == true and counter is equal to arrayMatch[iterator].length
				if (arrAndOr[iterator] == true && intCategoryCheck > 0 && intCategoryCheck == intCategoryCheckIterator) {
					intShowHotel++;
				} else if (arrAndOr[iterator] == false && intCategoryCheck > 0) {
    				intShowHotel++;
				} else if(intCategoryCheckIterator == 0) { //intCategoryCheck == 0 ||
					intShowHotel++;
				}
			}
		});

		if(intShowHotel == arrCategories.length) {
			arrIndexer[n['id']] = true;
			blnShowAllHotels = false;
            arrNewResult.push(arrResult[n['id']]);
            intHotelCounter++;
		} else {
			arrIndexer[n['id']] = false;
		}
	});

    intShowHotelCounter = 0;

	// Loop through all hotels
	$.each(arrNewResult, function(i, n) {
		// Loop through categories
		$.each(arrCategories, function(iterator_test, iterator) {
			// Check if array exists
            if (arrMatch[iterator]) {
				if (n) {
					if (n[iterator]) {
					// Loop through the options
						$.each(n[iterator], function(j, m) {
							if (m) {
								// Check if the (resultset) array contains the optionid
								if (!arrData[iterator]) {
									arrData[iterator] = [];
								}
								if (!arrData[iterator][m]) {
									arrData[iterator][m] = 0;
								}
								arrData[iterator][m]++;
							}
						});
					}
				}
			}
		});

		intShowHotelCounter++;
	});

	// Whether or not to hide a filter option
	var blnHide = true;
	var arrFilterElements = $(".filter_item ul li");

    // Loop through filter options
	$.each(arrFilterElements, function(i, n) {
		// Get id
		var intKey = $(this).attr('filterid');

		blnHide = true;
		// Check if filter category exists in filtered data array (this array has been filled in the code above)
		if(arrData[intKey]) {
			// Check if filter option exists
			if (arrData[intKey][$(n).attr('optionid')] > 0) {
				// Show parent of filter
				$("span#value_"+intKey+"_"+ $(n).attr('optionid') + "").parent().show();

                // Remove hide class and put the filter option hotel amount in the span
				$(n).show();
				blnHide = false;
			} else {
				if (arrStayOpen[intKey] == true) {
					blnHide = false;
				}
			}
		}

		if(blnHide == true) {
			var statsObject = $("span#value_"+intKey+"_"+ $(n).attr('optionid') + "");
			statsObject.html("<b>(0)</b>");
			statsObject.parent().hide();
			$(n).hide();
		}
	});

	if(blnShowAllHotels == true) {
		arrIndexer = [];
	}

    setTimeout("reset()", timeout_fast);
    print_r("filter end", "1");
}

// Reset pagination
function reset()
{
	setLoader();
    print_r("reset start", 1);
    if(bBackbutton == true) {
        setTimeout("reorganize()", timeout_slow);
    } else {
        if(arrResult == undefined || arrResult == '') {
        } else {
            setTimeout("reorganize()", timeout_slow);
        }
    }

    var request_page = getRequest('pg');
    print_r("request_page", request_page);
    
    if(request_page > 0) {
        paginator((parseInt(request_page)), ".page_"+parseInt(request_page), true, null, null, true);
    } else {
        paginator(0, ".page_1", true, null, initnourl, true);
    }
    requestsLoaded = false;
    print_r("reset end", 1);
}

// Get search dropdowns from ajax
function loadResults(strBase, strVars)
{
	setLoader();
    var strUrl = '/ajaxresult.php?rewrittenrequest=' + strBase;
    if (strVars) strUrl += '&' + strVars;
    var objDiv = document.getElementById('resultContainer');
    if (objDiv) ajaxRequest(strUrl);
    return false;
}


// Get all results from ajax
function getHotelData(arrHotelID)
{
    if(!arrHotelID) {
        $.get("/result_cache.php?args[]="+base_url+"&"+query_string, null,
        function(data, textStatus) {
            if(textStatus == 'success') {
                ajaxLoaded = true;
            }
        },
        "json");
        return;
    }

    var newHotelsID = [];
    $.each($(arrHotelID), function(i, n) {
       if(!arrHotels[n]) {
           newHotelsID.push(n);
       }
    });

    if(newHotelsID.length == 0) {
        hotelDataLoaded = true;
        return;
    }

    $.get("/result_cache.php?args[]="+base_url+"&"+query_string+"&hotel_ids="+newHotelsID.join(','), null,
        function(data, textStatus) {
            if(textStatus == 'success') {
                $($(data)).each(function(i, m) {
                    arrHotels[m.id] = m.html;
                });
                hotelDataLoaded = true;
            }
        },
        "json");
}

function showPriceclass(elementid)
{
    if ($("#"+elementid).is(':hidden')) {
        $("#"+elementid).show();
        $("#img"+elementid).attr('src', imageCollapse);
        $("#img"+elementid).parent().attr('title', "Meer informatie sluiten");
    } else {
        $("#"+elementid).hide();
        $("#img"+elementid).attr('src', imageExpand);
        $("#img"+elementid).parent().attr('title', "Meer informatie tonen");
    }
}

function microtime(get_as_float) {
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);

    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

// Debug method wrapper
function print_r(title, value) {
	if(!debug) return false;

    var micro_time_tmp = microtime(true);
    if(micro_time == null) {
        micro_time = micro_time_tmp;
    }

    if($.browser.msie) {
        var str = dump(value, 1000)

        setTimeout("$('#debugWindow').append('"+(micro_time_tmp-micro_time)+" - <b>"+title + "</b>: "+str+"<br /><br />')", 100);
    } else {
        console.log(title +" : "+ dump(value, 1000));
    }

    micro_time = micro_time_tmp;
}

function dump(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;
}

// Some standard functions
function submitValue(strurl)
{
    window.location.href=strurl;
}

function openNewWindow()
{
    var winTypes = window.open('/hoteltypes.php', 'hoteltypes', 'height=400, width=400');
}

// Generate analytics call for stats
function GA_call(ga_url, ga_order, ga_asc_desc, ga_page, ga_gotourl)
{
	var ga_full_url = ga_url;

    if(noinit != '0') {
        if (ga_url.split("?").length > 1) {
            var real_url = ga_url.split("?");
            ga_full_url = real_url[0];
            print_r('ga 2', ga_full_url);
        }

        if (ga_full_url.split("options/").length > 1) {
            var real_url = ga_full_url.split("options/");
            ga_full_url = real_url[0]+real_url[1];
            print_r('ga 3', ga_full_url);
        }
    }
    print_r('ga 4', ga_full_url);

    var ga_full_url_extra = '';
    if(arrActiveOptions.length > 0) {
        var category_used = [];
        $.each(arrActiveOptions, function(i, n) {
            var currentItem = handleID(n);
            if(!category_used[currentItem['cat']]) category_used[currentItem['cat']] = false;
            
            if(category_used[currentItem['cat']] != true) {
                print_r('whosd', currentItem['cat']);
                switch(parseInt(currentItem['cat'])) {
                    case 0:
                        if(noinit == '0') {
                            ga_full_url_extra+= 'region/';
                        }
                        break;
                    case 1:
                        if(noinit == '0') {
                            ga_full_url_extra+= 'city/';
                        }
                        break;
                    case 2:
                        if(noinit == '0') {
                            ga_full_url_extra+= 'facility/';
                        }
                        break;
                    case 3:
                        if(noinit == '0') {
                            ga_full_url_extra+= 'feature/';
                        }
                        break;
                    case 4:
                        if(noinit == '0') {
                            ga_full_url_extra+= 'stars/';
                        }
                        break;
                }
                category_used[currentItem['cat']] = true;
            }
            ga_full_url_extra+= getLink(currentItem['cat'], currentItem['id'])+'/';
        });
    }

    if(noinit == '0') {
        if(ga_full_url_extra != '') {
            ga_full_url+= 'filters/'+ga_full_url_extra;
        }
    }

    if(ga_order != '' || ga_asc_desc > 0 || ga_page > 0) {
        ga_full_url += "?";
        if(ga_order != '') ga_full_url += "&srt=" + ga_order;
        if(ga_asc_desc > 0) ga_full_url += "&rev=" + ga_asc_desc;
        if(ga_page  > 0) ga_full_url += "&pg=" + ga_page;

        if(query_string != '') {
            ga_full_url += "&"+query_string;
        }
    } else {
        if(query_string != '') {
            ga_full_url += "?"+query_string;
        }
    }

    if(noinit == '1' && ga_gotourl != undefined) {
        document.location.href = ga_full_url;
        return;
    }

    if (pageTracker) {
        print_r("GA ======== ", ga_full_url);
        pageTracker._trackPageview(ga_full_url);
	}
}

// Handle filter id
function handleID(id)
{
    if(id != undefined) {
        var arrKeys = id.split('_');
        var arrReturn = [];
        arrReturn['id'] = arrKeys[1];
        arrReturn['cat'] = arrKeys[0];
        return arrReturn;
    }
}

// Get link based on filter id
function getLink(cat, id) {
    var strReturn = '';
    if(cat != undefined && id != undefined) {
        $.each(arrFilter[cat], function(i, n) {
            if(n['id'] == id) {
                strReturn = n['url'];
                return;
            }
        });
    }

    return strReturn;
}

