; (function($) {
	// default settings
	$.tinysort = {
		id: "TinySort",
		version: "0.2.0",
		defaults: {
			order: "asc", // order: asc, desc or rand
			attr: "", 	// order by attribute value
			place: "start", // place ordered elements at position: start, end, org (original position), first
			returns: false	// return all elements or only the sorted ones (true/false)
		}
	};
	$.fn.extend({
		tinysort: function(_find, _settings) {
			if (_find && typeof (_find) != "string") {
				_settings = _find;
				_find = null;
			}
			var oSettings = $.extend({}, $.tinysort.defaults, _settings);

			var oElements = {};
			this.each(function(i) {
				// element or sub selection
				var mElm = (!_find || _find == "") ? $(this) : $(this).find(_find);
				// text or attribute value
				var sSort = oSettings.order == "rand" ? "" + Math.random() : (oSettings.attr == "" ? mElm.text() : mElm.attr(oSettings.attr));
				// to sort or not to sort
				var mParent = $(this).parent();
				if (!oElements[mParent]) oElements[mParent] = { s: [], n: [] }; // s: sort, n: not sort
				if (mElm.length > 0) oElements[mParent].s.push({ s: sSort, e: $(this), n: i }); // s:string, e:element, n:number
				else oElements[mParent].n.push({ e: $(this), n: i });
			});
			//
			// sort
			for (var sParent in oElements) {
				oParent = oElements[sParent];
				oParent.s.sort(
					function zeSort(a, b) {
						var x = a.s.toLowerCase();
						var y = b.s.toLowerCase();

						if (isNum(a.s) && isNum(b.s)) {

							x = parseFloat(a.s);
							y = parseFloat(b.s);
						}
						return (oSettings.order == "asc" ? 1 : -1) * (x < y ? -1 : (x > y ? 1 : 0));
					}
				);
			}
			//
			// order elements and fill new order
			var aNewOrder = [];
			for (var sParent in oElements) {
				oParent = oElements[sParent];
				var aOrg = [];
				var iLow = $(this).length;
				switch (oSettings.place) {
					case "first": $.each(oParent.s, function(i, obj) { iLow = Math.min(iLow, obj.n) }); break;
					case "org": $.each(oParent.s, function(i, obj) { aOrg.push(obj.n) }); break;
					case "end": iLow = oParent.n.length; break;
					default: iLow = 0;
				}
				var aCnt = [0, 0];
				for (var i = 0; i < $(this).length; i++) {
					var bSList = i >= iLow && i < iLow + oParent.s.length;
					if (contains(aOrg, i)) bSList = true;
					var mEl = (bSList ? oParent.s : oParent.n)[aCnt[bSList ? 0 : 1]].e;
					mEl.parent().append(mEl);
					if (bSList || !oSettings.returns) aNewOrder.push(mEl.get(0));
					aCnt[bSList ? 0 : 1]++;
				}
			}
			//
			return this.setArray(aNewOrder); // setArray or pushStack?
		}
	});
	// is numeric
	function isNum(n) {
		return !isNaN(parseFloat(n));
	}
	// array contains
	function contains(a, n) {
		var bInside = false;
		$.each(a, function(i, m) {
			if (!bInside) bInside = m == n;
		});
		return bInside;
	}
	// set functions
	$.fn.TinySort = $.fn.Tinysort = $.fn.tsort = $.fn.tinysort;
})(jQuery);


function ShopObject() {
	this.productAttributes = null; // json attribute object
	this.filter = null; // json filter object
	this.selectedBrands = null;
	this.selectedCompare = null;
	this.checkboxSubscription = null;
	this.activeSubscription = null;
	this.maxPrice = null; // maxprice var from url
	this.isReady = false;

	this.start = function() {
	    this.isReady = false;
	    // highlight discounted subscriptions
	    this.doDiscountSubscriptions();
	    var showText = false;
	    var items = this.start.arguments.length;
	    //has subscriptions
	    this.hasSubscriptionRadios = ($('.subscriptions input').length != 0)

	    if (items != 0) {
	        // dynamic updated shop call
	        this.selectedBrands = this.start.arguments[0];
	        this.filter = this.start.arguments[1];
	    }
	    $('.subscriptions input').removeAttr("checked");
	    $('#attribs input').removeAttr("checked");
	    if (this.filter) {
	        var attribs = this.filter.split(',');
	        for (var i = 0; i < attribs.length; i++) {
	            var attrib = $('#attribs input[value="attrib-' + attribs[i] + '"]');
	            attrib.attr("checked", "checked");
	            attrib.parent().find('label').addClass("selected");
	            showText = true;
	        }
	    }
	    $('.shop .phone input').attr("checked", "");
	    if (this.selectedCompare) {
	        var attribs = this.selectedCompare.split(',');
	        var len = Math.min(attribs.length, 5);
	        for (var i = 0; i < len; i++) {
	            $('.shop .phone[id="phone-' + attribs[i] + '"] input').attr("checked", "checked");
	        }
	    }

	    if (this.selectedSubscription) {

	        this.checkboxSubscription = $('div.subscriptions input[value=' + this.selectedSubscription + ']');
	        this.checkboxSubscription.attr("checked", "checked");
	    }
	    var brands = this.selectedBrands.split(',');
	    var allBrands = 0;
	    var selectedBrands = 0;
	    $('div.subscriptions input[name=thesub]').bind("click", function() {
	        shop.checkboxSubscription = $(this);

	        if (shop.activeSubscription != $(this).val()) {
	            shop.activeSubscription = $(this).val()
	            shop.renderPhones(true);
	            if ($('.simonly .price')) {
	                var soprice = shop.simOnlySubscriptions[$(this).val()];

	                if (!soprice || soprice == '-1,00') {
	                    $('.simonly').hide();
	                } else {

	                    $('.simonly').show();
	                    var sopricef = parseFloat(soprice);
	                    var normalpricef = parseFloat(shop.subscriptions['PRICE-' + $(this).val()]);
	                    var offprice = parseFloat(shop.subscriptions['REDUCED-PRICE-' + $(this).val()]);

	                    var percentage = ((1 - (sopricef / normalpricef)) * 100) + '';
	                    if (percentage.indexOf('.') > 0) percentage = percentage.substring(0, percentage.indexOf('.'));
	                    if (percentage.indexOf(',') > 0) percentage = percentage.substring(0, percentage.indexOf(','));
	                    $('.simonly .discount span:first').html(percentage + '%');
	                    if (soprice.indexOf(',00') > -1) {
	                        soprice = soprice.substring(0, soprice.indexOf(','));
	                        $('.simonly .price').html('&euro;' + soprice + ',-');
	                    } else {
	                        $('.simonly .price').html(soprice);
	                    }
	                    $('.simonly .bundlename').html($(this).parents('.bundleRow').find('.name').text());
	                }
	            }
	        }
	    });
	    $('#brands input').each(function(index) {
	        $(this).removeAttr("checked");
	        if ($.inArray($(this).attr("value").substring(6), brands) != -1) {
	            $(this).attr("checked", "checked");
	            $(this).next("label").addClass("selected");
	            selectedBrands++;
	        }
	        allBrands = index + 1;
	    });
	    if (selectedBrands == allBrands) {
	        $("#brands input").removeAttr("checked");
	        $("#brands input").next("label").removeClass("selected");
	    }
	    if (this.maxPrice == null || this.maxPrice == undefined) {
	        // do we have a "mp" parameter in the url? if so use it!
	        if ($(document).getUrlParam("mp")) {
	            this.maxPrice = Number($(document).getUrlParam("mp"));
	            if (isNaN(this.maxPrice)) {
	                this.maxPrice = null;
	            }
	        }
	    }

	    this.renderPhones(false);

	    $('.bundlebottomtext').hide();
	    $('.bundlefreebottomtext').hide();
	    var taberonis;
	    if (this.selectedSubscription) {
	        var tab = 0;
	        if (this.selectedSubscription.indexOf('BB') > -1) {
	            $('.bundlefreebottomtext').show();
	            tab = 2;
	            var bundleFreeTab = $('a[@href="#panelBundleFree"]').parent();
	            if (bundleFreeTab) tab = $('div.subscriptiontabs ul li').index(bundleFreeTab);
	        } else if (this.selectedSubscription.indexOf('-12') > -1) {
	            tab = 1
	            $('.bundlebottomtext').show();
	        } else if (this.selectedSubscription.indexOf('PREPAID') > -1) {
	            if ($(".subscriptiontabs > ul li").length == 1) {
	                tab = 0;
	            } else {
	                tab = 3;
	            }
	        } else {
	            $('.bundlebottomtext').show();
	        }
	        taberonis = $(".subscriptiontabs > ul").tabs({ selected: tab });
	    } else {
	        $('.bundlebottomtext').show();
	        taberonis = $(".subscriptiontabs > ul").tabs();
	    }

	    taberonis.bind('tabsselect', function(event, ui) {
	        var panel = ui.tab.href;
	        if (panel.indexOf('panelBundleFree') > -1) {
	            $('.bundlefreebottomtext').show();
	        } else {
	            $('.bundlefreebottomtext').hide();
	        }
	        if (panel.indexOf('y') > -1) {
	            $('.bundlebottomtext').show();
	        } else {
	            $('.bundlebottomtext').hide();
	        }
	    });




	};
	this.clickedFilter = function() {
		if ($('#rmacties').length > 0) {
			pulldowndontclose = true;
		} else {
			this.renderPhones(true);
		}
	}
	this.reset = function() {
		// reset filters
		$('#attribs input').removeAttr("checked");
		$("#attribs label").removeClass("selected");
		// reset brands
		$('#brands input').removeAttr("checked");
		$('#brands label').removeClass("selected");
		this.maxPrice = null;
		this.renderPhones(false);
		this.updateServer();
	};
	this.resetAttributes = function() {
		$('#attribs input').removeAttr("checked");
		$("#attribs label").removeClass("selected");
		this.maxPrice = null;
		this.renderPhones(false);
		this.updateServer();
	}
	this.resetBrands = function() {
		$('#brands input').not(":checked").attr("checked", true);
		$('#brands label').not(".selected").addClass("selected");
		// this.checkboxSubscription = null;
		this.maxPrice = null;
		this.renderPhones(false);
		this.updateServer();
	}
	this.resetSubscriptions = function() {
		$('.subscriptions input:checked').removeAttr("checked");
		$('.subscriptions tr').removeClass("selected");
		$('.subscriptions .bar').removeClass("baractive");
		this.activeSubscription = null;
		this.selectedSubscription = null;
		this.checkboxSubscription = null;
		this.maxPrice = null;
		this.renderPhones(false);
		this.updateServer();

	}
	this.checkedComparePhone = function(sendUpdate) {
		var notcheckedinputs = $('.shop input').not(":checked");
		var checkedinputs = $('.shop input:checked');
		notcheckedinputs.each(function(i) {
			var parlink = $(this).parent().find('.comparePhoneLink');
			parlink.attr('style', 'color:#ccc');
			parlink.removeAttr('href');
		});
		notcheckedinputs.parents(".phone").removeClass("compared");

		var bufallselected = '';
		checkedinputs.parents('.phone').find('div.textheader a').each(function(i) {
			if (bufallselected != '') bufallselected += ' / ';
			bufallselected += $(this).text();
		});
		checkedinputs.parents('.phone').addClass("compared");


		if (checkedinputs.length >= 2) {

			$('#comparePhones p').html(bufallselected);
			$('#comparePhonesButton p').html(' <a style="text-decoration:underline" href="javascript:shop.resetCompare();">Verwijder selectie</a>');
			checkedinputs.each(function(i) {
				var parlink = $(this).parent().find('.comparePhoneLink');
				parlink.attr('style', 'color:#009');
				parlink.attr('href', 'javascript:shop.comparePhones();');
			});
		} else {
			$('.shop input').each(function(i) {
				var parlink = $(this).parent().find('.comparePhoneLink');
				parlink.attr('style', 'color:#ccc');
				parlink.removeAttr('href');
			});

		}
		if (checkedinputs.length == 5) {
			notcheckedinputs.attr("disabled", true);
		} else {
			notcheckedinputs.attr("disabled", false);
		}

		if (sendUpdate) {
			this.updateServer();
			renderCompare();
		}
	}
	this.resetCompare = function() {
		$('.shop input').attr('checked', '');
		this.checkedComparePhone(true);
	}

	this.comparePhones = function() {

		var compare = '';
		var rateplan = $('.shop input').filter(":checked").attr("name");

		$('.shop input').filter(":checked").each(function(i) {
			if (i != 0) compare += ',';
			compare += $(this).attr("value");
		});
		document.location = '/rabomobiel/particulieren/telefoons/vergelijk?compare=' + compare + '&rateplan=' + rateplan;
	}
	this.nodeArray = null;
	this.brandNodeArray = null;
	this.nodes = $('#attribs input');
	this.brandNodes = $('#brands input');
	this.fillActiveArrays = function() {

		this.nodes = $('#attribs input');
		this.brandNodes = $('#brands input');
		var brandNodeArray = new Array();

		$('#brands input:checked').each(function(i) {
			brandNodeArray[i] = ($(this).val().substring(6));
		});
		this.brandNodeArray = brandNodeArray;
		var nodeArray = new Array();
		$('#attribs input:checked').each(function(i) {
			nodeArray.push($(this).val().substring(7));
		});
		this.nodeArray = nodeArray;

	}

	this.shouldShowProduct = function(p) {
		var product = this.productAttributes[p];
		for (i = 0; i < this.nodeArray.length; i++) {
			if (!product[this.nodeArray[i]] || product[this.nodeArray[i]] == 0) {
				return false;
			}
		}
		if (this.brandNodeArray.length != 0 && $.inArray(product["brand"], this.brandNodeArray) == -1) return false;
		return true;
	}

	this.showOrHidePhones = function() {

		var countOn = 0;
		for (p in this.productAttributes) {
			if (this.shouldShowProduct(p)) {
				countOn++;
				this.showProduct(p);
			} else {
				this.hideProduct(p);
			}
		}
		return countOn;
	}

	this.renderPhones = function(sendUpdate) {
		this.fillActiveArrays();


		if (shop.checkboxSubscription && shop.checkboxSubscription.val() && shop.checkboxSubscription.val().indexOf('PREPAID') > -1) {
			$('.prepaidbutton').show();
			$('.postpaidbutton').hide();
		} else {
			$('.postpaidbutton').show();
			$('.prepaidbutton').hide();
		}

		var countOn = this.showOrHidePhones();

		this.checkedComparePhone(false);
		if (sendUpdate) this.updateServer();
		if (countOn == 0) {
			$('.nophones').show();
		} else {
			$('.nophones').hide();
		}
		// show amount of selected phones
		if (countOn == 0) {
			// hack to show the zero instead of an empty string
			countOn = "0";
		}
		$(".textinfo .selected").html(countOn);


		this.showAttributesOfSelectedPhones();
		this.isReady = true;
	};

	this.showAttributesOfSelectedPhones = function() {
		// show attributes for selected phones
		var selectedFilters = "";
		var filterCount = 0;

		if (selectedFilters.length > 0) {
			$(".textinfo .text .filters").html(selectedFilters.substring(0, selectedFilters.length - 2));
			$(".textinfo .text .filters").show();
			$(".textinfo .text .meta").show();
			$(".textinfo").show();
		} else {
			$(".textinfo .text .filters").hide();
			$(".textinfo .text .meta").hide();
		}
	}


	this.showProduct = function(p) {

		if (this.checkboxSubscription == null || this.checkboxSubscription.length == 0) {
			$('#phone-' + p).show();
			this.maxPrice = null;
			this.shownPhones++;
		}
		else {

			var phonePrice = this.getPhonePrice(p);
			phonePrice = phonePrice.substr(0, phonePrice.indexOf(","))
			if (phonePrice <= this.maxPrice && this.maxPrice != null || this.maxPrice == null) {
				$('#phone-' + p).show();
			} else {
				$('#phone-' + p).hide();
			}
		}
	};

	this.hideProduct = function(p) {
		$('#phone-' + p).hide();
		//$('#phone-'+p).fadeOut(1000);
		$('#phone-' + p).find('input').attr('checked', false);
	};

	this.updateServer = function() {

		var prefix = $('#siebelMainDiv').length > 0 ? 'Siebel' : '';

		var url = '/rabomobiel/functions/' + prefix + 'ShopCallbackHandler.ashx?ts=' + new Date().getTime() + '&filter=';

		$('#attribs input:checked').each(function() {
			url += $(this).attr("value").substring(7) + ',';
		});
		url += "&brands=";

		$('#brands input:checked').each(function() {
			url += $(this).attr("value").substring(6) + ',';
		});
		url += "&selectedCompare=";
		$('.shop input').filter(":checked").each(function(i) {
			url += $(this).attr("value") + ',';
		});
		if (shop.checkboxSubscription && shop.checkboxSubscription.val()) {
			url += '&selectedSubscription=' + shop.checkboxSubscription.val();
		} else {
			url += '&selectedSubscription=';
		}
		if (shop.checkboxSubscription && shop.checkboxSubscription.val() && shop.checkboxSubscription.val().indexOf('PREPAID') > -1) {
			url += '&rateplan=PREPAID' + (shop.checkboxSubscription.val().indexOf('SMS') > -1 ? 'SMS' : '');
		}

		$.get(url, function(data) {
			//if (false && window.console) console.log('url' + url + ' data ' + data);
			//maybe do something with fault case
		});
	};
}

function ShopObjectNew() {
	this.phonePrices = null; // json attribute object
	this.subscriptions = null;
	this.selectedSubscription = null;
}

ShopObjectNew.prototype = new ShopObject();

ShopObjectNew.prototype.getPhonePrice = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;
	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.phonePrices[p][subscriptionKey];
}
ShopObjectNew.prototype.getOriginalPrice = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;
	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.phoneOriginalPrices[p][subscriptionKey];
}
ShopObjectNew.prototype.getSubscription = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;

	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.subscriptions[subscriptionKey];
}
ShopObjectNew.prototype.getShortSubscription = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;

	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.subscriptions['SHORT-' + subscriptionKey];
}
ShopObjectNew.prototype.getSubscriptionPrice = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;

	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.subscriptions['PRICE-' + subscriptionKey];
}
ShopObjectNew.prototype.getSubscriptionReducedPrice = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;

	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.subscriptions['REDUCED-PRICE-' + subscriptionKey];
}
ShopObjectNew.prototype.getSubscriptionMinutes = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;

	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.subscriptions['MINUTES-' + subscriptionKey];
}
ShopObjectNew.prototype.getSubscriptionExtraMinutes = function(p) {
	var subscriptionKey = this.checkboxSubscription && this.checkboxSubscription.val() ? this.checkboxSubscription.val() : this.productAttributes[p]["preferredprice"];
	if (this.hasSubscriptionRadios == false) subscriptionKey = this.selectedSubscription;

	if (subscriptionKey == "PREPAIDSMS") subscriptionKey = "PREPAID";
	return this.subscriptions['EXTRAMINUTES-' + subscriptionKey];
}
ShopObjectNew.prototype._shouldShowProduct = ShopObjectNew.prototype.shouldShowProduct;
ShopObjectNew.prototype.shouldShowProduct = function(p) {
	var ret = this._shouldShowProduct(p);
	if (ret == false) return false;
	//if (!this.checkboxSubscription || this.checkboxSubscription.length == 0) return true;

	var price = this.getPhonePrice(p);
	var originalPrice = this.getOriginalPrice(p);
	if (!price) {
		return false;
	} else {
		var floatPrice = price.replace(',', '.');
		var priceDescription = this.getSubscription(p);
		//if (window.console) console.log('desc: ' + priceDescription);

		var phoneDiv = $('#phone-' + p);
		var jqPrice = phoneDiv.find('.priceouter .pricedescription');

		//always store active price so initial price is always correct
		phoneDiv.find('.hiddenPrice').text(floatPrice);

		if (jqPrice.html() != priceDescription) {

			var euro = price.substring(0, price.indexOf(','));
			var cents = price.substring(price.indexOf(',') + 1);

			phoneDiv.find('.priceouter .price .euro').html('&euro;' + euro);
			if (cents == '00') {
				phoneDiv.find('.priceouter .price .cents').html('&nbsp;');
			} else {
				phoneDiv.find('.priceouter .price .euro').append(',');
				phoneDiv.find('.priceouter .price .cents').html(cents);
			}
			var col = $('#rmacties').length > 0 ? '#333333' : '#000099';
			phoneDiv.find('.priceouter .price .euro').animate({ color: "#FF6600" }, 100).animate({ color: col }, 1500);
			phoneDiv.find('.priceouter .price .cents').animate({ color: "#FF6600" }, 100).animate({ color: col }, 1500);
			jqPrice.html(priceDescription);
			var shortJqPrice = phoneDiv.find('.priceouter .priceshortdescription');

			if (shortJqPrice.length > 0) {
				shortJqPrice.html(this.getShortSubscription(p));
				var subscriptionPrice = this.getSubscriptionPrice(p);
				if (subscriptionPrice == null) return false;
				var subscriptionReducedPrice = this.getSubscriptionReducedPrice(p);
				if (subscriptionReducedPrice != null && subscriptionReducedPrice != '-1') {
					this.enterSubscriptionPrice(subscriptionPrice, phoneDiv);
					phoneDiv.find('.extracontainer').show();
					var diff = parseFloat(subscriptionReducedPrice.replace(',', '.'));
					var printit = '&euro;' + diff.toFixed(0).replace('.', ',');
					if (diff.toFixed(2) != diff + '.00') {
						printit = diff.toFixed(2).replace('.', ',');
					}
					phoneDiv.find('.extracontainer .extra').html(printit)
				} else {
					this.enterSubscriptionPrice(subscriptionPrice, phoneDiv);
					phoneDiv.find('.extracontainer').hide();

				}
				if (phoneDiv.find('.minutes').length > 0) {
					var minutes = this.getSubscriptionMinutes(p);
					var extraMinutes = this.getSubscriptionExtraMinutes(p);
					phoneDiv.find('.minutes').html(minutes);
					if (extraMinutes != '-1' && minutes != extraMinutes) {
						phoneDiv.find('.minutesextracontainer').hide();
						phoneDiv.find('.minutesextra').html('' + (parseFloat(extraMinutes) - parseFloat(minutes)));
					} else {
						phoneDiv.find('.minutesextracontainer').hide();
					}
				}

			}
		}
		phoneDiv.find('.priceouter .price .interval').html(priceDescription.toLowerCase().indexOf("bundelvrij") < 0 ? 'eenmalig' : 'p/mnd');
		if (originalPrice && priceDescription.toLowerCase().indexOf("bundelvrij") < 0) {
			var euro = Number(price.substring(0, price.indexOf(',')));
			var cents = Number(price.substring(price.indexOf(',') + 1));
			var oEuro = Number(originalPrice.substring(0, originalPrice.indexOf(',')));
			var oCents = Number(originalPrice.substring(originalPrice.indexOf(',') + 1));
			if (oEuro > euro || (oEuro == euro && oCents > cents)) {
				// discount!
				phoneDiv.addClass("actie");
				var centString = '';
				if (oCents > 0) {
					centString = ',' + oCents;
				}
				phoneDiv.find(".fromprice").html('&euro;' + oEuro + centString);
				phoneDiv.find(".fromprice").css("visibility", "visible");
			} else {
				// no discount
				phoneDiv.removeClass("actie");
				phoneDiv.find(".fromprice").css("visibility", "hidden");
			}
		} else {
			phoneDiv.removeClass("actie");
			phoneDiv.find(".fromprice").css("visibility", "hidden");
		}
	}
	return true;
}
ShopObjectNew.prototype.enterSubscriptionPrice = function(subscriptionPrice, phoneDiv) {
	var euro = subscriptionPrice.substring(0, subscriptionPrice.indexOf(','));
	var cents = subscriptionPrice.substring(subscriptionPrice.indexOf(',') + 1);

	phoneDiv.find('.priceouter .subscriptionprice .euro').html('&euro;' + euro);

	if (cents == '00') {
		phoneDiv.find('.priceouter .subscriptionprice .cents').html('&nbsp;');
	} else {
		phoneDiv.find('.priceouter .subscriptionprice .euro').append(',');
		phoneDiv.find('.priceouter .subscriptionprice .cents').html(cents);
	}
}
ShopObjectNew.prototype.doDiscountSubscriptions = function() {
	if (this.discountSubscriptions) {
		for (var i = 0; i < this.discountSubscriptions.length; i++) {
			var discount = this.discountSubscriptions[i];
			$(".subscriptions .radio input[value=" + discount + "]").parents("tr").addClass("discount");
		}
	}
}
ShopObjectNew.prototype.updateStatus = function() {
	var buffer = '';
	if ($('#brands input').not(':checked').length > 0) {
		$('#brands input:checked').each(function() {
			if (buffer != '') buffer += " / ";
			buffer += $(this).val().substring(6);
		});
	}
	$('#attribs input:checked').each(function() {
		if (buffer != '') buffer += " / ";
		buffer += $(this).parent().find('label').text();
	});

	buffer = this.addSubscriptionInfo(buffer);
	if (this.maxPrice != null) {
		if (buffer != '') buffer += " / ";
		buffer += 'Maximale toestel prijs &euro; ' + this.maxPrice;
	}
	if (buffer == '') {
		$('#shopinfoYourSelection').html('');
	} else {
		$('#shopinfoYourSelection').html('<p id="shopInfoBox">Uw selectie: ' + buffer + '</p>');
	}
	if ($('#shopInfoBox').height() > 40) {
		var html1 = $('#shopinfoYourSelection').html();
		$('#shopinfoYourSelection').html(html1 + '<a id="shopInfoboxje" href="#" onmouseover="$(\'#extrainfoDiv\').show();" onmouseout="$(\'#extrainfoDiv\').hide();">Meer</a>' +
                    '<SPAN id="extrainfoDiv" style="DISPLAY: none; POSITION: absolute" oldblock="inline"><SPAN class="popinshopspec">' + buffer + '</SPAN></SPAN>');
	}
}
ShopObjectNew.prototype.updateStatusNew = function() {
	var bufferBrands = '';
	var bufferAttribs = '';

	if ($('#brands input').not(':checked').length > 0) {
		$('#brands input:checked').each(function() {
			if (bufferBrands != '') bufferBrands += " / ";
			bufferBrands += $(this).val().substring(6);
		});
	}
	$('#attribs input:checked').each(function() {
		if (bufferAttribs != '') bufferAttribs += " / ";
		bufferAttribs += $(this).parent().find('label').text();
	});

	var bufferSubscription = '';
	bufferSubscription = this.addSubscriptionInfo(bufferSubscription);
	var buffer = '';

	if (bufferSubscription != '') {
		buffer += '<p>Gekozen abonnement: ' + bufferSubscription +
        ' <a href="#" onclick="shop.resetSubscriptions();return false;">verwijder selectie</a></p>';
	}
	if (bufferAttribs != '') {
		buffer += '<p id="shopInfoBox">Eigenschapen: ' + bufferAttribs +
        ' <a href="#" onclick="shop.resetAttributes();return false;">verwijder selectie</a></p>';
	}
	if (bufferBrands != '') {
		buffer += '<p id="shopInfoBox">Merken: ' + bufferBrands +
        ' <a href="#" onclick="shop.resetBrands();return false;">verwijder selectie</a></p>';
	}


	if (buffer == '') {
		$('#shopinfoYourSelection').html('');
	} else {
		$('#shopinfoYourSelection').html(buffer);
	}

}
ShopObjectNew.prototype.timedOutPhones = function(sendUpdate) {

	this._renderPhones(sendUpdate);

	var now = new Date().getTime();
	var oldCount = $('#shopinfoCountPhones').html();
	$('#shopinfoCountPhones').html($('.shopoverflow .phone:visible').length + ' telefoons beschikbaar');
	if (oldCount != $('#shopinfoCountPhones').html()) {
		//$('#shopinfoCountPhones').animate({ color: "#FF6600" }, 10).animate( { color: "#000000" }, 1000);
		$('#shopinfoCountPhones').parents(".shoptopbar").css("backgroundColor", "#FFAA66").animate({ backgroundColor: "#ebebeb" }, 1500, "linear", function() { $(this).css("backgroundColor", "transparent") });
	}

	if ($('#rmacties').length > 0) {
		this.updateStatusNew();
	} else {
		this.updateStatus();
	}

	this.sortPhones();

	renderCompare();
	renderBrandCount();
	$(".bundleRow").removeClass('selected');
	if (this.checkboxSubscription)
		this.checkboxSubscription.parents('tr.bundleRow').addClass('selected');
	$('#divNowLoading').hide();
	if (window.checkShowPhones) checkShowPhones();
}

ShopObjectNew.prototype._renderPhones = ShopObjectNew.prototype.renderPhones;
ShopObjectNew.prototype.renderPhones = function(sendUpdate) {

	$().mousemove(function(e) {
		$('#divNowLoading').css("top", e.pageY + 20);
		$('#divNowLoading').css("left", e.pageX + 20);
	});
	$('#divNowLoading').show();

	setTimeout('shop.timedOutPhones(' + sendUpdate + ')', 1);

}

ShopObjectNew.prototype.addSubscriptionInfo = function() {
	var buffer = '';
	if (this.checkboxSubscription) {
		var name = this.checkboxSubscription.parents('.bundleRow').find('.name').text();

		if (name && buffer != '') buffer += " / ";
		if (this.checkboxSubscription.parents('#panel1y').length == 1) {
			buffer += '1 jarig abonnement ' + name;
		} else if (this.checkboxSubscription.parents('#panel2y').length == 1) {
			buffer += '2 jarig abonnement ' + name;
		} else if (this.checkboxSubscription.parents('#panelBundleFree').length == 1) {
			buffer += name.substring(0, name.indexOf(','));
		} else if (this.checkboxSubscription.parents('#panelPrepaid').length == 1) {
			if (name.indexOf('Prepaid SMS') > -1) {
				buffer += "Prepaid SMS";
			} else {
				buffer += "Prepaid";
			}
		} else {
			if (name.indexOf(',') > 0) {
				buffer += name.substring(0, name.indexOf(','));
			} else {
				buffer += name;
			}
		}

	}
	return buffer;
}

ShopObjectNew.prototype.sortPhones = function() {
	var sorting = $('#shopsortselect option:selected').text();

	if (sorting == "Prijs") {
		$(".shopoverflow>div.phone:visible").tsort("div.hiddenPrice");
	} else if (sorting == "Naam") {
		if ($('h3.title').length > 0) {
			$(".shopoverflow>div.phone").tsort("h3.title");
		} else {
			$(".shopoverflow>div.phone").tsort("div.textheader>a");
		}
	}
}



function renderBrandCount() {
	var brandsCount = new Array();

	for (p in shop.productAttributes) {
		var addPhone = true;
		var product = shop.productAttributes[p];
		var price = shop.getPhonePrice(p);
		if (!price) addPhone = false;

		inner: for (i = 0; i < shop.nodeArray.length; i++) {
			if (!product[shop.nodeArray[i]] || product[shop.nodeArray[i]] == 0) {
				addPhone = false;
				break inner;
			}
		}

		var brand = product["brand"];
		if (addPhone) {
			if (brandsCount[brand]) {
				brandsCount[brand] += 1;
			} else {
				brandsCount[brand] = 1;
			}
		} else {
			if (!brandsCount[brand]) {
				brandsCount[brand] = 0;
			}
		}
	}
	var all = 0;
	for (b in brandsCount) {
		$('#brand-count-' + b.replace(' ', '_')).html('(' + brandsCount[b] + ')');
		all += brandsCount[b];
	}
	$('#removebrands').html('Alle merken(' + all + ')');

}

function renderCompare() {
	var columns = 4;
	if ($('.shop.shopSmall')[0]) columns = 3;
	if ($('#originalCompare')[0]) {
		$('.clonedCompareClearer').remove();
		$('.clonedCompare').remove();
		if ($('.shop input').filter(":checked").length >= 2) {
			$('#originalCompare').show();
			for (xi = columns; xi < $('div.phone:visible').length; xi += columns) {
				$('div.phone:visible:eq(' + (xi - 1) + ')').after('<div class="clearer clonedCompareClearer"></div>');
				$('div.phone:visible:eq(' + (xi - 1) + ')').after($('#originalCompare').clone().addClass('clonedCompare'));
				$('div.phone:visible:eq(' + (xi - 1) + ')').after('<div class="clearer clonedCompareClearer"></div>');
			}
		} else {
			$('#originalCompare').hide();
		}
	}
}
$(document).ready(function() {
	$("#brands input").bind("click", function() {
		$(this).parent().find('label').toggleClass("selected");
		hbxIt($(this).attr("value"), null, null);
	});
	$("#attribs input").bind("click", function() {
		$(this).parent().find('label').toggleClass("selected");
		hbxIt($(this).next().text(), null, null);
	});
});
