function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
}

function cTabs(selector){
    var hash = false;
    var initIndex = 0;
    if (window.location.hash.length > 0 ){
        hash = window.location.hash.substr(1);
        var tabname,tmp;
        if (selector == ".tabblock"){
            tabname = "tab";
        } else {
            tabname = selector;
        }
        var regex = new RegExp(""+tabname+"=(.+)");
        if (tmp = hash.match(regex)){
            hash = tmp[1];
        }
    }
    jQuery(selector + " .tabs").first().children('a').each(function(index){
       if (hash){
        regex = new RegExp(""+tabname+"=(.+)");
        if (tmp = this.href.match(regex)){
           if (tmp[1] == hash){
           jQuery(this).parent().find('a').removeClass('selected');
           jQuery(this).addClass('selected');
           initIndex = index;
           }
        }
       } else {
            if (jQuery(this).hasClass('selected') && index != initIndex){
                initIndex = index;
            }
        }

       jQuery(this).click(function(){
           jQuery(this).parent().find('a').removeClass('selected');
           jQuery(this).addClass('selected');
           jQuery(this).parent().parent().find('.tabitems').first().children('.titem').removeClass('selected');
           jQuery(this).parent().parent().find('.tabitems').first().children('.titem').each(function(indx){
               if (indx == index){
                   jQuery(this).addClass('selected');
               }
           });
       });
       jQuery(selector).find('.tabitems').first().children('.titem').removeClass('selected');
       jQuery(selector).find('.tabitems').first().children('.titem').each(function(indx){
       if (indx == initIndex){
           jQuery(this).addClass('selected');
       }
    });
    });
}
$(document).ready(function () {
    var dateNowts = Math.floor(Date.now()/1000), dateLastts = 1635206400;//2021-10-26
    var days30ts = 30*24*3600;
    if (
        window.myUserId && (/*window.adminRole === 1 || */!window.isUserInOrg) &&
        ((+window.localStorage.getItem("newui")||0) + days30ts < dateNowts)
    ){
        var daysLeft = Math.ceil((dateLastts - dateNowts)/(24*3600));
        var daysLeftText = daysLeft <= 1 ? '1 day' : daysLeft + ' days';
        window.localStorage.setItem("newui", dateNowts);
        popupFactory("New UI",
            '<div style="font-size: 20px; max-width: 760px">' +
            'Thanks to your feedback, 3DPrinterOS now sports a fresh design that looks more professional, cleaner ' +
            'and more intuitive.<br><br>' +
            'We will be discontinuing the previous UI in about '+daysLeftText+'.'+
            (daysLeft>7 ? ' We hope that this will give you enough time to get used to the new look.' : '')+
            '<br><br></div>' +
            '<img style="width: 760px" src="'+ getConst("cdn_url")  +'/assets/img/banner_new_ui.jpg" /><div> ' +
            '<input type="button" value="Cancel" class="btn w_popup red b_cancel_theme" name="cancel">' +
            '<input type="button" style="float: right"  value="Switch to New Interface" class="btn w_popup b_ok_theme" name="ok"></div>', 'none'
        );
    }

    $(document).on('click', '.b_cancel_theme', function () {
        $('#newui_3dos .close').click()
    })


    $(document).on('click', '.b_ok_theme', function () {
        $('#newui_3dos .close').click();
        if(window.adminRole === 1){
            $.post('/workgroup/set_organization_settings/', {'theme': 3}, function (data) {
                location.reload();
            }, 'json');

        }else{

            $.post('/ajax/change_theme', {'theme': 3}, function (data) {
                location.reload();
            }, 'json');
        }

        return false;
    })


    /* set theme */
    $('.set-theme').click(function(){
        $.post('/ajax/change_theme', {'theme': $(this).data('theme')}, function (data) {
            location.reload();
        }, 'json');
        return false;
    });

    /* draggable */
    var dAndDHandle = {
        handle :  'h1.title',
        cursor: "move"
    }
    if(typeof $.draggable !== 'undefined'){

        $('.simple_universal_popup').draggable(dAndDHandle);
        $('#picsUpdatePopup').draggable(dAndDHandle);
        $('#logs_popup_box').draggable(dAndDHandle);
        $('#slicer_popup').draggable(dAndDHandle);
        $('#material_info_popup').draggable(dAndDHandle);
        $('.popup_box').draggable(dAndDHandle);
        $('#console_popup').draggable(dAndDHandle);
        $('#joystick_popup').draggable(dAndDHandle);
        $('#joystick_popup').draggable(dAndDHandle);
        $('#print_check').draggable(dAndDHandle);
        $('#print_questions').draggable(dAndDHandle);

    }




    $('#menuitem_account').hover(function () {
            $(this).attr('src', getConst("cdn_url") + '/assets/i/header/hover.png');
        },
        function () {
            $(this).attr('src', getConst("cdn_url") + '/assets/i/header/cogs.png');
        });

    $('#menuitem_user').mouseenter(function () {
        $('#menuitem_account').attr('src', getConst("cdn_url") + '/assets/i/header/hover.png');
    });
    $('#menuitem_user').mouseleave(function () {
        $('#menuitem_account').attr('src', getConst("cdn_url") + '/assets/i/header/cogs.png');
    });
    if(typeof $.tablesorter !== 'undefined') {
        $.tablesorter.addParser({
            id: 'date-sorting',
            is: function (s) {
                return false;
            },
            format: function (s) {
                var match = s.match(/(\d+)\.(\d+)\.(\d+) (\S+)/);
                if (!match) {
                    return s;
                }
                return match[3] + "." + match[2] + "." + match[1] + " " + match[4];
            },
            type: 'text'
        });
        $.tablesorter.addParser({
            id: 'print-hours-sorting',
            is: function (s) {
                return false;
            },
            format: function (val) {
                var h = 0, m = 0, s = 0, match;
                match = val.match(/(\d+)h/);
                if (match) h = match[1];
                match = val.match(/(\d+)m/);
                if (match) m = match[1];
                match = val.match(/(\d+)s/);
                if (match) s = match[1];
                return h * 3600 + m * 60 + s;
            },
            type: 'numeric'
        });
        $.tablesorter.addParser({
            id: 'sort-val-sorting',
            is: function (s) {
                return false;
            },
            format: function (val, table, cell) {
                return $(cell).data('sort-val');
            },
            type: 'numeric'
        });
    }
});

function progress(percent, $element) {
    var progressBarWidth = percent * $element.width() / 100;
    $element.find('div').animate({width: progressBarWidth}, 500).html(percent + "%&nbsp;");
}
var residue  = 0;

function progress_new(percent, $element, total_duration, one_protsent) {
    var progressBarWidth = percent * $element.width() / 100;
    $element.find('div').animate({width: progressBarWidth}, 500);


	total_duration = total_duration - (percent * one_protsent) + residue; //toHHMMSS(parseInt(total_duration - (percent * one_protsent)) + residue)
	residue = getDecimal(total_duration)

    var oldProcent = parseInt($('#data-progress').text());
    if(oldProcent == percent){
        return false;
    }

	total_duration = toHHMMSS(parseInt(total_duration));

	$('#end-time-print').text(total_duration)

	if(percent == 0){
		$('#progressBar').show().addClass('heating');
		$element.find('div').html('<span id="data-progress">HEATING...</span>');
	}else{
		$('#progressBar').removeClass('heating');
		if(percent == 100){
			$('#end-time-print').text('00:00:00');
			$element.find('div').html('<span id="data-progress">PRINTING COMPLETE</span>');
		}else{
			$element.find('div').html('<span id="data-progress">' + percent + "%&nbsp;</span>");
		}
	}
}


function getDecimal(num) {

  intValue = parseInt(num);
  floatValue = num - intValue;
  return +floatValue.toFixed(6);

}

function gcode_print_time(seconds){
    var sec_num = parseInt(seconds);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);

    if (isNaN(minutes)) return '-';
    if ( !hours ) return minutes+'m';
    if ( !minutes ) return hours+'h';

    return hours+'h '+minutes+'m';
}

function toHHMMSS(sec,h24format, defVal = 'unknown') {
    if (sec==0) return defVal;
    var sec_num = parseInt(sec);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var time    =  addPaddingZero(hours)+':'+addPaddingZero(minutes);
    if ( h24format || h24format == undefined ) {
        time += ':' + addPaddingZero(sec_num % 60);
    }
    return time;
}

function toHHMM(sec, defVal = 'unknown') {
    if (sec==0) return defVal;
    var sec_num = parseInt(sec);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.ceil((sec_num - (hours * 3600)) / 60);

    return addPaddingZero(hours)+':'+addPaddingZero(minutes);
}

function toHM(sec, defVal = 'unknown') {
    if (sec==0 || sec === null) return defVal;
    var sec_num = parseInt(sec);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.ceil((sec_num - (hours * 3600)) / 60);
    return (hours>0?hours+"h ":"") + minutes + "m";
}

function isNull(a) {
    var rc = false;

    if (a === null || typeof(a) === "undefined") {
        rc = true;
    }

    return rc;
}
//===============================================
var popupIds = [
    'terms_block',
    'print_check',
    'print_questions',
    'popup_box',
    'logs_popup_box',
    'popup_box2',
    'confirm_printing_window',
    'message_window',
    'delete_confirmation_window',
    'picsUpdatePopup',
    'invite_block',
    'feedback_block'
];


/**
 * type : 1- only ok button

 */


function popupFactory(title, content, type, data, on_ok, on_cancel, inject_func, on_close, buttons) {

    $('.preloader-wrap').hide();
    //if (id == undefined) id=guid();
    if (type == undefined) type = 1;
    if (data == undefined) data = '';
    if (on_ok == undefined) on_ok = function () {
    };
    if (on_cancel == undefined) on_cancel = function () {
    };
    if (on_close == undefined) on_close = function () {
    };
    if (inject_func == undefined) inject_func = function () {
    };

    var t={};
    t.title=title;
    t.content=content;
    t.type=type;
    t.data=data;
    t.on_ok=on_ok;
    t.on_cancel=on_cancel;
    t.on_close=on_close;
    t.level = data['level']||0;
    if (data.level) {
        delete data.level;
        if ($.isEmptyObject(data)) {
            data = undefined;
        }
    }
    t.popupClass = 'simple_universal_popup_'+t.level;
    t.t_popup = $('.'+t.popupClass);
    if (t.t_popup.length==0) {
        var sup0 = 'simple_universal_popup_0', $sup0 = $('.'+sup0);
        t.t_popup = $($sup0.prop('outerHTML')).removeClass(sup0).addClass(t.popupClass).css('z-index', 100000+t.level*2);
        $sup0.parent().append(t.t_popup);
    }
    t.bgId = 'BG'+(t.level>0?'_popup_'+t.level:'');
    t.$bg = $('#'+t.bgId);
    if (t.$bg.length==0) {
        var $BG = $('#BG');
        t.$bg = $($BG.prop('outerHTML')).attr('id', t.bgId).addClass('BG-popup').css('z-index', 100000+t.level*2-1);
        $BG.parent().append(t.$bg);
    }
    if(t.title){
        var htmlId = t.title.toLowerCase().replace(/\s+/g, '').replace(/[/]/gim,'') + '_3dos';
        t.t_popup.attr('id',htmlId);
    }else{
        t.t_popup.removeAttr('id');
    }

    t.t_title = t.t_popup.find('.s_p_title');
    t.t_content = t.t_popup.find('.popup_content .popup_content_main');
    t.btn_ok = t.t_popup.find('.popup_content_buttons .b_ok');
    t.btn_close = t.t_popup.find('.popup_content_buttons .b_close');
    t.btn_cancel = t.t_popup.find('.popup_content_buttons .b_cancel');
    t.close = t.t_popup.find('.close');
    t.t_title.text(t.title);
    if (typeof(content)!='object') t.t_content.html(t.content);
    else {
        t.t_content.html('');
        t.t_content.append(t.content);
        t.t_content.children().show();
    }

    t.btn_ok.val(buttons && buttons['ok'] ? buttons['ok'] : 'Ok');
    t.btn_cancel.val(buttons && buttons['cancel'] ? buttons['cancel'] : 'Cancel');
    t.t_popup.find('.popup_content_buttons').show();

    if (type == 1) {
        t.btn_cancel.hide();
        t.btn_ok.show();
        t.btn_ok.focusin();
        t.btn_close.hide();
    }else if(type == 2){
        t.btn_cancel.hide();
        t.btn_ok.hide();
        t.btn_close.show();
    }else if(type == 'none') {
        t.t_popup.find('.popup_content_buttons').hide();
    }else {
        t.btn_cancel.show();
        t.btn_ok.show();
        t.btn_cancel.focusin(); // By default cancel is active
        t.btn_close.hide();
    }

    inject_func(t); // If need change logic or structure use injected function

    t.$bg.show();
    centrify(t.t_popup,100);
    t.t_popup.show();
    t.btn_close.unbind('click');
    t.close.unbind('click');
    t.btn_ok.unbind('click');
    t.btn_cancel.unbind('click');

    t.btn_ok.on('click', function () {
        if (t.on_ok(data)!='stop') {
            t.t_popup.hide();
            t.$bg.hide();
        }
    });
    t.btn_close.on('click', function () {
        if (t.on_close(data)!='stop') {

            t.t_popup.hide();
            t.$bg.hide();
        }
    });
    t.close.on('click', function () {
        if (t.on_close(data)!='stop') {
            t.t_popup.hide();
            t.$bg.hide();
        }
    });
    t.btn_cancel.on('click', function () {
        if (t.on_cancel(data)!='stop') {
            t.t_popup.hide();
            t.$bg.hide();
        }
    });

    return t.t_popup;
};

function centrify(win ,top) {
    win.css("position", "absolute");

    if(top){
        win.css("top", top + $(window).scrollTop() +  "px");
    }else{
        win.css("top", Math.max(0, (($(window).height() - win.outerHeight()) / 2) +
                $(window).scrollTop()) + "px");
    }


    win.css("left", Math.max(0, (($(window).width() - win.outerWidth()) / 2) +
    $(window).scrollLeft()) + "px");
}






function isAnyPopupOpened() {
    var isOpened = false;
    popupIds.forEach(function (popupId) {
        if ($('#' + popupId).css('display') != 'none') {
            isOpened = true;
        }
    });
    return isOpened;
}

function hideAllPopups() {
    popupIds.forEach(function (popupId) {
        $('#' + popupId).fadeOut('fast');
    });
}

function enablePopupsBlur() {
    if ($('#popup_box_blur').not('[hiding=1]').length == 0) {
        $("body").prepend("<div id='popup_box_blur'></div>").fadeIn("slow");
    }
    /*$('#popup_box_blur').click(function() {
     hideAllPopups();
     disablePopupsBlur();
     });*/
}

function disablePopupsBlur() {
    $('body #popup_box_blur').each(function (index) {
        $(this).attr('hiding', 1).fadeOut('fast', function () {
            $(this).remove();
            if (typeof interval !== 'undefined') {
                clearInterval(interval);
            }
        });
    });
}

$(document).ready(function () {
    if (phpconst === undefined) {
        updateConst();
    }
});

function clearFeedback() {
    $('div#feedback_block').fadeOut();
    $('div#feedback_block_bg').fadeOut();
    $('input#fb_subject').val('');
    $('textarea#fb_message').val('');
    $('div#feedback_success').hide();
    $('input#fb_subject').removeClass('error_empty');
    $('textarea#fb_message').removeClass('error_empty');
    $('div#feedback_form').show();
    disablePopupsBlur();
}

function enableUserSubmenuBlur() {
    if ($('#user_submenu_blur').length == 0) {
        $("body").prepend("<div id='user_submenu_blur'></div>").fadeIn("slow");
    }

    $('.apps_block_triangles').click(function () {
        if (!$('div#user_submenu').hasClass('hidden')) {
            $('div#user_submenu').addClass('hidden');
        }
        $('.apps-block').fadeOut();
        $('.social-block').fadeOut();
        disableUserSubmenuBlur();
    });

    $('#user_submenu_blur').click(function () {
        if (!$('div#user_submenu').hasClass('hidden')) {
            $('div#user_submenu').addClass('hidden');
        }
        $('.apps-block').fadeOut();
        $('.social-block').fadeOut();
        disableUserSubmenuBlur();
    });
}

function disableUserSubmenuBlur() {
    $('.apps_block_triangles').fadeOut();
    $('body #user_submenu_blur').each(function (index) {
        $(this).fadeOut('fast', function () {
            $(this).remove();
        });
    });
}

function pageIsVisible() {
    return (document.visibilityState||
    document.mozVisibilityState||
    document.msVisibilityState||
    document.webkitVisibilityState)
    =='visible';
}
var phpconst;

function updateConst() {
    $.ajax({
        url: "/ajax/get_const",
        type: "POST",
        data: {},
        dataType: 'json',
        success: function (result) {
            phpconst=result;
        },
        error: function (a, b, c) {
            phpconst= {'test1':3,'test2':4};
        }
    });
}

function getConst(constName) {
    if ( phpconst === undefined || phpconst[constName] === undefined ) {
        return 'https://cloud.3dprinteros.com';
    }
    else return phpconst[constName];
}

function templater(src, params) {
    $.each(params, function (i, str) {
        src = src.replace(new RegExp(":"+i+":", 'g'), str?str:'');
    });
    return src;
}

//==========================================================
(function($) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
})(jQuery);
$(document).ready(function () {

    $('.footer_menu .gotop').click(function () {
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    });

    $('.dropup .dropup-btn').click(function (e) {
        e.preventDefault();
        $('.dropup-menu').toggleClass('hidden');
    });

    // ADD NEW PRINTER BUTTON

    $('.close_prev_block').click(function () {
        hideAllPopups();
        disablePopupsBlur();
    });
    $('div#feedback, .open-feedback').click(function () {
        hideAllPopups();
        enablePopupsBlur();
        $('div#feedback_block').fadeIn();
    });

    $('a#feedback_close').click(function () {
        hideAllPopups();
        disablePopupsBlur();
    });

    $('a#user_info').click(function () {
        if ($('div#user_submenu').hasClass('hidden')) {
            $.post("/a/account/get_my_account_info", {}, function(object) {
                if (object.result == true){
                    var storage = '100 GB';//Number(object.message.storage/(1024*1024*1024)).toFixed(2);
                    var traffic = '100 GB'; //Number(object.message.traffic_per_month/(1024*1024*1024)).toFixed(2);
                    //10GB without license
                    if ($('.account a.unactivated').length > 0) {
                        storage = '5 MB';//Number(object.message.storage/(1024*1024*1024)).toFixed(2);
                        traffic = '25 MB'; //Number(object.message.traffic_per_month/(1024*1024*1024)).toFixed(2);
                    }

                    $("#user_submenu .storage").text(storage);
                    $("#user_submenu #streams").text(traffic);
                }
                $('div#user_submenu').removeClass('hidden');
                enableUserSubmenuBlur();
            }, 'json');
        } else {
            $('div#user_submenu').addClass('hidden');
            disableUserSubmenuBlur();
        }
    });

    $('#menuitem_user').click(function () {
        if ($('div#user_submenu').hasClass('hidden')) {
            $.post("/a/account/get_my_account_info", {}, function(object) {
                if (object.result == true){
                    var storage = 100;//Number(object.message.storage/(1024*1024*1024)).toFixed(2);
                    var traffic = 100; //Number(object.message.traffic_per_month/(1024*1024*1024)).toFixed(2);

                    $("#user_submenu .storage").text(storage + " GB");
                    $("#user_submenu #streams").text(traffic + " GB");
                }
                $('div#user_submenu').removeClass('hidden');
                enableUserSubmenuBlur();
            }, 'json');
        } else {
            $('div#user_submenu').addClass('hidden');
            disableUserSubmenuBlur();
        }
    });

    $('input#send_fb').click(function () {
        var title = $('input#fb_subject').val();
        var msg = $('textarea#fb_message').val();
        var send = true;
        if (title == '') {
            $('input#fb_subject').addClass('error_empty');
            var send = false;
        }
        if (msg == '') {
            $('textarea#fb_message').addClass('error_empty');
            var send = false;
        }
        if (send == true) {
            $('#fbh1').text('Sending...');
            $("#loading_circle").show();
            $('div#feedback_form').hide();
            $.ajax({
                url: "/ajax/feedback",
                type: "POST",
                dataType: 'json',
                data: {
                    subject: title,
                    message: msg
                }, success: function (result) {
                    $("#loading_circle").hide();
                    $('div#feedback_success').show();
                    $('#fbh1').text('Message sent!');
                    setTimeout('clearFeedback()', 5000);
                }
            });
        }
    });

    $('input#fb_subject').keyup(function () {
        if ($('input#fb_subject').val().length > 0) {
            $('input#fb_subject').removeClass('error_empty');
        }
    });

    $('textarea#fb_message').keyup(function () {
        if ($('textarea#fb_message').val().length > 0) {
            $('textarea#fb_message').removeClass('error_empty');
        }
    });


    /*
     * Sing In/Up tabs
     */
    if(typeof $.tabs !== 'undefined') {
        $("#signBlock").tabs();
    }

    $("#signBlock a[href='#signIn']").click(function () {
        document.title = '3DPrinterOS » Sign In';
    });

    $("#signBlock a[href='#signUp']").click(function () {
        document.title = '3DPrinterOS » Sign Up';
    });

    /*
     * Preview Models
     */

    /* CONFIG */
    yOffset = 10;
    xOffset = 30;
    finishedLoadPrev = false;

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result

    /* END CONFIG
     * must be deleted. if I quick change mouse to download other preview, then
     * checkPosition works for older one and for new and for this reason topY can be change by first and second checkPosition's function
     * */
    function checkPosition(e, n) { //For 5 times with 1s interval check preview position
        return false;
        e.preventDefault();
        xPos = (e.pageX + xOffset);
        yPos = ((e.pageY - yOffset) + $("p#preview").height() + 20 - $(window).scrollTop() < document.documentElement.clientHeight) ? e.pageY - yOffset : document.documentElement.clientHeight - $("p#preview").height() + $(window).scrollTop() - 20;
        $("#preview")
            .css("top", yPos + "px");
        //.css("left", xPos + "px");

        if (n < 5) {
            n++;
            setTimeout(function () {
                checkPosition(e, n)
            }, 1000);
        }
    }



    $(document).on('mouseover', 'a.preview_dashboard', function (e) {
        e.preventDefault();
        this.t = this.title;
        this.title = "";
        var c = (this.t != "") ? "<br/>" + this.t : "";
        $("#previewContainer").html("");

        myImage = new Image();
        myImage.src = this.href;
        myImage.onload = function () {
            $("#previewContainer").append("<p id='preview'><img src='" + myImage.src + "' alt='Image preview' />" + c + "</p>");
            xPos = (e.pageX + xOffset);
            yPos = ((e.pageY - yOffset) + $("p#preview").height() + 20 - $(window).scrollTop() < document.documentElement.clientHeight) ? e.pageY - yOffset : document.documentElement.clientHeight - $("p#preview").height() + $(window).scrollTop() - 20;
            $("#preview")
                .css("top", yPos + "px")
                .css("left", xPos + "px")
                .fadeIn("fast");
        }
    });

    $(document).on('mouseout', 'a.preview_dashboard', function (e) {
        e.preventDefault();
        this.title = this.t;
        $("#preview").remove();
        $("#previewContainer").html("");
    });

    $(document).on('mousemove', 'a.preview_dashboard', function (e) {
        e.preventDefault();
        xPos = (e.pageX + xOffset);
        yPos = ((e.pageY - yOffset) + $("p#preview").height() + 20 - $(window).scrollTop() < document.documentElement.clientHeight) ? e.pageY - yOffset : document.documentElement.clientHeight - $("p#preview").height() + $(window).scrollTop() - 20;
        $("#preview")
            .css("top", yPos + "px")
            .css("left", xPos + "px");
    });

    $(document).on('click', 'a.preview_dashboard', function (e) {
        e.preventDefault();
        this.t = this.title;
        this.title = "";
        var c = (this.t != "") ? "<br/>" + this.t : "";

        $("#previewContainer").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");

        $("#preview")
            .css("top", (e.pageY - yOffset) + "px")
            .css("left", (e.pageX + xOffset) + "px")
            .fadeIn("fast");
    });



    $(document).click(function (event) {
        if (!$(event.target).closest('a.preview').length) {
            $("#preview").hide();
        }
    });

    $(".previewd").hover(function (e) {
            this.t = this.title;
            this.title = "";
            var c = (this.t != "") ? "<br/>" + this.t : "";
            $("#previewContainerd").append("<p id='previewd'>" + this.t + "</p>");

            $("#previewd")
                .css("top", (e.pageY + yOffset) + "px")
                .css("left", (e.pageX + xOffset) + "px")
                .fadeIn("fast");
        },
        function () {
            this.title = this.t;
            $("#previewd").remove();
        });

    $(".previewd").mousemove(function (e) {
        $("#preview")
            .css("top", (e.pageX - xOffset) + "px")
            .css("left", (e.pageY + yOffset) + "px");
    });


	$(document).on('click', '#slicer_popup #popup_footer .start_button',function(){
		ga('send', 'event', 'button', 'click', 'slicer-start');
	});

	$(document).on('click', '.blue.print',function(){
		ga('send', 'event', 'button', 'click', 'print');
	});

	/* окно  сриминг  и кнопки кроме континюе бег */


    $(document).on('click', 'input[type=button]',function(){

        var titlePage = $('head > title').text()
        var titilePopUp = $(this).parents('.popup').attr('id')
        var eventLabel =  $(this).val()

        ga('send', {
            hitType: 'event',
            eventCategory: titlePage,
            eventAction: titilePopUp,
            eventLabel:  eventLabel
        });


        Intercom('trackEvent', titlePage, {key: titilePopUp, other: eventLabel});

    });


    $(document).on('click', 'a',function(){

        var titlePage = $('head > title').text()
        var titilePopUp = $(this).parents('.popup').attr('id')
        var eventLabel= $(this).text().replace(/^\s*(.*)\s*$/, '$1')

        ga('send', {
            hitType: 'event',
            eventCategory: titlePage,
            eventAction: titilePopUp,
            eventLabel:  eventLabel
        });
        Intercom('trackEvent', titlePage, {key: titilePopUp, other: eventLabel});

    });


    $(document).on('click', 'a.viewer3d-btn',function(){
		ga('send', 'event', 'button', 'click', 'viewer3d');
	});
	$(document).on('click', 'a.stl-editor-btn',function(){
		ga('send', 'event', 'button', 'click', 'stl-editor');
	});
	$(document).on('click', 'a.slicer-btn',function(){
		ga('send', 'event', 'button', 'click', 'slicer');
	});
	$(document).on('click', 'a.dmtp-btn',function(){
		ga('send', 'event', 'button', 'click', 'dmtp');
	});
	$(document).on('click', 'a.stl-editor3d-btn',function(){
		ga('send', 'event', 'button', 'click', 'stl-editor3d');
	});

	$(document).on('click', 'a.netfabb-btn',function(){
		ga('send', 'event', 'button', 'click', 'netfabb');
	});
	$(document).on('click', 'a.i-materialize-btn',function(){
		ga('send', 'event', 'button', 'click', 'i-materialize');
	});


	$(document).on('click', 'input.liveView',function(){
		ga('send', 'event', 'button', 'click', 'liveView');
	});
        $(document).on('click', 'input.liveView-New',function(){
            ga('send', 'event', 'button', 'click', 'liveView');
        });
	$(document).on('click', 'input#add_new_printer_button',function(){
		ga('send', 'event', 'button', 'click', 'add_new_printer');
	});

	$(document).on('click', '.titem.files a.file_name',function(){
		ga('send', 'event', 'file', 'click', 'download');
	});

    $(document).on('click', '.titem.projects a.file_name',function(){
        ga('send', 'event', 'file', 'click', 'download');
    });


	$(document).on('click', '.search3d .addbtn',function(){
		ga('send', 'event', 'button', 'click', 'search3d add');
	});


  $(document).on('click', '.search3d .addbtn',function(){
    ga('send', 'event', 'button', 'click', 'search3d add');
  });


  $(document).on('click', '#add_new_file',function(){
    ga('send', 'event', 'button', 'click', 'Add new file');
  });

  $(document).on('click', '#create_file',function(){
    ga('send', 'event', 'button', 'click', 'open Create file app');
  });


	$( "#serch_form" ).submit(function( event ) {
	   ga('send', 'event', 'file', 'click', 'serch_form');
	});

	$(document).on('click', '.social-block a.facebook-btn',function(){
		 ga('send', 'event', 'share', 'click', 'share-file');
	});
	$(document).on('click', '.social-block a.share',function(){
		 ga('send', 'event', 'share', 'click', 'share-file');
	});
	$(document).on('click', '.printerlist .share',function(){
		 ga('send', 'event', 'share', 'click', 'share-printer');
	});
        $(document).on('click', '.redis_table caption .share',function(){
		 ga('send', 'event', 'share', 'click', 'share-printer');
	});
	// клик на картинки add

    $(document).on('click', '.rotate_live_view',function(){

        var $live_view_container = $(this).prev();
        /*var printer_id =  $live_view_container.parents('.popup_content').data('cam_printer_id');
        var rotate = 1;
        if ( $live_view_container.hasClass('transform180') ){
            rotate = 0;
        }*/

        var $img = $live_view_container.parents('.popup_content').find('img');
        var printer_id =  $img.data('printer_id');
        var rotate = 1;
        if ( $img.hasClass('transform180') ){
            rotate = 0;
            $img.removeClass('transform180');
        } else {
            $img.addClass('transform180');
        }

        $.post('/a/print/set_camera_rotate', {'printer_id': printer_id, 'rotate': rotate})

    });


    //License popup
    $('.license-activation-popup .btn.skip').on('click', function() {
        $('.license-activation-popup .popup').hide();
    });
    $('.license-activation-popup .close').on('click', function() {
        $('.license-activation-popup .popup').hide();
    });
    $('.license-activation-popup .btn.activate').on('click', function() {
        var key = $('.license-activation-popup input').val();
        if ($.trim(key) == '') {
            return;
        }
        $.ajax({
            url: "/a/license/activate",
            type: "POST",
            dataType: 'json',
            data: {
                'license_key': key
            },
            success: function (response) {
                if (response.result) {
                    $('.license-activation-popup .popup').hide();
                    location.href = '/';
                } else {
                    $('.license-activation-popup .license-error').html(response.message);
                }
            }
        });
    });
    $('a.unactivated').on('click', function() {
        $('.license-activation-popup .popup').show();
    });

    // Full pop UP
    $(document).on('click','.simple_universal_popup .fullscreen_popup',function(){
        var selector = $(this).parent();
        var height = selector.height();
        selector.attr('startWidth',selector.width()+"px");
        selector.attr('startHeight',height+"px");
        var doc_w = jQuery(window).width();
        var doc_h = jQuery(window).height();

        selector.height(doc_h);
        selector.width(doc_w);
        selector.addClass('fullscreen');
        selector.find('.minimize_popup').show();
        selector.find('.fullscreen_popup').hide();
    });

    $(document).on('click','.simple_universal_popup .minimize_popup',function(){
        var selector = $(this).parent();

        selector.height(selector.attr('startHeight'));
        selector.width(selector.attr('startWidth'));

        selector.removeClass('fullscreen');
        selector.find('.fullscreen_popup').show();
        selector.find('.minimize_popup').hide();

    });
});


function showLIveViewHD(){

    var html = '<div id="live-view-hd">' +
        '<div class="l"> <img src="'+getConst('cdn_url')+'/assets/i/liveview/connecting_grey.jpg" /> </div>'+
        '<div class="r"><button id="hd_cam_setting">Setting</button><div class="control"><div class="box-hd"><div class="title">Setting</div>' +
        '<div class="item"><label>Screen resolutions</label><select class="s-val"></select> <button class="orange" id="set_resolution_hd">Set</button></div>' +
        //'<div class="item"><label>Night Vision</label><button class="green on_night_vision">On</button><button class="green off_night_vision">of</button></div>' +
        '</div>' +
        '<div class="box-hd file_info-box-hd"><div class="title">File info</div>' +
        '<div class="file-info-ico"><img src="/assets/apps/toolpath-viewer/img/info_icon_rest.png" /></div>' +
        '<ul class="list-box">' +
        '</ul>' +
        '</div></div>' +
        '</div>'

    popupFactory('Live View HD',html,'none',null,null,null,null,function () {
        //clearInterval(Interval.liveView);
    });

}


function Timer() {
    var t = this;
    t.makeAlive = function() {
        t.state = true;
    };
    t.isAlive = function(){
        return t.state == true;
    };
    t.stopTimeout = function(){
        clearTimeout( t.timeOut );
        t.state = false;
    };
    t.runTimeout = function( timeOut ){
        t.stopTimeout();
        t.timeOut = timeOut;
        t.state = true;
    };
    t.setTimeout = function(callback, delay, data){
        t.callback = callback;
        t.delay = delay;
        t.data = data;
        t.run();
    };
    t.run = function(){
        if (!t.isAlive()) return;
        t.runTimeout(setTimeout(function () {
            t.callback(t.data);
        }, t.delay));
    };
}

function CheckResponse( data ){
    if ( data && !data.result && data.message && (data.message == "You are not loged in" ) ){
        location.href = "/";
    }
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
}

function rgb2hex(rgbString){

       var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
       // parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

       delete (parts[0]);
       for (var i = 1; i <= 3; ++i) {
           parts[i] = parseInt(parts[i]).toString(16);
           if (parts[i].length == 1) parts[i] = '0' + parts[i];
       }
       var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"
       return hexString;

}
function getIconSvgUrl(name){

    var svgUrl = '/assets/i/icon-svg/';
    if(!empty(name) && iconArray(name)){
        return svgUrl + name + '.svg';
    }
    return svgUrl + 'default_workflow.svg';
}

function iconArray(name){

    var data = [
        'default_workflow',
        'approved',
        'buildfile',
        'buildfile_ok',
        'buildfile_preparation',
        'camera',
        'certificate',
        'cnc',
        'design',
        'desktop',
        'factory',
        'folder',
        'group',
        'mail',
        'monitor',
        'part',
        'part_finished',
        'post_processing',
        'print',
        'print_ok',
        'print_ok1',
        'printing',
        'project_workflow',
        'relocate',
        'repair',
        'robot',
        'search',
        'shipping',
        'time',
        'user_cog',
        'wizard',
        'workflow1',

    ];


    if(name){
        if(find(data,name) > -1){
            return true;
        }else{
            return false;
        }
    }

    return data;
}

function find(array, value) {

    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) return i;
    }

    return -1;
}

function isAdminOrganization(){

    return ($('#user_submenu a[href="/workgroup/"]').length > 0) ? true : false;
}

function showDisclaimerMessage(userId,agreement){

    if(empty(accepted_terms_and_conditions)){
        var cantentDisclaimerMwssage = '<div class="l-box"><img src="/assets/i/svg/ok_explanation.svg"></div>' +
            '<div class="r-box"><h3>It is a long established fact that a reader will </h3>' +
            '<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for \'lorem ipsum\' will uncover many web sites still in their infancy.</p>' +
            '<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for \'lorem ipsum\' will uncover many web sites still in their infancy.</p>' +
            '<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for \'lorem ipsum\' will uncover many web sites still in their infancy.</p>' +
            '</div>';

        popupFactory(
            'Printing with 3dprinteros',
            cantentDisclaimerMwssage,
            null,
            null,
            function(){
                $.post('/ajax/accept_terms_and_conditions',{accepted : true},function(data){
                    console.log(data);
                });
            }
        );

        $('#printingwith3dprinteros_3dos .popup_content_buttons').prepend('<a href="/#" target="_blank" class="btn t_con_link">Terms & Conditions</a>')  ;

    }
}
function wrapTag (item,tag, attr){

    attrString = '';

    if(attr){
        $.each(attr,function(name,value){
            attrString += name + '="' + value + '"';
        });
    }

    return  '<' + tag + ' ' + attrString +'>' + item  + '</' + tag + '>';
}

function showPopupUsingAppstartResult(result)
{
    if (!result.result) {
        popupFactory('ERROR', result.message, 1);
        return true;
    }
    if (result.message['job_waiting']) {
        var limit = result.message['running_jobs_limit'] || 1,
            html = 'This app will be queued and executed later, when your account will have free execution slots.<br><br>' +
                   'Currently '+limit+' or more applications are running. ' +
                   'Your license supports '+limit+' simultaneous application execution.<br>' +
                   'If you need to increase the quote, please contact your organization administrator ' +
                   'or <a href="mailto:sales@3dprinteros.com">sales@3dprinteros.com</a>';
        popupFactory('You have to many running apps', html, 1);
        return true;
    }
    return false;
}

function addPaddingZero(val) {
    return val<10 ? '0'+val : val;
}
function addPaddingZeros(val, count) {
    var v = String(val);
    return v.length>10 || v.length>=count ? v : "0000000000".slice(-count+v.length)+v;
}
var moment = {'version': '2.18.1', 'fn': {}, 'ctz': null,
    getZoneData: function (timestamp) {
        if (!moment.ctz) moment.ctz = moment.tz.zone(userSettings.tz || 'Etc/UTC');
        var ind = moment.ctz._index(timestamp);
        return {offset: moment.ctz.offsets[ind], abbr: offset = moment.ctz.abbrs[ind]};
    },
    parse: function (timestamp) {
        if (!moment.tz) return 0;
        if (!moment.ctz) moment.ctz = moment.tz.zone(userSettings.tz || 'Etc/UTC');
        return moment.ctz.parse(timestamp);
    },
    getY: function (date) { return date.getUTCFullYear(); },
    getM: function (date) { return addPaddingZero(date.getUTCMonth()+1); },
    getD: function (date) { return addPaddingZero(date.getUTCDate()) },
    getV: function (date, nm) { return moment['get'+nm](date); }
};
var datetimeRegExp = /(\d{1,2})[\.-](\d{1,2})[\.-](\d{4}) (\d{2}):(\d{2})/;
function getTimestamp(datetime)
{
    var res = datetime.match(datetimeRegExp);
    return Date.UTC(res[3], res[2]-1, res[1], res[4], res[5]);
}
function fixTimestamp(timestamp, timefirst, isHideZone)
{
    var d = moment.getZoneData(timestamp), date = new Date(timestamp - (d.offset*60000)),
        df = userSettings.df || '.DMY', delim = df[0],
        time = addPaddingZero(date.getUTCHours())+':'+addPaddingZero(date.getUTCMinutes());
    return (timefirst?time+' ':'')+
        moment.getV(date, df[1])+delim+moment.getV(date, df[2])+delim+moment.getV(date, df[3])+
        (timefirst?'':' '+time) + (d.abbr=='UTC' || isHideZone ?'':' '+d.abbr);
}
function fixDatetime(datetime)
{
    return fixTimestamp(getTimestamp(datetime));
}
function fixDatetimeForTable(datetime, $el)
{
    var timestamp = getTimestamp(datetime), $td = $el.is('td') ? $el : $el.parent();
    $td.data('sort-val', timestamp);
    $el.text(fixTimestamp(timestamp, undefined, true));
}
function nl2br (str, is_xhtml) {
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

var printerTypesManager = function() {
    /**
     * Get all available printer types
     * @param {function} callback
     */
    this.getAllPrinterTypes = function(callback) {
        updateIfEmpty(callback);
    };

    /**
     * Get types of user printers
     * @param {function} callback
     */
    this.getUserPrinterTypes = function(callback) {
        updateIfEmpty(function(result) {
            callback(
                result.filter(function(type) {
                    return type.used;
                })
            );
        });
    };

    /**
     * Get all available printer types instead types of user printers
     * @param {function} callback
     */
    this.getOtherPrinterTypes = function(callback) {
        updateIfEmpty(function(result) {
            callback(
                result.filter(function(type) {
                    return !type.used;
                })
            )
        });
    };

    var updateIfEmpty = function(callback) {
        var url = '/ajax/get_printer_types?virtual=1';
        if (requestManager.requests[url+'&full=1']) {
            url += '&full=1';
        }
        requestManager.post(url, callback);
    };
};

function cRequest(url) {
    var t = this, data = -1, error = null, callbacks = [];
    t.url = url;
    t.useCallbacks = function () {
        while (callbacks.length>0) callbacks.shift()(data, error);
    };
    t.post = function (callback) {
        if (data<0) {
            callbacks.push(callback);
            if (data===-1) {
                data = -2;
                $.post(t.url, {}, function (result) {
                    data = result.result ? result.message : [];
                    error = !result.result ? result.message : null;
                    t.useCallbacks();
                    setTimeout(t.useCallbacks, 200);
                }, 'json');
            }
        } else {
            callback(data);
        }
    };
}
var requestManager = new function () {
    this.requests = {};
    this.post = function (url, callback) {
        if (!this.requests[url]) {
            this.requests[url] = new cRequest(url);
        }
        this.requests[url].post(callback);
    };
}();

function preparePrinterTypesSelect($el, ptypes, hideFavorite, vCol, skipVirtual) {
    $el.empty();
    var $myPrintersGroup = $('<optgroup label="- My Printers">'),
        $otherPrintersGroup = $('<optgroup label="- All Printers">'),
        favoritePrinters = hideFavorite ? null : [];
    vCol = vCol||'id';
    $.each(ptypes, function (i, type) {
        if (skipVirtual && type.used===2) return;
        if (type.used) $myPrintersGroup.append($('<option>').val(type[vCol]).html(type.description));
        $otherPrintersGroup.append($('<option>').val(type[vCol]).html(type.description));
        if (!hideFavorite && type.fav>0) {
            favoritePrinters[type.fav-1] = $('<option>').val(type[vCol]).html(type.description);
        }
    });
    if (!hideFavorite && favoritePrinters.length>0) {
        $el.append($('<optgroup label="- Favorite Printers">').append(favoritePrinters));
    }
    $el.append($myPrintersGroup);
    $el.append($otherPrintersGroup);
}

function getArrayFromString(data)
{
    data = data.replace(/[\n\r]/g, ',').split(',');
    var arr = [];
    $.each(data, function (i, el) {
        if ((el = el.trim()).length>0 && arr.indexOf(el)==-1) {
            arr.push(el);
        }
    });
    return arr;
}
function showExecutingPopup(cur, count, block, blockTitle) {
    if (count===0 || count===1 || count<0) return;
    var $p = $('.simple_universal_popup');
    if (!block) {
        block = 'standard-exec-block';
    }
    if (!blockTitle) {
        blockTitle = 'Executing';
    }
    if (!$p.find('.execute-progress').length) {
        popupFactory('Please wait', '<div class="execute-popup-block"><div class="'+block+'" style="text-align: center; height: 50px"><img src="/assets/i/ico/ajax-loader.gif"> '+blockTitle+' <span class="execute-progress"></span>...</div></div>', 'none');
    } else if (!$p.find('.' + block).length) {
        $p.find('.execute-popup-block').append('<div class="'+block+'" style="text-align: center; height: 50px"><img src="/assets/i/ico/ajax-loader.gif"> '+blockTitle+' <span class="execute-progress"></span>...</div>');
    }
    if (count>1) $p.find('.'+block+' .execute-progress').text(''+cur+'/'+count);
}
function getErrorsFromArray(arr, title, delim, afterText) {
    return arr.length>0 ? '<strong>'+title+'</strong><br>'+arr.join(delim || ', ')+'.'+(afterText||'')+'<br><br>' : '';
}

window.PTM = new printerTypesManager();

$(document).ready(function(){
    $('.release_notes_list .title-note').click(function(){

        if(!$(this).parent().hasClass('open')){
            $('.release_notes_list .open').removeClass('open')
        }
        $(this).parent().addClass('open')
    });


  var element = $('.footer_menu_login');
  $(window).on('scroll', function(){

    //element['fade'+ ($(this).scrollTop() > 100 ? 'In': 'Out')](500);

    if(element.hasClass('footer-no-fixed')){


      if($(this).scrollTop() === 0){
        element.css('position','absolute')
      }else if($(this).scrollTop() < 60){
        element.css('position','relative')
      }else{
        element.css('position','fixed')
      }

    }
  });

});

var JobDetailsPopup = function() {

    var popup;
    var init = false;

    var job_id;
    var flags;
    var notes;
    var qa;
    var slicer_settings;
    var monitoring;
    var transaction;
    var notes_exists;
    var fid;
    var ftype_id;
    var has_qa;
    var p_id;

    this.openDetails  = function(open_job_id, job_flags, has_notes, file_type_id, file_id, has_questions, printer_id, can_access_as_owner, tab) {
        popup = $('#job_details_box');
        job_id = open_job_id;
        flags = job_flags;
        notes_exists = has_notes;
        ftype_id = file_type_id;
        fid = file_id;
        has_qa = has_questions;
        p_id = printer_id;
        notes = qa = slicer_settings = monitoring =transaction = false;
        if (file_type_id != 2) {
            popup.find('.job_tab_slicing').hide();
        } else {
            popup.find('.job_tab_slicing').show();
        }
        if (flags&4) {
            popup.find('.job_tab_monitoring').show();
        } else {
            popup.find('.job_tab_monitoring').hide();
        }
        if (can_access_as_owner && flags&8) {
            popup.find('.job_tab_transactions').show();
        } else {
            popup.find('.job_tab_transactions').hide();
        }
        bindEvents();
        enablePopupsBlur();
        popup.fadeIn("slow");
        centrify(popup, 100);
        if (tab && popup.find('#job_details_content-header a.' + tab).length > 0) {
            popup.find('#job_details_content-header a.' + tab).trigger('click');
        } else {
            popup.find('#job_details_content-header a').first().trigger('click');
        }
        var $el = popup.find('.job_details_app');
        if (ftype_id==2) {
            $el.attr('href', "/myfiles/#t;app=toolpath-viewer;id="+fid).text('OPEN IN TOOLPATH VIEWER');
            $el.show();
        } else if (ftype_id==1) {
            $el.attr('href', "/myfiles/#t;app=stl-editor3d;id="+fid).text('OPEN IN STLEDITOR');
            $el.show();
        } else {
            $el.hide();
        }
        init = true;
    };

    var getJobNotes = function(callback) {
        $.ajax({
            url: '/a/job/get_job_notes',
            data: {job_id: job_id},
            dataType: 'json',
            method: 'POST',
            success: function(response) {
                if (response.result) {
                    qa = response.message.qa;
                    if (typeof qa === "string" && qa.substr(0, 5) === "error") {
                        qa = null;
                    }
                    notes = response.message.notes;
                    callback();
                }
            }
        });
    };

    var getSlicerSettings = function(callback) {
        $.ajax({
            url: '/a/job/get_job_slicer_settings',
            data: {job_id: job_id},
            dataType: 'json',
            method: 'POST',
            success: function(response) {
                if (response.result) {
                    slicer_settings = response.message;
                    callback();
                }
            }
        });
    };

    var getJobMonitoring = function(callback) {
        $.post('/a/print/get_monitoring_data', {job_id: jobId, time: time}, function(response) {
            if (response.result) {
                monitoring = response.message;
                callback();
            }
        });
    };

    var bindEvents = function() {
        if (init) {
            return;
        }
        var tabs = popup.find('#job_details_content-header a');
        tabs.on('click', function() {
            var target = $(this).attr('target');
            tabs.removeClass('selected');
            $(this).addClass('selected');
            popup.find('.content-body .job-detail-content').hide();
            popup.find('#' + target).show();
            openTab(target);
        });
        popup.find('.job_details_close').on('click', function() {
            popup.fadeOut();
            disablePopupsBlur();
        });
        popup.find('#send_new_job_note').on('click', function() {
            var textarea = popup.find('#new_job_note');
            var note = textarea.val();
            if (note.trim()) {
                addNote(note);
                textarea.val('');
            }
        });
    };

    var addNote = function(note) {
        $.ajax({
            url: '/a/job/add_job_note',
            data: {job_id: job_id, note: note, feedback: popup.find('#job_details_note_type').val() === "feedback"},
            dataType: 'json',
            method: 'POST',
            success: function(response) {
                if (response.result) {
                    notes = false;
                    showNotes();
                }
            }
        });
    };

    var openTab = function(target) {
        switch(target) {
            case 'job_details_notes':
                showNotes();
                break;
            case 'job_details_slicing':
                showSlicingSettings();
                break;
            case 'job_details_transactions':
                showTransactions();
                break;
            case 'job_details_monitoring':
                showMonitoring();
                break;
        }
    };

    var showNotes = function() {
        var notesBlock = popup.find('.job-notes');
        if (notes === false) {
            showLoader(notesBlock);
            getJobNotes(showNotes);
            return;
        }
        notesBlock.html('');
        if (has_qa && qa) {
            var qaNote = createJobNoteBlockForQA();
            notesBlock.append(qaNote);
        }
        for (var i in notes) {
            var data = notes[i];
            var note = createJobNoteBlock(data.datetime, data.user, data.note, data.myself === 't', data.feedback === 't');
            notesBlock.append(note);
        }
        notesBlock.scrollTop(notesBlock.prop("scrollHeight"))
    };

    var showSlicingSettings = function() {
        var block = popup.find('#job_details_slicing');
        if (ftype_id != 2) {
            block.html('Slicing settings available only for gcode files');
            return
        }
        if (slicer_settings === false) {
            showLoader(block);
            getSlicerSettings(showSlicingSettings);
            return;
        }
        block.html('');
        addSyntaxHighlightText(block, JSON.stringify(slicer_settings, null, 2));
    };

    var showTransactions = function() {
        var block = popup.find('#job_details_transactions');
        block.html('');
        block.append($('body>#job-transact-popup').clone());
        var $pEl = block.find('#job-transact-popup');
        generateJobTransactionsPopup(job_id, block, $pEl);
        $pEl.show();
    };

    var showMonitoring = function() {
        var $p = popup.find('#job_details_monitoring');
        if (flags&4) {
            $p.html($('#printer-monitoring-popup-parent').html());
            generateJobMonitoringPopup(job_id, $p);
        } else {
            $p.html('Wrong job status');
        }
    };

    var createJobNoteBlock = function(datetime, user, note, is_myself, is_feedback) {
        var noteBlock = $('<div class="note-item">');
        var box = $('<div class="note-item-block">');
        if (is_myself) {
            box.addClass('myself');
        }
        var margin = '5px';
        if (is_feedback) {
            box.append('<div class="note-item-title">FEEDBACK</div>');
            margin = '23px';
        }
        box.append('<div class="note-item-header"><div class="note-item-author">'+user+'</div><div class="note-item-datetime">'+fixTimestamp(datetime*1000,true)+'</div></div>');
        box.append('<div class="clearfix"></div>');
        box.append('<div class="note-item-content" style="margin-top: '+margin+'">'+note+'</div>');
        noteBlock.append(box);
        noteBlock.append('<div class="clearfix"></div>');

        return noteBlock;
    };

    var createJobNoteBlockForQA = function() {
        var noteBlock = $('<div class="note-item">');
        var box = $('<div class="note-item-block">');
        box.append('<div class="note-item-title">Q/A</div>');
        box.append('<div class="clearfix"></div>');
        box.append('<div class="note-item-content">'+questionsView(qa)+'</div>');
        noteBlock.append(box);
        noteBlock.append('<div class="clearfix"></div>');

        return noteBlock;
    };

    var addSyntaxHighlightText = function(block, text) {
        var content = $('<div style="height: 300px; overflow: auto;">');
        content.append("<div style='max-width: 600px'><code class='language-html'>"+text+"</code></div>");
        block.append(content);
        content.syntaxHighlight();
        block.find('.prettyprint').css('border','0').width('98%');
    };

    var showLoader = function(block) {
        block.html('');
        var loader = $('<div class="loader" style="text-align: center; width: 100%; margin-top: 50px;">');
        loader.append('<img src="/assets/i/ico/ajax-loader.gif" />');
        block.append(loader);
    };

    var hideLoader = function(block) {
        block.find('.loader').remove();
    }

};

var jobDetailsPopup = new JobDetailsPopup();
