var currentLocation = document.location.href;
var splittedLocation = currentLocation.split('loadSession');

$(document).ready(function() {

	if ($('#theFilterForm').length != 0) {
		$.getScript('/handleFilterSession.php?action=loadSession', function() {
			$.getJSON('/json/all.json', false, function(data, textStatus){

				updateFilter(data.brands, data.productgroups);



				//check for a diff page
				var difP = getVar('bp');
				if (difP != '')	{
					//number?
					var filter=/^[0-9]+$/i
					if (filter.test(difP)) 	{
						handleSearchBrands(difP, true);
					}else	{
						//handleSearchBrands(1, true);
					}
				}else	{
					//handleSearchBrands(1, true);
				}
			});
		});
	}
});

function updateFilter(brands, productgroups, sort)
{
	splittedLocation = document.location.href.split('loadSession');

	//Object.prototype.toString = myProductGroupToString;
	myBubbleSort(brands,brands.length);


	var getVarsUrl = getUrlVars();


	var brandsHtml = '';
	//add brands to fieldset
	$.each(brands, function(i, val) {
		if (val != undefined) {
			//$('#brandsFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="brand[]" id="brand_' + i + '" value="' + i + '" onclick="addLoadSession(); handleSearchBrands()"><label class="active" for="brand_' + i + '">' + val + '</label><br>');

			var checked = '';
			var inArray = in_array('brands[]', getVarsUrl);

			if (inArray && getVarsUrl[getVarsUrl[inArray]].length > 0 && splittedLocation[1] == undefined) {
				for (indexI = 0; indexI < getVarsUrl[getVarsUrl[inArray]].length; indexI++) {
					if (val.id == getVarsUrl[getVarsUrl[inArray]][indexI]) {
						checked = ' checked="checked"';
					}
				}
			} else {
				if ($('#brand_' + val.id).length && $('#brand_' + val.id).attr('checked')) {
					checked = ' checked="checked"';
				} else if (splittedLocation[1] != undefined && sessionBrands != undefined) {
					if (in_array(val.id, sessionBrands)) {
						//$('#brand_'+i).attr('checked', true);
						checked = ' checked="checked"';
					}
				}
			}

			brandsHtml += '<input class="checkbox floatLeft" ' + checked + 'type="checkbox" name="brand[]" id="brand_' + val.id + '" value="' + val.id + '" onclick="addLoadSession(); handleSearchBrands()"><label class="active" for="brand_' + val.id + '">' + val.name + '</label><br><div class="clear">&nbsp;</div>';
		}

	});
	$('#brandsFieldset').html(brandsHtml);

	//Object.prototype.toString = myProductGroupToString;

	myBubbleSort(productgroups,productgroups.length);
	$('#productgroupsFieldset').html('');
	//add productgroups to fieldset
	$.each(productgroups, function(i, val) {
		if (val != undefined) {

			$('#productgroupsFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="productgroup[]" id="productgroup_' + val.id + '" value="' + val.id + '" onclick="addLoadSession();handleSearchBrands()"><label class="active" for="productgroup_' + val.id + '">' + val.name + '</label><br><div class="clear">&nbsp;</div>');
			var inArray = in_array('productgroups[]', getVarsUrl);
			if (inArray && getVarsUrl[getVarsUrl[inArray]].length > 0 && splittedLocation[1] == undefined) {
				for (indexI = 0; indexI < getVarsUrl[getVarsUrl[inArray]].length; indexI++) {
					$('#productgroup_'+getVarsUrl[getVarsUrl[inArray]][indexI]).attr('checked', true);
				}
			} else {
				if (sessionProductGroups != undefined) {
					if (in_array(val.id, sessionProductGroups)) {
						$('#productgroup_'+val.id).attr('checked', true);
					}
				}
			}
		}
	});
}

function hrefLoadSession(hrefElement)
{
	var currentLocation = document.location.href.split('loadSession');
	if (currentLocation[1] != undefined) {
		var location = hrefElement.href;
		var splitted = location.split('?');
		if (splitted[1] != undefined) {
			hrefElement.href = location + '&loadSession';
		} else {
			hrefElement.href = location + '?loadSession';
		}
	}
}

function addLoadSession()
{
	var currentLocationCheck = document.location.href;
	var splittedLocationCheck = currentLocationCheck.split('loadSession');
	if (splittedLocationCheck[1] == undefined) {
		document.location.href = document.location.href + '#loadSession';
	}
}

function uncheckAfterGenderChange(clicked)
{
	var checkedProductgroups = $('#productgroupsFieldset > input:checked');
	$.each(checkedProductgroups, function (i, val) {
		val.checked = false;
	});
}

function handleSearchBrands(currentPage, isFirst)
{
	if (isFirst == undefined) {
		$('#loadingFilter').css('opacity', '0.6');
		$('#loadingFilter').fadeIn(100);
		$('#loadingProducts').css('opacity', '0.6');
		$('#loadingProducts').fadeIn(100);
	}
	if (currentPage == undefined) {
		page = 1;
	} else {
		page = currentPage;
	}


	var  checkedBoxes = '';

	var checkedBrands = $('#brandsFieldset > input:checked');
	checkedBrandIDs = new Array();
	$.each(checkedBrands, function (i, val) {
		checkedBrandIDs[checkedBrandIDs.length] = val.value;
		checkedBoxes += '&brands[]=' + val.value;
	});

	var checkedProductgroups = $('#productgroupsFieldset > input:checked');
	checkedProductGroupIDs = new Array();
	$.each(checkedProductgroups, function (i, val) {
		checkedProductGroupIDs[checkedProductGroupIDs.length] = val.value;
		checkedBoxes += '&productgroups[]=' + val.value;
	});

	var htmlOrPhp = document.location.href;
	htmlOrPhp = htmlOrPhp.split('/');

	//save checked items to session through ajax
	$.ajax({
		url: "/handleFilterSession.php",
		type: "POST",
		data: 'action=saveSession&cPage=' + htmlOrPhp[htmlOrPhp.length-1] + checkedBoxes,
		dataType: "html",
		cache: false,
		success: function(msg){

			var productHTML = headerHTML = '';
			var productCountTotal = productCountFound = 0;
			var brandsFound = new Array();
			var productGroupsFound= new Array();
			var teller = 1;
			var tellerBrands = 0;
			var jsonFiles = new Array();

			jsonFiles[jsonFiles.length] = '/json/all.json';

			$.each(jsonFiles, function (jsonFileIndex, jsonFile) {
				//load products in this productgroup
				$.getJSON(jsonFile, false, function(data, textStatus){
					$.each(data.products, function() {
							if (objectInArray(brandsFound, this.info.pijler) == true) {

							} else {
								var currentBrandFound = new Object();
								currentBrandFound.id = this.info.pijler;
								currentBrandFound.name = this.info.pijlernaam;
								brandsFound[brandsFound.length] = currentBrandFound;
							}
							//pijler gevonden in aangevinkte brands
							if (checkedBrandIDs.length == 0 || in_array(this.info.pijler, checkedBrandIDs)) {
								if (objectInArray(productGroupsFound, this.info.productGroupID) == true) {

								} else {
									var currentProductGroupFound = new Object();
									currentProductGroupFound.id = this.info.productGroupID;
									currentProductGroupFound.name = this.info.productGroupName;
									currentProductGroupFound.gender = this.info.productGroupGender;
									productGroupsFound[productGroupsFound.length] = currentProductGroupFound;
								}
								//productgroep gevonden in aangevinkte productgroups
								if (checkedProductGroupIDs.length == 0 || in_array(this.info.productGroupID, checkedProductGroupIDs)) {

										//product voldoet aan alle eisen
										if ( (productCountFound >= ( (page-1) * resultsPerPage) )
											&& (productCountFound < (page * resultsPerPage) )
										)
										{
											if (teller == 2) {
												productLastClass = ' even_box';
												teller = 0;
											} else {
												productLastClass = '';
											}
											if (documentLocation.length == 1) {
												currentLink = this.info.link_static + '?p='+page;
											} else {
												currentLink = this.info.link_dynamic + '&p='+page;
											}

											productHTML += '<div class="product_wrap' + productLastClass + '">';
											productHTML += '	<div class="product_text">';
											productHTML += '		<div class="product_title" style="color: #FFFFFF;">' + this.info.productnaam + '</div>';
											productHTML += '		<div class="product_short_description">';
											productHTML += '			<div class="sd_text">';
											productHTML += '				<strong>' + this.info.productheadline + '</strong><br>';
											productHTML += 					this.info.korte_omschrijving;
											productHTML += '			</div>';
											productHTML += '			<div style="width:144px;" class="description_border">&nbsp;</div>';
											productHTML += '			<a class="more_info" id="productDetail_' + this.info.structuurID + '" onclick="showProduct(\'product_' + this.info.structuurID + '\');">Meer informatie</a>';//' + currentLink + '
											productHTML += '			<div style="width:144px;" class="description_border">&nbsp;</div>';
											productHTML += '			<div class="product_pijler floatRight">';
											productHTML += '				<a id="productDetail_' + this.info.structuurID + '" onclick="showProduct(\'product_' + this.info.structuurID + '\');"><img src="/media/28x51/' + this.info.pijlerImage + '"></a>';
											productHTML += '			</div>';
											productHTML += '		</div>';
											if (this.in_actie) {
												productHTML += '		<div class="floatLeft">Prijs per stuk ' + this.actie.prijs + '</div>';
												this.info.prijs = this.actie.prijs;
											} else {
												if (this.info.prijs_van != '' && this.info.prijs_van != undefined && this.info.prijs_van != '&euro; 0,00' && this.info.prijs_van != '€ 0,00' && this.info.prijs_van != '&#8364; 0,00') {
													productHTML += '		<div class="floatLeft">Prijs per stuk</div>';
													productHTML += '		<div class="floatLeft">&nbsp;van<span class="euro_van"> ' + this.info.prijs_van + '</span></div>';
													productHTML += '		<div class="floatLeft">voor ' + this.info.prijs + '</div>';
												} else {
													productHTML += '		<div class="floatLeft">Prijs per stuk ' + this.info.prijs + '</div>';
												}
											}
											productHTML += '		<div class="clear">&nbsp;</div>';
											productHTML += '		<div class="floatLeft">Aantal:</div>';
											productHTML += '		<div class="input">';
											productHTML += '			<form class="floatLeft" id="product_acc_form" name="product_acc_form" action="#">';
											productHTML += '				<div class="input_left">&nbsp;</div>';
											productHTML += '				<input class="aantal" type="text"  name="quantity_' + this.info.structuurID + '" id="quantity_' + this.info.structuurID + '" value="1">';
											productHTML += '			</form>';
											productHTML += '		</div>';
											productHTML += '		<a class="shopping_button" onclick="AddOrder(' + this.info.structuurID + ',\'cartDiv\',\'nl\',\'add\',\'order\');">&nbsp;</a>';
											productHTML += '		<div class="pijler_tag"></div>';
											productHTML += '	</div>';
											productHTML += '	<div class="product_image floatLeft">';
											if (this.in_actie) {
												productHTML += '		<div class="spotprijs_icon">&nbsp;</div>';
											}

											productHTML += '		<table width="100%" height="242">';
											productHTML += '			<tr>';
											productHTML += '				<td align="center" valign="bottom">';
											productHTML += '					<a id="productDetail_' + this.info.structuurID + '" onclick="showProduct(\'product_' + this.info.structuurID + '\');"><img src="/media/105x242/' + this.info.voorzijde + '" alt="' + this.info.productnaam + '"></a>';
											productHTML += '				</td>';
											productHTML += '			</tr>';
											productHTML += '		</table>';
											productHTML += '	</div>';
											productHTML += '	<div class="db_acties" style="width: 256px; margin-top: 10px;">&nbsp;</div>';
											productHTML += '</div>';


											//productdetail
											var prodName = this.info.productnaam;
											if (this.info.productnaam_sifr != undefined && this.info.productnaam_sifr != '') {
												prodName = this.info.productnaam_sifr;
											}
											productHTML += '<div class="productdetail_wrap" id="detail_product_' + this.info.structuurID + '">';
											productHTML += '	<div class="productdetail_header">';
											productHTML += '		<a class="close_button" href="#" onclick="$.modal.close();">&nbsp;</a>';
											productHTML += '		<h1 class="productdetail">' + prodName + '</h1>';
											productHTML += '		<div class="clear">&nbsp;</div>';
											productHTML += '		<div class="productdetail_ft">';
											productHTML += '			' + this.info.productheadline + '';
											productHTML += '		</div>';
											productHTML += '	</div>';
											productHTML += '	<div class="productdetail_img_wrap">';
											productHTML += '		<div class="productdetail_product_images" id="productImages_' + this.info.structuurID + '">';
											for (i = 0; i < this.info.afbeeldingen.length; i++) {
												productHTML += '			<img src="/media/43x43/' + this.info.afbeeldingen[i].bestandID + '-' + this.info.afbeeldingen[i].bestandOrigineleNaam + '" alt="" class="headImageShow">';
											}
											productHTML += '		</div>';
											productHTML += '		<div class="clear">&nbsp;</div>';
											productHTML += '		<div class="productdetail_img_main">';
											productHTML += '		<table style="height: 100%;">';
											productHTML += '			<tr><td valign="bottom" >';
											productHTML += '				<img src="/media/255x310/' + this.info.voorzijde + '" id="headImage_' + this.info.structuurID + '" alt="">';
											productHTML += '			</td></tr>';
											productHTML += '			</table>';
											productHTML += '		</div>';
											productHTML += '	</div>';
											productHTML += '	<div class="productdetail_txt_wrap">';
											//productHTML += '		<div class="productdetail_text" id="productdetail_text_' + this.info.structuurID + '">';
											productHTML += '		<div class="productdetail_text productdetail_text_' + this.info.structuurID + '">';
											productHTML += 				this.info.lange_omschrijving;
											productHTML += '		</div>';
											productHTML += '		<a class="scroll_up" href="#" onmouseover="scrollUp(' + this.info.structuurID + ')" onmouseout="cancelScroll()">&nbsp;</a>';
											productHTML += '		<a class="scroll_down" href="#" onmouseover="scrollDown(' + this.info.structuurID + ')" onmouseout="cancelScroll()">&nbsp;</a>';
											productHTML += '	</div>';
											productHTML += '	<div class="productdetail_shop_wrap">';
											productHTML += '	<div class="db_acties" style="width:265px;">&nbsp;</div>';
											productHTML += '	<div style="padding-right: 10px;" class="floatLeft">Prijs per stuk: ' + this.info.prijs + '</div>';
											productHTML += '		<div class="input floatLeft">';
											productHTML += '		<div class="input_left">&nbsp;</div>';
											productHTML += '			<form class="floatLeft" id="product_acc_form_' + this.info.structuurID + '" name="product_acc_form_' + this.info.structuurID + '" action="#">';
											productHTML += '				<div>';
											productHTML += '					<input type="hidden" name="structuurId" id="structuurId_' + this.info.structuurID + '" value="' + this.info.structuurID + '">';
											productHTML += '					<input class="aantal" type="text" name="quantity_' + this.info.structuurID + '" id="quantity_' + this.info.structuurID + '"  value="1">';
											productHTML += '				</div>';
											productHTML += '			</form>';
											productHTML += '		</div>';
											productHTML += '		<a class="shopping_button floatLeft" onclick="AddOrder(' + this.info.structuurID + ',\'cartDiv\',\'nl\',\'add\',\'order\');">&nbsp;</a>';
											productHTML += '	<div class="db_acties" style="width:265px; margin-bottom:0px;">&nbsp;</div>';
											productHTML += '	</div>';
											if (this.bundle != undefined) {
												productHTML += this.bundle.bundleHTML;
//												productHTML += '	<div class="productdetail_bundel">';
//												productHTML += '		<div class="productdetail_bundel_text">';
//												productHTML += '			<strong>' + this.bundle.actienaam + '</strong>';
//												productHTML += '			' + this.bundle.korte_omschrijving;
//												productHTML += '		</div>';
//												productHTML += '		<div class="bundleImages">';
//												productHTML += '			{%bundelImagesHtml%}';
//												productHTML += '		</div>';
//												productHTML += '		<div class="clear">&nbsp;</div>';
//												productHTML += '		<div class="productdetail_bundel_footer">';
//												productHTML += '			<div style="padding-right: 10px;" class="floatLeft">Bundelprijs ' + this.bundle.prijs + '</div>';
//												productHTML += '				<div style="margin-top:2px;" class="input floatLeft">';
//												productHTML += '					<form class="floatLeft" id="product_acc_form_' + this.bundle.id + '" name="product_acc_form_' + this.bundle.id + '" action="#">';
//												productHTML += '							<div><input type="hidden" name="structuurId_' + this.bundle.id + '" id="structuurId_' + this.bundle.id + '" value="' + this.bundle.id + '"></div>';
//												productHTML += '							<div class="input_left">&nbsp;</div>';
//												productHTML += '							<div><input class="aantal" type="text" name="quantity_' + this.bundle.id + '" id="quantity_' + this.bundle.id + '" value="1"></div>';
//												productHTML += '					</form>';
//												productHTML += '				</div>';
//												productHTML += '				<a class="shopping_button_pd floatLeft" onclick="AddOrder(' + this.bundle.id + ',\'cartDiv\',\'nl\',\'add\',\'order\');">&nbsp;</a>';
//												productHTML += '			</div>';
//												productHTML += '		</div>';

											}

											productHTML += '</div>';




//											productHTML += '<div class="productdetail_wrap" id="detail_product_' + this.info.structuurID + '">';
//											productHTML += '	<div class="productdetail_properties">';
//											productHTML += '		<div class="productdetail_titel">';
//											productHTML += '			<h1>' + this.info.productnaam + '</h1>';
//											productHTML += '		</div>';
//											productHTML += '		<div class="productdetail_ft">';
//											productHTML += 				this.info.korte_omschrijving;
//											productHTML += '			<div class="clear">&nbsp;</div>';
//											productHTML += '		</div>';
//											productHTML += '		<div class="clear">&nbsp;</div>';
//											productHTML += '	</div>';
//											productHTML += '	<a class="close_button" href="#" onclick="$.modal.close();">&nbsp;</a>';
//											productHTML += '	<div class="productdetail_image_text_wrap">';
//											productHTML += '		<div class="productdetail_image">';
//											productHTML += '			<!-- Link voor de hoofdafbeelding -->';
//											productHTML += '			<img src="/media/230x307/' + this.info.voorzijde + '">';
//											productHTML += '		</div>';
//											productHTML += '		<div class="productdetail_text">';
//											productHTML += 				this.info.lange_omschrijving;
//											productHTML += '		</div>';
//											productHTML += '	</div>';
//											productHTML += '</div>';


											//product toevoegen aan het overzicht als > start < start+8
//											productHTML += '<div class="product' + productLastClass + '">';
//											productHTML += '<a href="' + currentLink + '" title="' + this.info.pijlernaam + ' ' + this.info.productnaam + '" class="imgLink" onclick="hrefLoadSession(this);">';
//											productHTML += '<img src="/media/130x208/' + this.info.voorzijde + '" alt="' + this.info.pijlernaam + ' ' + this.info.productnaam + '"  id="img_front_' + this.info.structuurID + '">';// onmouseover="showBack(\'img_front_' + this.info.structuurID + '\',\'img_back_' + this.info.structuurID + '\');"
//											if (this.info.achterzijde != '') {
//												productHTML += '<img src="/media/130x208/' + this.info.achterzijde + '" alt="' + this.info.pijlernaam + ' ' + this.info.productnaam + '" style="display: none;" id="img_back_' + this.info.structuurID + '" onmouseout="hideBack(\'img_front_' + this.info.structuurID + '\',\'img_back_' + this.info.structuurID + '\');">';
//											}
//											productHTML += '</a>';
//											productHTML += '<div class="text">';
//											productHTML += '<div class="titel">';
//											if (this.info.productNewSale != '' ) {
//												productHTML += '<span class="new">' + this.info.productNewSale + '</span>';
//											}
//											productHTML += '<a class="titel"  href="' + currentLink + '" title="' + this.info.pijlernaam + ' ' + this.info.productnaam + '" onclick="hrefLoadSession(this);">' + this.info.pijlernaam + ' ' + this.info.productnaam + '</a></div>';
//											if (this.info.prijs_van != '' && this.info.prijs_van != undefined) {
//												productHTML += '<div class="prijs"><span class="euro_van">&euro; ' + this.info.prijs_van + '</span></div>';
//											}
//											productHTML += '<div class="prijs"><span class="euro">' + this.info.prijs + '</span></div>';
//											productHTML += '</div>';
//											productHTML += '<div class="clear">&nbsp;</div>';
//											productHTML += '</div>';
											teller++;
										}
										productCountFound++;


								}
							}

						productCountTotal++;
					});
					tellerBrands++;
					if (tellerBrands == jsonFiles.length) {
						pagingHTML = $.getPaging(page, productCountFound, resultsPerPage, 'handleSearchBrands');

						$('.editor').html('<div class="pageNr">'  + pagingHTML + '</div><div class="clear"></div>'+ productHTML + '<div class="clear"></div><div class="pageNr">'  + pagingHTML + '</div>');
						$.getScript('/handleFilterSession.php?action=loadSession', function() {
							//updateFilter(brandsFound, productGroupsFound);
						});
						$('#loadingFilter').fadeOut(200);
						$('#loadingProducts').fadeOut(200);
						$(".headImageShow").mouseover(function(event){
							var parentID = $(this).parent().attr('id');
							var splitted = parentID.split('_');
							var productID = splitted[1];
							var src = $(this).attr('src');
							var splitted = src.split('/');
							var src = $('#headImage_' + productID).attr('src');
							var splittedLarge = src.split('/');
 							$('#headImage_' + productID).attr('src','/media/' + splittedLarge[2] + '/' + splitted[3]);
						});
						$.getScript('/javascript/sifr-config.js');
					}
				});
			});
		}
	});

}



function objectInArray(arr, objectID)
{
	for (i = 0 ; i < arr.length; i ++) {
		if (arr[i].id == objectID) {
			return true;
		}
	};
}


function myProductGroupToString() {
    return '' + this.name;
}

function myBubbleSort(arrayName,length)
{
    for (var i=0; i<(length-1); i++)
    {
    	if (arrayName[i] != undefined)
    	{
	        for (var j=i+1; j<length; j++)
	        {
	            if (arrayName[j] < arrayName[i]) {
	                var dummy = arrayName[i];
	                arrayName[i] = arrayName[j];
	                arrayName[j] = dummy;
	            }
			}
		}
	}
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        var arr = hash[0].split('[');
        if (arr.length > 1 && arr[1] == ']') {
        	if (vars[hash[0]] == undefined) {
        		vars.push(hash[0]);
        		vars[hash[0]] = new Array();
			}
			vars[hash[0]][vars[hash[0]].length] = unescape(hash[1]);
		} else {
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
    }

    return vars;
}

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return key;
            }
        }
    }
     return false;
}
