; (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);

var chosenSubscription = '';
var shop = null;

function showBanner(el) {
    var h = $.trim(el.html()+'');
    if (h.indexOf('<!--') == 0) {
        el.html(h.substr(4, h.length - 7));
    }
    el.show();
}

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.isbusiness = false;
	this.isReady = false;

	this.start = function () {

	    this.isReady = false;
	    // highlight discounted subscriptions
	    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;
	        }
	    }

	    if (this.selectedSubscription) {
	        var tmp = this.selectedSubscription.split("-");
	        if (tmp[0] == "RM") {
	            $(".yearSwitch tr").removeClass("active");
	            $(".yearSwitch input:checked").removeAttr("checked");
	            $(".yearSwitch input[value=" + tmp[2] + "]").attr("checked", "checked").parents("tr").addClass("active");
	            $("#panelBundels .subscriptionpanel").hide();
	            $("#panelBundels ." + tmp[2]).show();

	            this.checkboxSubscription = $('div.subscriptionpanel input[value=' + this.selectedSubscription + ']');
	            this.checkboxSubscription.attr("checked", "checked");
	        }
	        else if (this.selectedSubscription != '') {
	            this.checkboxSubscription = $('div.subscriptions input[value=' + this.selectedSubscription + ']');
	            this.checkboxSubscription.attr("checked", "checked");

	            shop.setSimOnly(this.checkboxSubscription);
	        }
	    } else {
	        $(".yearSwitch input[value=24]").attr("checked", "checked").parents("tr").addClass("active");
	    }
	    if (!this.selectedBrands == null) 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, this);
	            shop.setSimOnly($(this));

	        }
	    });

	    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);

	    if (this.selectedSubscription) {
	        var tab = 0;

	        if (this.selectedSubscription.indexOf('BB') > -1) {
	            if ($(".subscriptiontabs > ul li").length == 1) {
	                tab = 0;
	            } else {
	                tab = 1;
	            }

	            var bundleFreeTab = $('a[href="#panelBundleFree"]').parent();
	            if (bundleFreeTab) tab = $('div.subscriptiontabs ul li').index(bundleFreeTab);
	            this.setBanner(1);
	        } else if (this.selectedSubscription.indexOf('-12') > -1) {
	            tab = 0;
	            this.setBanner(tab);
	        } else if (this.selectedSubscription.indexOf('PREPAID') > -1) {

	            ($(".subscriptiontabs > ul li").length == 1) ? tab = 0 : tab = 2;
	            this.setBanner(2);
	        } else {
	            this.setBanner(tab);
	        }
	        $(".subscriptiontabs > ul").tabs({ selected: tab });

	    } else {
	        $(".subscriptiontabs > ul").tabs();
	        this.setBanner(tab);
	    }
	    $(".subscriptiontabs > ul").bind('tabsshow', function (event, ui) {

	        shop.setBanner(ui.index);
	        var panel = $(".subscriptions>div:not(.ui-tabs-hide)")[2];
	        $(panel).find(".bundleRow:first").addClass("selected");
	        $(panel).find(".bundleRow:first input").attr("checked", "checked").click();
	    });
	    $('.orderButton').click(function (e) { e.stopPropagation(); });
	    $(".shopoverflow .phone").hover(function () {
	        $('.orderButton', this).addClass("orderButtonHover");
	    }, function () {
	        $('.orderButton', this).removeClass("orderButtonHover");
	    });
	};
	this.setSimOnly = function(i) {
	    var soprice = shop.simOnlySubscriptions[i.val()];

	    if (!soprice || soprice == '-1,00') {
	        $(".extraAction").hide();
	    } else {
	        var sopricesopr = soprice.replace(',', '.');
	        $(".extraAction").show();
	        var sopricef = parseFloat(sopricesopr);
	        if (this.isbusiness) sopricef = soprice;
	        var normalpricef = parseFloat(shop.subscriptions['PRICE-' + i.val()]);
	        if (this.isbusiness) normalpricef = shop.subscriptions['PRICE-' + i.val()];
	        var sub = i.val().split("-")[1];
	        $(".extraAction .subscription").html("Rabo Mobiel " + sub);
	        $(".extraAction .pre").html("&euro;" + normalpricef);
	        $(".extraAction .post").html("&euro;" + soprice);

	    }
	};
	//set banner for shop page
	this.setBanner = function(i) {
	    
		var current = $('div.subscriptions input[name=thesub]:checked').val();
		$(".banner>div").hide();
		switch (i) {
			case 0:
				if (current != undefined && current.indexOf('-12') > -1) {
				    showBanner($(".banner .bundel12"));
				}
				else {
				    showBanner($(".banner .bundel"));
				}
				break;
			case 1:
			    showBanner($(".banner .bundelvrij"));
				break;
			case 2:
			    showBanner($(".banner .prepaid"));
				break;
			default:
				showBanner($(".banner .bundel"));
		}
	};
	this.clickedFilter = function() {
	    if ($('#rmacties').length > 0) {
	        pulldowndontclose = true;
	    } else {
	        $("#brandsList, #propertiesList").hide();
	        $("#eigenschappenButton, #merkbutton").removeClass("open");
	        this.renderPhones(true, this);
	    }
	};
	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').removeAttr("checked");
        $('#brands label').removeClass("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");
        $('.yearSwitch input:checked').removeAttr("checked");
        $('.yearSwitch tr').removeClass("active");
        $('.yearSwitch input[value=24]').attr("checked", "checked").click();
        $('.yearSwitch input[value=24]').parents("tr").addClass("active");
        $('.extraAction').hide();
        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];
        if (
            ((this.activeSubscription != null && this.activeSubscription.indexOf("PREPAID") == 0) ||
            (this.selectedSubscription != null && this.selectedSubscription.indexOf("PREPAID") == 0))
            && product.hideonprepaid) {
            return false;
        }

        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, from) {
    	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(from);
    	}
    	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("fast");
            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("fast");
            } 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(from) {

        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;
    this.payOff = 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);

        //always store active price so initial price is always correct
        phoneDiv.find('.hiddenPrice').text(floatPrice);

        var euro = price.substring(0, price.indexOf(','));
        var cents = price.substring(price.indexOf(',') + 1);
        var time;
        var callminutes;
        var vat;
        var boolTakePreferred = false;
        var subscription;

        if (shop.checkboxSubscription != null && shop.checkboxSubscription.val() != null) {
            time = shop.checkboxSubscription.val().split("-");
            subscription = shop.checkboxSubscription.val();
            callminutes = shop.checkboxSubscription.parents("td").next().next().text()
        } else {
            time = shop.productAttributes[p].preferredprice.split("-");
            subscription = shop.productAttributes[p].preferredprice;
            var tmp = shop.subscriptions["MINUTES-RM-" + time[1] + "-" + time[2]];
            callminutes = tmp;
            boolTakePreferred = true;
        }

        this.setSubscriptionForProductDetail(subscription, phoneDiv);

        if (time[0] == "RM") {
            vat = shop.subscriptions["PRICE-RM-" + time[1] + "-" + time[2]].split(",");
        }
        if (cents == '00') {
            cents = '';
            euro = euro + ",-";
        } else {
            euro = euro + ",";
        }

        // console.log(time);
        if (time[0] == "RM") {
            var data = "";
            if (boolTakePreferred) {
                data = "-" + this.productAttributes[p]["preferredinternet"];
                if (!shop.payOff["bundel" + data]) data = "";
                var override = this.productAttributes[p]["preferredinternetoverride"];

                if (override) {
                    var splitOverride = override.split(',');
                    vat[0] = splitOverride[0];
                    vat[1] = splitOverride[1];
                    if (vat[1] == '0') vat[1] = '00';
                }

            }
            phoneDiv.find('.phonePrice .text').text('Toestelprijs');
            phoneDiv.find('.phonePrice .price .euro').html('&euro;' + euro);
            phoneDiv.find('.phonePrice .price .cents').text(cents);
            if (vat[1] == "00") {
                phoneDiv.find('.monthly .price .euro').html('&euro;' + vat[0] + ",-");
                phoneDiv.find('.monthly .price .cents').text("");
            } else {
                phoneDiv.find('.monthly .price .euro').html('&euro;' + vat[0] + ",");
                phoneDiv.find('.monthly .price .cents').text(vat[1]);
            }

            // console.log('Time[0]='+time[0]+'&Time[2]='+time[2]);
            if (time[2] == "24") {
                phoneDiv.find('.monthly .text').html('Kosten/mnd,<br />vanaf');
                phoneDiv.find(".payoff").text(shop.payOff["bundel" + data].text1);
                phoneDiv.find(".payoff2").text(shop.payOff["bundel" + data].text2);
                phoneDiv.find(".payoff3").text(shop.payOff["bundel" + data].text3);
            } else if (time[2] == "12") {
                phoneDiv.find('.monthly .text').html('Kosten/mnd,<br />vanaf');
                phoneDiv.find(".payoff").text(shop.payOff["bundel12" + data].text1);
                phoneDiv.find(".payoff2").text(shop.payOff["bundel12" + data].text2);
                phoneDiv.find(".payoff3").text(shop.payOff["bundel12" + data].text3);
            }
            phoneDiv.find('.monthly .years').html(time[2] / 12);
            phoneDiv.find('.minutes .text').text('Belminuten');
            phoneDiv.find('.minutes .price .euro').text(callminutes);
            phoneDiv.find('.minutes .price .cents').text('');
        } else {

            if (time[0] == "BB" && time[1] == "24") {
                phoneDiv.find('.monthly .text').html('Kosten/mnd,<br />2 jaar');
            } else if (time[0] == "BB" && time[1] == "12") {
                phoneDiv.find('.monthly .text').html('Kosten/mnd,<br />1 jaar');
            } else {
                phoneDiv.find('.monthly .text').text('Eenmalig');
            }
            phoneDiv.find('.monthly .price .euro').html('&euro;' + euro);
            phoneDiv.find('.monthly .price .cents').text(cents);

            var ppmin = shop.payOff.bundelvrij.pmin.split(',');
            var ppsms = shop.payOff.bundelvrij.psms.split(',');

            if (time[0] == "BB") {

                var data = "";
                if (boolTakePreferred) {
                    data = "-" + this.productAttributes[p]["preferredinternet"];
                    if (!shop.payOff["bundelvrij" + data]) data = "";
                }

                switch (time[0]) {
                    case "24":
                        phoneDiv.find(".payoff").html(shop.payOff["bundelvrij24" + data].text1);
                        phoneDiv.find(".payoff2").html(shop.payOff["bundelvrij24" + data].text2);
                        phoneDiv.find(".payoff3").html(shop.payOff["bundelvrij24" + data].text3);
                        ppmin = shop.payOff["bundelvrij"].pmin.split(',');
                        ppsms = shop.payOff["bundelvrij"].psms.split(',');
                        break;
                    case "12":
                        phoneDiv.find(".payoff").html(shop.payOff["bundelvrij12" + data].text1);
                        phoneDiv.find(".payoff2").html(shop.payOff["bundelvrij12" + data].text2);
                        phoneDiv.find(".payoff3").html(shop.payOff["bundelvrij12" + data].text3);
                        ppmin = shop.payOff["bundelvrij"].pmin.split(',');
                        ppsms = shop.payOff["bundelvrij"].psms.split(',');
                        break;
                    default:
                        phoneDiv.find(".payoff").html(shop.payOff["bundelvrij" + data].text1);
                        phoneDiv.find(".payoff2").html(shop.payOff["bundelvrij" + data].text2);
                        phoneDiv.find(".payoff3").html(shop.payOff["bundelvrij" + data].text3);
                        ppmin = shop.payOff["bundelvrij"].pmin.split(',');
                        ppsms = shop.payOff["bundelvrij"].psms.split(',');
                        break;
                }
            } else if (time[0] == "PREPAID") {
                phoneDiv.find(".payoff").html(shop.payOff.prepaid.text1);
                phoneDiv.find(".payoff2").html(shop.payOff.prepaid.text2);
                phoneDiv.find(".payoff3").html(shop.payOff.prepaid.text3);
                ppmin = shop.payOff.prepaid.pmin.split(',');
                ppsms = shop.payOff.prepaid.psms.split(',');
            } else if (time[0] == "PREPAIDSMS") {
                phoneDiv.find(".payoff").html(shop.payOff.prepaidsms.text1);
                phoneDiv.find(".payoff2").html(shop.payOff.prepaidsms.text2);
                phoneDiv.find(".payoff3").html(shop.payOff.prepaidsms.text3);
                ppmin = shop.payOff.prepaidsms.pmin.split(',');
                ppsms = shop.payOff.prepaidsms.psms.split(',');
            }
            phoneDiv.find('.phonePrice .text').text('p/min');
            phoneDiv.find('.phonePrice .price .euro').html("&euro;" + ppmin[0] + ",");
            phoneDiv.find('.phonePrice .price .cents').text(ppmin[1]);
            phoneDiv.find('.minutes .text').text('p/sms');
            phoneDiv.find('.minutes .price .euro').html("&euro;" + ppsms[0] + ",");
            phoneDiv.find('.minutes .price .cents').text(ppsms[1]);
        }
        var col = $('#rmacties').length > 0 ? '#333333' : '#000099';

        //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.setSubscriptionForProductDetail = function (subscription, phoneDiv) {
    var orderurl = phoneDiv.find('.orderButton').attr('href');
    if (orderurl.indexOf('&subscription') > 0) {
        orderurl = orderurl.substring(0, orderurl.indexOf('&subscription'));
    }
    orderurl = orderurl + '&subscription=' + subscription;
    phoneDiv.find('.orderButton').attr('href', orderurl);
}
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 = '';
	buffer = this.addSubscriptionInfo(buffer);
	if ($('#brands input').not(':checked').length > 0 && $('#brands input:checked').length > 0) {
	//if ($('#brands input:checked').length > 0) {
		buffer += "<br />Filter: Merk ";
		var c = 0;
		$('#brands input:checked').each(function() {
			if (c != 0) buffer += ", ";
			buffer += "<strong>" + $(this).val().substring(6) + "</strong>";
			c++;
		});
		buffer += " <a href='#' onclick='shop.resetBrands();return false;'>Verwijderen x</a>";
	}
	if ($('#attribs input:checked').length > 0) {
		buffer += "<br />Filter: Eigenschap ";
		var c = 0;
		$('#attribs input:checked').each(function() {
			if (c != 0) buffer += ", ";
			buffer += "<strong>" + $(this).parent().find('label').text() + "</strong>";
			c++;
		});
		buffer += " <a href='#'  onclick='shop.resetAttributes();return false;'>Verwijderen x</a>";
	}
	if (this.maxPrice != null) {
		if (buffer != '') buffer += " / ";
		buffer += 'Maximale toestel prijs &euro; ' + this.maxPrice;
	}
	if (buffer == '') {
		$('#shopinfoYourSelection').html('');
		$('.shoptopbar').removeClass("filtered");
	} else {
		$('#shopinfoYourSelection').html('<p id="shopInfoBox">' + buffer + '</p>');
		$('.shoptopbar').addClass("filtered").hide().show("fast");
	}
}
ShopObjectNew.prototype.updateStatusNew = function() {
    var bufferBrands = '';
    var bufferAttribs = '';
    var removeSubscriptionText = '<a href="#" onclick="shop.resetSubscriptions();return false;">verwijder selectie</a></p>';
    if ($('.subscriptiontabs li').length <= 1) removeSubscriptionText = '';

    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 + removeSubscriptionText;
        
    }
    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('');
        $('#shoptopbar').removeClass("filtered");
    } else {
        $('#shopinfoYourSelection').html(buffer);
        $('.shoptopbar').addClass("filtered").hide().show("fast");
    }

}
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();
	}
	var countOn = this.showOrHidePhones();
	this.sortPhones();

	renderCompare();
	renderBrandCount();
	$(".bundleRow").removeClass('selected');
	if (this.checkboxSubscription)
		this.checkboxSubscription.parents('tr.bundleRow').addClass('selected');
	$('#divNowLoading, #divNowLoadingContent').hide();
	if (window.checkShowPhones) checkShowPhones();
}

ShopObjectNew.prototype._renderPhones = ShopObjectNew.prototype.renderPhones;
ShopObjectNew.prototype.renderPhones = function(sendUpdate, hideNowLoading) {
    if (!hideNowLoading) {
        $('#divNowLoading, #divNowLoadingContent').show();
        if ($.browser.msie && $.browser.version < 7) {
            $(".shop .phone").hide();
        }
        setTimeout('shop.timedOutPhones(' + sendUpdate + ')', 1);
    }
    else {
        shop.timedOutPhones(sendUpdate);
    }
}

ShopObjectNew.prototype.addSubscriptionInfo = function() {
    var buffer = '';
    var removeSubscriptionText = " <a href='#' onclick='shop.resetSubscriptions();return false;'>Verwijderen x</a>";
    if ($('.subscriptiontabs li').length <= 1) removeSubscriptionText = '';
    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 += "BundelVrij" + name;
        } 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;
            }
        }

    }
    if (buffer != '') buffer = "Filter: Toestelprijzen zijn afgebeeld i.c.m. " + buffer + removeSubscriptionText;
    return buffer;
}

ShopObjectNew.prototype.sortPhones = function() {
	var sorting = $('#shopsortselect option:selected').text();
	if (document.location.href.indexOf('sort=price') > 0) {
		sorting = 'Prijs';
	}


	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);
	});
	var extention;
	($.browser.msie && $.browser.version < 7) ? extention = "jpg" : extention = "png";
	$("#abonnementenButton").click(function () {
		$("#shoptop").slideToggle();
		if ($(this).text().indexOf("Prepaid") == -1) {
			if ($(this).text() == "Abonnementen laten zien") {
				$(this).text("Abonnementen verbergen");
				$(this).css("background", "url(/rabomobiel/static/images/newShop/abbo_slideUp_bg." + extention + ") no-repeat 0 -4px");
			} else {
				$(this).text("Abonnementen laten zien");
				$(this).css("background", "url(/rabomobiel/static/images/newShop/abbo_slideDown_bg." + extention + ") no-repeat 0 -4px");
			}
		} else {
			if ($(this).text() == "Prepaid opties laten zien") {
				$(this).text("Prepaid opties verbergen");
				$(this).css("background", "url(/rabomobiel/static/images/newShop/abbo_slideUp_bg." + extention + ") no-repeat 0 -4px");
			} else {
				$(this).text("Prepaid opties laten zien");
				$(this).css("background", "url(/rabomobiel/static/images/newShop/abbo_slideDown_bg." + extention + ") no-repeat 0 -4px");
			}
		}

		return false;
	});
	$("#closeTop").click(function () {
		$("#shoptop").slideUp();
		$("#abonnementenButton").text($("#abonnementenButton").text().indexOf("Prepaid") == -1 ? "Abonnementen laten zien" : "Prepaid opties laten zien");
		$("#abonnementenButton").css("background", "url(/rabomobiel/static/images/newShop/abbo_slideDown_bg." + extention + ") no-repeat 0 -4px");
	});
	$("#merkbutton").click(function () {
		$(this).toggleClass("open");
		$("#brandsList").toggle();
		$("#eigenschappenButton").removeClass("open");
		$("#propertiesList").hide();
		return false;
	});
	$("#eigenschappenButton").click(function () {
		$(this).toggleClass("open");
		$("#propertiesList").toggle();
		$("#merkbutton").removeClass("open");
		$("#brandsList").hide();
		return false;
	});
	$(".yearSwitch tr").bind("mouseenter mouseleave", function () {
		$(this).toggleClass("hover");
	});

	$(".yearSwitch tr.row").click(function (e) {
		if (e.target.nodeName != "INPUT") $(this).find("input").attr("checked", "checked").click();
	});

	$(".yearSwitch input").click(function (e) {
		$(this).parents("table").find("tr").removeClass("active");
		$(this).parents("tr").addClass("active");

		e.stopPropagation();
		$("." + $(this).attr("value")).show();
		try {
			var current = $("#panel2y, #panel1y").find("input:checked").val();
			if (current == undefined) current = 'RM-15-' + $(this).attr("value")
			var old = current.split("-");
			var _new = "RM-" + old[1] + "-" + $(this).attr("value");
			$("#panel2y, #panel1y").hide();
			$("." + $(this).attr("value")).show();
			$("." + $(this).attr("value")).find("input[value=" + _new + "]").click();

			shop.setBanner(0);
		} catch (e) { }
	});

	$(".subscriptionpanel input").click(function () {
		$(this).parents("table").find(".bundleRow").removeClass("selected");
		if ($(this).parents(".looptijd").length > 0) {
			$(this).parents(".looptijd").find(".bundleRow").removeClass("selected");
		}

		var i = $('.subscriptionpanel.internet input:checked').val();
		if ($(this).val() == 'panel1y') {
			showBanner($(".banner .bundel12"));
			$(".banner .bundel").hide();
		}
		else if ($(this).val() == 'panel2y') {
			$(".banner .bundel12").hide();
			showBanner($(".banner .bundel"));
		} else {
			if ($('#panelBundleFree:visible').length > 0) {
				var sel_sub = $('#panelBundleFree input[name="thesub"]:checked');
			}
		}

		var b = $('input[value=panel1y]').attr('checked') ? 'rm12' : 'rm24';
		if (sel_sub && sel_sub.length > 0) {
			b = sel_sub.attr("id").replace("-", "").toLowerCase();
		}

		doPayoffText(b, i);
		$(this).parents("tr").addClass("selected");
	});

	$(".subscriptionpanel .bundleRow").click(function (e) {
		if (e.target.nodeName != "INPUT") $(this).find("input").attr("checked", "checked").click();
	});
	$(".bundleRow").each(function () {
		$(this).find("td:nth-child(1), td:nth-child(2), td:nth-child(6)").css("borderRight", 0);
		if ($(this).find("input:checked").length > 0) {
			$(this).addClass("selected");
		}
	});
	$(".shopoverflow .phone").click(function () {
		window.location.href = $(this).find("a").attr("href");
		return false;
	});
	$("#shoptop, #panel1y").hide();
	$(".phonedetail012010 .product .phones .small img").bind("mouseenter mouseleave", function (e) {
		if (e.type == "mouseenter") {
			var baseURL = $(this).attr("src").split("?");
			$("#big").attr("src", baseURL[0] + "?width=116");
		}
	});
	$(".phonedetail012010 #magnify, .phonedetail012010 #big").click(function () {
		var baseURL = $("#big").attr("src").split("?");
		tb_show($("#big").attr("alt"), baseURL[0] + "?width=300", null);
	});

	if (chosenSubscription) {
		var selectedTab = 0;
		var nroftabs = $('.subscriptiontabs li').length;
		if (chosenSubscription.indexOf('PREPAID') > -1) {
			setBanner(2);
			selectedTab = nroftabs == 1 ? 0 : 2;
		}
		else if (chosenSubscription.indexOf('BB') > -1) {
			selectedTab = nroftabs == 1 ? 0 : 1
			setBanner(1);
		} else {
			setBanner(selectedTab);
		}
		$(".phonedetail012010 .subscriptiontabs > ul").tabs({ selected: selectedTab });

	}
	else {
		$(".phonedetail012010 .subscriptiontabs > ul").tabs();
		setBanner(0);
	}
	$(".phonedetail012010 .subscriptiontabs > ul").bind('tabsshow', function (event, ui) {
		setBanner(ui.index);
		if ($(".datacardCheckbox:checked").length > 0) {
			if ($(".panel:visible .datacardCheckbox:checked").length == 0) {
				$(".panel:visible .datacardCheckbox").click();
			}
			$(".panel:visible .datacardCheckbox").parents("tr").removeClass("selected");
			$(".panel:visible .datacardCheckbox").parents(".datacard").addClass("datacardOpen");
			$("#datacardDiv").show();
		} else {
			$(".panel:visible .datacardCheckbox").parents("tr").removeClass("selected");
			$(".panel:visible .datacardCheckbox").parents(".datacard").removeClass("datacardOpen");
			$("#datacardDiv").hide();
		}
	});

	function doPayoffText(bundle, internet) {		
		$("#panelBundels .payoff").hide();
		$("#panelBundleFree .payoff").hide();
		if (bundle == null || bundle.length == 0) return;
		if (!internet || $(".payoff." + bundle + "." + internet.toLowerCase()).length == 0) {
			$(".payoff." + bundle + ":first").show()
		} else {
			$(".payoff." + bundle + "." + internet.toLowerCase()).show();
		}
	}
	function setBanner(i) {
		$(".banner>div").hide();

		switch (i) {

			case 0:
				if ($("#panelBundleFree .sms input:checked").length > 0) {
					$("#panelBundels .sms input[value=" + $("#panelBundleFree .sms input:checked").val() + "]").attr("checked", "checked");
				}
				if ($("#panelBundleFree .internet input:checked").length > 0) {
					$("#panelBundels .internet input[value=" + $("#panelBundleFree .internet input:checked").val() + "]").attr("checked", "checked");
				}
				setSelected();
				//check for existing rm selection
				if (chosenSubscription.indexOf('RM-') > -1) {
					$("#panel2y .subscriptionpanel .bundleRow input#" + chosenSubscription.replace('-12', '-24')).attr("checked", "checked").click();
					//check if 1 year should be selected
					if (chosenSubscription.indexOf('-12') > 0) {
						showBanner($(".banner .bundel12"));
						$(".payoff.rm12").show();
						$(".payoff.rm24").hide();
						$(".looptijd .subscriptionpanel input[value='panel1y']").click();
					} else {
						showBanner($(".banner .bundel"));
						$(".payoff.rm12").hide();
						$(".payoff.rm24").show();
						$(".looptijd .subscriptionpanel input[value='panel2y']").click();
					}
				} else {
					showBanner($(".banner .bundel"));
					$("#panel2y .subscriptionpanel .bundleRow:first input").attr("checked", "checked").click();
					$(".yearSwitch input[value='24']").click();
				}
				break;
			case 1:
				showBanner($(".banner .bundelvrij"));
				if ($("#panelBundels .sms input:checked").length > 0) {
					$("#panelBundleFree .sms input[value=" + $("#panelBundels .sms input:checked").val() + "]").attr("checked", "checked");
				}
				if ($("#panelBundels .internet input:checked").length > 0) {
					$("#panelBundleFree .internet input[value=" + $("#panelBundels .internet input:checked").val() + "]").attr("checked", "checked");
				}
				setSelected();
				if (chosenSubscription == "BB-24") {
					$("#panelBundleFree .subscriptionpanel:first .bundleRow:first input").attr("checked", "checked").click();
				}
				else if (chosenSubscription == "BB-12") {
					$($("#panelBundleFree .subscriptionpanel:first .bundleRow input")[1]).attr("checked", "checked").click();
				}
				else {
					$("#panelBundleFree .subscriptionpanel:first .bundleRow:last input").attr("checked", "checked").click();
				}
				break;
			case 2:
				showBanner($(".banner .prepaid"));
				if (chosenSubscription == "PREPAIDSMS") {
					$("#panelPrepaid .subscriptionpanel .bundleRow:last input").attr("checked", "checked").click();
				} else {
					$("#panelPrepaid .subscriptionpanel .bundleRow:first input").attr("checked", "checked").click();
				}
				break;
			default:
				//console.log('default');
				showBanner($(".banner .bundel"));
		}
	};
	$(".phonedetail012010 .specifications .row").each(function (i) {
		if (i % 2 == 0) $(this).addClass("alt");
	});

	$(".phonedetail012010 .subscriptions .infoDiv, .shopnewcontainer  .subscriptions .infoDiv").hide();
	$(".phonedetail012010 .panel .info, .shopnewcontainer #panelBundels .info").parent().bind("mouseenter mouseleave", function (e) {
		$(this).find("a").css("cursor", "pointer").toggleClass("infoOpen");
		$(".phonedetail012010 .subscriptions .infoDiv, .shopnewcontainer  .subscriptions .infoDiv").hide();
	});



	// new
	$(".bundlefree.datacard").parent().height(163); // TODO: is this dynamic or static?
	if ($.browser.msie && $.browser.version == 8) $(".bundlefree.datacard").parent().height(133);
	if ($(".datacardCheckbox:checked").length > 0) {
		$(".datacardCheckbox:checked").parents("tr").removeClass("selected");
		$(".datacardCheckbox:checked").parents(".datacard").addClass("datacardOpen");
		$("#datacardDiv").show();
	}
	$(".datacardCheckbox").click(function () {
		// undo default row check
		if ($(this)[0].checked) {
			$(this).css("checked", true);
		} else {
			$(".datacardCheckbox").removeAttr("checked");
		}
		$(this).parents("tr").removeClass("selected");
		$(this).parents(".datacard").toggleClass("datacardOpen");
		$("#datacardDiv").toggle();
		if ($('.bon').length > 0) {
			var height = $('.receipt').height();
			var divheight = $('#datacardDiv').outerHeight();
			var schuifuit = 0;
			if (height > 340) {
				schuifuit = height - 340;
				if ($.browser.msie && $.browser.version < 7) {
					schuifuit = schuifuit - 30;
				}
			}
			$('#uitschuifstuk').css('height', schuifuit + 'px');
			$('#bestelknopspan').css('top', 340 + schuifuit + 'px');

			if ($("#datacardDiv").css("display") == "block") {
				$('#uitschuifstuk').css('height', schuifuit + divheight + 'px');
			} else {
				$('#uitschuifstuk').css('height', schuifuit + 'px');
			}
		}
	});
	// /new
});


function checkShowPhones() {
	var windowHeight = $(window).height();
	var scrollTop = $(document).scrollTop();
	$('.phone:has(.lessactive)').each(function() {
	    var phoneActionTop = $(this)[0].offsetTop;
	    //console.log('phoneActionTop: ' + phoneActionTop + '. windowHeight: ' + windowHeight + '. scrollTop: ' + scrollTop);
	    if (phoneActionTop <= (scrollTop + windowHeight - 283)) {

	        $(this).find('.lessactive').remove();
	        $(this).find('.moreactive').show('slow');
	        var imgsrc = $(this).find('.hidden').text();
	        $(this).find('.image img.productimage').attr('src', imgsrc);
	    }
	});
}
function setSelected() {
    $(".subscriptionpanel").find(".bundleRow").removeClass("selected");
    $(".subscriptionpanel").find("input:checked").parents("tr").addClass("selected");
}
$(window).scroll(function() {
	checkShowPhones();
});
$(window).resize(function() {
	checkShowPhones();
});
$(document).ready(function() {
	checkShowPhones();
});

