﻿var flipCount = 1;
var project;
var projectCallbackInterval;
var projectCallbacks = new Array();
var projectFetchInProgress = false;

var waitHtml = '<div style="width: 100%; height: 100%; text-align: center; vertical-align: middle;"><img src="/images/pre-loaders/pre-loader-cap-bracket-140x140.gif" style=""></div>'

var saveDlgHtml = '<div id="saveDialog">          <div class="saveDialogInr">            <div class="contentWide contentInfo">              <p class="title">Save &amp; Email me my Project</p>              <p>Now                that you\'ve come this far we can save your project and send you a link                 so that you can come back any time and carry on from where you left off.                It\'s that simple.</p>              <div class="clear"> </div>            </div>            <div class="divider"> </div>            <div class="content contentTip">              <label class="title">Your Project Number: </label><em>[projectCode]</em>            </div>            <div class="content contentTip">              <label class="title" for="mbName"> Your Name: </label>              <input type="text" name="mbName" id="mbName" class="text" /><div class="error" id="mbNameMsg"></div>              <div class="clear"> </div>            </div>            <div class="content contentTip">              <label class="title" for="mbEmail"> Your Email: </label>              <input type="email" name="mbEmail" id="mbEmail" class="text" /><div class="error" id="mbEmailMsg"></div>              <div class="clear"> </div>            </div>            <div class="content contentTip">              <input type="checkbox" name="mbSignup" id="mbSignup" checked="checked" class="checkbox" />              <div class="signup">                <p>We would like to keep you up to date on any new products by Richard Burbidge. We will not pass on your data to anyone else. Please untick the box if you don\'t want to receive this information.</p>              </div>            </div>            <div class="clear"></div>            <div class="puButtons buttonsection">                <span class="useLnk"><a class="puButton" href="#" id="saveDialogSave" >Email My Project</a></span>                <div class="clear"> </div>            </div>           </div>        </div>';

var projectMethods = {
    getOption:
            function (optionName) {
                for (var i in this.ProjectOptions) {
                    if (this.ProjectOptions[i].OptionName == optionName) {
                        var ret = this.ProjectOptions[i];
                        $.extend(ret, projectMethods);
                        return ret;
                        break;
                    }
                }
                return false;
            },
    getOptionValue:
            function (optionName) {
                for (var i in this.ProjectOptions) {
                    if (this.ProjectOptions[i].OptionName == optionName) {
                        if (this.ProjectOptions[i].OptionValueBool != null) {
                            return this.ProjectOptions[i].OptionValueBool;
                        } else if (this.ProjectOptions[i].OptionValueInt != null) {
                            return this.ProjectOptions[i].OptionValueInt;
                        } else if (this.ProjectOptions[i].OptionValueNumeric != null) {
                            return this.ProjectOptions[i].OptionValueNumeric;
                        } else if (this.ProjectOptions[i].OptionValueString != null) {
                            return this.ProjectOptions[i].OptionValueString;
                        }
                        break;
                    }
                }
                return false;
            },
    saveandemail:
            function (email, name, signup, onsuccess) {
                var mb = {
                    email: email,
                    name: name,
                    signup: signup
                };

                var mbData = JSON.stringify(mb);

                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: '/webservices/stairplanner.svc/project/save',
                    dataType: "json",
                    success: function (data, success) {
                        if (success == 'success') {
                            var p = eval(data);
                            $.extend(p, projectMethods);
                            project = p;
                            if (onsuccess) {
                                onsuccess.apply(this, [project]);
                            }
                        }
                    },
                    data: mbData
                });
            },
    save: function (onsuccess) {
        $.ajax({
            type: 'GET',
            url: '/webservices/stairplanner.svc/project/save',
            dataType: "json",
            success: function (data, success) {
                if (success == 'success') {
                    var p = eval(data);
                    $.extend(p, projectMethods);
                    project = p;
                    if (onsuccess) {
                        onsuccess.apply(this, [p]);
                    }
                }
            }
        });
    },
    copy: function (onsuccess) {
        $.ajax({
            type: 'GET',
            url: '/webservices/stairplanner.svc/project/copy',
            dataType: "json",
            success: function (data, success) {
                if (success == 'success') {
                    var p = eval(data);
                    $.extend(p, projectMethods);
                    project = p;
                    if (onsuccess) {
                        onsuccess.apply(this, [p]);
                    }
                }
            }
        });
    }
};

function HasErrors(data)
{
    if (data.Errors != null && data.Errors.length > 0)
    {
        if (window.location.pathname != '/')
        {
            window.location = '/';
        }

        return true;
    }

    return false;
}

function flipCard(elm) {
    if ($(elm).hasClass('flipped')) {
        //$(elm).revertFlip();
        $(elm).flip({
            direction: 'lr',
            speed: 'fast',
            dontChangeColor: true,
            bgColor: $(elm).css('background-color'),
            color: $(elm).css('background-color'),
            height: '100px',
            content: $('.cardcontent', this),
            onBefore: function () {
                $(".cardcontent", $(elm)).show();
            },
            onEnd: function () {
                if ($(elm).hasClass('flipped')) {
                    $(elm).removeClass('flipped');
                } else {
                    $(elm).addClass('flipped');
                }
                setupCard(elm);
                $(".cardslide", elm).hide();
            }
        });
        flipCount -= 1;
    } else {
        $(elm).flip({
            direction: 'rl',
            speed: 'fast',
            dontChangeColor: true,
            bgColor: $(elm).css('background-color'),
            color: $(elm).css('background-color'),
            height: '100px',
            content: $('.cardinfo', this),
            onBefore: function () {
                $(".cardslide", $(elm)).show();
            },
            onEnd: function () {
                if ($(elm).hasClass('flipped')) {
                    $(elm).removeClass('flipped');
                } else {
                    $(elm).addClass('flipped');
                }
                setupCard(elm);
            }
        });

        flipCount += 1;
    }
    if ($('.infopanelcard').size() == flipCount) {
        $("#compareall").addClass('comparing').html('Close All Ranges');
    } else {
        $("#compareall").removeClass('comparing').html('Compare All Ranges');
    }
}

function tooltipTop() {

}

var stpTooltipConfig = {
    track: true,
    delay: 0,
    showURL: false,
    opacity: 1,
    fixPNG: true,
    showBody: ' :: ',
    extraClass: 'tooltip',
    top: 25,
    left: -125
}

function setupCard(elm) {
    var $card = $(elm);

    $(".cardslide", $card).hide();

    $('.cardhero', $card).hoverIntent({
        over: function () {
            $(".cardslide", $card).slideDown();

            $(".moreinfo, .cardhero", $card).click(function () {
                flipCard($card);

                $(".closebutton", $card).click(function () {
                    flipCard($card);
                    return false;
                });

                return false;
            });
        },
        timeout: 100,
        out: function () {
            $(".cardslide", $card).slideUp();
        }
    });

    //$('.popuptooltip', $card).tooltip(stpTooltipConfig);
}

function Cookie() {
    var cookie = $.cookie('_stairplanner');

    var cv = {
        code: '',
        mode: '',
        laststep: ''
    };

    if (cookie != null)
    {
        var vals = cookie.split('&');

        for (var i = 0; i < vals.length; i++)
        {
            var kv = vals[i].split('=');
            switch (kv[0])
            {
                case '_projectcode':
                    cv.code = kv[1];
                    break;
                case '_mode':
                    cv.mode = kv[1];
                    break;
                case '_laststep':
                    cv.laststep = kv[1];
                    break;
            }
        }
    }

    return cv;
}

$(document).ready(function () {

    $('.cabGlryItm, .popuptooltip').tooltip(stpTooltipConfig);

    $(".infopanelcard").each(function () {
        var $card = $(this);
        setupCard($card);
    });

    $("#compareall").click(function () {
        if ($(this).hasClass('comparing')) {
            $(".infopanelcard").each(function () {
                if ($(this).hasClass('flipped')) {
                    flipCard(this);
                }
            });
            $(this).removeClass('comparing').html('Compare All Ranges');
        } else {
            $(".infopanelcard").each(function () {
                if (!$(this).hasClass('flipped')) {
                    flipCard(this);

                    $(".closebutton", this).click(function () {
                        var card = $(this).parents(".infopanelcard");
                        flipCard(card);
                        return false;
                    });
                }
            });
            $(this).addClass('comparing').html('Close All Ranges');
            return false;
        }
        return false;
    });
    $('.breadCrumb').jBreadCrumb({
        beginingElementsToLeaveOpen: 0,
        endElementsToLeaveOpen: 0,
        previewWidth: 35
    });
    $('#tabs').tabs();

    jQuery('.useLnk > a').click(saveRangeSelection);

    $("#projID, #ProjectNumber").focus(function() {
        $(this).filter(function() {
            return $(this).val() == "Enter project number to retrieve"
        }).removeClass("watermark").val("");
    });

    $("#projID, #ProjectNumber").blur(function() {
        $(this).filter(function() {
            return $(this).val() == ""
        }).addClass("watermark").val("Enter project number to retrieve");
    });

    getProject(false);

    $('.go .retrieve').click(onRetrieve);
});

function onRetrieve()
{
    loadProject($('.search_box #projID').val());
    return false;
}

function htmlDecode(enc) {
    return $('<div/>').html(enc).text();
}

function getCrop(imageCrops, cropName) {
    for (var crop in imageCrops) {
        if (imageCrops[crop].name == cropName) {
            return imageCrops[crop];
        }
    }
}

function loadProject(projID) {
    if (projID == null)
    {
        projID = $('#projID').val();
    }
    $.get(
        '/webservices/stairplanner.svc/projects/' + projID,
        function (data, success) {
            if (success == 'success') {
                if (!HasErrors(data))
                {
                    project = eval(data);
                    $('#ProjectID').text(project.code).parent().show();
                    $.extend(project, projectMethods);
                    GoToLastStep(project);
                } else {                
                     jQuery.fancybox({
                        'padding': 0,
                        'content': '<div class=\'content contentInfo clearfix\'><p>' + data.Errors[0].Message + '</p></div>',
                        'autoDimensions': true,
                        'width': 240,
                        'transitionIn': 'elastic',
                        'transitionOut': 'elastic'});
                }
            }
        });
}

function parseMode(proj, cookie)
{
    var mode;

    if (proj == null || proj.mode == null)
    {
        if (cookie != null && cookie.mode != null)
        {
            mode = cookie.mode;
        }
    }
    else
    {
        mode = proj.mode;
    }

    switch (parseInt(mode))
    {
        case 2:
            return 'Expert';
            break;
        case 1:
            return 'Easy';
            break;
        default:
            return '';
            break;
    }
}

function parseLastStep(proj, cookie)
{
    if (proj == null || proj.lastStep == null)
    {
        if (cookie != null && cookie.laststep != null)
        {
            return parseInt(cookie.laststep);
        }

        return 0;
    }

    return parseInt(proj.lastStep);
}

function GoToLastStep(proj) {
    var cookie = Cookie();
    
    var mode = parseMode(proj, cookie).toLowerCase();
    var lastStep = parseLastStep(proj, cookie);

    switch (mode) {
        case 'easy':
            switch (lastStep)
            {
                case 4:
                case 3:
                    if (window.location.href.indexOf('/project-summary') == -1)
                    {
                        window.location = '/project-summary';
                    }
                    break;
                case 2:
                case 1:
                    if (window.location.href.indexOf('/easy-system-configuration') == -1)
                    {
                        window.location = '/easy-system-configuration';
                    }
                    break;
                default:
                    if (window.location.href.indexOf('/easy-system-designer') == -1)
                    {
                        window.location = '/easy-system-designer';
                    }
                    break;
            }
            break;
        case 'expert':
            switch (lastStep) {
                case 5:
                case 4:
                    if (window.location.href.indexOf('/project-summary') == -1)
                    {
                        window.location = '/project-summary';
                    }
                    break;
                case 3:
                    if (window.location.href.indexOf('/expert-system-configuration') == -1)
                    {
                        window.location = '/expert-system-configuration';
                    }
                    break;
                case 2:
                    if (window.location.href.indexOf('/expert-system-designer') == -1)
                    {
                        window.location = '/expert-system-designer';
                    }
                    break;
                case 1:
                    if (window.location.href.indexOf('/expert-systems') == -1)
                    {
                        window.location = '/expert-systems';
                    }
                    break;
                default:
                    if (window.location.href.indexOf('/expert-ranges') == -1)
                    {
                        window.location = '/expert-ranges';
                    }
                    break;
            }
            break;
        default:
            if (window.location.href.indexOf('/') == -1) {
                window.location = '/';
            }
            break;
    }

//    if (proj.RangeID == null || proj.SystemID == null) {
//        if (window.location.indexOf('/') == -1) {
//            window.location = '/';
//        }
//    } else if (proj.RangeID != null && proj.SystemID == null) {
//        if (window.location.indexOf('/expert-systems') == -1) {
//            window.location = '/expert-systems';
//        }
//    } else if (proj.RangeID != null && proj.SystemID != null) {
//        if (window.location.indexOf('/expert-system-designer') == -1) {
//            window.location = '/expert-system-designer';
//        }
//    }
}

function saveOption(opt, onsuccess) {
    //opt.Options = new {Options: opt.Options};

    var projectOption = JSON.stringify(opt);

    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: '/webservices/stairplanner.svc/project/setoption',
        dataType: "json",
        success: function (data, success) {
            if (success == 'success') {
                project = eval(data);
                $.extend(project, projectMethods);
                if (onsuccess) {
                    onsuccess.apply(this, [project]);
                }
            }
        },
        data: projectOption
    });

    return project;
}

function removeOption(optName, onsuccess) {
    //opt.Options = new {Options: opt.Options};

    $.ajax({
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        url: '/webservices/stairplanner.svc/project/deleteoption/' + optName,
        dataType: "json",
        success: function (data, success) {
            if (success == 'success') {
                project = eval(data);
                $.extend(project, projectMethods);
                if (onsuccess) {
                    onsuccess.apply(this, [project]);
                }
            }
        },
        data: optName
    });

    return project;
}

function newProject() {
    $.get(
        '/webservices/stairplanner.svc/project/new',
        function (data, success) {
            if (success == 'success') {
                if (!HasErrors(data))
                {
                    project = eval(data);
                    $.extend(project, projectMethods);
                    window.location = "/";
                }
            }
        });
    return project;
}

function saveProject() {

    if (project.memberId) {
        project.save(function (p) {
            $("#saveComplete").dialog({
                resizable: false,
                modal: true
            });
        });
    } else {
        saveDlgHtml = saveDlgHtml.replace('[projectCode]', project.code);

        jQuery.fancybox({
            'padding': 0,
            'content': saveDlgHtml,
            'autoDimensions': false,
            'height': 380,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'onComplete': function () {
                $('#mbName').blur(function () {
                    if ($(this).val() == '') {
                        $(this).addClass('errorIcon');
                        $('#mbNameMsg').html('You must enter your Name.');
                        $('#mbNameMsg').fadeIn();
                    } else {
                        $(this).removeClass('errorIcon');
                        $('#mbNameMsg').fadeOut();
                    }
                });
                $('#mbEmail').blur(function () {
                    if ($(this).val() == '' || !isValidEmailAddress($(this).val())) {
                        $(this).addClass('errorIcon');
                        $('#mbEmailMsg').html('You must enter a valid Email Address');
                        $('#mbEmailMsg').fadeIn();
                    } else {
                        $(this).removeClass('errorIcon');
                        $('#mbEmailMsg').fadeOut();
                    }
                });
                jQuery('#saveDialogSave').click(function () {
                    if ($('#mbEmail').val() != '' && $('#mbName').val() != '' && isValidEmailAddress($('#mbEmail').val())) {
                        project.saveandemail($('#mbEmail').val(), $('#mbName').val(), $('#mbSignup').attr('checked'), function (p) {
                            if (p.memberId) {
                                jQuery.fancybox.close();
                                $("#saveComplete").dialog({
                                    resizable: false,
                                    modal: true
                                });
                            }
                        });
                    }
                });
            },
            'onClosed': function () {

            }
        });
    }
    return false;
}

function shareProject()
{
    jQuery.fancybox({
        'type': 'iframe',
        'padding': 0,
        'href': '/share-my-project/FancyBox.aspx',
        'autoDimensions': false,
        'height': 730,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'onStart': function ()
        {
            $.fancybox.showActivity();
        },
        'onComplete': function ()
        {
            $.fancybox.hideActivity();
        },
    });
}

function completeProject()
{
    if (project.memberId == null)
    {
        jQuery.fancybox({
            'type': 'iframe',
            'padding': 0,
            'href': '/project-completion/FancyBox.aspx',
            'autoDimensions': false,
            'width': 750,
            'height': 830,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'onStart': function ()
            {
                $.fancybox.showActivity();
            },
            'onComplete': function ()
            {
                $.fancybox.hideActivity();
            },
            'onClosed': function ()
            {
                $.fancybox.hideActivity();
            },
        });
    }
    else
    {
        moveToSummary();
    }
}

function moveToSummary()
{
    window.location = '/project-summary';
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

function saveRangeSelection(evt) {
    evt.stopImmediatePropagation();

    var tgt = evt.originalTarget;
    if (tgt === undefined) { tgt = evt.target; }
    var rid = tgt.className.substr(3);

    // Store users range selection, then redirect them to the system selection page
    jQuery.get(
      '/webservices/stairplanner.svc/project/setrange/' + rid,
      function (data, success) {
          if (success == 'success') {
              if (!HasErrors(data))
              {
                  window.location = '/expert-systems';
              }
          }
      }
    );
    return false;
}

function setUpOptionTiles() {
    $('.infoslide').hoverIntent(
         function () {
             //        $(".tileinfo", this).animate({
             //            top: "0"
             //        }, 200, "swing");
             flipCard(this);
         },
         function () {
             //            $(".tileinfo", this).animate({
             //                top: "54px"
             //            }, 200, "swing");
             flipCard(this);
         }
    );

    $('.tile').draggable({
        revert: 'invalid',
        helper: 'clone',
        opacity: 0.8,
        zIndex: 2000
    });
}

(function ($) {
    $.fn.fader = function (settings) {
        return this.each(function () {
            var $this = $(this), obj, $clone, newContent;

            if ($this.data('fadelock')) {
                return false;
            }

            obj = {
                width: $this.width,
                height: $this.height,
                bgColor: $this.css('background-color'),
                fontSize: $this.css('font-size'),
                speed: settings.speed || 500,
                top: $this.offset().top,
                left: $this.offset().left,
                target: settings.content || null,
                onBefore: settings.onBefore || function () { },
                onEnd: settings.onEnd || function () { },
                onAnimation: settings.onAnimation || function () { }
            };

            $this.data('fadelock', 1);

            newContent = function () {
                var target = obj.target;
                return target && target.jquery ? target.html() : target;
            };

            var nC = newContent();

            $clone = $this
                            .clone(true)
                            .data('fadelock', 1)
                            .appendTo('body')
                            .html(nC)
              .css({ display: 'none', position: 'absolute', left: obj.left, top: obj.top, margin: 0, zIndex: 5000, "-webkit-box-shadow": "0px 0px 0px #000", "-moz-box-shadow": "0px 0px 0px #000" });

            $clone.queue(function () {
                obj.onBefore($clone, $this);
                $clone.dequeue();
            });

            $clone.fadeIn(obj.speed);

            $clone.queue(function () {
                obj.onAnimation($clone, $this);
                $clone.dequeue();
            });

            $clone.queue(function () {
                $this.html(nC);
                $clone.remove();
                obj.onEnd($clone, $this);
                $this.removeData('fadelock');
                $clone.dequeue();
            });

        });
    };
})(jQuery);


(function ($) {
    $.fn.fancytooltip = function (settings) {
        if (settings == null) {
            settings = {};
        }

        return this.each(function () {
            var $this = $(this);

            // ensure we don't modify the settings object passed in
            var lclSettings = $.extend({}, settings);

            var content;

            if ($this.attr('href')) {
                var contentElm = $($this.attr('href')).hide();
                if (contentElm.length > 0) {
                    content = contentElm.html();
                    $this.click(function () {
                        return false;
                    });
                }
            } else if ($this.attr('rel')) {
                contentElm = $($this.attr('rel'));
                if (contentElm.length > 0) {
                    content = contentElm.html();
                } else if (!content) {
                    content = $this.attr('rel');
                }
            }

            if (content) {
                lclSettings = $.extend(lclSettings, {
                    bodyHandler: function () {
                        return content;
                    }
                });
            }

            $this.tooltip(lclSettings);
        });
    };
})(jQuery);


/****************************************************************************************************************
*																												                                                                                    *
*	switchButton Plugin by Rich Haigh																			                                                                    *
*																												                                                                                    *
*	Allows for multiple options to be setup by inclusion of additional span tags within the container element	                                            *
*	Setting name is derived from the id attribute of the container element										                                                        *
*																												                                                                                    *
****************************************************************************************************************/

(function ($) {

    var methods = {
        init: function (settings) {
            return this.each(function () {
                var options = {
                    onBefore: function () { return true; },
                    onEnd: function () { return true; },
                    onInit: function () { }
                }, $this, $opts;
                $this = $(this),
                data = $this.data('switchButton');

                if (!data) {
                    $opts = $("span", $this);
                    if (settings) {
                        $.extend(options, settings);
                    }
                    options.onInit($this, $opts);
                    $opts.each(function () {
                        $(this).addClass('switchbutton');
                        $(this).click(function () {
                            var $elm = $(this);

                            if (options.onBefore($this, $elm)) {
                                var cssClass = $elm.attr('class');
                                if (!$elm.hasClass("Sel")) {
                                    $elm.addClass("Sel");
                                    $elm.selected = true;
                                    $elm.siblings().each(function () {
                                        $(this).removeClass("Sel");
                                        $(this).selected = false;
                                    });
                                }
                                options.onEnd($this, $elm);
                            }
                        });
                    });
                    $(this).data('switchButton', {
                        target: $this
                    });
                }
            });
        },
        Select: function (args) {
            var $elm
            if (args) {
                $elm = $('.' + args.val, $(this));
            } else {
                $elm = $(this);
            }

            var cssClass = $elm.attr('class');
            if (!$elm.hasClass("Sel")) {
                $elm.addClass("Sel");
                $elm.selected = true;
                $elm.siblings().each(function () {
                    $(this).removeClass("Sel");
                    $(this).selected = false;
                });
            }
        }
    };

    var ext = {
        selected:
                function getValue() {
                    var val;
                    $('span', $(this)).each(function (idx, opt) {
                        if ($(opt).hasClass('Sel')) {
                            val = $(opt);
                            return false;
                        }
                    });
                    return val;
                }
    };

    $.fn.switchButton = function (method) {
        var ret;

        if (methods[method]) {
            ret = methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            ret = methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.switchButton');
        }

        return $.extend(ret, ext);
    };

})(jQuery);



/****************************************************************************************************************
*																												                                                                                    *
*	GreyOut Plugin by Rich Haigh																			                                                                            *
*																												                                                                                    *
*	Allows for elements to be faded out and made inactive                                                                              								    *
*																												                                                                                    *
****************************************************************************************************************/

(function ($) {

    $.fn.greyOut = function (settings) {
        return this.each(function () {

            var data = $(this).data('grayoverlay');

            if (!data) {
                var options = {
                    color: '#ffffff',
                    opacity: 0.7,
                    content: '',
                    onBefore: function () { return true; },
                    onEnd: function () { return true; },
                    onInit: function () { },
                    includeMargins: false
                }, $this, $overlay;

                $this = $(this);

                if (settings) {
                    $.extend(options, settings);
                }


                $overlay = $('<div class="greyOut-overlay" />')
                                        .data('fadelock', 1)
                                        .appendTo('body')
                                        .html(options.content)
                                        .css({ display: 'none',
                                            width: $this.outerWidth(true),
                                            height: $this.outerHeight(options.includeMargins),
                                            position: 'absolute',
                                            left: $this.offset().left,
                                            top: $this.offset().top,
                                            margin: 0,
                                            marginTop: options.includeMargins ? '-' + $this.css('margin-top') : 0,
                                            marginLeft: '-' + $this.css('margin-left'),
                                            zIndex: 999,
                                            background: options.color,
                                            opacity: options.opacity,
                                            '-webkit-box-shadow': '0px 0px 0px #000',
                                            '-moz-box-shadow': '0px 0px 0px #000'
                                        });

                $(window).resize(function () {
                    $overlay.css({ left: $this.offset().left, top: $this.offset().top });
                });

                if (options.onBefore(this, $overlay)) {
                    $overlay.fadeIn('fast');
                    $this.data('grayoverlay', $overlay);
                    options.onEnd(this, $overlay);
                }
            }
        });
    };
    $.fn.unGrey = function (settings) {
        return this.each(function () {
            var $overlay = $(this).data('grayoverlay');
            if ($overlay) {
                var options = {
                    speed: 'fast',
                    onBefore: function () { return true; },
                    onEnd: function () { return true; }
                };

                if (settings) {
                    $.extend(options, settings);
                }

                if (options.onBefore(this, $overlay)) {
                    $overlay.fadeOut(options.speed);
                    $overlay.remove();
                    $(this).removeData('grayoverlay');
                    options.onEnd(this);
                }
            }
        });
    };
})(jQuery);

function setTextOption(optionName, optionValue, optionType, callback) {
    var projectOption = {
        OptionName: optionName,
        BooleanValue: null,
        IntValue: null,
        DecimalValue: null,
        StringValue: optionValue,
        OptionType: optionType
    };
    saveOption(projectOption, callback);
}

function setBooleanOption(optionName, optionValue, optionType, callback) {
    var projectOption = {
        OptionName: optionName,
        BooleanValue: optionValue,
        IntValue: null,
        DecimalValue: null,
        StringValue: null,
        OptionType: optionType
    };
    saveOption(projectOption, callback);
}

function setIntOption(optionName, optionValue, optionType, callback) {
    var projectOption = {
        OptionName: optionName,
        BooleanValue: null,
        IntValue: optionValue,
        DecimalValue: null,
        StringValue: null,
        OptionType: optionType
    };
    saveOption(projectOption, callback);
}

function setDecimalOption(optionName, optionValue, optionType, callback) {
    var projectOption = {
        OptionName: optionName,
        BooleanValue: null,
        IntValue: null,
        DecimalValue: optionValue,
        StringValue: null,
        OptionType: optionType
    };
    saveOption(projectOption, callback);
}

function EnsureProjectLoaded(callback) {

    if(project == null)
    {
        if(projectFetchInProgress)
        {
            projectCallbacks.push(callback);
        }
        else
        {
            getProject(callback);
        }
    }
    else
    {
        callback();
    }
}

function ExecuteProjectCallbacks() {
    
    for(callback in projectCallbacks)
    {
        if(projectCallbacks[callback])
        {
            projectCallbacks[callback]();
        }
    }
    projectCallbacks = new Array();
}

function getProject(callback) {

    projectFetchInProgress = true;
    projectCallbacks.push(callback);

    $.get(
        '/webservices/stairplanner.svc/project',
        function (data, success) {
            if (success == 'success') {
                if (!HasErrors(data))
                {
                    project = eval(data);
                    $('#ProjectID').html(project.code).parent().show("fast");
                    $.extend(project, projectMethods);
                    ExecuteProjectCallbacks();
                }
            }
            projectFetchInProgress = false;
        });
}
