﻿

var swiftCustomModule = angular.module('swiftCustomModule', []);

app.controller('ContactFormController', ["$scope", "$http", "$parse", "swiftDataCUService", "swiftDataCUService1", "$compile", function ($scope, $http, $parse, swiftDataCUService, swiftDataCUService1, $compile) {


    //console.log("SwiftDataController ---- ");
    $scope.eCubeForm_master = {};
    $scope.model_master = {};
    $scope.files_master = {};

    $scope.model = {};
    $scope.files = {};
    $scope.loading = true;
    $scope.addMode = false;
    $scope.invalidSubmitAttempt = false;
    /*regular expressions for email and phone nunmbers */
    //$scope.EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z]+)$/i;

    $scope.EMAIL_REGEXP = /^[a-z0-9](\.?[a-z0-9_-]){0,}@[a-z0-9-]+\.([a-z]{1,6}\.)?[a-z]{2,6}$/i;
    $scope.PHONE_REGEXP = /^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4,5})(?: *x(\d+))?\s*$/;
    $scope.FormStartTime = new Date().getTime();
    
    angular.element(document).ready(function () {
        //keep the safecopy of initial stage
        $scope.eCubeForm_master = angular.copy($scope.eCubeForm); //save the inital state of the form model
        $scope.model_master = angular.copy($scope.model); //save the inital state of the form model
        $scope.files_master = angular.copy($scope.files); //save the inital state of the form model
        //ProgressBar showing
        $scope.PagesCount = $('.stepwizard-step').length;
        if ($scope.PagesCount != 0) {
            $scope.initwdith = 0;
            $(".progress-bar").css("width", $scope.initwdith + '%');
            $(".progress-bar").html($scope.initwdith + '%');
            $scope.progressWidth = 100 / $scope.PagesCount;
        }

        $scope.showForm = true;
        $("#divProcessing").hide();
        $("#success").hide();

        $(".errorMessage").removeClass('hide');

	//	$scope.hostname = window.name;
		
        ////console.log("Form init");
        ////console.log($scope.model);
        ////console.log($scope.master);

        try {
            // $scope.loadQueryStringVariables();

            if ($scope.formlevelSettings == null)
                $scope.formlevelSettings = {}; //to avoid error in existing forms


            var formSettings = $scope.formlevelSettings;
            //var fieldRules = $scope.fieldrules;

            if (formSettings.fieldrules == null)
                return;
            //console.log(fieldRules);
            if (formSettings.RuleEnable == false)
                return;
            formSettings.fieldrules.forEach(function (rule) {
                $scope.executeFieldRule(rule);
            });

        }
        catch (err) {
            console.log(err.message);
            $("#divProcessing").hide();
            bootbox.alert({
                size: 'small',
                title: lang1.appHeading,
                message: err.message,
                animate: true,
                callback: function () { /* your callback code */ }

            })

        }
    });

    $scope.loadQueryStringVariables = function () {
        var queryStringVars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            //vars.push(hash[0]);
            queryStringVars[hash[0]] = hash[1];
        }
        // console.log(vars);
        if (queryStringVars.length > 0) {
            $.each(queryStringVars, function (index, value) {
                //  console.log(value);
            });

        }
    }
    //$scope.cascadingDropdownChange = function (thisctrl, cascadingNextCtrl, position, modelData, NoOflevels) {


    //    var value = this.model[thisctrl];
    //    $("#" + cascadingNextCtrl).html('');
    //    for (var i = position + 2; i <= NoOflevels; i++) {
    //        $("#" + modelData + "C" + i).html('');
    //    }
    //    var nextIndex = position + 1;
    //    if (value !== '') {
    //        var htmlOption = '<option value="">Please select value</option>';
    //        var data = $scope[modelData];// $scope.cascadingJsonData;
    //        console.log(data);
    //        $.each(data, function (key, val) {
    //            console.log(val);
    //            var uniqueNames = [];
    //            $.each(val, function (index, val1) {
    //                if (val1[position] == value) {
    //                    if ($.inArray(val1[nextIndex], uniqueNames) === -1) uniqueNames.push(val1[nextIndex]);
    //                    console.log(uniqueNames);

    //                }
    //            });
    //            if (uniqueNames.length > 0) {
    //                $.each(uniqueNames, function (index, name) {
    //                    htmlOption += '<option value="' + name + '" ng-value="' + name + '" optionText="' + name + '" >' + name + '</option>';
    //                });

    //            }

    //        });

    //        $("#" + cascadingNextCtrl).append(htmlOption);



    //    }

    //},




    //variable used to hold cascading controls data on the form
    $scope.cascadingdata = {};

    $scope.cascadingDropdownInit = function (selected, cascadingNextCtrl, position, modelData, NoOflevels) {

        var value1 = $scope.model[selected];
        //console.log("Current DDL val:" + value1);
        var value = $scope.model[cascadingNextCtrl];

        var modelVarName = 'model.' + selected;
        $scope.$watch(modelVarName, function (newValue, oldValue) {
            var valueChanged = newValue == oldValue ? false : true;
            $scope.cascadingDropdownChange(selected, cascadingNextCtrl, position, modelData, NoOflevels, valueChanged);
        });

    }

    $scope.cascadingDropdownChange = function (thisctrl, cascadingNextCtrl, position, modelData, NoOflevels, dropdownValueChanged) {

        var value = this.model[thisctrl];//current control value

        //reset the dropdown data arrays and reset model values if user switches values
        //reset the values for next  dropdown controls in the sequence
        $scope.cascadingdata[cascadingNextCtrl] = new Array();
        for (var i = position + 2; i <= NoOflevels; i++) {
            var nextSelectCtrl = modelData + "C" + i;
            $scope.cascadingdata[nextSelectCtrl] = new Array();
            if (dropdownValueChanged == true)
                $scope.model[nextSelectCtrl] = "";
        }

        //loop through the json data to fill the cascading dropdown of the current level
        var nextIndex = position + 1;
        if (value !== '') {
            var data = $scope[modelData]; //json data  for cascading controls
            $.each(data, function (key, val) {
                var uniqueValues = new Array(); //uniquevalues for each level
                $.each(val, function (index, val1) {
                    if (val1[position] == value) {
                        if ($.inArray(val1[nextIndex], uniqueValues) === -1)
                            uniqueValues.push(val1[nextIndex]);
                    }
                });
                if (uniqueValues.length > 0) {

                    $scope.cascadingdata[cascadingNextCtrl] = uniqueValues.slice(); //duplicate the array
                    //console.log($scope.cascadingdata[cascadingNextCtrl]);
                    ////$.each(uniqueValues, function (index, value) {
                    ////    $scope.cascadingdata[cascadingNextCtrl].push(value); //fill the respective array
                    ////});
                }
            });
        }
    },
    //This will be fired when there is any change of value in the controls value and check for any field rules are applicable to input controls.
    $scope.fieldOnChange = function (elementId) {
        try {
            var formSettings = $scope.formlevelSettings;
            //var fieldRules = $scope.fieldrules;
            if (formSettings.fieldrules == null)
                return;
            if (formSettings.RuleEnable == false)
                return;
            formSettings.fieldrules.forEach(function (rule) {
                var requiredrule = false;
                rule.fieldConditions.forEach(function (condition) {
                    if (condition.fieldName.indexOf(elementId) != -1)
                        requiredrule = true;
                });
                if (requiredrule) {
                    $scope.executeFieldRule(rule);
                }
            });

        }
        catch (err) {
            console.log(err);
            bootbox.alert({
                size: 'small',
                title: lang1.appHeading,
                message: err.message,
                animate: true,
                callback: function () { /* your callback code */
                }
            })
        }
    }
    //This function is called when there is rule applied on a particular filed, and check the rule is valid ornot and returns boolean value
    $scope.executeFieldRule = function (rule) {
        var fieldActions;
        var isConditionSuccessCount = 0;
        //loop through all conditions on a rule
        rule.fieldConditions.forEach(function (condition) {
            if ($scope.isConditionValid(condition)) {
                isConditionSuccessCount++;
            }
        });
        //get the actions on field to a variable
        fieldActions = rule.fieldActions;
        //if all the configured condtions are checked and the join condition is AND
        if (isConditionSuccessCount == rule.fieldConditions.length && rule.conditionsJoinRule == enum_conditionJoinOp.And)//1 means AND
        {
            //loop through all the field actions
            fieldActions.forEach(function (action) { //loop through all the configured field actions
                $scope.setFieldAction(action, action.fieldAction, true);
            });
        }
            //if all the configured condtions are checked (at least one condition satisfied) and the join condition is OR
        else if (isConditionSuccessCount > 0 && rule.conditionsJoinRule == enum_conditionJoinOp.Or) { // 2 means OR               
            fieldActions.forEach(function (action) {
                $scope.setFieldAction(action, action.fieldAction, true);
            });
        }
        else {
            fieldActions.forEach(function (action) {
                $scope.setFieldAction(action, action.fieldAction, false);
            });

        }
    }
    $scope.getFormattedDate = function (datevalue) {
        var mm = datevalue.getMonth() + 1;
        var dd = datevalue.getDate();
        var yyyy = datevalue.getFullYear();
        var date = mm + '/' + dd + '/' + yyyy;
        return date;
    }

    $scope.getFormattedTime = function (datevalue) {
        //var timevalue = new Date().getTime();
        var d = new Date(datevalue);
        var hh = d.getHours();
        var mm = d.getMinutes();
        var ss = d.getSeconds();
        var time = hh + ':' + mm;
        return time;
    }

    //This function is used to check one condition is valid or not based on the selected operator
    $scope.isConditionValid = function (condition) {
        if (condition.sourceCtrlType == null) {
            return false;
        }
        var fieldValue = $scope.model[condition.fieldName];
        if (condition.sourceCtrlType.toLowerCase() == "select" || (condition.sourceCtrlType.toLowerCase() == "address" && condition.fieldName.indexOf("A6") != -1)) {

            if (condition.comapareCondition == enum_conditionTypes.is || condition.comapareCondition == enum_conditionTypes.isNot) {
                fieldValue = $("select[name='" + condition.fieldName + "'] option:selected").val();
                // alert(fieldValue);
                if (condition.comaparevalue == null && (typeof fieldValue == 'undefined' || fieldValue == "")) {
                    return true;
                }
            }

            else
                fieldValue = $("select[name='" + condition.fieldName + "'] option:selected").attr("optionText"); //$("#" + condition.fieldName + " option:selected").attr("optionText");

        }
        if (condition.sourceCtrlType.toLowerCase() == "radio" || condition.sourceCtrlType.toLowerCase() == "segment") {
            if (condition.comapareCondition == enum_conditionTypes.is || condition.comapareCondition == enum_conditionTypes.isNot) {
                fieldValue = $("input[name=" + condition.fieldName + "]:checked").val();
                if (condition.comaparevalue == null && typeof fieldValue == 'undefined') {
                    return true;
                }
            }

            else
                fieldValue = $("input[name=" + condition.fieldName + "]:checked").attr("optionText");
            // alert(fieldValue);
        }
        if (condition.sourceCtrlType.toLowerCase() == "checkboxlist") {
            var checkboxName = condition.fieldName;
            var values = '';
            fieldValue = $("input[name=" + condition.fieldName + "]:checked").val();
            if (condition.comapareCondition == enum_conditionTypes.is || condition.comapareCondition == enum_conditionTypes.isNot) {
                if (condition.comaparevalue == null && typeof fieldValue == 'undefined') {
                    return true;
                } else {
                    $("[name=" + checkboxName + "]:checked").map(function () {
                        if (values.length == 0) {
                            values = $(this).attr("optionValue");
                        }
                        else {
                            values += "," + $(this).attr("optionValue");
                        }
                    });
                }
            }
            else {
                if (condition.comaparevalue == null && typeof fieldValue == 'undefined') {
                    return true;
                } else {
                    $("[name=" + checkboxName + "]:checked").map(function () {
                        if (values.length == 0) {
                            values = $(this).next().html().trim();
                        }
                        else {
                            values += "," + $(this).next().html().trim();
                        }
                    });
                }
            }
            // alert(values);


            //var ischecked = $("input:checkbox[name=" + checkboxName + "]:checked").attr("ng-model");
            //if(ischecked)
            //    fieldValue = $("input:checkbox[name=" + checkboxName + "]:checked").attr("optionText");

            fieldValue = values;

        }
        if (condition.sourceCtrlType.toLowerCase() == "likert") {

            if (condition.comapareCondition == enum_conditionTypes.is || condition.comapareCondition == enum_conditionTypes.isNot) {
                fieldValue = $("input[name=" + condition.fieldName + "]:checked").val();
                if (condition.comaparevalue == null && typeof fieldValue == 'undefined') {
                    return true;
                }


            }

            else
                fieldValue = $("input[name=" + condition.fieldName + "]:checked").attr("optionText");

        }

        if (typeof fieldValue == 'undefined') {

            return false;
        }
        if (condition.comapareCondition == enum_conditionTypes.is) {
            if (condition.sourceCtrlType.toLowerCase() == 'bool') {
                if (Boolean(condition.comaparevalue) == fieldValue)
                    return true;
            }
            else if (condition.sourceCtrlType.toLowerCase() == 'date') {
                if (fieldValue != "") {
                    var CompareDate = new Date(condition.comaparevalue);
                    if (CompareDate.toLocaleDateString() == fieldValue.toLocaleDateString())
                        //if (condition.comaparevalue == $scope.getFormattedDate(fieldValue))
                        return true;
                }
            }
            else if (condition.sourceCtrlType.toLowerCase() == 'time') {
                if (fieldValue != "") {
                    if (condition.comaparevalue == $scope.getFormattedTime(fieldValue))
                        return true;
                }
            } else if (condition.sourceCtrlType.toLowerCase() == "checkboxlist") {
                if (fieldValue.indexOf(condition.comaparevalue) != -1)
                    return true;
            }
            else {
                if (condition.comaparevalue == fieldValue)
                    return true;
            }
        }
        if (condition.comapareCondition == enum_conditionTypes.beginsWith) {
            if (fieldValue.startsWith(condition.comaparevalue)) {
                return true;
            }
        }
        if (condition.comapareCondition == enum_conditionTypes.endsWith) {
            if (fieldValue.endsWith(condition.comaparevalue)) {
                return true;
            }
        }
        if (condition.comapareCondition == enum_conditionTypes.contains) {

            if (fieldValue.indexOf(condition.comaparevalue) != -1) {
                return true;
            }
        }
        if (condition.comapareCondition == enum_conditionTypes.doesNotContain) {
            if (fieldValue.indexOf(condition.comaparevalue) == -1) {
                return true;
            }
        }
        if (condition.comapareCondition == enum_conditionTypes.isNot) {
            if (condition.sourceCtrlType.toLowerCase() == 'bool') {
                if (Boolean(condition.comaparevalue) != fieldValue)
                    return true;
            } else if (condition.sourceCtrlType.toLowerCase() == 'checkboxlist') {
                if (fieldValue.indexOf(condition.comaparevalue) != -1)
                    return true;
            }
            else {
                if (condition.comaparevalue.toUpperCase() != fieldValue.toUpperCase()) {
                    return true;
                }
            }
        }
        if (condition.comapareCondition == enum_conditionTypes.lessThan) {
            if (condition.sourceCtrlType.toLowerCase() == 'date') {
                if (fieldValue != "") {
                    //if (condition.comaparevalue > $scope.getFormattedDate(fieldValue))
                    var CompareDate = new Date(condition.comaparevalue);
                    if (CompareDate.toLocaleDateString() > fieldValue.toLocaleDateString())
                        return true;
                }
            }
            else if (condition.sourceCtrlType.toLowerCase() == 'time') {
                if (fieldValue != "") {
                    if (condition.comaparevalue > $scope.getFormattedTime(fieldValue))
                        return true;
                }
            }
            else {
                if (parseFloat(fieldValue) < parseFloat(condition.comaparevalue)) {
                    return true;
                }
            }

        }

        if (condition.comapareCondition == enum_conditionTypes.greaterThan) {
            if (condition.sourceCtrlType.toLowerCase() == 'date') {
                if (fieldValue != "") {
                    var CompareDate = new Date(condition.comaparevalue);
                    if (CompareDate.toLocaleDateString() < fieldValue.toLocaleDateString())
                        //if (condition.comaparevalue < $scope.getFormattedDate(fieldValue))
                        return true;
                }
            }
            else if (condition.sourceCtrlType.toLowerCase() == 'time') {
                if (fieldValue != "") {
                    if (condition.comaparevalue < $scope.getFormattedTime(fieldValue))
                        return true;
                }
            }
            else {
                if (parseFloat(fieldValue) > parseFloat(condition.comaparevalue)) {
                    return true;
                }
            }
        }


        return false;

    }
    $scope.setFieldAction = function (fieldaction, actiontype, actionstatus) {

        var defaultrequired = false;
        var hidefieldname = "hide" + fieldaction.fieldName;
        var requiredField = "required" + fieldaction.fieldName;
        //get the default required configured for this field from form designer.
        var ecDesignerRequired = $("input[name=" + fieldaction.fieldName + "]").attr("ec-DesignerRequired");

        if (typeof defaultrequired != "undefined") {
            defaultrequired = ecDesignerRequired == "False" ? false : true;
        }



        if (actiontype == enum_fieldActions.Show) {
            $scope[hidefieldname] = !actionstatus;//false            
            $scope[requiredField] = actionstatus && defaultrequired;//true
        }
        if (actiontype == enum_fieldActions.Hide) {
            $scope[hidefieldname] = actionstatus;//false            
            $scope[requiredField] = !actionstatus && defaultrequired;//true
        }
        if (actiontype == enum_fieldActions.Required) {
            $scope[requiredField] = actionstatus;
            if (actionstatus == true)
                $scope[hidefieldname] = false;
        }

        if (actiontype == enum_fieldActions.NotRequired) {
            $scope[requiredField] = !actionstatus;

        }
        if (!$scope.$$phase) $scope.$apply();
    }
    $scope.setFormAction = function (formaction, actiontype, actionstatus) {
        if (actiontype == enum_formActions.ShowMessage) {
            $scope.formlevelSettings.confirmationOption = 1;//false            
            $scope.formlevelSettings.confirmationValue = formaction.formShowmsgValue;
        }
        else if (actiontype == enum_formActions.RedirectToWebsite) {
            $scope.formlevelSettings.confirmationOption = 0;//false            
            $scope.formlevelSettings.confirmationValue = formaction.formWebsiteValue;
        }
        else if (actiontype == enum_formActions.SendEmail) {
            //$scope.formlevelSettings.confirmationEmail.IsConfirmationEmail = true;
            //$scope.formlevelSettings.confirmationEmail.IsIncludeEntityData = true;
            //$scope.formlevelSettings.confirmationEmail.sendTo = pageaction.pageActionValue;
        }
        if (!$scope.$$phase) $scope.$apply();
    }
    $scope.setPageAction = function (formaction) {
        $scope.dividfornext = "step-" + (formaction.PageAction - 1);
        //$scope.dividforprevious = "step-" + ((parseInt(divid.split('-')[1]) + 1).toString());
    }
    $scope.formreset = function () {
        $scope.model = {
        };
        $scope.showForm = true;
    };

    $scope.showSelectValue = function (mySelect) {
        var DropDownSelectedValue = $("#mySelect :selected").val();
    }

    $scope.modelhelper = {
        currentDate: new Date()
    };
    $scope.uploadFile = function () {
        var filename = event.target.files[0].name;
        //  alert('file was selected: ' + filename);
    };

    $scope.validateForm = function (ngForm, divid) {
        debugger;
        //var curStep = $(this).closest(".setup-content"),
        //   curStepBtn = curStep.attr("id"),
        //   nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
        //   curInputs = curStep.find("input[type='text'],input[type='url']");
        $scope.dividfornext = divid;
        //$scope.dividforprevious = "step-" + ((parseInt(divid.split('-')[1]) + 1).toString());
        var formSettings = $scope.formlevelSettings;
        if (formSettings.RuleEnable != false && formSettings.pagerules != null) {
            formSettings.pagerules.forEach(function (rule) {
                $scope.executePageRule(rule, divid);
            });
        }

        var curStepBtn = $scope.dividfornext;
        var nextStepWizard;
        if (curStepBtn == "step-0")
            nextStepWizard = $('div.setup-panel div a[href="#' + "step-1" + '"]');
        else
            nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a");
        $scope.isValid = true;
        var curInputs = $("#" + divid).find(".wizardValidation");

        $(".form-group").removeClass("has-error");


        if (ngForm.$invalid) {
            $scope.ChekSubmitAttempt = false;
            $scope.invalidSubmitAttempt = true;
            $scope.isValid = true;


            // var myForm = $scope.eCubeForm;
            angular.forEach(ngForm, function (value, key) {
                if (typeof value === 'object' && value.hasOwnProperty('$modelValue') && value.$invalid) {
                    for (var i = 0; i < curInputs.length; i++) {
                        var controlName = curInputs[i].name;
                        if (controlName == value.$name) {
                            $scope.isValid = false;
                            return;
                        }

                    }

                }
            });

        }

        if ($scope.isValid) {
            //ProgressBar showing

            if ($scope.PagesCount != 0) {
                $('.progress').css("display", "block");
                $scope.initwdith = $scope.progressWidth + $scope.initwdith;
                $(".progress-bar").css("width", $scope.initwdith + '%');
                var roundvalue = Math.ceil($scope.initwdith);
                $(".progress-bar").html(roundvalue);
            }

            nextStepWizard.removeAttr('disabled').trigger('click');
        }
    }
    $scope.PrevButtonClick = function (ngForm, stepid) {
        //ProgressBar showing
        if ($scope.PagesCount != 0) {
            $scope.initwdith = $scope.initwdith - $scope.progressWidth;
            $(".progress-bar").css("width", $scope.initwdith + '%');
            var roundvalue = Math.ceil($scope.initwdith);
            $(".progress-bar").html(roundvalue);
        }
        $scope.dividforprevious = stepid;
        var iValue; var count = 0;
        var formSettings = $scope.formlevelSettings;
        if (formSettings.RuleEnable != false && formSettings.pagerules != null) {
            formSettings.pagerules.forEach(function (rule) {
                rule.fieldConditions.forEach(function (condition) {
                    if ($scope.isConditionValid(condition)) {
                        rule.pageActions.forEach(function (action) { //loop through all the configured field actions
                            if ("step-" + (action.PageAction) == stepid) {
                                if (rule.fieldConditions.length >= 2 && rule.conditionsJoinRule == enum_conditionJoinOp.And) {
                                    count++;
                                    //this condition is checked for in and condition when user click on previous need to check all field conditions. 
                                    if (count == rule.fieldConditions.length) {
                                        //get the all step div's
                                        var siblings = $('#' + stepid).parent().children();
                                        if (condition.sourceCtrlType.toLowerCase() == "radio" || condition.sourceCtrlType.toLowerCase() == "checkboxlist" || condition.sourceCtrlType.toLowerCase() == "segment") {
                                            $scope.optionText = $("input[name=" + condition.fieldName + "]:checked").attr("optionText");
                                        } else if (condition.sourceCtrlType.toLowerCase() == "likert") {
                                            $scope.optionText = condition.comaparevalue;
                                        }
                                        else {
                                            $scope.optionText = "";
                                        }
                                        //loop through all pages for check the page having condition field or not.
                                        for (var i = 1; i < siblings.length; i++) {
                                            if (angular.equals($('#' + siblings[i].id).find('#' + condition.fieldName + $scope.optionText).length, 0)) {
                                                continue;
                                            }
                                            else {
                                                iValue = siblings[i].id;
                                                break;
                                            }
                                        }
                                        // loop through all div's having condition field based upon that we can assign the value for previous divid.
                                        for (var i = parseInt(iValue.split('-')[1]) ; i > 0 ; i--) {
                                            if (angular.equals($('#' + 'step-' + i).find('#' + condition.fieldName + $scope.optionText).length, 1)) {
                                                $scope.dividforprevious = "step-" + (i + 1);
                                                break;
                                            }
                                        }
                                    }
                                } else {
                                    //get the all step div's
                                    var siblings = $('#' + stepid).parent().children();
                                    //loop through all pages for check the page having condition field or not.
                                    for (var i = 1; i < siblings.length; i++) {
                                        if (condition.sourceCtrlType.toLowerCase() == "radio" || condition.sourceCtrlType.toLowerCase() == "checkboxlist" || condition.sourceCtrlType.toLowerCase() == "segment") {
                                            var fieldvalue = $("input[name=" + condition.fieldName + "]:checked").attr("optionText");
                                            if (condition.comaparevalue == null && typeof fieldvalue == 'undefined') {
                                                $scope.optionTextValue = "";
                                            }
                                            else {
                                                $scope.optionTextValue = fieldvalue;
                                            }
                                        } else if (condition.sourceCtrlType.toLowerCase() == "likert") {
                                            $scope.optionTextValue = condition.comaparevalue;
                                        }
                                        else {
                                            $scope.optionTextValue = "";
                                        }
                                        if (angular.equals($('#' + siblings[i].id).find('#' + condition.fieldName + $scope.optionTextValue).length, 0)) {
                                            continue;
                                        }
                                        else {
                                            iValue = siblings[i].id;
                                            break;
                                        }

                                    }
                                    for (var i = parseInt(iValue.split('-')[1]) ; i > 0 ; i--) {
                                        if (angular.equals($('#' + 'step-' + i).find('#' + condition.fieldName + $scope.optionTextValue).length, 1)) {
                                            $scope.dividforprevious = "step-" + (i + 1);
                                            break;
                                        }
                                    }
                                }

                            }
                        });

                    }
                });

            });
        }

        var curStepBtn = $scope.dividforprevious,
            prevStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().prev().children("a");

        $(".form-group").removeClass("has-error");
        prevStepWizard.removeAttr('disabled').trigger('click');

    }


    //ProgressBar showing
    $('.stepwizard-step a').click(function (evt) {
        evt.preventDefault();
        $scope.CurrentStep = $(this).html();
        if ($scope.PagesCount != 0) {
            $scope.initwdith = ($scope.CurrentStep - 1) * $scope.progressWidth;
            $(".progress-bar").css("width", $scope.initwdith + '%');
            var roundvalue = Math.ceil($scope.initwdith);
            $(".progress-bar").html(roundvalue);
        }

    });


    $scope.checkPassword = function (ngForm) {
        if (ngForm.$invalid) {
            $http.post('/SwiftForms/checkPassword', { entity: FromID, password: langcode })
            .success(function (data) {
                //    console.log(data);
            }).error(function (e) {
                console.log(e);
            });
        }
    }


    //created by arun for reload form after submiting data
    //$scope.pagereload = function ()
    //{

    //    window.location.reload();

    //}
    //for unique validation enter press
    $scope.blurOnEnter = function ($event) {
        //console.log($event.keyCode);

        if ($event.keyCode != 13) {
            return
        }
        $event.target.blur();

    }
    $scope.executeFormRule = function (rule) {
        var formActions;
        var isConditionSuccessCount = 0;
        //loop through all conditions on a rule
        rule.fieldConditions.forEach(function (condition) {
            if ($scope.isConditionValid(condition)) {
                isConditionSuccessCount++;
            }
        });
        //get the actions on field to a variable
        formActions = rule.formActions;
        //if all the configured condtions are checked and the join condition is AND
        if (isConditionSuccessCount == rule.fieldConditions.length && rule.conditionsJoinRule == enum_conditionJoinOp.And)//1 means AND
        {
            //loop through all the field actions
            formActions.forEach(function (action) { //loop through all the configured field actions
                $scope.setFormAction(action, action.formAction, true);
            });
        }
            //if all the configured condtions are checked (at least one condition satisfied) and the join condition is OR
        else if (isConditionSuccessCount > 0 && rule.conditionsJoinRule == enum_conditionJoinOp.Or) { // 2 means OR               
            formActions.forEach(function (action) {
                $scope.setFormAction(action, action.formAction, true);
            });
        }

    }
    $scope.executePageRule = function (rule, divid) {
        var pageActions;
        var isConditionSuccessCount = 0;
        //loop through all conditions on a rule
        rule.fieldConditions.forEach(function (condition) {
            if (rule.fieldConditions.length >= 2 && rule.conditionsJoinRule == enum_conditionJoinOp.And) {
                if (condition.sourceCtrlType.toLowerCase() == "radio" || condition.sourceCtrlType.toLowerCase() == "checkboxlist" || condition.sourceCtrlType.toLowerCase() == "segment") {
                    var fieldValue = $("input[name=" + condition.fieldName + "]:checked").attr("optionText");
                    if (condition.comaparevalue == null && typeof fieldValue == 'undefined') {
                        $scope.optionvalue = "";
                    }
                    else {
                        $scope.optionvalue = fieldValue;
                    }
                } else if (condition.sourceCtrlType.toLowerCase() == "likert") {
                    $scope.optionvalue = condition.comaparevalue;
                }
                else {
                    $scope.optionvalue = "";
                }
                //get the all step div's
                if (angular.equals($('#' + divid).find('#' + condition.fieldName + $scope.optionvalue).length, 1)) {
                    if ($scope.isConditionValid(condition)) {
                        isConditionSuccessCount++;
                    }
                    rule.fieldConditions.forEach(function (condition) {
                        var siblings = $('#' + divid).siblings();
                        //loop through all pages for check the page having condition field or not.
                        for (var i = 1; i < siblings.length; i++) {
                            if (angular.equals($('#' + siblings[i].id).find('#' + condition.fieldName + $scope.optionvalue).length, 0)) {
                                continue;
                            }
                            else {
                                if ($scope.isConditionValid(condition)) {
                                    isConditionSuccessCount++;
                                }
                            }
                        }
                    })
                }
            } else {
                if (condition.sourceCtrlType.toLowerCase() == "radio" || condition.sourceCtrlType.toLowerCase() == "checkboxlist" || condition.sourceCtrlType.toLowerCase() == "segment") {
                    var fieldValue = $("input[name=" + condition.fieldName + "]:checked").attr("optionText");
                    if (condition.comaparevalue == null && typeof fieldValue == 'undefined') {
                        $scope.optionvalue = "";
                    }
                    else {
                        $scope.optionvalue = fieldValue;
                    }
                } else if (condition.sourceCtrlType.toLowerCase() == "likert") {
                    $scope.optionvalue = condition.comaparevalue;
                }
                else {
                    $scope.optionvalue = "";
                }

                if (angular.equals($('#' + divid).find('#' + condition.fieldName + $scope.optionvalue).length, 0)) {
                    return;
                }
                else {
                    if ($scope.isConditionValid(condition)) {
                        isConditionSuccessCount++;
                    }
                }

            }

        });
        //get the actions on field to a variable
        pageActions = rule.pageActions;
        //if all the configured condtions are checked and the join condition is AND
        if (isConditionSuccessCount == rule.fieldConditions.length && rule.conditionsJoinRule == enum_conditionJoinOp.And)//1 means AND
        {
            //loop through all the field actions
            pageActions.forEach(function (action) { //loop through all the configured field actions
                $scope.setPageAction(action);
            });
        }
            //if all the configured condtions are checked (at least one condition satisfied) and the join condition is OR
        else if (isConditionSuccessCount > 0 && rule.conditionsJoinRule == enum_conditionJoinOp.Or) { // 2 means OR               
            pageActions.forEach(function (action) {
                $scope.setPageAction(action);
            });
        }

    }


    //var frmdata = new FormData();
    $scope.save = function (ngForm) {


        $scope.FormEndTime = new Date().getTime();

        if (ngForm.$invalid) {
            $scope.ChekSubmitAttempt = false;
            $scope.invalidSubmitAttempt = true;
            return;
        }
        // to add the share id to model 
        if ($("#hdpublicshareid").val() != undefined) {

            var shareid = $parse("shareid");
            shareid.assign($scope.model, $("#hdpublicshareid").val());
        }

        if (!$scope.paymentSettings) {

            delete this.model.paymentjson;

        }


        this.model.F6 = window.name;
		this.model.formid = 3622;
		this.model.shareid = 0;

        $("#btnsubmit").html('Sending...');
        //$("#loading").show();
        swiftDataCUService.saveModel(this.model, this.files)
         .success(function (response) {
             var mailurl = "https://Custom.ecubeapps.com/Custom/ContactformSendemail";
             var emailtemplatename = "Contactform.html";
             var fullurl = window.location.host.split('.')[1];
             var logoimage, Regardsmsg, subjectmsg;
             if (fullurl =='ecubeapps') {
                 logoimage = "ecubelogo.png";
                 Regardsmsg = "ecubeApps";
                 subjectmsg = "ecubeApps - ContactForm"
             }
             else if (fullurl == 'ispatialtec') {
                 logoimage = "ispatialteclogo.png";
                 Regardsmsg = "iSpatialTechnoSolutions";
                 subjectmsg = "iSpatialTechnoSolutions - ContactForm"
             }
             else if (fullurl =='ecubesoftware') {
                 logoimage = "ecubeSoftwarelogo.png";
                 Regardsmsg = "eCubeSoftware";
                 subjectmsg = "eCubeSoftware - ContactForm"
             }
             else if (fullurl =='smartpermit') {
                 logoimage = "smartPermitlogo.png";
                 Regardsmsg = "SmartPermit";
                 subjectmsg = "SmartPermit - ContactForm"
             }
             else if (fullurl =='smartfieldgeo') {
                 logoimage = "smartFieldlogo.png";
                 Regardsmsg = "SmartFieldGeo";
                 subjectmsg = "SmartFieldGeo - ContactForm"
             }
             else if (fullurl == 'smartgeoapp') {
                 logoimage = "smartGeoapplogo.png";
                 Regardsmsg = "SmartGeoApps";
                 subjectmsg = "SmartGeoApps - ContactForm"
             }
             $.ajax({
                 url: mailurl,
                 type: 'POST',
                 data: {
                     name: response.F1,
                     emailids: response.F2,
                     message: response.F4,
                     subject: subjectmsg,
                     templatename: emailtemplatename,
                     backgroundimage: "",
                     logoimg: logoimage,
                     Regards: Regardsmsg
                 },
                 success: function (result) {
                     var smsurl = "https://Custom.ecubeapps.com/Custom/Sendsms";
                     $.ajax({
                         url: smsurl,
                         type: 'POST',
                         data: {
                             username: "ispatecsol",
                             password: "ispatec123",
                             Senderid: "iSpaTS",
                             Tonumber: "9949068658,9100634846",
                             message: "You got a new message from " + Regardsmsg,
                             datetime: ""
                         },
                         success: function (resultvalue) {

                             var Indata = { 'modeljson': JSON.stringify(response), 'Formid': response.formid, 'Emailid': "connectus@iSpatialtec.com", 'EmailDesc': "Contact form data" };

                             $http({
                                 method: "POST",
                                 url: "/SwiftForms/SendEmail/",
                                 data: Indata

                             }).success(function (data) {
                                 $scope.model = {};
                                 $("#btnsubmit").html('Send message');
                                 $("#success").show();
								 $( "#success" ).fadeIn( 300 ).delay( 1500 ).fadeOut( 1500 );
                                 $scope.eCubeForm.$setPristine();
								  $scope.ChekSubmitAttempt = true;
                                   $scope.invalidSubmitAttempt = false;
                             })
                         }
                     })
                 }
             })




         })
         .error(function (err) {
             $("#btnsubmit").html('Send message');
             //$("#loading").hide();
             $scope.invalidSubmitAttempt = true;
             if (err.Message.toLowerCase().indexOf("validation failed") >= 0) {
                 $("#divValidation").show();
                 $("#spnValidationMessages").text(jqXHR.Message);
             } else if (err.Message.toLowerCase().indexOf("your entries  limit") >= 0) {
                 $("#divValidation").hide();
                 $("#diventrieslimitmessage").removeClass("hide");
             }
             else {
                 bootbox.alert({
                     size: 'small',
                     title: lang1.appHeading,
                     message: lang1.unablecreaterecord,
                     animate: true,
                     callback: function () { /* your callback code */
                     }
                 })
             }
             //try {
             //    responseText = jQuery.parseJSON(xhr.responseText);
             //} catch (e) {
             //    responseText = xhr.responseText;
             //    //alert(responseText);
             //}
         });



        // console.log(status);

    }


    $scope.savefee = function (ngForm) {


        $scope.FormEndTime = new Date().getTime();

        if (ngForm.$invalid) {
            $scope.ChekSubmitAttempt = false;
            $scope.invalidSubmitAttempt = true;
            return;
        }


        $("#divProcessing").show();
        swiftDataCUService.saveModel(this.model, this.files)
         .success(function (response) {

             //  $("#divthanyoumessage").removeClass("hide");
             $(".ecubeForm").addClass('hide');
             $(".feeclass").removeClass('hide');

             var formSettings = $scope.formlevelSettings;
             //   $("#divthanyoumessage").removeClass("hide");
             //  $("#swiftformsControlsRoot").addClass("hide");
             $("#divProcessing").hide();
             $scope.showForm = false;
             //this line needs to be removed later after implementing the formlevel settings option. Present the code was commented for this build. written by shanmu
             if (typeof (formSettings) == 'undefined') {
                 if ($("#hdloginid").val() != "" && $("#hdloginid").val() != "0") {
                     //  setTimeout("location.reload(true);", 1000);
                     $(".ecubeForm").addClass('hide');
                     $(".feeclass").removeClass('hide');


                 }
             }

             //till here

             if (!formSettings) //if there is no data
                 formSettings = {
                 };
             else {
                 if (formSettings.RuleEnable != false && formSettings.formrules != null) {
                     formSettings.formrules.forEach(function (rule) {
                         $scope.executeFormRule(rule);
                     });
                 }
             }

             if (formSettings.confirmationOption == 1) {
                 var html = $.parseHTML(formSettings.confirmationValue);
                 $("#divCustomMessage").text('');
                 $("#divCustomMessage").append(html);
                 $(".ecubeForm").addClass('hide');
                 $("#feerecipt").removeClass('hide');

                 // this condition created by arun for checking the user is loged in or not
                 if ($("#hdloginid").val() != "" && $("#hdloginid").val() != "0") {
                     // setTimeout("location.reload(true);", 1000);
                 }
             }
             else {
                 $("#divCustomMessage").text("Thank you for filling this form.");
                 if ($("#hdloginid").val() != "" && $("#hdloginid").val() != "0") {

                     if (formSettings.confirmationValue) {
                         $(".ecubeForm").addClass('hide');
                         $(".feeclass").removeClass('hide');
                         //setTimeout(function () {
                         //    window.location.href = formSettings.confirmationValue;
                         //}, 3000);
                     }
                     else {
                         // setTimeout("location.reload(true);", 1000);
                     }

                 }
             }

         })
         .error(function (err) {
             $("#divProcessing").hide();
             $scope.invalidSubmitAttempt = true;
             if (err.Message.toLowerCase().indexOf("validation failed") >= 0) {
                 $("#divValidation").show();
                 $("#spnValidationMessages").text(jqXHR.Message);
             } else {
                 bootbox.alert({
                     size: 'small',
                     title: lang1.appHeading,
                     message: lang1.unablecreaterecord,
                     animate: true,
                     callback: function () { /* your callback code */
                     }
                 })
             }
             //try {
             //    responseText = jQuery.parseJSON(xhr.responseText);
             //} catch (e) {
             //    responseText = xhr.responseText;
             //    //alert(responseText);
             //}
         });



        // console.log(status);

    }


    $scope.saveFormPreview = function (ngForm) {
        if (ngForm.$invalid) {
            $scope.ChekSubmitAttempt = false;
            $scope.invalidSubmitAttempt = true;
            return;
        }
    }

    $scope.ShowTextareaCount = function (maxlength) {
        var text_max = maxlength;
        //alert("here" + maxlength);

        var text_length = $('.textarea').val().length;
        var text_remaining = text_max - text_length;
        $('#textarea_max').html('Max Allowed:' + text_max + ' Charecters ');
        $('#textarea_current').html('Currently Used:' + text_length + ' Charecters ');

    }
    $scope.ValidateFile = function (validFileTypes, fileName) {
        var Isvalid = false;
        for (var i = 0; i < validFileTypes.length; i++) {
            if (fileName.toUpperCase().indexOf(validFileTypes[i].toUpperCase()) != -1) {
                //if ("." + filetype.toUpperCase() == validFileTypes[i].toUpperCase()) {              
                Isvalid = true;
                break;
            }
        }


        return Isvalid;
    }
    $scope.toggleAdd = function () {
        $scope.addMode = !$scope.addMode;
    };
    $scope.changeLanguage = function (langKey) {
        console.log("selected language " + langKey);
        if (langKey == "1") {
            $scope.loadjscssfile("../../Content/bootstrap-rtl.min.css", "css");
        }
        else {
            $scope.removejscssfile("../../Content/bootstrap-rtl.min.css", "css");
        }

    };
    $scope.ShowFormLanguage = function (FromID, langcode) {
        // $http.post('/SwiftForms/GetAllLanguagesData', { entity: FromID, langcode: langcode })
        var url = "";
        if (window.location.hostname == "localhost")
            url = '@Url.Action("GetAllLanguagesData", "SwiftForms")';
        else if (window.location.hostname.toLowerCase().indexOf("ecubeforms.com") > -1) {
            url = '@Url.Action("GetAllLanguagesData", "SwiftForms")';
        }
        else if (window.location.hostname.toLowerCase().indexOf("smartgeoapps.com") > -1) {
            url = '@Url.Action("GetAllLanguagesData", "SwiftForms")';
        }
        else
            url = '@Url.Action("GetAllLanguagesData", "SwiftForms")';
        $http.post(url, { entity: FromID, langcode: langcode })
  .success(function (data) {

      //alert(data);
      //console.log(data);

  }).error(function (e) {
      console.log(e);
      alert(e.message);
  });

    }

    $scope.loadjscssfile = function (filename, filetype) {

        if (filetype == "js") { //if filename is a external JavaScript file
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", filename);
        }
        else if (filetype == "css") { //if filename is an external CSS file
            var fileref = document.createElement("link");
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", filename);
        }
        if (typeof fileref != "undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref);
    };

    $scope.removejscssfile = function (filename, filetype) {
        var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none";//determine element type to create nodelist from
        var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none"; //determine corresponding attribute to test for
        var allsuspects = document.getElementsByTagName("link");
        for (var i = allsuspects.length; i >= 0; i--) { //search backwards within nodelist for matching elements to remove
            if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
                allsuspects[i].parentNode.removeChild(allsuspects[i]); //remove element by calling parentNode.removeChild()
        }
    };


    $scope.closeAlert = function (ngform) {

        try {
            userCloseAction = true;
            //var targeturl = "../ecubeHome/ManageForms.aspx?id=" + $("[id$='hidAppId']").val();
            var targeturl = '/FormsAdmin/index';
            if ($scope.eCubeForm.$dirty) {
                bootbox.confirm({
                    size: 'small',
                    title: lang1.appHeading,
                    message: "The are unsaved changes <br> Want to stay on the page?",
                    animate: true,
                    callback: function (result) {
                        if (!result) {
                            // $scope.eCubeForm.$pristine = true;
                            window.location.href = '/FormsAdmin/index';
                        }
                    }
                })
            }
            else {
                window.location.href = '/FormsAdmin/index';
            }

        } catch (e) {
            LogError("Error", e, true);
        }

        return;
    };

    //
    //reset function to clear the form ,to clear the form status without reloading the page
    //
    $scope.resetForm = function (ngform) {

        //reset the model and files model
        //http://stackoverflow.com/questions/18874019/angularjs-set-the-model-to-be-again-doesnt-clear-out-input-type-url

        //clear the model--to clear ui for invalid data controls as well



        $scope.eCubeForm = angular.copy($scope.eCubeForm_master);
        $scope.model = angular.copy($scope.model_master);
        $scope.files = angular.copy($scope.files_master); //reset to original state
        //reset dirty state
        $scope.eCubeForm.$setPristine();
        //$scope.eCubeForm.$setValidity(); //should not use
        $scope.eCubeForm.$setUntouched();

        //clear the file and inout controls
        $("input").val(null); //clear all input controls to null
        angular.forEach(
                angular.element("input[type='file']"),
                function (inputElem) {
                    angular.element(inputElem).val(null);
                    //console.log(inputElem);
                });

        //reset the global error flag
        $scope.invalidSubmitAttempt = false;
        //$scope.eCubeForm.$rollbackViewValue();

        //console.log("clear");

    }


    //Date Picker Functions Start

    $scope.formats = ['dd-MMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    $scope.dateformat = $scope.formats[0];
    $scope.datedisplayformat = $scope.formats[0];

    $scope.altInputFormats = ['M!/d!/yyyy'];

    $scope.openCalendar = function ($event, picker) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope[picker] = true;
    };

    //Date Picker Functions End

    // webcam

    //var canvas = document.getElementById("snapshotF1");
    //var ctx = canvas.getContext("2d");

    //ctx.setLineDash([5, 15]);

    //ctx.beginPath();
    //ctx.moveTo(0, 100);
    //ctx.lineTo(400, 100);
    //ctx.stroke();

    //var _video = null,
    //   patData = null;


    //$scope.patOpts = {
    //    x: 0, y: 0, w: 25, h: 25
    //};

    // Setup a channel to receive a video property
    // with a reference to the video element
    // See the HTML binding in main.html
    //$scope.channel = {
    //};

    //$scope.webcamError = false;
    //$scope.onError = function (err) {
    //    $scope.$apply(
    //        function () {
    //            $scope.webcamError = err;
    //        }
    //);
    //};

    //$scope.onSuccess = function () {

    //    // The video element contains the captured camera data
    //    _video = $scope.channel.video;
    //    $scope.$apply(function () {
    //        $scope.patOpts.w = _video.width;
    //        $scope.patOpts.h = _video.height;
    //        //$scope.showDemos = true;
    //    });
    //};

    //$scope.onStream = function (stream) {
    //    // You could do something manually with the stream.
    //};

    //$scope.makeSnapshot = function () {


    //    if (_video) {
    //        var patCanvas = document.querySelector('#snapshot'); // not dynamic
    //        if (!patCanvas) return;

    //        patCanvas.width = _video.width;
    //        patCanvas.height = _video.height;
    //        var ctxPat = patCanvas.getContext('2d');

    //        var idata = getVideoData($scope.patOpts.x, $scope.patOpts.y, $scope.patOpts.w, $scope.patOpts.h);
    //        ctxPat.putImageData(idata, 0, 0);

    //        var wc = $("#webcam").attr('ng-model'); // not dynamic
    //        var wcparse = $parse(wc);
    //        $(".wcm1").addClass('hide'); // not dynamic
    //        $(".snap").addClass('hide'); // not dynamic
    //        $(".stream").removeClass('hide'); // not dynamic
    //        $(".snapclass").removeClass('hide'); // not dynamic
    //        var model = $parse(wc);
    //        model.assign($scope, patCanvas.toDataURL());

    //        patData = idata;
    //    }
    //};

    //navigator.getMedia = (navigator.getUserMedia || // use the proper vendor prefix
    //               navigator.webkitGetUserMedia ||
    //               navigator.mozGetUserMedia ||
    //               navigator.msGetUserMedia);

    //navigator.getMedia({ video: true }, function () {
    //    $(".Camerabtn").removeClass('hide');
    //}, function () {
    //    $scope.CheckCam = false;
    //    $(".snabtnclass").addClass('hide');
    //    $(".canvasclass").removeClass('hide');
    //    $(".webcam").addClass('hide');
    //});


    //$scope.makeSnapshot = function (FieldId) {

    //    if (_video) {
    //        var patCanvas = document.querySelector('#snapshot' + FieldId);
    //        if (!patCanvas) return;

    //        patCanvas.width = _video.width;
    //        patCanvas.height = _video.height;
    //        var ctxPat = patCanvas.getContext('2d');
    //        var idata = getVideoData($scope.patOpts.x, $scope.patOpts.y, $scope.patOpts.w, $scope.patOpts.h);
    //        ctxPat.putImageData(idata, 0, 0);
    //        var wc = $("#webcamhidden" + FieldId).attr('ng-model');
    //        var wcparse = $parse(wc);
    //        $(".webcam" + FieldId).addClass('hide');
    //        $(".snapbtn" + FieldId).addClass('hide');
    //        $(".streambtn" + FieldId).removeClass('hide');
    //        $(".snapshotclass" + FieldId).removeClass('hide');
    //        $(".browsbtn" + FieldId).removeClass('hide');

    //        document.getElementById('imgctrl' + FieldId).setAttribute('src', patCanvas.toDataURL());

    //        var model = $parse(wc);
    //        model.assign($scope, patCanvas.toDataURL());
    //        patData = idata;
    //    }
    //};

    //$scope.Livestreeming = function (FieldId) {
    //    $(".browsbtn" + FieldId).addClass('hide');
    //    $(".webcam" + FieldId).removeClass('hide');
    //    $(".snapbtn" + FieldId).removeClass('hide');
    //    $(".streambtn" + FieldId).addClass('hide');
    //    $(".snapshotclass" + FieldId).addClass('hide');

    //};

    //var getVideoData = function getVideoData(x, y, w, h) {
    //    var hiddenCanvas = document.createElement('canvas');
    //    hiddenCanvas.width = _video.width;
    //    hiddenCanvas.height = _video.height;
    //    var ctx = hiddenCanvas.getContext('2d');
    //    ctx.drawImage(_video, 0, 0, _video.width, _video.height);
    //    return ctx.getImageData(x, y, w, h);
    //};

    //var sendSnapshotToServer = function sendSnapshotToServer(imgBase64) {
    //    $scope.snapshotData = imgBase64;
    //};




    // Payment json object


    $scope.paymentjson = {
        "paymentGateWAy": {
            "gatewaycredentials": {
                "payPalAccount": "arunaenamyna@gmail.com",
                "currencyId": "USD",
                "languageId": "EN"
            },
            "paymentTypeOptions": {
                "paymentTypeId": 3,
                "paymentBoxSubLabel": "buy me a tea",
                "suggestanAmount": true,
                "SuggestedAmount": "100",
                "sugeestedminAmount": true
            },
            "additionalGatewaySettings": {
                "multiple": true,
                "showTotalPriceontheForm": true,
                "sandboxMode": true,
                "authorizationOnly": true,
                "requireShipmentAddress": true,
                "IPNRelayURL": "www.google.com",
                "pendingPaymentEmailId": ""
            }
        },
        "products": [
          {
              "objectid": "P1",
              "name": "iball",
              "description": "iballdesc",
              "price": "75",
              "producttotal": 75,
              "discountedproducttotal": 50,
              "image": "Chrysanthemum.jpg",
              "required": true,
              "selectedbyDefault": true,
              "showsubtotalonForm": true,
              "stock": "",
              "shippingCost": {
                  "shippingByquantity": {
                      "firstItem": "100",
                      "addItem": "10"
                  },
                  "shippingByweight": {
                      "unit": "",
                      "value": ""
                  }
              },
              "qtyList": [
                {
                    "quantutyShowtypeId": "dropdown",
                    "label": "Quantity",
                    "range": {
                        "minRange": 1,
                        "maxRange": 10
                    },
                    "specialPricingPerQuantity": true,
                    "defaultQuantity": 1,
                    "selectedQuantity": 1,
                    "quantityItemsList": [
                      {
                          "quantity": 1,
                          "price": 75,
                          "$$hashKey": "object:286"
                      },
                      {
                          "quantity": 2,
                          "price": 200,
                          "$$hashKey": "object:287"
                      },
                      {
                          "quantity": 3,
                          "price": 300,
                          "$$hashKey": "object:288"
                      },
                      {
                          "quantity": 4,
                          "price": 400,
                          "$$hashKey": "object:289"
                      },
                      {
                          "quantity": 5,
                          "price": 500,
                          "$$hashKey": "object:290"
                      },
                      {
                          "quantity": 6,
                          "price": 600,
                          "$$hashKey": "object:291"
                      },
                      {
                          "quantity": 7,
                          "price": 700,
                          "$$hashKey": "object:292"
                      },
                      {
                          "quantity": 8,
                          "price": 800,
                          "$$hashKey": "object:293"
                      },
                      {
                          "quantity": 9,
                          "price": 900,
                          "$$hashKey": "object:294"
                      },
                      {
                          "quantity": 10,
                          "price": 950,
                          "$$hashKey": "object:295"
                      }
                    ]
                }
              ],
              "options": [
                {
                    "label": "color",
                    "createSubProductsfromOptions": false,
                    "populateOptionsPresetsId": "color",
                    "optionslist": [
                      "Red",
                      "Blue",
                      "Green",
                      "Yellow",
                      "Magenta",
                      ""
                    ],
                    "optionsid": 0
                }
              ],
              "CouponCodes": [
                "C1",
                //"C1",
                "C2"
              ]
          },
          {
              "objectid": "P2",
              "name": "Acer",
              "description": "Acer Aspirenotebook",
              "price": "100",
              "producttotal": 100,
              "discountedproducttotal": 50,
              "image": "Chrysanthemum.jpg",
              "required": true,
              "selectedbyDefault": true,
              "showsubtotalonForm": true,
              "stock": "",
              "shippingCost": {
                  "shippingByquantity": {
                      "firstItem": "10",
                      "addItem": "5"
                  },
                  "shippingByweight": {
                      "unit": "",
                      "value": ""
                  }
              },
              "qtyList": [
                {
                    "quantutyShowtypeId": "custom",
                    "label": "Quantity",
                    "range": {
                        "minRange": 1,
                        "maxRange": 10
                    },
                    "specialPricingPerQuantity": true,
                    "defaultQuantity": 1,
                    "selectedQuantity": 1,
                    "quantityItemsList": [
                      {
                          "quantity": 1,
                          "price": 100,
                          "$$hashKey": "object:286"
                      },
                      {
                          "quantity": 2,
                          "price": 150,
                          "$$hashKey": "object:287"
                      },
                      {
                          "quantity": 3,
                          "price": 300,
                          "$$hashKey": "object:288"
                      },
                      {
                          "quantity": 4,
                          "price": 400,
                          "$$hashKey": "object:289"
                      },
                      {
                          "quantity": 5,
                          "price": 500,
                          "$$hashKey": "object:290"
                      },
                      {
                          "quantity": 6,
                          "price": 600,
                          "$$hashKey": "object:291"
                      },
                      {
                          "quantity": 7,
                          "price": 700,
                          "$$hashKey": "object:292"
                      },
                      {
                          "quantity": 8,
                          "price": 800,
                          "$$hashKey": "object:293"
                      },
                      {
                          "quantity": 9,
                          "price": 900,
                          "$$hashKey": "object:294"
                      },
                      {
                          "quantity": 10,
                          "price": 970,
                          "$$hashKey": "object:295"
                      }
                    ]
                }
              ],
              "options": [
                {
                    "label": "color",
                    "createSubProductsfromOptions": false,
                    "populateOptionsPresetsId": "color",
                    "optionslist": [
                      "Red",
                      "Blue",
                      "Green",
                      "Yellow",
                      "Magenta",
                      ""
                    ],
                    "optionsid": 0
                }
              ],
              "CouponCodes": [
                "C1",

                "C2"
              ]
          },
          {
              "objectid": "P3",
              "name": "asus",
              "description": "Asusdesc",
              "price": "50",
              "producttotal": 50,
              "discountedproducttotal": 50,
              "image": "Chrysanthemum.jpg",
              "required": true,
              "selectedbyDefault": true,
              "showsubtotalonForm": true,
              "stock": "",
              "shippingCost": {
                  "shippingByquantity": {
                      "firstItem": "100",
                      "addItem": "10"
                  },
                  "shippingByweight": {
                      "unit": "",
                      "value": ""
                  }
              },
              "qtyList": [
                {
                    "quantutyShowtypeId": "dropdown",
                    "label": "Quantity",
                    "range": {
                        "minRange": 1,
                        "maxRange": 10
                    },
                    "specialPricingPerQuantity": false,
                    "defaultQuantity": 1,
                    "selectedQuantity": 1,
                    "quantityItemsList": [
                      {
                          "quantity": 1,
                          "price": 100,
                          "$$hashKey": "object:286"
                      },
                      {
                          "quantity": 2,
                          "price": 150,
                          "$$hashKey": "object:287"
                      },
                      {
                          "quantity": 3,
                          "price": 300,
                          "$$hashKey": "object:288"
                      },
                      {
                          "quantity": 4,
                          "price": 350,
                          "$$hashKey": "object:289"
                      },
                      {
                          "quantity": 5,
                          "price": 500,
                          "$$hashKey": "object:290"
                      },
                      {
                          "quantity": 6,
                          "price": 600,
                          "$$hashKey": "object:291"
                      },
                      {
                          "quantity": 7,
                          "price": 700,
                          "$$hashKey": "object:292"
                      },
                      {
                          "quantity": 8,
                          "price": 800,
                          "$$hashKey": "object:293"
                      },
                      {
                          "quantity": 9,
                          "price": 900,
                          "$$hashKey": "object:294"
                      },
                      {
                          "quantity": 10,
                          "price": 980,
                          "$$hashKey": "object:295"
                      }
                    ]
                }
              ],
              "options": [
                {
                    "label": "color",
                    "createSubProductsfromOptions": false,
                    "populateOptionsPresetsId": "color",
                    "optionslist": [
                      "Red",
                      "Blue",
                      "Green",
                      "Yellow",
                      "Magenta",
                      ""
                    ],
                    "optionsid": 0
                }
              ],
              "CouponCodes": [
                "C1",

                "C2"
              ]
          }
        ],
        "coupons": {
            "couponEntries": [
              {
                  "objectid": "C1",
                  "couponCode": "JWI54",
                  "couponExpiry": {
                      "couponLimiType": "expiration",
                      "expirationDate": "2017-03-25T18:30:00.000Z",
                      "ExpirationQty": 0
                  },
                  "discountTypeId": "percent",
                  "discountRate": "15",
                  "discountAmount": 0,
                  "applyDiscountto": "product",
                  "minDiscountAmount": 0,
                  "discountedProducts": [
                    {
                        "id": "P1"
                    },
                    {
                        "id": "P2"
                    },
                    {
                        "id": "P3"
                    }
                  ]
              },
              {
                  "objectid": "C2",
                  "couponCode": "UPV81",
                  "couponExpiry": {
                      "couponLimiType": "expiration",
                      "expirationDate": "2017-02-03T18:30:00.000Z",
                      "ExpirationQty": 0
                  },
                  "discountTypeId": "percent",
                  "discountRate": "15",
                  "discountAmount": 0,
                  "applyDiscountto": "product",
                  "minDiscountAmount": 0,
                  "discountedProducts": [
                    {
                        "id": "P1"
                    },
                    {
                        "id": "P2"
                    },
                    {
                        "id": "P3"
                    }
                  ]
              }
            ],
            "enterCoupon": "",
            "apply": "",
            "change": "",
            "couponisValid": "",
            "couponisExpired": "",
            "couponisInvalid": "",
            "pleaseenteracoupon": ""
        },
        "shipping": {
            "enableShipping": true,
            "chargeBasis": "product",
            "flatRate": 0,
            "shippingTextinForm": "laptop shpping text",
            "enableWeightValue": false,
            "weightUnit": "kgs",
            "shippingProducts": []
        },
        "tax": {
            "baseTaxRate": "5",
            "exemptedProducts": [
              {
                  "id": "P1"
              },
              {
                  "id": "P2"
              }
              //},
              //{
              //    "id": "P3"
              //}
            ],
            "taxTextontheForm": "tax text"
        }


    }


    $scope.paymentjson1 = {
        "paymentGateWAy": {
            "gatewaycredentials": {
                "payPalAccount": "arunmerchant1@gmail.com",
                "currencyId": "USD",
                "languageId": "EN"
            },
            "paymentTypeOptions": {
                "paymentTypeId": 1,
                "paymentBoxSubLabel": "",
                "suggestanAmount": false,
                "SuggestedAmount": "",
                "sugeestedminAmount": false
            },
            "additionalGatewaySettings": {
                "multiple": "",
                "showTotalPriceontheForm": "",
                "sandboxMode": true,
                "authorizationOnly": "",
                "requireShipmentAddress": "",
                "IPNRelayURL": "",
                "pendingPaymentEmailId": ""
            }
        },
        "products": [
          {
              "objectid": "P1",
              "name": "laptop",
              "description": "sfsdh",
              "price": "100",
              "image": "",
              "required": "",
              "selectedbyDefault": false,
              "showsubtotalonForm": "",
              "stock": "",
              "shippingCost": {
                  "shippingByquantity": {
                      "firstItem": "",
                      "addItem": ""
                  },
                  "shippingByweight": {
                      "unit": "",
                      "value": ""
                  }
              },
              "qtyList": [
                {
                    "quantutyShowtypeId": "dropdown",
                    "label": "Quantity",
                    "range": {
                        "minRange": 1,
                        "maxRange": 10
                    },
                    "specialPricingPerQuantity": true,
                    "defaultQuantity": 1,
                    "selectedQuantity": 1,
                    "quantityItemsList": [
                      {
                          "quantity": 1,
                          "price": 100,
                          "$$hashKey": "object:260"
                      },
                      {
                          "quantity": 2,
                          "price": 200,
                          "$$hashKey": "object:261"
                      },
                      {
                          "quantity": 3,
                          "price": 300,
                          "$$hashKey": "object:262"
                      },
                      {
                          "quantity": 4,
                          "price": 400,
                          "$$hashKey": "object:263"
                      },
                      {
                          "quantity": 5,
                          "price": 500,
                          "$$hashKey": "object:264"
                      },
                      {
                          "quantity": 6,
                          "price": 600,
                          "$$hashKey": "object:265"
                      },
                      {
                          "quantity": 7,
                          "price": 700,
                          "$$hashKey": "object:266"
                      },
                      {
                          "quantity": 8,
                          "price": 800,
                          "$$hashKey": "object:267"
                      },
                      {
                          "quantity": 9,
                          "price": 900,
                          "$$hashKey": "object:268"
                      },
                      {
                          "quantity": 10,
                          "price": 1000,
                          "$$hashKey": "object:269"
                      }
                    ]
                }
              ],
              "options": [],
              "CouponCodes": []
          },
          {
              "name": "mobile",
              "price": "150",
              "description": "zxfvg",
              "selectedbyDefault": false,
              "required": false,
              "showsubtotalonForm": false,
              "qtyList": [
                {
                    "quantutyShowtypeId": "custom",
                    "label": "sfgdh",
                    "range": {
                        "minRange": 1,
                        "maxRange": 10
                    },
                    "specialPricingPerQuantity": true,
                    "selectedQuantity": 1,
                    "defaultQuantity": 1,
                    "type": "productQuantity",
                    "quantityItemsList": [
                      {
                          "quantity": 1,
                          "price": 150,
                          "$$hashKey": "object:300"
                      },
                      {
                          "quantity": 2,
                          "price": 300,
                          "$$hashKey": "object:301"
                      },
                      {
                          "quantity": 3,
                          "price": 450,
                          "$$hashKey": "object:302"
                      },
                      {
                          "quantity": 4,
                          "price": 600,
                          "$$hashKey": "object:303"
                      },
                      {
                          "quantity": 5,
                          "price": 750,
                          "$$hashKey": "object:304"
                      },
                      {
                          "quantity": 6,
                          "price": 900,
                          "$$hashKey": "object:305"
                      },
                      {
                          "quantity": 7,
                          "price": 1050,
                          "$$hashKey": "object:306"
                      },
                      {
                          "quantity": 8,
                          "price": 1200,
                          "$$hashKey": "object:307"
                      },
                      {
                          "quantity": 9,
                          "price": 1350,
                          "$$hashKey": "object:308"
                      },
                      {
                          "quantity": 10,
                          "price": 1500,
                          "$$hashKey": "object:309"
                      }
                    ]
                }
              ],
              "objectid": "P2"
          }
        ],
        "coupons": {
            "couponEntries": [],
            "enterCoupon": "",
            "apply": "",
            "change": "",
            "couponisValid": "",
            "couponisExpired": "",
            "couponisInvalid": "",
            "pleaseenteracoupon": ""
        },
        "shipping": {
            "enableShipping": true,
            "chargeBasis": "flatRate",
            "flatRate": "150",
            "shippingTextinForm": "dsgdfh",
            "enableWeightValue": false,
            "weightUnit": "lbs",
            "shippingProducts": []
        },
        "tax": {
            "baseTaxRate": "5",
            "exemptedProducts": [],
            "taxTextontheForm": "dsgfdhj"
        }
    }


    $scope.$watch('paymentSettings', function () {

        if ($scope.paymentSettings != null) {
            $scope.model.paymentjson.clientid = $scope.paymentSettings.paymentGateWAy.gatewaycredentials.payPalAccountClientId;
            $scope.model.paymentjson.clientsecret = $scope.paymentSettings.paymentGateWAy.gatewaycredentials.payPalAccountClientSecretId;
        }



        //When your value is set, you can retrieve it
        //console.log($scope.model.F100.paymentGateWAy);
    });


    //$scope.model.paypal = {};


    $scope.model.paymentjson = {
        //paymentGateWAy: {},

        clientid: '',
        clientsecret: '',
        Products: [],
        //couponObj:{},
        shipping: 0,
        tax: 0,
        subtotal: 0,
        total: 0
    };
    $scope.appliedCoupon = '';

    $scope.quantity = 1;



    //GridField related
    $scope.isEdit = 0;
    $scope.AddtoList = function (ecubeForm, fieldName, fieldList) {

        angular.forEach(fieldList, function (value, key) {
            if (ecubeForm[value].$valid != false)
                $scope.invalidSubmitAttempt1 = false;
            else {
                $scope.invalidSubmitAttempt1 = true;
                angular.forEach.break();
            }

        });

        if ($scope.invalidSubmitAttempt1)
            return;
        //console.log("form:" + eCubeForm);
        //var re = new RegExp("^F[0-9]+");
        //angular.forEach($scope.eCubeForm, function (element, name) {
        //    if (!name.startsWith('$')) {
        //        if (!re.test(name)) {
        //            if (name != "formid" || name != "fieldrule" || name != "formlevelSettings") {
        //                console.log("nameif" + $scope[name]);
        //            }
        //            //console.log("name" + name);
        //        } else {

        //        }


        //    }
        //});


        //console.log("Text4" + $scope[fieldName]);



        //if (eCubeForm.$invalid) {

        //    $scope.ChekSubmitAttempt = false;
        //    $scope.invalidSubmitAttempt = true;
        //    return;
        //}

        //console.log("fieldName :" + fieldName);

        if ($scope.model[fieldName] == null) {
            $scope.model[fieldName] = [];
        }
        if ($scope.isEdit == 0) {
            $scope.model[fieldName].push($scope[fieldName]);
            $scope[fieldName] = null;
        }
        else {
            $scope.isEdit = 0;
            $scope[fieldName] = null;
        }
    };


    $scope.EditChild = function (record, fieldName) {

        $scope[fieldName] = record;
        $scope.isEdit = 1;
    };



    $scope.DeleteChild = function (record, fieldName) {
        var index = $scope.model[fieldName].indexOf(record);
        //alert(index);
        $scope.model[fieldName].splice(index, 1);
    };


    $scope.Print = function () {

        $('.printrecipt').jqprint();


    }
	$scope.refreshcaptcha=function()
{
$http.post('/SwiftForms/getRefreshCaptcha')//getRefreshCaptcha //RefreshCaptcha
.success(function (data) {
$("#ecubeSwiftCaptchatext").val('');
$("#ecubeSwiftCaptchaKey").val('');
$("#ecubeSwiftCaptchaImage").attr("src", "");

$("#ecubeSwiftCaptchatext").val(data.CaptchaText);
$("#ecubeSwiftCaptchaKey").val(data.CaptchaEncyptedCode);
$("#ecubeSwiftCaptchaImage").attr("src", data.GetEncodedImage);
//ecubeSwiftCaptchatext,ecubeSwiftCaptchaKey,ecubeSwiftCaptchaImage
}).error(function (e) {
console.log(e);
});
}

}]);
