jQuery(function($) {
  var 

        // Append selectors, comma seperated, that'll be bound to show the modal box
		bindSelectors = "div.banner a,div.content_hd1 .action a.btn_gold, a#productChooserCoverSearch",

		radioImgTmpl = "/redesign-img/modal/radio_%s.png",

		bundles = [
			["Mobila paketet", "10100"],
			["Kraftpaketet", "10101"],
			["Kraftpaketet Plus", "10102"],
			["Flexpaketet Singel", "10103"],
			["Flexpaketet Multi", "10104"]
		],

		addons = [
			["Båtantenn", "10062"],
			["Sommarstugeantenn", "10064"],
			["Husvagnsantenn", "10063"]
		],

		questions = [
			['Vem eller vilka kommer att använda bredbandet?',
				['Bara jag själv', 'Flera personer']],
			['Hur ofta kommer bredbandet att användas?',
				['Några gånger i veckan', 'Bara under ledighet']],
			['Var kommer bredbandet huvudsakligen att användas någonstans?',
				['Hemma', 'Sommarstugan', 'Båten', 'Husvagnen']]
		],

    // Each index in this object corresponds with the index of the array above
    // Each answer will filter out packages and addons depending on the choice.
    // For example, index 0 (first answer) on question 0, doesn't have any dependencies
    // while answer two, index 1, will filter out Mobila paketet (index 0 in bundles)
		deps = {
		    // Question 1
		    "0": [
		    // Answer 1
				{bundles: [], addons: [] },
		    // Answer 2
				{bundles: [0], addons: [] }
			],

		    // Question 2
		    "1": [
		    // Answer 1
				{bundles: [3, 4], addons: [] },

		    // Answer 2
				{bundles: [2], addons: [] }
			],

		    // Question 3
		    "2": [
		    // Answer 1
				{bundles: [0, 3], addons: [0, 1, 2] },

		    // Answer 2
				{bundles: [], addons: [0, 2] },

		    // Answer 3
				{bundles: [], addons: [1, 2] },

		    // Answer 4
				{bundles: [], addons: [0, 1] }
			]
		},

		answers = [],

		$win = $(window),
		$doc = $(document);
		var $background, $content, $title, $questionCnt, $btnClose, $btnPrev, $btnNext, $choice;

		function setup() {
			if ( $('#modal-background').length ) {
				$('#modal-background,#modal-content').remove();
				$background = $('<div id="modal-background"/>').appendTo('body');
				$content = $('<div id="modal-content"/>').appendTo('body');
				$title = $('<div id="modal-title"/>').appendTo($content);
			}

			$questionCnt = $('<div id="modal-questions">Fråga <span/>/<span/></div>').appendTo($content);
			$choice = $('<div class="modal-choice"><img src="/redesign-img/modal/radio_off.png"/><span/></div>');
			$btnClose = $('<button id="modal-close" title="Stäng fönstret"/>').appendTo($content);
			$btnPrev = $('<button id="modal-btn-prev"/>').appendTo($content);
			$btnNext = $('<button id="modal-btn-next"/>').appendTo($content);

			$questionCnt.find('span').eq(1).text(questions.length).end().end();

			// Prepare the generic radio image event
			$choice.mousedown(function() {
					$(this)
					.closest('div.modal-choice')
						.find('img')
							.attr('src', radioImgTmpl.replace('%s', 'on'))
							.end()
						.addClass('modal-chosen')
						.siblings()
							.removeClass('modal-chosen')
							.find('img')
								.attr('src', radioImgTmpl.replace('%s', 'off'));

					return false;
			});

			// Close button click
			$('#modal-close,#modal-background').click(function() {
					$background.hide();
					$content.hide();
			});

			// Back-button click
			$('#modal-btn-prev').click(function() {
					var no = parseFloat($questionCnt.find('span:eq(0)').text()) - 1;

					answers[no] = $content
					.find('.modal-choice img')
					.index($content.find('[src$=on.png]'));

					no - 1 >= 0 && renderQuestion(no - 1, no);
			});

			// Forward-button clicked
			$('#modal-btn-next').click(function() {
					var no = parseFloat($questionCnt.find('span:eq(0)').text()) - 1;

					if (!$content.find('[src$=on.png]').length) {
							alert('Vänligen välj ett alternativ för att fortsätta.');
							return false;
					}

					answers[no] = $content
					.find('.modal-choice img')
					.index($content.find('[src$=on.png]'));

					if (no + 1 < questions.length) {
							renderQuestion(no + 1, no);
					}
					else {
							sendToOrderPage();
					}
			});


		}

    $(bindSelectors).live('click', function() {
				setup();
        renderQuestion(0);
        $background.css('height', $doc.height()).show();
        $content.css('top', ($(window).height()/2) + $(window).scrollTop()).show();
        return false;
    });

    //
    //
    function renderQuestion(index, oldIndex) {
        var 
				errorTimer,
				i = 0,
				$c,
				noOfAnswers = questions[index][1].length,
        // 140 = The space we have to play with (height), 33 = each question line height
				singleMargin = (140 - (noOfAnswers * 33)) / noOfAnswers + 1;


        // Save the answer for later
        if (oldIndex !== undefined) {
            answers[oldIndex] = $content
					.find('.modal-choice img')
					.index($content.find('[src$=on.png]'));
        }

        $questionCnt.find('span').eq(0).text(index + 1);

        $title.css('height', '100px').text(questions[index][0]);
        $content.find('div.modal-choice').remove();

        for (; i < noOfAnswers; i++) {

            $c = $choice.clone(true);
            $c.css('margin', singleMargin / 2 + 'px auto');
            $c.find('span').text(questions[index][1][i]);

            $content.append($c);
        }
    }

    //
    //
    function sendToOrderPage() {
        var o, queryString = [], i, l, bundlesToRemove = [], addonsToRemove = [];

        for (o in deps) {
            for (i = 0, l = deps[o][answers[o]].bundles.length; i < l; i++) {
                bundlesToRemove.push(deps[o][answers[o]].bundles[i]);
            }

            for (i = 0, l = deps[o][answers[o]].addons.length; i < l; i++) {
                addonsToRemove.push(deps[o][answers[o]].addons[i]);
            }
        }

        for (i = 0, l = questions.length; i < l; i++) {
            if ($.inArray(i, bundlesToRemove) === -1) {
                queryString.push("ShowProduct=" + bundles[i][1]);
            }

            if ($.inArray(i, addonsToRemove) === -1) {
                queryString.push("ShowAntenna=" + addons[i][1]);
            }
        }

        location.href = '/privat/bredband-landningssida.aspx?' + queryString.join('&');
    }
});

