﻿// ## SwissChecklist.Extensions

// Extend jQuery to select extension tags (e.g: <span scl:extension="Forms")
$.extend($.expr[":"], {
    extension: function (a) {
        return $(a).attr("scl:extension") != "";
    }
});

//Extend String with startswith Function
String.prototype.startsWith = function (str) { return (this.match("^" + str) == str) }

//Contains method for arrays
Array.prototype.contains = function (element) { for (var i = 0; i < this.length; i++) { if (this[i] == element) { return true; } } return false; }


SwissChecklist.Extensions.ChangeExtensionChecklistMode = function (mode) {
    // viewformswrapper = the forms as they look when generated
    // formspreview = a preview of the forms control
    if (typeof (ChangeExtensionFormsChecklistMode) != 'undefined')
        ChangeExtensionFormsChecklistMode(mode);
    if (typeof (ChangeExtensionAttachmentsChecklistMode) != 'undefined')
        ChangeExtensionAttachmentsChecklistMode(mode);
}

SwissChecklist.Extensions.GetExtensionProperties = function (ObjectContainer, savetype) {
    // This function returns a generic object with Key/value and the extension name
    var Values = [];
    if (typeof (savetype) == "undefined" || savetype == null)
        savetype = "definition";

    $("*", ObjectContainer).not(".SCL_SubChecklists").filter(function () { return ($(this).attr("scl:extension") && $(this).attr("scl:savetype")); }).each(function () {
        if (($(this).attr("scl:save") == "true") && ($(this).attr("scl:savetype") == savetype)) {
            var Extension = $(this).attr("scl:extension");
            var Properties = {
                ExtensionName: Extension,
                Properties: new Array()
            };
            for (var i = 0; i < this.attributes.length; i++) {
                // Take all attributes that start with "scl:" and put them into array with value
                var CurrentAttribute = this.attributes[i];
                var SkippedAttributes = new Array("scl:extension", "scl:save", "id", "scl:savetype");
                if ((CurrentAttribute.name.startsWith("scl:") || CurrentAttribute.name == "value") && !SkippedAttributes.contains(CurrentAttribute.name.toString())) {
                    var Key = CurrentAttribute.name;
                    var Property = {
                        Key: Key.replace("scl:", ""),
                        Value: CurrentAttribute.value
                    };
                    Properties.Properties.push(Property);
                }
            }
            if (Properties.Properties.length > 0)
                Values.push(Properties);
        }
    });
    return Values;
}


SwissChecklist.Extensions.ChangeStepToEditMode = function (StepObject) {
    if ($(".ext_forms_wrapper", StepObject).length > 0) {
        $(".TitleInput", StepObject).css("width", "270px");
        $(".ext_forms_preview", StepObject).addClass("ext_forms_preview_editmode");
    }
    else
        $(".TitleInput", StepObject).removeAttr("style");
};
SwissChecklist.Extensions.ChangeStepToViewMode = function (StepObject) {
    //  $(".ext_forms_preview", StepObject).removeClass("ext_forms_preview_editmode");
};


SwissChecklist.Extensions.ValidateExtensions = function () {
    var isValid = true;
    $(".ext_forms_required").each(function () {
        if (($(this).val() == "") || ($(this).val() == null)) {
            isValid = false;
            $(this).effect("highlight");

            if ($(this).attr("scl:errormessage")) {
                // If there is an errormessage, show it
                var errormsg = $("<span>", {
                    text: $(this).attr("scl:errormessage")
                });
                $(this).after(errormsg);
            }
        }
    });

    $(".ext_forms_regex").each(function () {
        var expr = $(this).attr("scl:regex");
        if (!expr.test($(this).val())) {
            isValid = false;
            $(this).effect("highlight");
        }
    });

    return isValid;
}

SwissChecklist.Extensions.InitializeExtensions = function (context) {
    InitializeAttachments();
    SwissChecklist.Extensions.Forms.Initialize(context);
}



// ### SwissChecklist.Extensions.Forms.js

SwissChecklist.Extensions.Forms = {
    Initialize: function (context) {

        //Initialize the look of form fields
        $(".SCL_StepLine", context).each(function () {
            $("span", this).filter(function () { return $(this).attr("scl:extension") && ($(this).attr("scl:savetype") == "definition") }).each(function () {
                var FieldType = $(this).attr("scl:fieldtype");
                var Properties = getProperties($(this).closest("li"));
                var Control = FormsExtensionSettings.FieldTypeTable[FieldType](Properties.CustomProperties);
                // Append the preview control, disable it and float it on the right side
                $(Control).addClass("ext_viewforms_wrapper").css({ "float": "right" }).show();
                if ($(this).attr("scl:value") != "" && typeof($(this).attr("scl:value")) != "undefined") {
                    $(Control).val($(this).attr("scl:value"));
                    if (FieldType == "checkbox") {
                        if ($(this).attr("scl:value") == "true" || $(this).attr("scl:value") == "on")
                            $(Control).attr("checked", "checked");
                        else
                            $(Control).removeAttr("checked");

                    }
                }
                
                $(Control).attr({
                    "scl:savetype": "userdata",
                    "scl:save": "false",
                    "scl:extension": "Forms"
                });
                //alert("Parent step lines: " + $(this).parent(".SCL_StepLine:first").length);
                $(this).parent(".SCL_StepLine:first").append(Control);
                //$(this).closest(".SCL_StepLine").append(Control);
                if (FieldType == "dropdown") {
                    Control.val($.trim($('option[selected*="selected"]', Control).text()));
                }
            });
        });

        try {
            $(".ext_forms_datepicker", context).datepicker({
                onSelect: function (dateText, inst) {
                    var $formswrapper = $(this);

                    var value = this.dateText;
                    $formswrapper.attr("scl:value", value);
                    $formswrapper.attr("scl:save", "true");
                    ChecklistHasChange();
                }
            });
        } catch (err) { }

        $(".ext_forms_int", context).bind("keypress", function (e) {
            if (e.which != 8 && e.which != 110 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                return false;
            }
        });

        // Size and padding on radiobuttonlist
        $(".ext_forms_radiobuttonlist", context).each(function () {
            var px = $("tbody td", this).size() * 22;
            $(this).closest(".SCL_StepLine").css({
                height: px + "px"
            });
        });

        // Size and padding on textboxes
        $(".ext_forms_editor, .ext_forms_txtmulti", context).each(function () {
            var px = 86;
            $(this).closest(".SCL_StepLine").css({
                height: px + "px"
            });
        });

        // To set the value attribute on each extensionfield, to keep it as generic as possible
        //$(":text, :checkbox, :radio, textarea, select", ".ext_viewforms_wrapper").not(".ext_forms_datepicker").live("blur", function() {
        $(".ext_viewforms_wrapper:not(.ext_forms_datepicker)", context).live("focusout", function () {
            var formswrapper = $(this); //$(this).closest(".ext_viewforms_wrapper");

            var value = formswrapper.val();
            if (formswrapper.is(":checkbox"))
                value = formswrapper.is(":checked");
            if (formswrapper.is(":radio"))
                value = formswrapper.parent().find("label").text();


            // Set the value as swisschecklist attribute, to enable 
            // the extension method to get the value
            formswrapper.attr("scl:value", value);
            // set the save attribute to true, so that it will be saved
            // if its false, it won't be saved
            formswrapper.attr("scl:save", "true");

            // Call 2pas's method which shows the save dialog
            ChecklistHasChange();
        });
    }
}


// Shows the Forms button to add a custom form on a step



//
function aCheckClosePopupAndSave(NewProperties) {
    
}

function closePopupAndSave(NewProperties, Action) {
    
    closePopupAndSave2(NewProperties, Action);
}

function closePopupAndSave2(NewProperties, Action) {
    // Hide Step
    $(CurrentStep).before($("#LoadPanel"));
    $("#LoadPanel").css("height", $(CurrentStep).height() + "px");
    $(CurrentStep).hide();
    var StepDetailsAreHidden = $(".SCL_Details", CurrentStep).hasClass("SCL_Hidden");

    FormsProperties = NewProperties;
    var StepLine = $(".SCL_StepLine", $(CurrentStep).not(".SCL_SubChecklists"));
    if (typeof (NewProperties) != "undefined" && typeof (NewProperties.CustomProperties.fieldtype) != "undefined") {
        // That it won't be hidden on mouseover
        ExtForms_SavePropertiesToHtml();
        //SwissChecklist.ChecklistController.Steps.MarkStepAsChanged(CurrentStep, true);
        $(CurrentStep).attr("stephaschanged", "true");
        $(CurrentStep).prev().prev().attr("stephaschanged", "true");

        // Remove current contol
        $(".ext_viewforms_wrapper", StepLine).remove();
        // Get fully working control
        var ctrl = FormsExtensionSettings.FieldTypeTable[FormsProperties.CustomProperties.fieldtype](FormsProperties.CustomProperties);
        ctrl.addClass("ext_viewforms_wrapper");
        ctrl.attr({
            "scl:extension": "Forms",
            "scl:save": "true",
            "scl:savetype": "userdata",
            "scl:fieldtype": FormsProperties.CustomProperties.fieldtype,
            "value": FormsProperties.CustomProperties.defaultvalue,
            "scl:value": FormsProperties.CustomProperties.defaultvalue,
            "scl:iscurrent": "true"
        });

        //alert(ctrl.attr("value"));


        StepLine.append(ctrl);
        StepLine.hide();
        StepLine.show();

        //InitializeForms();
        //SwissChecklist.Extensions.Forms.Initialize(CurrentStep);
        ChangeExtensionFormsChecklistMode(SwissChecklist.ChecklistController.Checklist.CurrentViewMode);
    }
    else {
        // Remove forms preview and definition
       // $(".ext_viewforms_wrapper", StepLine).remove();
        //$(".ext_forms_wrapper", StepLine).remove();
    }

    // Only to debug
    //SwissChecklist.ChecklistController.SaveChecklistWithCallBack(null, false, "", null, null);

    SwissChecklist.ChecklistController.SaveChecklistWithCallBack($(".ChecklistContainer:first"), false, "ChecklistUpdate", function () { SaveStepExtensions($(CurrentStep), Action, true, function () { ReloadStepAfterSaving($(CurrentStep), StepDetailsAreHidden) }) }, function () { alert('aaa') }, false);
    jQuery.fancybox.close();
}


function SaveStepExtensions(StepObject, Action, IsForms, Callback) {
    // Prepare Extensions for Saving
    var Extensions = SwissChecklist.Extensions.GetExtensionProperties(StepObject, "definition");
    // Only Number
    var ExtensionIndex = -1;
    for (var i = 0; i < Extensions.length; i++) {
        var FoundProperty = false;
        for (var j = 0; j < Extensions[i].Properties.length; j++) {
            if (Extensions[i].Properties[j].Key == "iscurrent"){
                ExtensionIndex = i;
            }
        }
        if (IsForms && Extensions[i].ExtensionName == "Forms") {
            ExtensionIndex = i;
        }
    }

    var SingleExtension = Extensions[ExtensionIndex];

    var JobID = $.trim($(".UserChecklistID:first").text());
    var JobGuid = $.trim($(".UserChecklistGUID:first").text());
    var StepGuid = $(StepObject).attr("scl:stepguid");
    var TemplateID = $(StepObject).attr("scl:templateid");

    var SaveData = JSON.stringify({ 'JobGuid': JobGuid, 'StepGuid': StepGuid, 'TemplateID': TemplateID, 'Extension': SingleExtension, 'Action': Action });

    SwissChecklist.Ajax.AjaxRequest("/SwissChecklist/SwissChecklistServices.asmx/SaveStepExtensions", SaveData, Callback, function () { alert('step extension saving error'); });

}

function ReloadStepAfterSaving(StepObject, StepDetailsAreHidden) {
    SwissChecklist.ChecklistController.Steps.ReloadStep(StepObject, StepDetailsAreHidden);
}

function ExtForms_SavePropertiesToHtml() {
    var PropertiesHashtable = FormsProperties.CustomProperties;
    var FormPropertiesHtml = $("<span " + FormsExtensionSettings.Selector + " scl:save='true' scl:savetype='definition'></span>");
    for (var p in PropertiesHashtable) {
        var value = eval('PropertiesHashtable.' + p);
        FormPropertiesHtml.attr("scl:" + p, value);
    }
    $(FormPropertiesHtml).addClass("ext_forms_wrapper");
    var $CurrentHolder = $(".ext_forms_wrapper", $(CurrentStep).not(".SCL_SubChecklists"));
    if ($CurrentHolder.size() > 0)
        $CurrentHolder.replaceWith(FormPropertiesHtml);
    else
        $(CurrentStep).append(FormPropertiesHtml);
}

function getProperties(Sender) {
    if (Sender != undefined)
        CurrentStep = Sender;

    var $DataHtmlObject = $(".SCL_StepLine:first .ext_forms_wrapper", CurrentStep);
    var PropertiesFromHtml = {};
    PropertiesFromHtml.CustomProperties = [];
    if ($DataHtmlObject.length > 0) {
        // Remove invalid Attributes temporarly, that the Array isn't invalid
        $DataHtmlObject.removeAttr("scl:extension");
        $DataHtmlObject.removeAttr("scl:save");

        // Get all Attributes from the HTML
        var Attributes = new Array();
        for (var i = 0; i < $DataHtmlObject[0].attributes.length; i++) {
            var a = $DataHtmlObject[0].attributes[i];
            Attributes[a.name.replace("scl:", "")] = a.value;
        }

        // Add the scl Attributes again
        $DataHtmlObject.attr("scl:extension", "Forms");
        $DataHtmlObject.attr("scl:save", "true");
        PropertiesFromHtml.CustomProperties = Attributes;
    }
    FormsProperties = PropertiesFromHtml;
    return FormsProperties;
}


$(function () {




    SwissChecklist.Extensions.Forms.Initialize($("#ChecklistContainer"));




});


// Define the base settings, like where the values are saved
var FormsExtensionSettings = {
    Mode: "Edit",
    Selector: 'scl:extension="Forms"',
    FieldTypeTable: []
};

//Public storage variable which holds the current properties
var FormsProperties = new Object();
// Added 2010-12-12 by 2dk
// This methods changes the different inline modes
function ChangeExtensionFormsChecklistMode(mode) {
    // viewformswrapper = the forms as they look when generated
    // formspreview = a preview of the forms control

    switch (mode) {
        case "change":
            // Todo: Check this, since it doesnt work anymore when the controls are disabled
            // Add ", .ext_viewforms_wrapper" to this selector to enable clicking on formfield
            $("#FormsEdit, .ext_viewforms_wrapper").die("click");
            $("#FormsEdit, .ext_viewforms_wrapper").live("click", function () {

                var Url = "/SwissChecklist/Dialogs/Forms/ChooseFormField.aspx?Lang=" + $.trim($(".Language:first").text());

                var Step = $(this).parents(".SCL_Step:first");

                if ($(".ext_forms_wrapper", Step).length != 0) {
                    var ValueSetID = $(".ext_forms_wrapper", Step).attr("scl:valuesetid");
                    Url = "/SwissChecklist/Dialogs/Forms/ChangeFormField.aspx?Lang=" + $.trim($(".Language:first").text()) + "&ValueSetID=" + ValueSetID;
                }


                jQuery.fancybox({
                    type: 'iframe',
                    href: decodeURIComponent(Url),
                    title: GetLocalizedText("Forms"),
                    width: 593,
                    height: 500,
                    transitionIn: 'none',
                    transitionOut: 'none'
                });

                var PropertiesIframe = window.frames[$("iframe[name^='fancybox']").attr("name")];
                $(PropertiesIframe).focus();
                PropertiesIframe.closePopupAndSave = closePopupAndSave;
                PropertiesIframe.Sender = $(Step).not(".SCL_SubChecklists");
                PropertiesIframe.FormWrapper = $(".ext_forms_wrapper", $(Step));
                PropertiesIframe.getProperties = getProperties;
                PropertiesIframe.closePropertiesPopup = tb_remove;

                return false;
            });

            $("#ChecklistExtensions input").addClass("disabled");
            $(".ext_viewforms_wrapper").addClass("disabled");
            // $("#ChecklistExtensions input").disable();
            // $(".ext_viewforms_wrapper").disable();
            break;
        case "preview": 
            $("#ChecklistExtensions input").addClass("disabled");
            $(".ext_viewforms_wrapper").addClass("disabled");
            // $("#ChecklistExtensions input").disable();
            // $(".ext_viewforms_wrapper").disable();
            $("#FormsEdit, .ext_viewforms_wrapper").die("click mouseenter mouseout");
            break;
        case "sort":
            $("#ChecklistExtensions input").addClass("disabled");
            $(".ext_viewforms_wrapper").addClass("disabled");
            // $("#ChecklistExtensions input").disable();
            // $(".ext_viewforms_wrapper").disable();
            $("#FormsEdit, .ext_viewforms_wrapper").die("click mouseenter mouseout");
            break;
        case "use":
            $("#ChecklistExtensions input").removeClass("disabled");
            $(".ext_viewforms_wrapper").removeClass("disabled");
            // $("#ChecklistExtensions input").enable();
            // $(".ext_viewforms_wrapper").enable();
            $("#FormsEdit, .ext_viewforms_wrapper").die("click mouseenter mouseout");
            break;
    }

}

ChangeExtensionFormsChecklistMode(SwissChecklist.ChecklistController.Checklist.CurrentViewMode);

//
//Defines the Fieldtypes and its properties / events
//

FormsExtensionSettings.FieldTypeTable["textboxmultiline"] = function (Properties) {
    var Element = $("<textarea></textarea>");
    Element.val(Properties["defaultvalue"]);
    Element.attr({ "rows": "5", "cols": "25" });
    Element.addClass("ext_forms_txtmulti");
    if (Properties["isrequired"] && Properties["isrequired"] == "true")
        Element.addClass("ext_forms_required");
    if (Properties["fieldname"] != "undefined" && Properties["fieldname"] != undefined)
        Element.attr("name", Properties["fieldname"]);

    return ExtForms_AddRegex(Properties, Element);
};
FormsExtensionSettings.FieldTypeTable["textboxwysiwig"] = function (Properties) {
    var Element = $("<div class='wysiwig'></div>");
    Element.addClass("ext_forms_editor");
    if (Properties["isrequired"] && Properties["isrequired"] == "true")
        Element.addClass("ext_forms_required");
    if (Properties["fieldname"] != "undefined" && Properties["fieldname"] != undefined)
        Element.attr("name", Properties["fieldname"]);
}
FormsExtensionSettings.FieldTypeTable["datepicker"] = function (Properties) {
    var Element = $("<input type='text' title='datepicker' />");
    Element.val(Properties["defaultvalue"]);
    Element.addClass("ext_forms_datepicker");
    if (Properties["isrequired"] && Properties["isrequired"] == "true")
        Element.addClass("ext_forms_required");
    if (Properties["fieldname"] != "undefined" && Properties["fieldname"] != undefined)
        Element.attr("name", Properties["fieldname"]);
    Element.datepicker({
        onSelect: function (dateText, inst) {
            var $formswrapper = $(this).closest(".SCL_StepLine").find(".ext_viewforms_wrapper");

            var value = dateText;
            $formswrapper.attr("scl:value", value);
            $formswrapper.attr("scl:save", "true");
            ChecklistHasChange();
        }
    });
    return Element;
};
FormsExtensionSettings.FieldTypeTable["checkbox"] = function (Properties) {
    var Element = $("<input type='checkbox' />");
    if (Properties["defaultvalue"] == "true" || Properties["defaultvalue"] == true)
        Element.attr("checked", "checked");
    if (Properties["fieldname"] != "undefined" && Properties["fieldname"] != undefined)
        Element.attr("name", Properties["fieldname"]);
    return Element;
};
FormsExtensionSettings.FieldTypeTable["integer"] = function (Properties) {
    var Element = $("<input type='text' class='integer' />");
    Element.val(Properties["defaultvalue"]);
    Element.addClass("ext_forms_int");
    if (Properties["defaultvalue"] == true)
        Element.attr("checked", true);
    if (Properties["fieldname"] != "undefined" && Properties["fieldname"] != undefined)
        Element.attr("name", Properties["fieldname"]);

    //Add validation for integers            
    Properties["regex"] = /^\d*\.?\d*$/;
    Properties["regexerror"] = "Ungültige Zahl";
    return ExtForms_AddRegex(Properties, Element);
};
FormsExtensionSettings.FieldTypeTable["radiobuttonlist"] = function (Properties) {
    var Element = $("<span></span>");
    var TextboxLines = Properties["defaultvalue"].split('\n');
    for (var i = 0; i < TextboxLines.length; i++)
        if (TextboxLines[i] != " " && TextboxLines[i] != "") //Prevent emtpy strings and whitespaces
            Element.append("<input type='radio' value='" + TextboxLines[i] + "' name='hierkommteinname' />" + TextboxLines[i] + "<br />");
    return Element;
};
FormsExtensionSettings.FieldTypeTable["dropdown"] = function (Properties) {
    var Element = $("<select></select>");
    var TextboxLines = [];
    if (typeof (Properties["defaultvalue"]) != "undefined")
        TextboxLines = Properties["defaultvalue"].split('\n');
    for (var i = 0; i < TextboxLines.length; i++)
        if (TextboxLines[i] != " " && TextboxLines[i] != "" && TextboxLines[i] != "[d]") { //Prevent emtpy strings and whitespaces
            var IsDefault = (TextboxLines[i].indexOf("[d]") != -1)
            var CorrectTextboxLine = TextboxLines[i].replace("[d]", "");
            if (Properties["value"] == CorrectTextboxLine || (IsDefault && typeof(Properties["value"]) == "undefined"))
                Element.append("<option selected='selected'>" + CorrectTextboxLine + "</option>");
            else
                Element.append("<option>" + CorrectTextboxLine + "</option>");
        }
    if (Properties["fieldname"] != "undefined" && Properties["fieldname"] != undefined)
        Element.attr("name", Properties["fieldname"]);
    if (Properties["isrequired"] && Properties["isrequired"] == "true")
        Element.addClass("ext_forms_required");
    return Element;
};
FormsExtensionSettings.FieldTypeTable["textbox"] = function (Properties) {
    var Element = $("<input type='text' />");
    Element.val(Properties["defaultvalue"]);
    if (Properties["isrequired"] && Properties["isrequired"] == "true")
        Element.addClass("ext_forms_required");
    if (Properties["fieldname"] != "undefined" && Properties["fieldname"] != undefined)
        Element.attr("name", Properties["fieldname"]);

    return ExtForms_AddRegex(Properties, Element);
};


function ExtForms_AddRegex(Properties, Element) {
    //Test Regular expressions if in Hashtable
    if (Properties["regex"] != "undefined" && Properties["regex"] != undefined)
        Element.bind("blur", function () {
            var Regex = new RegExp(Properties["regex"]);
            if (!Regex.test($(this).val())) {
                if (!Element.data("haserrormessage")) {
                    Element.addClass("error");
                    Element.parent().append("<b class='errormessage'>" + Properties["regexerror"] + "</b>");
                    Element.data("haserrormessage", true);
                }
            }
            else {
                Element.removeClass("error");
                $(".errormessage", Element.parent()).remove();
                Element.removeData("haserrormessage");
            }
        });
    return Element;
}


// ### SwissChecklist.Extensions.Attachments.js

var CurrentStep;
var CurrentAttachment;
var PreviewSize = 150;

$(function () {
    InitializeAttachments();
});

function InitializeAttachments() {
    $(".ext_attachments").each(function () {
        var CStep = $(this).closest("li.SCL_Step");
        if ($("ul li", this).size() > 0) {
            $(".SCL_ShowDetails", CStep).removeClass("SCL_Hidden");
            $(".subcolumns").css("overflow", "visible");
        }
        $(".ext_attachments_preview", this).each(function () {
            CreateNotes(this);
        });


        $(".ext_attachmentitem", this).each(function () {
            var Thumb = $(".ext_attachments_lightbox img, .ext_attachments_link img", this);
            if (typeof (Thumb[0]) != "undefined") {
                var ImageHeight = 0;
                var Img = new Image();
                // Fix for Internet Explorer
                // positions the image on the correct height
                Img.onload = function () {
                    ImageHeight = Img.height >= PreviewSize ? 0 : (PreviewSize - Img.height);
                    if (Thumb.attr("type") == "link") {
                        // If it's a link, fix height
                        ImageHeight = (PreviewSize - (Img.height / (Img.width / PreviewSize)));
                    }
                    Thumb.css("margin-top", ImageHeight.toString() + "px");
                };
                Img.src = Thumb[0].src;
            }
        });

    });

    $("#AttachmentsButtons a").live("click", function () {
        var viewmode = $(this).attr("viewmode");
        TogglePreviewMode(viewmode);
        return false;
    });

    // Initialize the user mode and the thumb mode
    ChangeExtensionAttachmentsChecklistMode(SwissChecklist.ChecklistController.Checklist.CurrentView.Name);
    TogglePreviewMode("thumb");
}

function InitializeAttachment(CurrentStep) {
    $(".ext_attachments", CurrentStep).each(function () {
        if ($("ul li", this).size() > 0) {
            $(".SCL_ShowDetails", CurrentStep).removeClass("SCL_Hidden");
            $(".subcolumns", CurrentStep).css("overflow", "visible");
        }
        $(".ext_attachments_preview", this).each(function () {
            CreateNotes(this);
        });


        $(".ext_attachmentitem", this).each(function () {
            var Thumb = $(".ext_attachments_lightbox img, .ext_attachments_link img", this);
            if (typeof (Thumb[0]) != "undefined") {
                var ImageHeight = 0;
                var Img = new Image();
                // Fix for Internet Explorer
                // positions the image on the correct height
                Img.onload = function () {
                    ImageHeight = Img.height >= PreviewSize ? 0 : (PreviewSize - Img.height);
                    if (Thumb.attr("type") == "link") {
                        // If it's a link, fix height
                        ImageHeight = (PreviewSize - (Img.height / (Img.width / PreviewSize)));
                    }
                    Thumb.css("margin-top", ImageHeight.toString() + "px");
                };
                Img.src = Thumb[0].src;
            }
        });

    });

    $("#AttachmentsButtons a", CurrentStep).live("click", function () {
        var viewmode = $(this).attr("viewmode");
        TogglePreviewMode(viewmode);
        return false;
    });

    // Initialize the user mode and the thumb mode
    //ChangeExtensionAttachmentsChecklistMode(SwissChecklist.ChecklistController.Checklist.CurrentView.Name);
    //TogglePreviewMode("thumb");
}

var notes_timeout = 0;
function CreateNotes(Element) {
    // This method dispalys the notes on the images
    var Notes = $("<div>");
    Notes.text($(Element).attr("alt"));
    Notes.addClass("ext_attachments_notes");
    $(Element).parent().append(Notes);
    $(Element).mouseenter(function () {
        $(this).parent().find(".ext_attachments_notes").animate({ opacity: 0 }, 100, 'linear');
    })
    $(Element).mouseleave(function () {
        $(this).parent().find(".ext_attachments_notes").animate({ opacity: 0.6 }, 100, 'linear');
    });

    /*
    Notes.hover(function () {
        if (notes_timeout != 0) {
            clearTimeout(notes_timeout);
        }
        notes_timeout = setTimeout(function () {
            notes_timeout = 0;
            $(Element).parent().find(".ext_attachments_notes").animate({ opacity: 0 }, 100, 'linear');
        }, 10);
    }, function () {
        if (notes_timeout != 0) {
            clearTimeout(notes_timeout);
        }
        $(Element).parent().find(".ext_attachments_notes").animate({ opacity: 0.6 }, 100, 'linear');
    });*/
}
function HideNotes(Element) {
    if (notes_timeout != 0) {
        clearTimeout(notes_timeout);
    }
    notes_timeout = setTimeout(function () {
        notes_timeout = 0;
        $(Element).parent().find(".ext_attachments_notes").animate({ opacity: 0 }, 100, 'linear');
    }, 10);

}
function ShowNotes(Element) {
    if (notes_timeout != 0) {
        clearTimeout(notes_timeout);
    }
    $(Element).parent().find(".ext_attachments_notes").animate({ opacity: 0.6 }, 100, 'linear');

}

function TogglePreviewMode(mode) {
    switch (mode) {
        case "thumb":
            $(".ext_attachments_preview").show();
            $(".ext_attachments_notes").show();
            $(".ext_attachments_listdata").hide();
            $(".ext_attachmentitem").css({ "float": "left", "height": "150px" });
            $("#AttachmentsButtons .ext_attachments_viewmode_thumb").addClass("ext_attachments_viewmode_thumb_active");
            $("#AttachmentsButtons .ext_attachments_viewmode_list").removeClass("ext_attachments_viewmode_list_active");
            break;
        case "list":
            $(".ext_attachments_preview").hide();
            $(".ext_attachments_notes").hide();
            $(".ext_attachments_listdata").show();
            $(".ext_attachmentitem").css({ "float": "none", "height": "2px" });
            $("#AttachmentsButtons .ext_attachments_viewmode_list").addClass("ext_attachments_viewmode_list_active");
            $("#AttachmentsButtons .ext_attachments_viewmode_thumb").removeClass("ext_attachments_viewmode_thumb_active");
            break;
    }
}

function SaveLink(Link, replace, Action) {
    SwissChecklist.ChecklistController.Checklist.TryToAutosave(function (value) {
        if (value == true) {
            AddLink(Link, replace, Action);
        }
    });
}


function AddLink(Link, replace, Action) {

    $(CurrentStep).before($("#LoadPanel"));
    $("#LoadPanel").css("height", $(CurrentStep).height() + "px");
    $(CurrentStep).hide();
    var StepDetailsAreHidden = $(".SCL_Details", CurrentStep).hasClass("SCL_Hidden");

    var ParentKey = "0";
    if (replace) {
        if ($(".ext_attachments_wrapper", CurrentAttachment).attr("scl:parentkey"))
            ParentKey = $(".ext_attachments_wrapper", CurrentAttachment).attr("scl:parentkey");

        $(CurrentAttachment).remove();
    }

    $(".ext_attachments", CurrentStep).show();

    var AttachmentImage = $("<img />", {
        src: Link.PreviewUrl,
        width: "150",
        height: "112",
        "style": "margin-top: 37px; width: 150px; height: 112px;",
        "type" : "link",
        "title": Link.Title,
        "alt": Link.Title,
        "class": "ext_attachments_preview"
    });
    var AttachmentLink = $("<a />", {
        href: Link.Url,
        target: "_blank",
        "class": "ext_attachments_link"
    });
    AttachmentLink.append(AttachmentImage);

    var AttachmentItem = $("<li />", {
        "align": "center",
        "class": "ext_attachmentitem"
    });
    AttachmentItem.append(AttachmentLink);
    $(".ext_attachments ul", CurrentStep).append(AttachmentItem);
    CreateNotes(AttachmentImage);

    var extdiv = $("<span />", {
        "scl:extension": "Attachments",
        "scl:save": "true",
        "scl:savetype": "definition",
        "scl:url": Link.Url,
        "scl:urlid": Link.UrlID,
        "class": "ext_attachments_wrapper",
        "scl:iscurrent": "true"
    });
    if (ParentKey != "0")
        extdiv.attr("scl:parentkey", ParentKey);
    else
        extdiv.attr("scl:temp", "true");

    $(AttachmentItem).prepend(extdiv);

    var ListData = $("<div />", {
        "class": "ext_attachments_listdata"
    });

    var PreviewImage = $("<img />", {
        src: Link.IconImage
    });
    var Title = $("<a />", {
        href: Link.Url,
        target: "_blank",
        text: (Link.Title == "") ? Link.Url : (Link.Title + " - " + Link.Url)
    });

    ListData.append(PreviewImage);
    ListData.append(Title);

    $(AttachmentItem).append(ListData);



    $(".SCL_ShowDetails", CurrentStep).removeClass("SCL_Hidden");
    $(CurrentStep).attr("stephaschanged", "true");
    $(CurrentStep).prev().prev().attr("stephaschanged", "true");
    //SwissChecklist.ChecklistController.Steps.MarkStepAsChanged(CurrentStep, true);


    SwissChecklist.ChecklistController.SaveChecklistWithCallBack($(".ChecklistContainer:first"), false, "ChecklistUpdate", function () { SaveStepExtensions($(CurrentStep), Action, false, function () { ReloadStepAfterSaving($(CurrentStep), StepDetailsAreHidden) }) }, function () { alert('aaa') }, false);
}

function SaveAttachmentPreview(AttachmentObject, replace, Action) {
    SwissChecklist.ChecklistController.Checklist.TryToAutosave(function (value) {
        if (value == true) {
            AddAttachmentPreview(AttachmentObject, replace, Action);
        }
    });
}

function AddAttachmentPreview(AttachmentObject, replace, Action) {

    $(CurrentStep).before($("#LoadPanel"));
    $("#LoadPanel").css("height", $(CurrentStep).height() + "px");
    $(CurrentStep).hide();
    var StepDetailsAreHidden = $(".SCL_Details", CurrentStep).hasClass("SCL_Hidden");

    var ParentKey = "0";
    if (replace) {
        if ($(".ext_attachments_wrapper", CurrentAttachment).attr("scl:parentkey"))
            ParentKey = $(".ext_attachments_wrapper", CurrentAttachment).attr("scl:parentkey");

        $(CurrentAttachment).remove();
    }

    $(".ext_attachments", CurrentStep).show();

    var AttachmentImage = $("<img />", {
        src: AttachmentObject.FileUrl,
        "class": "ext_attachments_preview",
        "alt": AttachmentObject.Title,
        "scl:attachment": AttachmentObject.FileName,
        "attachment": AttachmentObject.FileName,
        title: AttachmentObject.Title,
        "scl:title": AttachmentObject.Title,
        "scl:notes": AttachmentObject.Notes
    });

    var AttachmentLink = $("<a />", {
        href: AttachmentObject.FileUrl + "&size=screen",
        "class": "ext_attachments_lightbox"
    });
    AttachmentLink.append(AttachmentImage);

    var AttachmentItem = $("<li />", {
        "align": "center",
        "class": "ext_attachmentitem"
    });
    AttachmentItem.append(AttachmentLink);

    $(".ext_attachments ul", CurrentStep).append(AttachmentItem);
    CreateNotes(AttachmentImage);

    // Generate the extension object to save it
    var extdiv = $("<span />", {
        "scl:extension": "Attachments",
        "scl:save": "true",
        "scl:savetype": "definition",
        "scl:filename": AttachmentObject.FileName,
        "class": "ext_attachments_wrapper",
        "scl:fileid": AttachmentObject.FileID,
        "scl:title": AttachmentObject.Title,
        "scl:notes": AttachmentObject.Notes,
        "scl:iscurrent": AttachmentObject.Current
    });
    if (ParentKey != "0")
        extdiv.attr("scl:parentkey", ParentKey);
    else
        extdiv.attr("scl:temp", "true");

    if (AttachmentObject.AttachmentID != "0" && AttachmentObject.AttachmentID != 0)
        extdiv.attr("scl:attachmentid", AttachmentObject.AttachmentID);

    $(AttachmentItem).append(extdiv);

    // Generate listview
    var ListData = $("<div />", {
        "class": "ext_attachments_listdata",
        "style": "display:none;"
    });

    var PreviewImage = $("<img />", {
        src: AttachmentObject.IconImage
    });
    var Title = $("<a />", {
        href: AttachmentObject.FileUrl,
        text: AttachmentObject.Title
    });

    ListData.append(PreviewImage);
    ListData.append(Title);

    $(AttachmentItem).append(ListData);

    $(".SCL_ShowDetails", CurrentStep).removeClass("SCL_Hidden");
    $(CurrentStep).attr("stephaschanged", "true");
    $(CurrentStep).prev().prev().attr("stephaschanged", "true");

    SwissChecklist.ChecklistController.SaveChecklistWithCallBack($(".ChecklistContainer:first"), false, "ChecklistUpdate", function () { SaveStepExtensions($(CurrentStep), Action, false, function () { ReloadStepAfterSaving($(CurrentStep), StepDetailsAreHidden) }) }, function () { alert('aaa') }, false);
}

function RemoveAttachment() {
    SwissChecklist.ChecklistController.Checklist.TryToAutosave(function (value) {
        if (value == true) {
            $(CurrentStep).attr("stephaschanged", "true");
            $(CurrentStep).prev().attr("stephaschanged", "true");
            //SwissChecklist.ChecklistController.Steps.MarkStepAsChanged(CurrentStep, true);
            // ToDo: Check this: Maybe important
            //$(CurrentAttachment).remove();
            $(".ext_attachments_wrapper", CurrentAttachment).attr("scl:iscurrent", "true");
            $(CurrentStep).before($("#LoadPanel"));
            $("#LoadPanel").css("height", $(CurrentStep).height() + "px");
            $(CurrentStep).hide();
            var StepDetailsAreHidden = $(".SCL_Details", CurrentStep).hasClass("SCL_Hidden");

            //            if ($(".ext_attachments ul li", CurrentStep).size() == 0) {
            //                $(".ext_attachments", CurrentStep).hide();
            //                $(".SCL_ShowDetails", CurrentStep).addClass("SCL_Hidden");
            //                $(".SCL_Details", CurrentStep).addClass("SCL_Hidden");
            //            }
            SwissChecklist.ChecklistController.SaveChecklistWithCallBack($(".ChecklistContainer:first"), false, "ChecklistUpdate", function () { SaveStepExtensions($(CurrentStep), "remove", false, function () { ReloadStepAfterSaving($(CurrentStep), StepDetailsAreHidden) }) }, function () { alert('SaveChecklistWithCallBack after removing Attachment fails') }, false);

        }
    });
}

function BindStepHover() {
    // 2011-05-26 Putted out because there will nomore be a list and a preview
   /* $(".SCL_Details").hover(function () {
        if ($(".ext_attachments ul li", this).size() > 0) {
            $("#Templates #AttachmentsButtons").appendTo(this);
            $("#AttachmentsButtons", this).css("top", ($(this).innerHeight() - $(".ext_attachments", this).innerHeight() + 30) + "px");
        }
    }, function () {
        $("#AttachmentsButtons", this).appendTo("#Templates");
    });*/
}

function ClosePopup() {
    tb_remove();
}

// Added 2010-12-12 by 2dk
// This methods changes the different inline modes
function ChangeExtensionAttachmentsChecklistMode(mode) {
    // viewformswrapper = the forms as they look when generated
    // formspreview = a preview of the forms control
    switch (mode) {
        case "change":
            // Bind the buttom to click event
            $(".ext_attachments_lightbox").unbind("click");

            $(".ext_attachments_file").each(function (i) {
                $(this).attr("link", $(this).attr("href"));
                $(this).attr("href", "javascript:;");
            });
            $(".SCL_MouseoverButtons").live("mouseover", function () {
                CurrentStep = $(this).closest("li.SCL_Step");
            });
            $("#AttachmentAdd").die("click");
            $("#AttachmentAdd").live("click", function () {

                var Url = "/SwissChecklist/Extensions/Attachments/ManageAttachments.aspx?Lang=" + $.trim($(".Language:first").text());

                jQuery.fancybox({
                    type: 'iframe',
                    href: decodeURIComponent(Url),
                    title: 'Attachment',
                    width: 593,
                    height: 500,
                    transitionIn: 'none',
                    transitionOut: 'none'
                });

                return false;
            });

            $("#LinkAdd").die("click");
            $("#LinkAdd").live("click", function () {

                var Url = "/SwissChecklist/Extensions/Attachments/ManageAttachments.aspx?Lang=" + $.trim($(".Language:first").text()) + "&tab=link";

                jQuery.fancybox({
                    type: 'iframe',
                    href: decodeURIComponent(Url),
                    title: 'Attachment',
                    width: 593,
                    height: 500,
                    transitionIn: 'none',
                    transitionOut: 'none'
                });

                return false;
            });

            $(".ext_attachments_lightbox, .ext_attachments_link, .ext_attachments_file").live("click", function () {
                CurrentStep = $(this).closest("li.SCL_Step");
                CurrentAttachment = $(this).closest("li.ext_attachmentitem");
                var Url = "/SwissChecklist/Extensions/Attachments/ManageAttachments.aspx?Lang=" + $.trim($(".Language:first").text());
                var ChecklistID = $.trim($(".ChecklistID:first", $(this).parents(".ChecklistContainer:first")).text());
                if ($(this).parent().find(".ext_attachments_wrapper").attr("scl:filename")) {
                    // Temporary
                    var FileName = $(this).parent().find(".ext_attachments_wrapper").attr("scl:filename");
                    Url = "/SwissChecklist/Extensions/Attachments/ManageAttachments.aspx?Lang=" + $.trim($(".Language:first").text()) + "&Attachment=" + FileName + "&ChecklistID=" + ChecklistID;
                }
                else if ($(this).parent().find(".ext_attachments_wrapper").attr("scl:url")) {
                    var UrlID = $(this).parent().find(".ext_attachments_wrapper").attr("scl:urlid");
                    Url = "/SwissChecklist/Extensions/Attachments/ManageAttachments.aspx?Lang=" + $.trim($(".Language:first").text()) + "&Link=" + UrlID + "&ChecklistID=" + ChecklistID;

                }
                else {
                    var AttachmentID = $(".ext_attachments_wrapper", CurrentAttachment).attr("scl:attachmentid");
                    Url = "/SwissChecklist/Extensions/Attachments/ManageAttachments.aspx?Lang=" + $.trim($(".Language:first").text()) + "&AttachmentID=" + AttachmentID + "&ChecklistID=" + ChecklistID;
                }

                jQuery.fancybox({
                    type: 'iframe',
                    href: decodeURIComponent(Url),
                    title: 'Attachment',
                    width: 593,
                    height: 500,
                    transitionIn: 'none',
                    transitionOut: 'none'
                });

                return false;
            });
            break;
        case "sort":
            $(".ext_attachments_preview").die("click");
            $(".ext_attachments_lightbox, .ext_attachments_link, .ext_attachments_file").die("click");
            $(".SCL_Details").unbind('mouseenter mouseleave');
            break;
        case "use":
            $(".ext_attachments_preview").die("click");
            $(".ext_attachments_lightbox, .ext_attachments_link, .ext_attachments_file").die("click");
            $(".ext_attachments_file").each(function (i) {
                if ($(this).attr("link") != "")
                    $(this).attr("href", $(this).attr("link"));
            });

            // Fancy
            $(".ext_attachments_lightbox").bind("click", function () {
                var Url = $(this).attr("href");
                var DownloadUrl = $("a:first", $(this).next()).attr("href");
                var Title = $(this).prev().attr("scl:title");
                var Description = $(this).prev().attr("scl:notes");





                // SwissChecklist.ChecklistController.Checklist.ShowAttachment(Url, DownloadUrl, Title, Description);

                return false;
            });

            $(".ext_attachments_lightbox").fancybox({
                title: 'Image',
                transitionIn: 'none',
                transitionOut: 'none',
                autoDimensions: true,
                showNavArrows: true,
                changeSpeed: 0,
                changeFade: 0,
                type: 'image',
                hideOnOverlayClick: true,
                onComplete: function () {
                    var ImageFile = $(this).attr("href");
                    var Selector = "#Checklist a[href='" + ImageFile + "']";
                    var ChecklistImageLink = $(Selector);
                    var Description = ChecklistImageLink.prev().attr("scl:notes");
                    var ImageLink = $("a:first", ChecklistImageLink.next()).attr("href");
                    var Title = ChecklistImageLink.prev().attr("scl:title");

                    $("#fancybox-title-float-main").html(Title);
                    $("#fancybox-wrap").css("width", "auto");
                    //$("#fancybox-content").css("width", parseInt($("#fancybox-content").css("width")) + 10 + "px");
                    $("#fancybox-content").append("<div id='fancybox-description'>" + Description + "</div>");
                    $("#fancybox-content").append("<div id='fancybox-download'><a href='" + ImageLink + "' target='_self'>Download</a></div>");
                }
            });


            BindStepHover();
            break;
        case "preview":
            $(".ext_attachments_preview").die("click");
            //$(".ext_attachments_lightbox").lightBox();
            BindStepHover();
            break;
    }
}



// ### SwissChecklist.Extensions.Tasks.js

$(function () {
    if (SwissChecklist.ChecklistController.PercentComplete != 100) {
        try {
                $(".jq_datepicker").datepicker({
                    showAnim: "fadeIn",
                    showButtonPanel: false,
                    minDate: 0,
                    altFormat: "dd.mm.yy",
                    dateFormat : "dd.mm.yy",
                    onSelect: function () {
                        ChecklistHasChange();
                        var dp = $(this);
                        if (dp.val() != dp.attr("defaulttext")) {
                            dp.closest("span").attr("scl:value", dp.val());
                            dp.closest("span").attr("scl:save", "true");
                        }
                    }, beforeShow: function (input, inst) {
                        $(input).removeClass("InactiveText");
                        var x = "";
                    }, onClose: function () {
                        var dp = $(this);
                        if (dp.val() == "")
                            dp.val(dp.attr("defaulttext")).addClass("InactiveText");
                    }
                });
        } catch (err) { }

        $(".jq_datepicker").change(function () {
            var dp = $(this);
            ChecklistHasChange();
            dp.closest("span").attr("scl:value", dp.val());
            dp.closest("span").attr("scl:save", "true");
        });

        $(".jq_datepicker").focus(function () {
            var dp = $(this);
            if (dp.val() == dp.attr("defaulttext"))
                dp.val("");
        });
    
    }
});


// ### SwissChecklist.Extensions.Delegate.js
$(function () {
    $("#DelegateChecklist").click(function () {
        $("#personlist :radio:checked").each(function () {
            $(this).removeAttr("checked");
        });
        var UserChecklistID = $.trim($(".UserChecklistID").text());
        tb_show("Delegate", "/SwissChecklist/Extensions/Teams/Personlist.aspx?UserChecklistID=" + UserChecklistID + "&TB_iframe=true&height=500&width=600&KeepThis=true", '');
    });
});


