﻿/* ----------------------------------------
	Title : mobiel internet
	Dependencies : 
		-	jquery.js
---------------------------------------- */

//Global object
var MB = MB || {};

MB.ui = (function () {

    var init = function () {
        $('#gallery').galleryView({
            panel_width: 720,
            panel_height: 340,
            frame_width: 46,
            frame_height: 32
        });
        //gallery detail page
        $('#gallery-content').galleryView({
            panel_width: 322,
            panel_height: 270,
            frame_width: 46,
            frame_height: 46
        });

        $("#placeOrderForm").submit(blockUserInterface);
    };

    var blockUserInterface = function () {

        $.blockUI({ message: "een ogenblik geduld aub" });

        // after 30 seconds, we show the user a message.
        setTimeout(function () {
            $.unblockUI({
                onUnblock: function () { alert('Uw aanvraag duurde te lang om te verwerken. Probeer het nogmaals of neem contact met ons op.'); }
            });
        }, 30000);
    }

    return {
        init: init
    };

})();

/*
 *  plan selector table allows users to choose a different telco
 */
MB.planSelector = (function() {

    var init = function(){       
        
        //updatePlans();
        
        $("select[class='updatePlans']").change(updatePlans);
        $(".abonnementen a[class='btn_add']").click(placeAlternativeOrder);
        $("a[class='ordernow_detailpage']").click(placeAlternativeOrder);
        $("input[class^='extras-']").change(updatePrice);
    };

    /*
     *  updates the price on a detail page & in the alternative table after a user
     *  changes an extra selection. Extra's can give extra discount, which effects the price.
     *  note; by law the price can never fall below 0, so the maximum discount is the price of the hardware
     */
    var updatePrice = function(e){

        // only products with a price can have a discount.
        var priceLabel = $('.priceLabel');
        if(priceLabel == undefined) return;

      //  var basePrice = parseInt($(priceLabel).attr('price')) / 100.0;
        var discount = 0;

        // find the visible & checked options
        $("input[class^='extras-']:visible:checked").each( function(i, extra) {
            discount+= parseInt($(extra).attr('price')) / 100.0;
        });

        // This updates the main price, but it looks sooooo awkward that I'm removing it
        // from a UI point of view there is absolutly NO relation between the add to cart
        // button on top of the page and the selected options on the bottom.
        //
        // If this is turned on, make sure to add some code that posts the selected extras
        // to the server. (ATM you add the package ID)
        //
        //$(priceLabel).html(getPriceLabelText(basePrice, discount));

        // update the altervative table
        var alternativePriceLabels = $('.actie > span > span');
        $(alternativePriceLabels).each( function(i, altPrice) {
            var basePrice = parseInt($(altPrice).attr('price')) / 100.0;
            $(altPrice).html(getPriceLabelText(basePrice, discount));
        });
        
    }

    var getPriceLabelText = function(basePrice, discount) {
        var price = Math.round((basePrice - discount)*100)/100;
        if (price <= 0) price = 'GRATIS'
        else price = "&euro; " + price.toFixed(2).replace(',', ',,').replace('.', ',').replace(',,', '.');
        return price;
    }

    /*
     *  This function places an order based on the customer selection
     *  of a alternative plan & the selected extra's.
     */
    var placeAlternativeOrder = function(e){
     
        e.preventDefault();

        var target = $(e.currentTarget);

		if (target.is('a')) {
            // product id's
            var id = target.attr('rel');

            var vendorHash = $("#vendorSelection").val();
            var extras = ',';
            $.each( $("input[class='extras-" + vendorHash + "']:visible:checked") , function(i, extraInput) {
                extras += $(extraInput).val() + ",";
            });

            id += extras;

            $.ajax({
                type: "POST",
                url: "/shoppingcart/add",
                dataType: 'json',
                data: {'id' :  id},
                success: function(data){
                   window.location = "/shoppingcart/";
                }
            });

        }        
    }
    
    /*
     *  Updates the visible plans after the customer selected a network / plan family
     */
    var updatePlans = function(){
        updatePackageDurationSelectBox();
        updatePlanListing();        
        updatePrice();
    }

    /*
     *  Updates the duration boxes after the customer selected a network / plan family
     */
    var updatePackageDurationSelectBox = function() {

        var vendorHash = $("#vendorSelection").val();
        if(vendorHash == undefined) return;
        
        // hide all the package duration & extra options
        $("select[id^='packageDuration']").hide();
        $("div[id^='extras']").hide();

        // show package & extra options for the seleted vendor
        $("#packageDuration-" + vendorHash).show();
        $("#extras-" + vendorHash).show();
    };

    /*
     *  Update the table with available plans after the customer selected a network / plan family
     */
    var updatePlanListing = function(){

        var vendorHash = $("#vendorSelection").val();
        var durationHash = $("#packageDuration-" + vendorHash).val();

        // filter contains the rows that should become visible
        var filter = "";
        filter += vendorHash != '' && vendorHash != undefined  ? "[class*='vendor-" + vendorHash + "']" : "";
        filter += durationHash != '' && durationHash != undefined ? "[class*='duration-" + durationHash  + "']" : "";
        filter += vendorHash != undefined ? ",.abonnementen tr[class*='brand-" + vendorHash + "']" : "";

        $(".abonnementen tbody tr:visible").fadeOut();        
        $(".abonnementen tbody tr" + filter).fadeIn('slow');
    };
    
    return{
        init : init
    };

})();

/*
 *   shopping cart functions
 */
MB.shoppingCart = (function () {
	
    var init = function() {
        $('.removeFromCart').bind('click',removeFromCartClickHandler);
        $('#toggleCart').bind('click', toggleCartClickHandler);
	};

    /*
     * Handles the 'remove' link click in the shoppingcart on the shopping cart overview page
     */
    var removeFromCartClickHandler = function(e) {
    
        e.preventDefault();

        var target = $(e.target);

		if (target.is('a')) {
            var id = target.attr('rel');

            $.ajax({
                type: "POST",
                url: "/shoppingcart/removefromcart",
                dataType: 'json',
                data: {'id' :  id},
                success: function(data){
                    // Update the page elements
                    //$('#row-' + data.DeleteId).fadeOut('slow');                    
                    $('#row-' + data.DeleteId).addClass('strikeout');
                    $('#cart-count').html(data.CartCount);
                    $('#update-message').html(data.Message);
                    $('#update-message').show();
                    $('.cart-total').html(data.CartTotal);
                    $('.cart-subtotal').html(data.CartSubTotal);
                    $('.cart-discount').html(data.CartDiscount);
                }
            });
        }
    };

    /*
     *  Handles the click of the shoppingcart button in the main menu
     */
    var toggleCartClickHandler = function (e) {
        $('#cart').slideToggle();
        $('.shoppingcarttoggle').toggleClass("shoppingcarttoggle-active");

    }

    //Public
	return {
		init: init
	};

})();


MB.orderForm = (function () {
	
    var companyFields;

    var init = function() {

        if (companyFields == undefined) {
            companyFields = $("#companyFields").children();            
        }

        updateCompanyFields();
        $("#AccountType").change(updateCompanyFields);
     };

    /*
     *  show or hides the company fields according to the selected 
     *  value of the drop down listbox 'accounttype'
     */
    var updateCompanyFields = function(e){
        
        var accountType = $("#AccountType").val();
                
        switch (accountType) {
            case "Private":
                $("#companyFields").children().remove();
                break;
            case "Business":
                $("#companyFields").append(companyFields);
                break;
        }
    };
    //Public
	return {
		init: init
	};
})();

/*
 *  internet gebruik wizard.
 */
MB.internetAdviesWizard = (function () {

    var init = function () {

        $(".bestemming a").click(regionClickHandler);

        $("#internetAdviesWizard .slider").slider({
            range: "min",
            step: 1,
            slide: refreshSliderValue,
            change: refreshSliderValue
        });

        $("#internetAdviesWizard .radio").buttonset();
        $("#internetAdviesWizard input[type=radio]").change(intervalChangedHandler);

        $("#internetAdviesWizard .internetAdviesLink").click(getAdvice);

        intervalChangedHandler();
    };

    var regionClickHandler = function (e) {
        e.preventDefault();

        var target = $(e.target);

        $("div[id$='Info']").hide();
        $("#" + target.attr("id") + "Info").show();
    }

    var refreshSliderValue = function (e) {
        $(".option").each(function (i, data) {
            var sliderControl = $(data).find(".slider");
            var v = sliderControl.slider("value")

            $(data).find(".value").text(v);
        });

        // Megabytes update
        var usage = [];

        // option div
        $(".option").each(function (i, data) {
            var v = parseInt($(data).find(".slider").slider("value"));
            var m = parseInt($(data).find("input[type=hidden][name='multiply']").val());
            usage.push(v * m);
        });

        var amount = 0;
        for (i = 0; i < usage.length; i++) {
            amount += usage[i];
        }

        $("#megabytes").html(Math.ceil(amount/1000) + " Mb");
    }

    var intervalChangedHandler = function () {
        $(".option").each(function (i, data) {
            var sliderControl = $(data).find(".slider");
            var interval = parseInt($(data).find("input[type=radio]:checked").val());

            var maxValue = parseInt($(data).find("input[type=hidden][name='max']").val());

            sliderControl.slider("option", "max", maxValue * interval);
            // redraww the value indicator
            sliderControl.slider("value", sliderControl.slider("value"));
        });
    };

    var getAdvice = function () {

        var usage = [];

        // option div
        $(".option").each(function (i, data) {
            var v = parseInt($(data).find(".slider").slider("value"));
            var m = parseInt($(data).find("input[type=hidden][name='multiply']").val());
            usage.push(v * m);
        });

        var region = $("div[id$='Info']:visible");
        var data = { usage: usage, region: region.length ? region.attr("id").replace('Info', '') : '' };

        $.ajax({
            type: "POST",
            url: "/wizard/internetadvies",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            success: function (data) {
                $("#result").html(data);
            }
        });
    }

    return {
        init: init
    };

})();


$(function () {
    MB.ui.init();
    MB.shoppingCart.init();
    MB.orderForm.init();
    MB.planSelector.init();
    MB.internetAdviesWizard.init();
});
