/* Variables */
var elementTemplateID_normal = "elementOptionsTemplate";
var elementTemplateID_address = "addressElementOptionsTemplate";
var elementTemplateID_countryState = "cntryStateElementOptionsTemplate";
var elementOptionDiv = "fieldSettings";
var formObj = new formClass();
/* JQuery UI */
$(document).ready(function () {
    /* START : Form Settings& Action  Form is Linked with The Object __FORM_SETTINGS [in Form Javascript] */
    $("#formSettings,#frmAction").link(true, __FORM_SETTINGS);
    $("#emailPopups").link(true, __FORM_SETTINGS);
    /* END	 : Form Settings Form is Linked with The Object __FORM_SETTINGS [in Form Javascript] */
    /* make the controler draggable */
    $("#controllerList li").draggable({
            connectToSortable: "#dynamicForm",
            helper: 'clone',
            start: function (ui, event) {
                $(ui.currentTarget).addClass('fade');
            },
            stop: function () {
                $(".formElement,.controls").removeClass('fade');
            }
        });
    /* make the container droppable  */
    $("#dynamicForm").sortable({
            cursor: "cross",
			items: "li:not(.ui-disabled)",
			cancel: ".ui-disabled",
            placeholder: "controllerplaceholder",
            update: function (event, ui) {
                var elementType = ui.item.data('controller');
                formObj.createFormElement(elementType, ui.item, event, false);
                addLiClass();
                reorderList();
            },
            start: function (event, ui) {
                /* Get the height of sort li and given the height to placeholder  */
                var height = ui.helper.height();
                $(".controllerplaceholder").height(height);
            }
        }).disableSelection();
	$(".accessGroupIDs_class").click(function(){
		if($(".accessGroupIDs_class:checked").length ==$(".accessGroupIDs_class").length ){
			$(".accessGroupIDsAll_class").prop('checked',true);
		}else{
			$(".accessGroupIDsAll_class").prop('checked',false);
		}
		if($(".accessGroupIDs_class:checked").length>0){
			$("#accessGroupIDValidate").val(1);
		}else{
			$("#accessGroupIDValidate").val('');
		}
	});
	
    $(document).on('click', ".element-duplicate", function () {
        var objElement = $("[uniqueID='" + $(this).attr('rel') + "']");
        var uniqueID = objElement.attr('uniqueID');
        var elementType = $(this).attr('data');
        var html = formObj.createFormElement(elementType, objElement.clone(), '', true);
        $("[uniqueID='" + uniqueID + "']").after(html);
        addLiClass();
        reorderList();
    });
    /* Form element settings */
    $(document).on('click', ".element-edit", function () {
        var uniqueID = $(this).attr('rel');
        var elementType = $(this).attr('data');
        formObj.createFieldSettings(uniqueID, elementType);
        formObj.assignRelDataToSettingsButton(uniqueID, elementType);
        formObj.showLeftTab('fieldSettings');
        if ($(".inner-field").hasClass('minimise')) {
            $(".inner-field").removeClass('minimise').show();
        }
    });
    /* Form element settings */
    $(document).on('click', ".formElement:not(add-anchor)", function (event) {
        if ($(event.target).hasClass('add-anchor')) {
            $(".inner-field").removeClass('minimise').show();
            $(".dynamicForm-container").addClass("rmv-add-fld");
            formObj.showLeftTab('controllerList');
        } else {
            var uniqueID = $(this).attr('uniqueid');
            var elementType = $(this).data('controller');
            formObj.createFieldSettings(uniqueID, elementType);
            formObj.assignRelDataToSettingsButton(uniqueID, elementType);
            formObj.showLeftTab('fieldSettings');
            if ($(".inner-field").hasClass('minimise')) {
                $(".inner-field").removeClass('minimise').show();
            }
        }
    });
    /* Delete the element from Form */
    $(document).on('click', ".element-delete", function () {
        var uniqueID = $(this).attr('rel');
        var elementType = $(this).attr('data');
        formObj.assignRelDataToSettingsButton(uniqueID, elementType);
        formObj.destroyField(uniqueID);
    });
    /* Delete the element from Form */
    $('.saveForm').click(function () {
        formObj.saveForm();
    });
    $(document).on('click', ".add-field", function () {
        var rel = $(this).attr('rel');
        if (rel == 'controllerList') {
            $(".dynamicForm-container")
                .removeClass('frm-style01')
                .removeClass('frm-style02')
                .removeClass('frm-style03')
                .removeClass('frm-style04')
                .addClass(__FORM_SETTINGS['fieldAlignment']);
        }
        if ($("#add-field").hasClass('hide')) {
            $(".form-tab-div").addClass('hide');
            $("#add-field").removeClass('hide');
        }
        formObj.showLeftTab(rel);
        removeEditMode();
    });
    $(document).on("click", "[name='setting-validate']", function () {
        if ($("[name='setting-validate']:checked").length > 0) {
            $("#validate-error").removeClass('hide');
        } else {
            $("#validate-error").addClass('hide');
        }
    })
});

function formClass() {
    /* Private Variables */
    var currentUniqueID,
        currentKey,
        currentData;
    /* Public Variables */
    /* Methods */
    /* 
	Function createFormElement()
	elementType :	text,textarea .. etc
	*/
    this.createFormElement = function (elementType, obj, event, htmlonly) {
        if (htmlonly) {
            /* For Duplicate element  */
            var templateID = controllerObject[elementType].template;
            var data = controllerObject[elementType].data;
            /* Unique id is used for identifiying the created element in Form object */
            var uniqueID = $.random();
            html = $("#" + templateID).render(data, $.extend(fieldOptions, {
                        "uniqueID": uniqueID,
                        'elementType': elementType
                    }));
            obj.attr('uniqueid', uniqueID);
            obj.attr('rel', 'fieldSettings');
            __FORMOBJECT.push({
                    "uniqueID": uniqueID,
                    "data": $.extend(true, {}, data)
                });
            obj.html(html);
            return obj;
        } else {
            /* Normal Drag element */
            if (typeof elementType != 'undefined' && obj.hasClass('controls')) {
                if (elementType == 'address' || elementType == 'countryState' || elementType == 'name') {
                    var html = this.makeHtmlForMultipleType(elementType);
                    obj.after(html);
                    obj.remove();
                    return true;
                }
                var templateID = controllerObject[elementType].template;
                var data = controllerObject[elementType].data;
                /* Unique id is used for identifiying the created element in Form object */
                var uniqueID = $.random();
                html = $("#" + templateID).render(data, $.extend(fieldOptions, {
                            "uniqueID": uniqueID,
                            'elementType': elementType
                        }));
                obj.removeClass('controls').addClass('formElement');
                obj.attr('uniqueid', uniqueID);
                obj.attr('rel', 'fieldSettings');
                __FORMOBJECT.push({
                        "uniqueID": uniqueID,
                        "data": $.extend(true, {}, data)
                    });
                obj.html(html);
            }
        }
    }
    this.makeHtmlForMultipleType = function (elementType) {
        var html = "",ui_state_disabled='',
            data = {}, counrtyData = {};
        switch (elementType) {
        case 'address':
            data = controllerObject[elementType].data['address'];
            break;
        case 'countryState':
        case 'name':
            data = controllerObject[elementType].data['items'];
            break;
        }
        for (key in data) {
            var extradata = new Object();
            extradata.uniqueID = $.random();
            extradata.elementType = data[key].type;
            var templateID = controllerObject[extradata.elementType].template;
            var currdata = data[key];
            if (extradata.elementType == 'country') {
                var countryKey = $.objCount(__FORMOBJECT);
            } else if (extradata.elementType == 'state') {
                __FORMOBJECT[countryKey]['data']['linkWith'] = extradata.uniqueID;
            } else if (extradata.elementType == 'province') {
                __FORMOBJECT[countryKey]['data']['linkWith'] += "," + extradata.uniqueID;
            }
            __FORMOBJECT.push({
                    "uniqueID": extradata.uniqueID,
                    "data": $.extend(true, {}, currdata)
                });
			if( elementType == 'countryState' || elementType == 'address' ){
				ui_state_disabled = 'ui-disabled';
			}	
            html += '<li class="sub clearfix ui-draggable formElement '+ ui_state_disabled +'" data-controller="' + extradata.elementType + '" style="display: block;" uniqueid="' + extradata.uniqueID + '" rel="fieldSettings">' + $("#" + templateID).render(currdata, extradata) + '</li>';
        }
        return html;
    }
    /* This function is uded to render the field settings based on the 
	fieled Data object; field data object are idetified by previouly defined unique ID */
    this.createFieldSettings = function (uniqueID, elementType) {
        var result = $.getObj(uniqueID);
        var key = result['key'];
        var data = result['data'];
        currentKey = key;
        currentUniqueID = uniqueID;
        fieldOptions['uniqueID'] = currentUniqueID;
        fieldOptions['currentKey'] = currentKey;
        html = $("#" + elementTemplateID_normal).render(data, fieldOptions);
        $("#" + elementOptionDiv).html(html);
        removeEditMode();
        $('.scroll-pane').jScrollPane({
                mouseWheelSpeed: 15
            });
        $("[uniqueID='" + uniqueID + "']").addClass('edit-mode');
        if (elementType == 'html') {
            formObj.getEditor(currentKey,elementType);
        }
    }
    /* Destroy the form Element from form, the elemets are found form the object using the unique key which assigend early */
    this.destroyField = function (uniqueID) {
        removeEditMode();
        $("[uniqueID='" + uniqueID + "']").addClass('edit-mode');
        jConfirm(msgDeleteItem, lblWarningMessage, function (r) {
            if (r) {
                var result = $.getObj(uniqueID);
                var key = result['key'];
                var data = result['data'];
                $("[uniqueid='" + uniqueID + "']").fadeOut(1000, function () {
                    $(this).remove();
                });
                __FORMOBJECT[key]['deleted'] = true;
                formObj.showLeftTab('controllerList');
            } else {
                removeEditMode();
            }
        });
    }
    this.showLeftTab = function (id) {
        $("#" + id).siblings().not('.tab-block-01').addClass('hide');
        $("#" + id).removeClass('hide');
    }
    /* This function used to update the object [Single Option properties like label, value , Instructions etc..] */
    this.updateSingleValueFieldSettings = function (obj, propertyType, elementType) {
        var prop = (propertyType).split(".");
        var currentValue;
        if (elementType == 'html') {
			if(prop[1]=='text'){
				currentValue = CKEDITOR.instances.htmlEditor.getData();
			}
			else{
				currentValue = obj.val();
			}
        } else {
            switch (obj.prop('type')) {
            case 'checkbox':
                currentValue = obj.prop('checked');
                break;
            default:
                currentValue = obj.val();
            }
        }
        currentValue = $.str_replace('"', "", currentValue);
        switch (prop.length) {
        case 1:
            __FORMOBJECT[currentKey]['data'][prop[0]] = currentValue;
            break;
        case 2:
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]] = currentValue;
            break;
        case 3:
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]][prop[2]] = currentValue;
            break;
        case 4:
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]][prop[2]][prop[3]] = currentValue;
            break;
        }
        var templateID = controllerObject[elementType].template;
        var data = __FORMOBJECT[currentKey]['data'];
        html = $("#" + templateID).render(data, {
                "uniqueID": currentUniqueID,
                'elementType': elementType
            });
        $("[uniqueid='" + currentUniqueID + "']").html(html);
    }
    this.updateValidationRule = function (obj, propertyType, elementType) {
        var valiadate_name = obj.attr('name'),
            rules = new Array();
        $("[name='" + valiadate_name + "']:checked").each(function () {
            rules.push($(this).val());
        });
        var items = rules;
        var prop = (propertyType).split(".");
        switch (prop.length) {
        case 1:
            __FORMOBJECT[currentKey]['data'][prop[0]] = items;
            break;
        case 2:
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]] = items;
            break;
        }
        var templateID = controllerObject[elementType].template;
        var data = __FORMOBJECT[currentKey]['data'];
        html = $("#" + templateID).render(data, {
                "uniqueID": currentUniqueID,
                'elementType': elementType
            });
        $("[uniqueid='" + currentUniqueID + "']").html(html);
    }
    /* This function used to update the option text and selected item. This function will handle both the check box and the text box changes */
    this.updateChoicesSettings = function (callForm, obj, propertyType, elementType, key) {
        var prop = (propertyType).split(".");
        if (callForm == 'radio') {
            var formObj = __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]];
            for (elem in formObj) {
                formObj[elem]['selected'] = false;
            }
            formObj[key]['selected'] = true;
            __FORMOBJECT[currentKey]['data'][prop[0]]['value'] = $("[name='opt-textbox_" + key + "']").val();
        } else {
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]][key]['text'] = obj.val();
        }
        var templateID = controllerObject[elementType].template;
        var data = __FORMOBJECT[currentKey]['data'];
        html = $("#" + templateID).render(data, {
                "uniqueID": currentUniqueID,
                'elementType': elementType
            });
        $("[uniqueid='" + currentUniqueID + "']").html(html);
    }
    /* Crate an option after clicking the add new Option */
    this.createNewChoice = function (obj, propertyType, elementType) {
        this.addOptionToObject(obj, propertyType, elementType, {
                "text": NEW_ITEM,
                "selected": false
            }, 'add')
    }
    /* Crate an option after clicking the add new Option */
    this.deleteChoice = function (obj, propertyType, elementType, key) {
        var thisClass = this;
        obj.closest('li').fadeOut(function () {
            var prop = (propertyType).split(".");
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]][key]['deleted'] = true;
            var templateID = controllerObject[elementType].template;
            var data = __FORMOBJECT[currentKey]['data'];
            html = $("#" + templateID).render(data, {
                    "uniqueID": currentUniqueID,
                    'elementType': elementType
                });
            $("[uniqueid='" + currentUniqueID + "']").html(html);
        });
    },
    /* Import the selected predefined options from text box and assigning of object as well as template */
    this.addPredefinedOptions = function (thisObj, obj) {
        var elementType = thisObj.attr('elementtype');
        var choices = (obj.val()).split('\n');
        var pre_options = choices.map(function (value, index) {
            if (value != '') {
                return {
                    'text': value,
                    'selected': false
                }
            }
        });
        this.addOptionToObject(obj, 'defaults.items', elementType, pre_options, 'import');
        $.colorbox.close();
    }
    /* Common Function for assignment [createNewChoice,addPredefinedOptions] */
    this.addOptionToObject = function (obj, propertyType, elementType, opts, from /*Form Where (Import or Add)*/ ) {
        var prop = (propertyType).split(".");
        if (from == 'add') {
            (__FORMOBJECT[currentKey]['data'][prop[0]][prop[1]]).push(opts);
        } else if (from == 'import') {
            /* Append the old option with newly imported opts */
            var appendObj = $.objMerge(__FORMOBJECT[currentKey]['data'][prop[0]][prop[1]], opts);
            /* Convert the object list into array list */
            opts = $.map(appendObj, function (el) {
                return $.makeArray(el)
            });
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]] = opts;
        } else if (from == 'delete') {
            __FORMOBJECT[currentKey]['data'][prop[0]][prop[1]] = opts;
        }
        var templateID = controllerObject[elementType].template;
        var data = __FORMOBJECT[currentKey]['data'];
        html = $("#" + templateID).render(data, {
                "uniqueID": currentUniqueID,
                'elementType': elementType
            });
        $("[uniqueid='" + currentUniqueID + "']").html(html);
        updateOptionOrder(currentKey);
        this.createFieldSettings(currentUniqueID, elementType);
    }
    /* Change the filed type after create a new field */
    /* this.changeField=function(obj){
		var elementType	=	obj.val();
		var elemParent	=	$("[uniqueid='"+currentUniqueID+"']");
		var templateID	=	controllerObject[elementType].template;
		var data		=	controllerObject[elementType].data;
		__FORMOBJECT[currentKey]['data']=data;
		html=$( "#"+templateID).render( data ,{"uniqueID":currentUniqueID,'elementType':elementType});
		elemParent.attr('data-controller',elementType);
		elemParent.html(html);
		this.createFieldSettings(currentUniqueID,elementType);
	} */
    this.assignRelDataToSettingsButton = function (uniqueID, elementType) {
        $("#element-delete").attr('data', elementType).attr('rel', uniqueID).addClass('element-delete');
        $("#element-duplicate").attr('data', elementType).attr('rel', uniqueID).addClass('element-duplicate');
    }
    this.saveForm = function () {
        if (__FORM_SETTINGS['disableForm'] != 'never' && __FORM_SETTINGS['disableFormCriteria'] == '' && __FORM_SETTINGS['disableFormMessage'] == '') {
            $("#disableFormCriteria,#disableFormMessage").trigger('blur');
        } else if (__FORM_SETTINGS['disableForm'] != 'never' && __FORM_SETTINGS['disableFormCriteria'] == '') {
            $("#disableFormCriteria").trigger('blur');
        } else if (__FORM_SETTINGS['disableForm'] != 'never' && __FORM_SETTINGS['disableFormMessage'] == '') {
            $("#disableFormMessage").trigger('blur');
        } else {
            var value = __FORM_SETTINGS['disableFormCriteria'];
            var wholeNumberRegex = /^[0-9]+$/i;
            if (__FORM_SETTINGS['disableForm'] != 'never' && !(wholeNumberRegex.test(value))) {
                $("#disableFormCriteria").trigger('blur');
            } else {
                var form = new Object();
                form['__FORM_SETTINGS'] = this.setSettingsArray();                
                form['__FORMOBJECT'] = $.stringify(__FORMOBJECT);
                if (formID > 0) {
                    form['formID'] = formID;
                }
                $.ajax({
                        type: "POST",
                        url: GLOBAL_BASE_PATH + "/form/ajaxSaveForm/",
                        data: form,
                        beforeSend: function () {
                            $(".save-load-display").removeClass('hide');
                        },
                        complete: function () {
                            $(".save-load-display").addClass('hide');
                        },
                        success: function (data) {
                            var formID = $.trim(data);
                            if (formID > 0) {
                                window.location = GLOBAL_BASE_PATH + "/form/build/id/" + formID + "/";
                            }
                        }
                    });
            }
        }
    }
    this.setSettingsArray = function () {
        var adminEmails = '';
        if (__FORM_SETTINGS['afterFormSubmission'] == 'ShowText') {
            __FORM_SETTINGS['afterFormSubmissionAction'] = __FORM_SETTINGS['afterFormSubmissionActionarea'];
        } else {
            __FORM_SETTINGS['afterFormSubmissionAction'] = __FORM_SETTINGS['afterFormSubmissionActiontext'];
        }        
        return {
            "formName": __FORM_SETTINGS['formName'],
            "formDesc": __FORM_SETTINGS['formDesc'],
            "fieldAlignment": __FORM_SETTINGS['fieldAlignment'],
            "globalUploadFolder": __FORM_SETTINGS['globalUploadFolder'],
            "accessGroupIDs": __FORM_SETTINGS['accessGroupIDs'],
            "formStatus": __FORM_SETTINGS['formStatus'],
            "enableCaptcha": __FORM_SETTINGS['enableCaptcha'],    
             "captchaValidation": __FORM_SETTINGS['captchaValidation'],
            "disableForm": __FORM_SETTINGS['disableForm'],
            "disableFormCriteria": __FORM_SETTINGS['disableFormCriteria'],
            "disableFormMessage": __FORM_SETTINGS['disableFormMessage'],
            "adminEmails": __FORM_SETTINGS['adminEmails'],
            "sendConfirmMailToSubmitter": __FORM_SETTINGS['sendConfirmMailToSubmitter'],
            "sendCopyToSubmitter": __FORM_SETTINGS['sendCopyToSubmitter'],
            "afterFormSubmission": __FORM_SETTINGS['afterFormSubmission'],
            "afterFormSubmissionAction": __FORM_SETTINGS['afterFormSubmissionAction'],
            "afterFormSubmissionActionarea": __FORM_SETTINGS['afterFormSubmissionAction'],
            "afterFormSubmissionActiontext": __FORM_SETTINGS['afterFormSubmissionAction'],
            "submitButtonValue": __FORM_SETTINGS['submitButtonValue'],
            "emailFromName": __FORM_SETTINGS['emailFromName'],
            "saveToDataBase": __FORM_SETTINGS['saveToDataBase'],
            "agreementText": __FORM_SETTINGS['agreementText'],
            "enableAgreement": __FORM_SETTINGS['enableAgreement'],
            "adminEmailSubject": __FORM_SETTINGS['adminEmailSubject'],
            "adminEmailContent": __FORM_SETTINGS['adminEmailContent'],
            "userEmailSubject": __FORM_SETTINGS['userEmailSubject'],
            "userEmailFields": __FORM_SETTINGS['userEmailFields'],
            "userEmailContent": __FORM_SETTINGS['userEmailContent'],
            "brandID": __FORM_SETTINGS['brandID']     
        };
        
    }
    this.updateFormSettings = function (obj) {
       
        var name = (obj.attr('name')).replace("[]", "");
		if(name == 'accessGroupIDs'){
			var val = [];
			$("[name='accessGroupIDs[]']:checked").each(function(){
				val.push(this.value);
			});
		}else{
			var val = obj.val();
		}
        __FORM_SETTINGS[name] = val;
        if (obj.attr('name') == 'fieldAlignment') {
            addLiClass();
        }
        if(obj.attr('id')=='enableCaptcha'){
            if(val=='Yes') {
                $(".captchaValidation").show();
            } else {
                $(".captchaValidation").hide();
            }
        }
    }    
    if($("#enableCaptcha").val()=='Yes'){
        $(".captchaValidation").show();
    } else {
        $(".captchaValidation").hide();
    }
        
    this.selectAllAccessGroupIDs = function (Obj, ClassObj,errObj) {
        //Obj.click(function(){
            if(Obj.prop('checked')==true){
                    errObj.val(0);
                    ClassObj.prop('checked',true);
            }
            else{
                    errObj.val(0);
                    ClassObj.prop('checked',false);
            }
        //});
    }
    
    this.getEditor = function (key,elementType) {
        var content = $("#htmlEditor").val();
        var data = $("#html_textarea").val();
        $.ajax({
                method: 'POST',
                url: GLOBAL_BASE_PATH + "/form/ajaxGetEditor/",
                data: {
                    content: content
                },
                success: function (data) {
                    $('#editor').html(data);
                    editor = data;
                }
            }).done(function (data) {
				CKEDITOR.instances.htmlEditor.on('change', function (e) {
                    formObj.updateSingleValueFieldSettings(CKEDITOR.instances.htmlEditor, 'defaults.text', elementType);
                });
            });
    }
}
/* Extended Functions */
$.getObj = function (uniqueID) {
    for (key in __FORMOBJECT) {
        if (__FORMOBJECT[key]['uniqueID'] == uniqueID) {
            return {
                "key": key,
                "data": __FORMOBJECT[key]['data']
            };
        }
    }
}
$.random = function () {
    return Math.round(Math.random() * 10000000000000) + 1;
}