﻿/////////////////////////////////////////////////////////////
// Namespace declaration.
/////////////////////////////////////////////////////////////
var SherWeb = SherWeb || {};

/////////////////////////////////////////////////////////////
// Wizard.
/////////////////////////////////////////////////////////////

// Class.
SherWeb.Wizard = function(container, language) {
	if (typeof container != 'string')
		throw '\'container\' must be the name of a DOM object';

	if (language != 'en' && language != 'fr')
		throw language + ' is an invalid language (en/fr supported)';

	this._container = document.getElementById(container);
	this._language = language;

	if (typeof this._container != 'object')
		throw 'DOM object \'container\' cannot be found';
};

/////////////////////////////////////////////////////////////
// Wizard static member variables.
/////////////////////////////////////////////////////////////

// Used to declare the different page types the wizard
// can have.
SherWeb.Wizard.PageType = { MultipleChoices: 0, Slider: 1,SliderChoice : 2, MultipleRadioChoices : 3 };

// Sets the seed to generate unique IDs
SherWeb.Wizard.UniqueSeed = 10000;

// Sets the base tags for element insertion
SherWeb.Wizard.HeaderTag = '<div class="page_header"></div>';
SherWeb.Wizard.TitleTag = '<div class="page_title"></div>';
SherWeb.Wizard.DescriptionTag = '<div class="page_description"></div>';
SherWeb.Wizard.IconTag = '<img class="icon" src="" alt=""/>';
SherWeb.Wizard.HelpLinkTag = '<a href="javascript:;" class="help"><img src="" alt="" /></a>';
SherWeb.Wizard.QuestionTag = '<div class="page_question"></div>';
SherWeb.Wizard.UserInputTag = '<div class="page_userinput"></div>';
SherWeb.Wizard.ButtonsTag = '<div class="page_buttons"></div>';
SherWeb.Wizard.ChoiceTag = '<div class="page_multichoice"></div>';
SherWeb.Wizard.RadioTag = '<div class="page_multichoice"></div>';
SherWeb.Wizard.CheckboxTag = '<input type="checkbox" />';
SherWeb.Wizard.RadioBoxTag = '<input type="radio" name="{0}" />';
SherWeb.Wizard.LabelTag = '<label></label>';
SherWeb.Wizard.LearnMoreHoverTag = '<div id="page_more_tooltip" class="wizard_more_tooltip"></div>';
SherWeb.Wizard.LearnMoreTag = '<a href="javascript:;" class="more"><img src="" alt=""/></a>';
SherWeb.Wizard.LinkTag = '<a href="javascript:void(0);"></a>';
SherWeb.Wizard.SliderTag = '<div class="page_slider"></div>';
SherWeb.Wizard.SliderControlTag = '<div class="slider_control"></div>';
SherWeb.Wizard.SliderValueTag = '<div class="slider_value"></div>';
SherWeb.Wizard.SliderInputTag = '<input type="text" disabled="disabled" />';
SherWeb.Wizard.SliderIcons = '<div class="slider_icons"></div>';
SherWeb.Wizard.SliderIconUnder10 = '<img class="under10" />';
SherWeb.Wizard.SliderIcon50 = '<img class="fifty" />';
SherWeb.Wizard.SliderIconOver100 = '<img class="over100" />';
SherWeb.Wizard.TooltipTag = '<div class="wizard_tooltip"></div>';
SherWeb.Wizard.TooltipHeaderTag = '<div class="title"></div>';
SherWeb.Wizard.TooltipTitleTag = '<h2 style="padding:0;"></h2>';
SherWeb.Wizard.TooltipTextTag = '<div class="text"></div>';
SherWeb.Wizard.TooltipLinkTag = '<div class="link_area"></div>';
SherWeb.Wizard.TooltipCloseTag = '<div class="close"><img src="" alt=""/></div>';
SherWeb.Wizard.TooltipFooterTag = '<div class="footer"></div>';
// Culture-related images
SherWeb.Wizard.Images = {
    fr: { Close: '/common/icons/wizard_tooltip-close.png', Help: '/common/icons/wizard_help.png', LearnMoreIcon: '/common/icons/wizard_arrow.gif', SliderIconUnder10: '/fr-ca/wizard_slider-less10.png', SliderIcon50: '/common/wizard_slider-250.png', SliderIconOver100: '/fr-ca/wizard_slider-over500.png', SliderIconNovice: '/fr-ca/wizard_slider-novice.png', SliderIconGood: '/fr-ca/wizard_slider-good.png', SliderIconExpert: '/fr-ca/wizard_slider-expert.png' },
    en: { Close: '/common/icons/wizard_tooltip-close.png', Help: '/common/icons/wizard_help.png', LearnMoreIcon: '/common/icons/wizard_arrow.gif', SliderIconUnder10: '/en-ca/wizard_slider-less10.png', SliderIcon50: '/common/wizard_slider-250.png', SliderIconOver100: '/en-ca/wizard_slider-over500.png', SliderIconNovice: '/en-ca/wizard_slider-novice.png', SliderIconGood: '/en-ca/wizard_slider-good.png', SliderIconExpert: '/en-ca/wizard_slider-expert.png' }
};

// Culture-related labels
SherWeb.Wizard.Labels = {
    fr: { Close:'Fermer', Previous: 'retour', Next: 'suivant', Finish: 'Voir mes plans', StartOver: 'recommencer', LearnMore: 'En savoir plus', LearnMoreIcon: '>', NotSure: 'je ne sais pas trop', Help: 'Aide', YourSelection: 'vos sélections', SliderIconUnder10: 'Moins que 10', SliderIcon50: '50', SliderIconOver100: 'Plus que 100', SliderIconNovice: 'Débutant', SliderIconGood: 'Bon', SliderIconExpert: 'Expert' },
    en: { Close:'Close', Previous: 'back', Next: 'next', Finish: 'Show me my plans', StartOver: 'start over', LearnMore: 'Learn more', LearnMoreIcon: '>', NotSure: 'I\'m not sure', Help: 'Help', YourSelection: 'your selections', SliderIconUnder10: 'Under 10', SliderIcon50: '50', SliderIconOver100: 'Over 100', SliderIconNovice: 'Novice', SliderIconGood: 'Good', SliderIconExpert: 'Expert' }
};

/////////////////////////////////////////////////////////////
// Wizard private member variables (decl. + init.)
/////////////////////////////////////////////////////////////

SherWeb.Wizard.prototype._language = undefined;
SherWeb.Wizard.prototype._container = undefined;
SherWeb.Wizard.prototype._friendly = false;
SherWeb.Wizard.prototype._currentPage = -1;
SherWeb.Wizard.prototype._callbackURL = '';
SherWeb.Wizard.prototype._redirectUrl = '';
SherWeb.Wizard.prototype._help = { title: '', description: '' };
SherWeb.Wizard.prototype._pages = [];
SherWeb.Wizard.prototype._learnMoreHover = undefined; // cached object accessor
SherWeb.Wizard.prototype._imagePath = '';

/////////////////////////////////////////////////////////////
// Wizard public member functions
/////////////////////////////////////////////////////////////

// (Re)initializes the Wizard and populates the container.
SherWeb.Wizard.prototype.Initialize = function (content) {
    if (typeof content != 'object')
        throw '\'content\' must be a valid object';

    this._imagePath = typeof (SherWeb.Context.app_path) == 'undefined'
        ? ''
        : SherWeb.Context.app_path + '/resources/images';
    this._help.title = content.Help.Title;
    this._help.description = content.Help.Description;
    this._currentPage = content.Pages.length;
    this._finished = content.Finished;
    this._callbackURL = content.CallbackURL;
    this._redirectUrl = content.RedirectUrl;
    this._pages = content.Pages;
    this._friendly = content.Friendly;
    if (this._finished == true) {
        this._onFinish();
    } else {
        this._rebuild();
    }
};

/////////////////////////////////////////////////////////////
// Wizard private member functions
/////////////////////////////////////////////////////////////

// Returns a label in the current language
SherWeb.Wizard.prototype._getLabel = function(label) {
	return SherWeb.Wizard.Labels[this._language][label];
};

// Returns an image path in the current language
SherWeb.Wizard.prototype._getImage = function(id) {
    return this._imagePath + SherWeb.Wizard.Images[this._language][id];
};

// Helper function to clear and re-populate the
// container according the current page.
SherWeb.Wizard.prototype._rebuild = function() {
	this._resetStructure();
	this._populateCommonUI();
	if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.MultipleChoices)
		this._populateMultipleChoices();
    if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.MultipleRadioChoices)
        this._populateRadioChoices();
    else if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.Slider)
        this._populateSlider();
    else if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.SliderChoice)
        this._populateSliderChoice();

	this._populateButtons();
};

// Helper function to return the current page.
SherWeb.Wizard.prototype._getCurrentPage = function() {
	return this._pages[this._currentPage - 1];
};

// Helper function to return a unique ID.
SherWeb.Wizard.prototype._getUniqueID = function() {
	return 'wizard_ctrl_' + (SherWeb.Wizard.UniqueSeed++).toString();
};

// Helper function to create or re-create the
// wizard structure.
SherWeb.Wizard.prototype._resetStructure = function() {
    $(this._container).empty();
    $(SherWeb.Wizard.HeaderTag).appendTo(this._container);
    $(SherWeb.Wizard.TitleTag).appendTo(this._container);
    //$(SherWeb.Wizard.DescriptionTag).appendTo(this._container);
    $(SherWeb.Wizard.QuestionTag).appendTo(this._container);
    $(SherWeb.Wizard.UserInputTag).appendTo(this._container);
    $(SherWeb.Wizard.ButtonsTag).appendTo(this._container);

    // Help button at the top right corner
    var help = $(SherWeb.Wizard.HelpLinkTag);
    $('img', help).attr({ src: this._getImage('Help'), alt: this._getLabel('Help') });
    // must use a closure here
    this._bindLearnMoreClick(help, this._help.title, this._help.description, '', '');
    
    help.appendTo(this._container);

    SherWeb.Wizard._learnMoreHover = $(SherWeb.Wizard.LearnMoreHoverTag).text(this._getLabel('LearnMore')).prependTo('body');

};

// Sets the common text and UI elements of the wizard
SherWeb.Wizard.prototype._populateCommonUI = function() {
	var p = this._getCurrentPage();
	
	$('.page_title', this._container).text(p.Title);
	$('.page_description', this._container).text(p.Description);
	$('.page_question', this._container).text(p.Question);	
};


// Populates the radio section of the current page
SherWeb.Wizard.prototype._populateRadioChoices = function() {
    var w = this;
    var p = this._getCurrentPage();
    var c = $('.page_userinput', this._container);
    var oneChecked = false;
    $.each(p.Choices, function(i, choice) {
        var id = w._getUniqueID();
        var group = $(SherWeb.Wizard.RadioTag);
        // IE fix: must declare name at the DOM element construction rather than set it after
        //var check = $(SherWeb.Wizard.RadioBoxTag).attr({ id: id, name: choice.Name, value: choice.Value });
        var check = $(SherWeb.Wizard.RadioBoxTag.replace('{0}', choice.Name)).attr({ 'id': id, 'value': choice.Value });
        var label = $(SherWeb.Wizard.LabelTag).attr({ 'for': id }).text(choice.Label);
        var more = $(SherWeb.Wizard.LearnMoreTag);
        $('img', more).attr({ src: w._getImage('LearnMoreIcon'), alt: w._getLabel('LearnMoreIcon') });
        
        // must use a closure here
        w._bindLearnMoreClick(more, choice.MoreInfo.Title, choice.MoreInfo.Text, choice.MoreInfo.Link, choice.MoreInfo.Value);

        group.append(more);
        group.append(check);
        group.append(label);
        c.append(group);

        // IE fix: must be done after adding to the DOM
        if (choice.Checked == true) {
            check.attr('checked', 'checked');
        }
    });
};
// Populates the checkbox section of the current page
SherWeb.Wizard.prototype._populateMultipleChoices = function() {
    var w = this;
    var p = this._getCurrentPage();
    var c = $('.page_userinput', this._container);

    $.each(p.Choices, function(i, choice) {
        var id = w._getUniqueID();
        var group = $(SherWeb.Wizard.ChoiceTag);
        var check = $(SherWeb.Wizard.CheckboxTag).attr({ id: id, name: choice.Name, value: choice.Value });
        var label = $(SherWeb.Wizard.LabelTag).attr({ 'for': id }).text(choice.Label);
        var more = $(SherWeb.Wizard.LearnMoreTag);

        var icon = choice.Icon != '' && choice.Icon != null
            ? $(SherWeb.Wizard.IconTag).attr({ src: choice.Icon, alt: choice.Name })
            : null;

        $('img', more).attr({ src: w._getImage('LearnMoreIcon'), alt: '' });

        // must use a closure here
        w._bindLearnMoreHover(more, w._getLabel('LearnMore'));
        w._bindLearnMoreClick(more, choice.MoreInfo.Title, choice.MoreInfo.Text, choice.MoreInfo.Link, choice.MoreInfo.Value);

        group.append(more);
        group.append(check);
        if (icon != null)
            group.append(icon);
        group.append(label);
        c.append(group);

        // IE6 fix: must be done after adding to the DOM
        if (choice.Checked == true)
            check.attr('checked', 'checked');
    });
};

// Populates the checkbox section of the current page
SherWeb.Wizard.prototype._populateSlider = function() {
    var w = this;
    var p = this._getCurrentPage();
    var c = $('.page_userinput', this._container);
    var group = $(SherWeb.Wizard.SliderTag);
    var slider = $(SherWeb.Wizard.SliderControlTag);
    var group_value = $(SherWeb.Wizard.SliderValueTag);
    var v = $(SherWeb.Wizard.SliderInputTag).attr({ name: p.Slider.Name, value: p.Slider.Value });
    var icons = $(SherWeb.Wizard.SliderIcons)
        .append($(SherWeb.Wizard.SliderIconUnder10).attr({ 'src': w._getImage('SliderIconUnder10'), 'alt': w._getLabel('SliderIconUnder10') }))
        .append($(SherWeb.Wizard.SliderIcon50).attr({ 'src': w._getImage('SliderIcon50'), 'alt': w._getLabel('SliderIcon50') }))
        .append($(SherWeb.Wizard.SliderIconOver100).attr({ 'src': w._getImage('SliderIconOver100'), 'alt': w._getLabel('SliderIconOver100') }));

    group_value.append(v);
    group.append(slider);
    group.append(group_value);
    c.append(group);
    c.append(icons);
    
    slider.slider({
        stop: function(event, ui) { w._sliderStop(event, ui); },
        slide: function(event, ui) { w._sliderMoving(event, ui); },
        value: p.Slider.Value,
        min: p.Slider.Min,
        max: p.Slider.Max
    });
};

// Populates the checkbox section of the current page
SherWeb.Wizard.prototype._populateSliderChoice = function() {
    var w = this;
    var p = this._getCurrentPage();
    var c = $('.page_userinput', this._container);
    var group = $(SherWeb.Wizard.SliderTag);
    var slider = $(SherWeb.Wizard.SliderControlTag);
    var group_value = $(SherWeb.Wizard.SliderValueTag);
    var v = $(SherWeb.Wizard.SliderInputTag).attr({ name: p.Slider.Name, value: p.Slider.Value });
    var icons = $(SherWeb.Wizard.SliderIcons)
        .append($(SherWeb.Wizard.SliderIconUnder10).attr({ 'src': w._getImage('SliderIconNovice'), 'alt': w._getLabel('SliderIconNovice') }))
        .append($(SherWeb.Wizard.SliderIcon50).attr({ 'src': w._getImage('SliderIconGood'), 'alt': w._getLabel('SliderIconGood') }))
        .append($(SherWeb.Wizard.SliderIconOver100).attr({ 'src': w._getImage('SliderIconExpert'), 'alt': w._getLabel('SliderIconExpert') }));

    group_value.append(v);
    group.append(slider);
    group.append(group_value);
    c.append(group);
    c.append(icons);

    slider.slider({
        stop: function(event, ui) { w._sliderStop(event, ui, false); },
        slide: function(event, ui) { w._sliderMoving(event, ui, false); },
        value: p.Slider.Value,
        min: p.Slider.Min,
        max: p.Slider.Max
    });

    var choice = p.Choice;
    var id = w._getUniqueID();
    var group = $(SherWeb.Wizard.ChoiceTag).css({'margin-top':'10px'});
    var check = $(SherWeb.Wizard.CheckboxTag).attr({ id: id, name: choice.Name, value: choice.Value });
    var label = $(SherWeb.Wizard.LabelTag).attr({ 'for': id }).text(choice.Label);
    var more = $(SherWeb.Wizard.LearnMoreTag);
    $('img', more).attr({ src: w._getImage('LearnMoreIcon'), alt: w._getLabel('LearnMoreIcon') });

    // must use a closure here
    w._bindLearnMoreClick(more, choice.MoreInfo.Title, choice.MoreInfo.Text, choice.MoreInfo.Link, choice.MoreInfo.Value);

    group.append(more);
    group.append(check);
    group.append(label);
    c.append(group);

    // IE6 fix: must be done after adding to the DOM
    if (choice.Checked == true)
        check.attr('checked', 'checked');
};

// Populates the checkbox section of the current page
SherWeb.Wizard.prototype._populateButtons = function() {
	var w = this;
	var c = $('.page_buttons', this._container);

	$(SherWeb.Wizard.LinkTag).attr('class', 'next').text(w._getLabel('Next')).click(function() { w._onNextClick(); }).appendTo(c);

	if (this._currentPage != 1) {
		$(SherWeb.Wizard.LinkTag).attr('class', 'previous').text(w._getLabel('Previous')).click(function() { w._onPreviousClick(); }).appendTo(c);
		$(SherWeb.Wizard.LinkTag).attr('class', 'finish').text(w._getLabel('YourSelection')).click(function() { w._onFinish(); }).appendTo(c);
		//$(SherWeb.Wizard.LinkTag).attr('class', 'startover').text(w._getLabel('StartOver')).click(function() { w._onStartOverClick(); }).appendTo(c);
	}
//	else if (!this._friendly) {
//		$(SherWeb.Wizard.LinkTag).attr('class', 'notsure').text(w._getLabel('NotSure')).click(function() { w._onNotSureClick(); }).appendTo(c);
//	}
	else {
		$('<div>&nbsp;</div>').appendTo(c);
	}
};

// Serializes the pages input parameters
SherWeb.Wizard.prototype._serializeInputs = function() {
    var q = new Array();

    // 1. take the previous pages values (based on the current one)
    // from our object, the user can't have modified them
    for (var i = 0; i < this._currentPage - 1; i++) {
        var p = this._pages[i];

        if (p.Type == SherWeb.Wizard.PageType.MultipleChoices) {
            for (var j = 0; j < p.Choices.length; j++) {
                if (p.Choices[j].Checked == true)
                    q.push(escape(p.Choices[j].Name) + '=' + escape(p.Choices[j].Value));
            }
        }
        else if (p.Type == SherWeb.Wizard.PageType.MultipleRadioChoices) {
            for (var j = 0; j < p.Choices.length; j++) {
                if (p.Choices[j].Checked == true)
                    q.push(escape(p.Choices[j].Name) + '=' + escape(p.Choices[j].Value));
            }
        }
        else if (p.Type == SherWeb.Wizard.PageType.Slider) {
            q.push(escape(p.Slider.Name) + '=' + escape(p.Slider.Value));
        }
        else if (p.Type == SherWeb.Wizard.PageType.SliderChoice) {
            q.push(escape(p.Choice.Name) + '=' + escape(p.Choice.Value));
            q.push(escape(p.Slider.Name) + '=' + escape(p.Slider.Value));
        }
    }

    // 2. Take the entered values from the user into the current
    // page's form
    var p = this._getCurrentPage();
    if (p.Type == SherWeb.Wizard.PageType.MultipleChoices) {
        q = q.concat($.map($('.page_userinput input[type=checkbox]:checked', this._container),
        function (c) {
            c = $(c);
            return escape(c.attr('name')) + '=' + escape(c.val()); 
        }));
    }
    if (p.Type == SherWeb.Wizard.PageType.MultipleRadioChoices) {
        q = q.concat($.map($('.page_userinput input[type=radio]:checked', this._container), function(c) { c = $(c); return escape(c.attr('name')) + '=' + escape(c.val()); }));
    }
    else if (p.Type == SherWeb.Wizard.PageType.Slider) {
        var input = $('.page_userinput input[type=text]', this._container);
        q.push(escape(input.attr('name')) + '=' + escape(input.val()));
    }
    else if (p.Type == SherWeb.Wizard.PageType.SliderChoice) {
        q = q.concat($.map($('.page_userinput input[type=checkbox]:checked', this._container), function(c) { c = $(c); return escape(c.attr('name')) + '=' + escape(c.val()); }));
        var input = $('.page_userinput input[type=text]', this._container);
        q.push(escape(input.attr('name')) + '=' + escape(input.val()));
    }

    // Add the step we're in
    q.push('step=' + this._currentPage);

    // Join the values into a query string
    return q.join("&");
};

/////////////////////////////////////////////////////////////
// Events
/////////////////////////////////////////////////////////////

// Todo: comments
SherWeb.Wizard.prototype._sliderStop =
SherWeb.Wizard.prototype._sliderMoving = function(event, ui, showValue) {
    var slider = $('.slider_value', this._container);
    if (showValue !== false)
        slider.show().css({ left: (ui.handle.offsetLeft + 30).toString() + 'px' });
    slider.children('input:eq(0)').val(ui.value);
};

SherWeb.Wizard.prototype._bindLearnMoreHover = function($link) {
    $link.mousemove(function(e) {
        SherWeb.Wizard._learnMoreHover.show().css({
            top: (e.pageY + 15).toString() + 'px',
            left: (e.pageX + 15).toString() + 'px'
        });
    });
    $link.mouseout(function() {
        SherWeb.Wizard._learnMoreHover.hide();
    });
};

// Declare a function to show the "learn more" tooltip. We must
// use a closure to achieve this.
// I named the parameter with a "$" to specify that it is a 
// jQuery object
SherWeb.Wizard.prototype._bindLearnMoreClick = function ($link, title, text, link, linkValue) {
    var w = this;
    $link.click(function () {
        var t = new SherWeb.Wizard.MoreTooltip($link, title, text, link, linkValue, w);
        if (SherWeb.Wizard.prototype._help.title == title) {
            TrackWidgetPerfectPlanHelp("Step_" + w._getCurrentPage().UniqueStepNumber + "_" + w._getCurrentPage().Question)
        }
        else {
            TrackWidgetPerfectPlanLearnMore("Step_" + w._getCurrentPage().UniqueStepNumber + "_" + title);
        }
        t.Show();
    });
};

// Todo: comments
SherWeb.Wizard.prototype._onPreviousClick = function () {

    var page = this._getCurrentPage();
    TrackWidgetPerfectPlanBack("Step_" + page.UniqueStepNumber + "_" + page.Question);

	this._currentPage--;
	this._rebuild();
};

// Todo: comments
SherWeb.Wizard.prototype._onNextClick = function () {

    if (!this._isPageValid()) {
        //alert('Please fill all the informations');
        //TODO this._getCurrentPage().Choices // Slide etc and log in analytics
        return;
    }

    var query = this._callbackURL + '?rnd=' + Math.random() + '&' + this._serializeInputs();
    var w = this;


    var page = this._getCurrentPage();

    if (page.Choices != null) {
        var log = "Step_" + page.UniqueStepNumber + "_";
        var choices = page.Choices;
        var i = 0;
        $("[id^=wizard_ctrl_]").each(function () {
            if ($(this).attr("checked") == true) {
                log += choices[i].ShortName;
                choices[i].Checked = true;
            }
            else {
                choices[i].Checked = false;
            }
            i++;
        });
        /*
        for (var i in choices) {
        var choice = choices[i];
        if (choice.Checked) {
        log += choice.ShortName;
        }
        else {
        log += "";
        }
        }*/
        TrackChoiceSelection(log);
    }
    else if (page.Slider != null) {
        var slider = page.Slider;
        TrackSliderSelection(slider.UniqueName, slider.Value)
    }
    TrackWidgetPerfectPlanNext("Step_" + page.UniqueStepNumber + "_" + page.Question);
    $.ajax({
        url: query,
        type: 'GET',
        data: {},
        dataType: 'json',
        success: function (content, textStatus, xhr) {
            w.Initialize(content);
        }
    });

};

//G.A. Traced external link
function redirect(url) {
    TraceExternalLink(url);
}

function delayedRedirect(url, time) {
    setTimeout('redirect("' + url + '")', time);
}


// We redirect with a 200 ms delay so we can trace the last event.
SherWeb.Wizard.prototype._onFinish = function () {
    delayedRedirect(this._redirectUrl, 200);
};

SherWeb.Wizard.prototype._onFinishSelection = function () {
    if (!this._isPageValid()) {
        //alert('Please fill all the informations');
        return;
    }

    var query = this._callbackURL + '?rnd=' + Math.random() + '&' + this._serializeInputs();
    var w = this;
    var redirect = this._redirectUrl;
    $.ajax({
        url: query,
        type: 'GET',
        data: {},
        dataType: 'json',
        success: function (content, textStatus, xhr) {
            w.Initialize(content);
            //location = redirect;
            TraceExternalLink(redirect);
        }
    });

};

// Todo: comments
SherWeb.Wizard.prototype._onStartOverClick = function() {
	var query = this._callbackURL + '?reset=true';
	var w = this;

	$.get(query, {}, function(content) {
		w.Initialize(content);
	}, 'json');
};

// Todo: comments
SherWeb.Wizard.prototype._onNotSureClick = function() {
	var query = this._callbackURL + '?reset=true&friendly=true';
	var w = this;

	$.get(query, {}, function(content) {
		w.Initialize(content);
	}, 'json');
};

/////////////////////////////////////////////////////////////
// Validation
/////////////////////////////////////////////////////////////

// Todo: comments
SherWeb.Wizard.prototype._isPageValid = function() {
    var valid = false;
    if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.MultipleChoices) {
        if (this._currentPage == 1)
            valid = $('.page_userinput input[type=checkbox]:checked', this._container).length > 0;
        else
            valid = true;
    }
    else if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.MultipleRadioChoices) {
        valid = $('.page_userinput input[type=radio]:checked', this._container).length > 0;
    }
    else if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.Slider) {
        valid = true;
    }
    else if (this._getCurrentPage().Type == SherWeb.Wizard.PageType.SliderChoice) {
        valid = true;
    }
    else {
        valid = true;
    }
    return valid;

};








/////////////////////////////////////////////////////////////
// 
/////////////////////////////////////////////////////////////

SherWeb.Wizard.MoreTooltip = function($anchor, title, text, link, value, wizard) {
    if (!$anchor.length && $anchor.length == 0)
        throw 'Invalid jQuery object specified';

    this._w = wizard;
    this._anchor = $anchor;
    this._title = title;
    this._text = text;
    this._link = link;
    this._value = value;
};

SherWeb.Wizard.MoreTooltip.prototype._anchor = undefined;
SherWeb.Wizard.MoreTooltip.prototype._handle = undefined;
SherWeb.Wizard.MoreTooltip.prototype._w = undefined;
SherWeb.Wizard.MoreTooltip.prototype._title = '';
SherWeb.Wizard.MoreTooltip.prototype._text = '';
SherWeb.Wizard.MoreTooltip.prototype._link = '';
SherWeb.Wizard.MoreTooltip.prototype._value = '';

SherWeb.Wizard.MoreTooltip.prototype.Reposition = function() {
    var left = ($(window).width() / 2) - this._handle.outerWidth() / 2;
    var top = (($(window).height() / 2) - this._handle.height() / 2) + $(window).scrollTop();
    this._handle.css({ 'left': left, 'top': top + 'px' });
};

SherWeb.Wizard.MoreTooltip.prototype.OnDocumentClick = function(event) {
	var tt = this._handle[0];
	if (tt != event.target && $.inArray(tt, $(event.target).parents()) == -1) {
		this.Close();
	}
};

SherWeb.Wizard.MoreTooltip.prototype.BindRemoval = function() {
	var tooltip = this;
	$(document.body).bind('mousedown.tooltip', function(event) { tooltip.OnDocumentClick(event); });
};

SherWeb.Wizard.MoreTooltip.prototype.Close = function() {
	this._handle.remove();
	delete this._handle;
	$(document.body).unbind('mousedown.tooltip');
};

SherWeb.Wizard.MoreTooltip.prototype.Show = function() {
    var tt = this;
    this._handle = $(SherWeb.Wizard.TooltipTag);

    var closeTag = $(SherWeb.Wizard.TooltipCloseTag);
    $('img', closeTag).attr({ 'src': this._w._getImage('Close'), 'alt': this._w._getLabel('Close') });
    closeTag.click(function() { tt.Close(); }).appendTo(this._handle);

    $(SherWeb.Wizard.TooltipHeaderTag).append($(SherWeb.Wizard.TooltipTitleTag).text(this._title)).appendTo(this._handle);

    var text = $(SherWeb.Wizard.TooltipTextTag).html(this._text)

    if (this._value != '' && this._value != undefined)
        $(SherWeb.Wizard.TooltipLinkTag).append($(SherWeb.Wizard.LinkTag).attr({ 'class': 'more', href: this._link }).text(this._value).click(function() { tt.Close(); })).appendTo(text);

    text.appendTo(this._handle);

    $(SherWeb.Wizard.TooltipFooterTag).appendTo(this._handle);
    this._handle.prependTo(document.body);
    this.Reposition();
    this.BindRemoval();
    this._handle.show();
};

