var skipValidation = false;
var skipWaitPopup = false;

$.extend($.fn.autoNumeric.defaults, {              
	aSep: '.',
	aDec: ','
});

function showWaitPopup() {
	return true;
}

function doShowWaitPopup() {
	$("#waitModal").modal("show");
	return true;
}

function hidePopWin() {
	$("#waitModal").modal("hide");
}

function showDojoAlertDialog(html, level) {
	if (level == "info") {
		//Non emettiamo il popup nel caso di semplici segnalazioni
		return;
	}
	$("#error-modal-body").append($(html));
	var errorModal = $("#errorModal");
	errorModal.find(".modal-header").addClass(level);
	//Emettiamo un popup che si toglie automaticamente dopo 2 secondi nel caso di warning, altrimenti lo lasciamo in caso di errori bloccanti.
	if (level == "warning") {
		errorModal.on('show.bs.modal', function () {
		    clearTimeout(errorModal.data('hideInteval'))
		    var id = setTimeout(function(){
		    	errorModal.modal('hide');
		    }, 2000);
		    errorModal.data('hideInteval', id);
		})
	}
	errorModal.modal("show");
}

function $n(myid) {
	var normalizedId = "#" + myid.replace( /(:|\.|\[|\])/g, "\\$1" );
	var result = $(normalizedId);
    return result;
}

$(function() {
	addWaitPopupOnAllLinks();
	removeEmptyButtonBars();
	addCalculators();
	
	$.validator.methods.date = function (value, element) {
//	    return this.optional(element) || $.datepicker.parseDate('dd/mm/yy', value); 
	    return this.optional(element) || true; 
	}
	
    //Datemask dd/mm/yyyy
    $("input.date").inputmask("dd/mm/yyyy", {"placeholder": "gg/mm/aaaa"});
	//$('input.number').autoNumeric('init', {aSign:'', pSign:'s' }); 
    
    //Date range picker
    $("input[readonly!='readonly'].date").datepicker({
    	format: "dd/mm/yyyy",
    	language: "it",
    	autoclose: true
    });

    //Datemask dd/mm/yyyy
    $("input.time").inputmask("99:99", {"placeholder": "hh:mm"});

    $("button.cancel").click(function() {
    	skipValidation = true;
    	return true;
    });
    
    //Timepicker
//    $(".timepicker").timepicker({
//        showInputs: false
//    });
    
    validateForm();
});

$(document).ready(function() {
//  Commented for performance reasons on large pages!!!!!!!!!!!!!!!
//  $(':not(label)[title!=""]').tooltip({
//		placement: "auto",
//		html: false,
//		delay: { "show": 600, "hide": 80 }
//    });
    
	if (window.GLOBAL_JUMP_TO_ID && window.GLOBAL_JUMP_TO_ID != '') {
		jumpTo();
	} else {
		formFocus();
	}
});

function hideIconImageBroken(image) {
	if (window.GLOBAL_CONTEXT_PATH) {
		image.src = window.GLOBAL_CONTEXT_PATH + "/resources/img/default_image_icon.png";
	} else {
		console.error("window.GLOBAL_CONTEXT_PATH is not defined");
	}
	return true;
}

function hideBannerImageBroken(image) {
	if (window.GLOBAL_CONTEXT_PATH) {
		image.src = window.GLOBAL_CONTEXT_PATH + "/resources/img/default_image_banner.png";
	} else {
		console.error("window.GLOBAL_CONTEXT_PATH is not defined");
	}
	return true;
}

//FIXME
function addCalculators() {
	if ($.calculator) {
		$('.form-control.value, .form-control.currency').calculator({showOn: 'operator'});
	}
}

function makeTooltip(id, html) {
	$n(id).tooltip({
		html: true,
		title: html,
		placement: "top",
		delay: { "show": 600, "hide": 80 }
	});
	$n(id).removeAttr("title");
}

function initMapForDetail(latitude, longitude, canvas) {
	if (latitude != '' && longitude != '') {
	  var myLatLng = new google.maps.LatLng(parseFloat(latitude), parseFloat(longitude));
	  var mapCanvas = document.getElementById(canvas);
	  var mapOptions = {
	    center: myLatLng,
	    zoom: 12,
	    scrollwheel: false,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  }
	  var map = new google.maps.Map(mapCanvas, mapOptions)
	  var iconBase = 'https://maps.google.com/mapfiles/kml/pushpin/';
	  var marker = new google.maps.Marker({
	    position: myLatLng,
	    map: map,
	    animation: google.maps.Animation.DROP,
	    icon: {
	        size: new google.maps.Size(32, 32),
	        scaledSize: new google.maps.Size(32, 32),
	        url: iconBase + 'red-pushpin.png'
	    }
	  });
	}
}

function initMapForList(canvas, list) {
	  //var myLatLng = new google.maps.LatLng(parseFloat(latitude), parseFloat(longitude));
	  var mapCanvas = document.getElementById(canvas);
	  var mapOptions = {
	    zoom: 12,
	    scrollwheel: false,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  }
	  var map = new google.maps.Map(mapCanvas, mapOptions)
	  var iconBase = 'https://maps.google.com/mapfiles/kml/pushpin/';
	  
	  var bound = new google.maps.LatLngBounds();
	  for (var i = 0; i < list.length; i++) {
		var item = list[i];
   		if (item.x != '' && item.y != '') {
    	  var myLatLng = new google.maps.LatLng(parseFloat(item.x), parseFloat(item.y));
    	  bound.extend(myLatLng);
    	  var marker = new google.maps.Marker({
    		    position: myLatLng,
    		    map: map,
    		    animation: google.maps.Animation.DROP,
   			 	url: 'view/' + item.objectKey + '?newFlow=true',
   			 	title: item.objectTitle,
    		    icon: {
    		        size: new google.maps.Size(32, 32),
    		        scaledSize: new google.maps.Size(32, 32),
    		        url: iconBase + 'red-pushpin.png'
    		    }
   		  });
    	  google.maps.event.addListener(marker, 'click', function() {
    		  window.location.href = this.url;
    	  });
   		}
      }
	  map.fitBounds(bound);
}

function jumpTo() {
    var divid = $n(window.GLOBAL_JUMP_TO_ID);
    if (divid.length > 0) {
    	$('html, body').animate({ scrollTop: divid.offset().top - 200}, 500);
    	if (divid.focus) {
    		divid.focus();
    	} else {
    	}
    }
    return false;
}

function formFocus() {
	if (window.GLOBAL_SKIP_FORM_FOCUS) {
		return;
	}
	//TODO verificare meglio 
	//$('#form :input.form-control:not([readonly]):visible:enabled:first').focus();
}

//Add onclick handlers to 'a' elements excluding of class noWaitPopup,
//for automatic wait poup div.
function addWaitPopupOnAllLinks() {
	$("a:not(.noWaitPopup)").each(function() {
		if (this.onclick == null) {
	          //href with 6578706f7274=1 means that are export links of display tag library.
					  if (this.href != undefined
							&& this.href.indexOf("javascript:") == -1
							&& this.href.indexOf("#") == -1
							&& this.href.indexOf("6578706f7274=1") == -1) {
		      this.onclick = function() {
		    	  doShowWaitPopup();
		          return true;
			  }
		  }
		}
	});
}

function removeEmptyButtonBars() { 
	if (window.GLOBAL_SKIP_REMOVE_EMPTY_BUTTON_BARS) {
		return;
	}
	$('ul.buttonBar:not(:has(*))').hide();
}

function switchFrameLayout(idFrame, forceSwitch) {
	if (window.GLOBAL_SKIP_SWITCH_FRAME_LAYOUT && !forceSwitch) {
		return;
	}
    var frameDiv = $n('IF' + idFrame);
	$("[data-widget='collapse']", frameDiv).trigger( "click" );
}

var validationRules = {};
function validateForm() {	
	jQuery.validator.addMethod("greaterThan", function(value, element, params) {
		var otherVal = $n(params[0]).val();
	    if (value != "" && otherVal != "") {
			var endDate = moment(value, "DD/MM/YYYY").toDate();
			var startDate = moment(otherVal, "DD/MM/YYYY").toDate();
	        return endDate > startDate;
	    }
	    return true;
	}, '{1} deve essere maggiore di {2}.');
	
	jQuery.validator.addMethod("greaterOrEqualThan", function(value, element, params) {
		var otherVal = $n(params[0]).val();
	    if (value != "" && otherVal != "") {
			var endDate = moment(value, "DD/MM/YYYY").toDate();
			var startDate = moment(otherVal, "DD/MM/YYYY").toDate();
	        return endDate >= startDate;
	    }
	    return true;
	}, '{1} deve essere maggiore o uguale a {2}.');

	$("#form").validate({
		onkeyup: function(element) {
	    },
		onsubmit: function(element) {
		    return !skipValidation;
	    },
		rules : validationRules,
		highlight : function(element) {
			$(element).addClass('error');
			$("label[for='" + element.id + "']").addClass('error');
			$n(element.id + "-error").remove();
//			$(element).closest('.form-group').find(".form-control, .control-label").addClass('error');
		},
		unhighlight : function(element) {
			$(element).removeClass('error');
			$("label[for='" + element.id + "']").removeClass('error');
			$n(element.id + "-error").remove();
//			$(element).closest('.form-group').find(".form-control, .control-label").removeClass('error');
		},
		submitHandler: function(form) {
			resetInputNumbers();
			return true;
		},
		invalidHandler: function(event, validator) {
			if (skipValidation) {
				event.target.submit();
			}
		},
		errorElement : 'span',
		errorClass : 'help-block error',
		errorPlacement : function(error, element) {
			if (element.parent('.input-group').length) {
				error.insertAfter(element.parent());
			} else {
				error.insertAfter(element);
			}
		}
	});
}

function resetInputNumbers() {
    $('input.number').each(function(i){
        var self = $(this);
        try{
            var v = self.autoNumeric('get');
            self.autoNumeric('destroy');
            self.val(v);
        }catch(err){
        }
    });
    doShowWaitPopup();
}

var currentPopupDialog;
var currentPopupDialogArg;
var gReturnFunc;
function openPopupDialog(popupDialogArg, width, height, retFunc)
{
    //Durante la composizione dell'URL verifica che i parametri siano valorizzati
    tempSrc = popupDialogArg.url ;
    if( popupDialogArg.parameter != null){
        separatorParam = "?" ;
        if( tempSrc.indexOf('?') > 0 )
            separatorParam = "&" ;
        tempSrc = tempSrc + separatorParam + popupDialogArg.parameter;
    }
    
	if (currentPopupDialog) {
		currentPopupDialog.close();
	}
	
	var content = "<iframe style=\"width:100%;height:" + height + ";overflow:auto;background-color:transparent;\" id=\"popupFrame\"" + " src='" + tempSrc + "' onload='resizePopupFrame()'/>";

	 // Using init options
	currentPopupDialog = new BootstrapDialog({
    	size: BootstrapDialog.SIZE_WIDE,
        title: popupDialogArg.title,
        message: $(content),
        style: "width: " + width + ";height: " + height,
        id: "popup"
    });
	currentPopupDialog.open();
    currentPopupDialogArg = popupDialogArg;
	gReturnFunc = retFunc;
}

function resizePopupFrame() {
}

function closePopupDialog(callReturnFunc, pReturnVal) {
	currentPopupDialog.close();
	
	if (callReturnFunc == true && gReturnFunc != null) {
		gReturnFunc(pReturnVal);
	}
}

function getFieldValue(id, isEscape) {
	element = $n(id);
	if (element) {
//		if (element instanceof dijit.form.DateTextBox) {
//			retField = formatDate(element.attr("value"));
//			if (retField == null) {
//				return "";
//			} else {
//				return escapeValue(retField, isEscape);
//			}
//		}		
		retField = escapeValue(element.val(), isEscape);
		if (retField == "NaN") {
			retField = "";
		}
		return retField;
	}
//	element = document.getElementById(id);
//	if (element) {
//		return escapeValue(element.value, isEscape);
//	}
	return null;
}

function setFieldValue(id, value, isEscape) {
	element = $n(id);
	if (element) {
//		if (element instanceof dijit.form.DateTextBox && value == "") {
//			value = null;
//		}
		element.val(escapeValue(value, isEscape));
		//element._onBlur();
		return;
	}
//	element = document.getElementById(id);
//	if (element) {
//		element.value = escapeValue(value, isEscape);
//	}
}

function escapeValue(value, isEscape) {
	if (isEscape) {
		return escape(value);
	}
	return value;
}

function safeEval(value) {
	try {
		return eval("return " + value);
	} catch (e) {
		return "";
	}
}

function clearFiltersStandard(divName) {
	if (divName == undefined) {
		divName = "IFBSearch";
	}
	var div = $n(divName);
	$(div).find('.form-control').each(function() {
		if ((this.type != "hidden" && this.readOnly != true) || (this.hasClass("cleanable"))) {
			if (this.type == "select-one" || this.type == "select-multi") {
				setFieldValue(this.id, "");
			} else if (this.type == "checkbox" || this.type == "radio") {
				this.checked = false;
			} else {
				setFieldValue(this.id, "");
			}
		}
	});
	return;
}

/*!
 * Author: Abdullah A Almsaeed
 * Date: 4 Jan 2014
 * Description:
 *      This file should be included in all pages
 !**/

/*
 * Global variables. If you change any of these vars, don't forget 
 * to change the values in the less files!
 */
var left_side_width = 220; //Sidebar width in pixels

$(function() {
    "use strict";

    //Enable sidebar toggle
    $("[data-toggle='offcanvas']").click(function(e) {
        e.preventDefault();

        //If window is small enough, enable sidebar push menu
        if ($(window).width() <= 992) {
            $('.row-offcanvas').toggleClass('active');
            $('.left-side').removeClass("collapse-left");
            $(".right-side").removeClass("strech");
            $('.row-offcanvas').toggleClass("relative");
        } else {
            //Else, enable content streching
            $('.left-side').toggleClass("collapse-left");
            $(".right-side").toggleClass("strech");
        }
    });

    //Add hover support for touch devices
    $('.btn').bind('touchstart', function() {
        $(this).addClass('hover');
    }).bind('touchend', function() {
        $(this).removeClass('hover');
    });

    //Activate tooltips
    $("[data-toggle='tooltip']").tooltip();

    /*     
     * Add collapse and remove events to boxes
     */
    $("[data-widget='collapse']").click(function() {
        //Find the box parent        
        var box = $(this).parents(".box").first();
        //Find the body and the footer
        var bf = box.find(".box-body, .box-footer");
        if (!box.hasClass("collapsed-box")) {
            box.addClass("collapsed-box");
            //Convert minus into plus
            $(this).children(".fa-minus").removeClass("fa-minus").addClass("fa-plus");
            bf.slideUp();
        } else {
            box.removeClass("collapsed-box");
            //Convert plus into minus
            $(this).children(".fa-plus").removeClass("fa-plus").addClass("fa-minus");
            bf.slideDown();
        }
    });

    /*
     * ADD SLIMSCROLL TO THE TOP NAV DROPDOWNS
     * ---------------------------------------
     */
    $(".navbar .menu").slimscroll({
        height: "200px",
        alwaysVisible: false,
        size: "3px"
    }).css("width", "100%");

    /*
     * INITIALIZE BUTTON TOGGLE
     * ------------------------
     */
    $('.btn-group[data-toggle="btn-toggle"]').each(function() {
        var group = $(this);
        $(this).find(".btn").click(function(e) {
            group.find(".btn.active").removeClass("active");
            $(this).addClass("active");
            e.preventDefault();
        });

    });

    $("[data-widget='remove']").click(function() {
        //Find the box parent        
        var box = $(this).parents(".box").first();
        box.slideUp();
    });

    /* Sidebar tree view */
    $(".sidebar .treeview").tree();

    /* 
     * Make sure that the sidebar is streched full height
     * ---------------------------------------------
     * We are gonna assign a min-height value every time the
     * wrapper gets resized and upon page load. We will use
     * Ben Alman's method for detecting the resize event.
     * 
     **/
    function _fix() {
        //Get window height and the wrapper height
        var height = $(window).height() - $("body > .header").height() - ($("body > .footer").outerHeight() || 0);
        $(".wrapper").css("min-height", height + "px");
        var content = $(".wrapper").height();
        //If the wrapper height is greater than the window
        if (content > height)
            //then set sidebar height to the wrapper
            $(".left-side, html, body").css("min-height", content + "px");
        else {
            //Otherwise, set the sidebar to the height of the window
            $(".left-side, html, body").css("min-height", height + "px");
        }
    }
    //Fire upon load
    _fix();
    //Fire when wrapper is resized
    $(".wrapper").resize(function() {
        _fix();
        fix_sidebar();
    });

    //Fix the fixed layout sidebar scroll bug
    fix_sidebar();

    /*
     * We are gonna initialize all checkbox and radio inputs to 
     * iCheck plugin in.
     * You can find the documentation at http://fronteed.com/iCheck/
     */
    /*
    $("input[type='checkbox']:not(.simple), input[type='radio']:not(.simple)").iCheck({
        checkboxClass: 'icheckbox_flat-blue',
        radioClass: 'iradio_flat-blue'
    });
    */
});
function fix_sidebar() {
    //Make sure the body tag has the .fixed class
    if (!$("body").hasClass("fixed")) {
        return;
    }

    //Add slimscroll
    $(".sidebar").slimscroll({
        height: ($(window).height() - $(".header").height()) + "px",
        color: "rgba(0,0,0,0.2)"
    });
}

/*
 * SIDEBAR MENU
 * ------------
 * This is a custom plugin for the sidebar menu. It provides a tree view.
 * 
 * Usage:
 * $(".sidebar).tree();
 * 
 * Note: This plugin does not accept any options. Instead, it only requires a class
 *       added to the element that contains a sub-menu.
 *       
 * When used with the sidebar, for example, it would look something like this:
 * <ul class='sidebar-menu'>
 *      <li class="treeview active">
 *          <a href="#>Menu</a>
 *          <ul class='treeview-menu'>
 *              <li class='active'><a href=#>Level 1</a></li>
 *          </ul>
 *      </li>
 * </ul>
 * 
 * Add .active class to <li> elements if you want the menu to be open automatically
 * on page load. See above for an example.
 */
(function($) {
    "use strict";

    $.fn.tree = function() {

        return this.each(function() {
            var btn = $(this).children("a").first();
            var menu = $(this).children(".treeview-menu").first();
            var isActive = $(this).hasClass('active');

            //initialize already active menus
            if (isActive) {
                menu.show();
                btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
            }
            //Slide open or close the menu on link click
            btn.click(function(e) {
                e.preventDefault();
                if (isActive) {
                    //Slide up to close menu
                    menu.slideUp();
                    isActive = false;
                    btn.children(".fa-angle-down").first().removeClass("fa-angle-down").addClass("fa-angle-left");
                    btn.parent("li").removeClass("active");
                } else {
                    //Slide down to open menu
                    menu.slideDown();
                    isActive = true;
                    btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
                    btn.parent("li").addClass("active");
                }
            });

            /* Add margins to submenu elements to give it a tree look */
            menu.find("li > a").each(function() {
                var pad = parseInt($(this).css("margin-left")) + 10;

                $(this).css({"margin-left": pad + "px"});
            });

        });

    };


}(jQuery));

/*
 * TODO LIST CUSTOM PLUGIN
 * -----------------------
 * This plugin depends on iCheck plugin for checkbox and radio inputs
 */
(function($) {
    "use strict";

    $.fn.todolist = function(options) {
        // Render options
        var settings = $.extend({
            //When the user checks the input
            onCheck: function(ele) {
            },
            //When the user unchecks the input
            onUncheck: function(ele) {
            }
        }, options);

        return this.each(function() {
            $('input', this).on('ifChecked', function(event) {
                var ele = $(this).parents("li").first();
                ele.toggleClass("done");
                settings.onCheck.call(ele);
            });

            $('input', this).on('ifUnchecked', function(event) {
                var ele = $(this).parents("li").first();
                ele.toggleClass("done");
                settings.onUncheck.call(ele);
            });
        });
    };

}(jQuery));

/* CENTER ELEMENTS */
(function($) {
    "use strict";
    jQuery.fn.center = function(parent) {
        if (parent) {
            parent = this.parent();
        } else {
            parent = window;
        }
        this.css({
            "position": "absolute",
            "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
            "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
        });
        return this;
    }
}(jQuery));

/*
 * jQuery resize event - v1.1 - 3/14/2010
 * http://benalman.com/projects/jquery-resize-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($, h, c) {
    var a = $([]), e = $.resize = $.extend($.resize, {}), i, k = "setTimeout", j = "resize", d = j + "-special-event", b = "delay", f = "throttleWindow";
    e[b] = 250;
    e[f] = true;
    $.event.special[j] = {setup: function() {
            if (!e[f] && this[k]) {
                return false;
            }
            var l = $(this);
            a = a.add(l);
            $.data(this, d, {w: l.width(), h: l.height()});
            if (a.length === 1) {
                g();
            }
        }, teardown: function() {
            if (!e[f] && this[k]) {
                return false
            }
            var l = $(this);
            a = a.not(l);
            l.removeData(d);
            if (!a.length) {
                clearTimeout(i);
            }
        }, add: function(l) {
            if (!e[f] && this[k]) {
                return false
            }
            var n;
            function m(s, o, p) {
                var q = $(this), r = $.data(this, d);
                r.w = o !== c ? o : q.width();
                r.h = p !== c ? p : q.height();
                n.apply(this, arguments)
            }
            if ($.isFunction(l)) {
                n = l;
                return m
            } else {
                n = l.handler;
                l.handler = m
            }
        }};
    function g() {
        i = h[k](function() {
            a.each(function() {
                var n = $(this), m = n.width(), l = n.height(), o = $.data(this, d);
                if (m !== o.w || l !== o.h) {
                    n.trigger(j, [o.w = m, o.h = l])
                }
            });
            g()
        }, e[b])
    }}
)(jQuery, this);

/*!
 * SlimScroll https://github.com/rochal/jQuery-slimScroll
 * =======================================================
 * 
 * Copyright (c) 2011 Piotr Rochala (http://rocha.la) Dual licensed under the MIT 
 */
(function(f) {
    jQuery.fn.extend({slimScroll: function(h) {
            var a = f.extend({width: "auto", height: "250px", size: "7px", color: "#000", position: "right", distance: "1px", start: "top", opacity: 0.4, alwaysVisible: !1, disableFadeOut: !1, railVisible: !1, railColor: "#333", railOpacity: 0.2, railDraggable: !0, railClass: "slimScrollRail", barClass: "slimScrollBar", wrapperClass: "slimScrollDiv", allowPageScroll: !1, wheelStep: 20, touchScrollStep: 200, borderRadius: "0px", railBorderRadius: "0px"}, h);
            this.each(function() {
                function r(d) {
                    if (s) {
                        d = d ||
                                window.event;
                        var c = 0;
                        d.wheelDelta && (c = -d.wheelDelta / 120);
                        d.detail && (c = d.detail / 3);
                        f(d.target || d.srcTarget || d.srcElement).closest("." + a.wrapperClass).is(b.parent()) && m(c, !0);
                        d.preventDefault && !k && d.preventDefault();
                        k || (d.returnValue = !1)
                    }
                }
                function m(d, f, h) {
                    k = !1;
                    var e = d, g = b.outerHeight() - c.outerHeight();
                    f && (e = parseInt(c.css("top")) + d * parseInt(a.wheelStep) / 100 * c.outerHeight(), e = Math.min(Math.max(e, 0), g), e = 0 < d ? Math.ceil(e) : Math.floor(e), c.css({top: e + "px"}));
                    l = parseInt(c.css("top")) / (b.outerHeight() - c.outerHeight());
                    e = l * (b[0].scrollHeight - b.outerHeight());
                    h && (e = d, d = e / b[0].scrollHeight * b.outerHeight(), d = Math.min(Math.max(d, 0), g), c.css({top: d + "px"}));
                    b.scrollTop(e);
                    b.trigger("slimscrolling", ~~e);
                    v();
                    p()
                }
                function C() {
                    window.addEventListener ? (this.addEventListener("DOMMouseScroll", r, !1), this.addEventListener("mousewheel", r, !1), this.addEventListener("MozMousePixelScroll", r, !1)) : document.attachEvent("onmousewheel", r)
                }
                function w() {
                    u = Math.max(b.outerHeight() / b[0].scrollHeight * b.outerHeight(), D);
                    c.css({height: u + "px"});
                    var a = u == b.outerHeight() ? "none" : "block";
                    c.css({display: a})
                }
                function v() {
                    w();
                    clearTimeout(A);
                    l == ~~l ? (k = a.allowPageScroll, B != l && b.trigger("slimscroll", 0 == ~~l ? "top" : "bottom")) : k = !1;
                    B = l;
                    u >= b.outerHeight() ? k = !0 : (c.stop(!0, !0).fadeIn("fast"), a.railVisible && g.stop(!0, !0).fadeIn("fast"))
                }
                function p() {
                    a.alwaysVisible || (A = setTimeout(function() {
                        a.disableFadeOut && s || (x || y) || (c.fadeOut("slow"), g.fadeOut("slow"))
                    }, 1E3))
                }
                var s, x, y, A, z, u, l, B, D = 30, k = !1, b = f(this);
                if (b.parent().hasClass(a.wrapperClass)) {
                    var n = b.scrollTop(),
                            c = b.parent().find("." + a.barClass), g = b.parent().find("." + a.railClass);
                    w();
                    if (f.isPlainObject(h)) {
                        if ("height"in h && "auto" == h.height) {
                            b.parent().css("height", "auto");
                            b.css("height", "auto");
                            var q = b.parent().parent().height();
                            b.parent().css("height", q);
                            b.css("height", q)
                        }
                        if ("scrollTo"in h)
                            n = parseInt(a.scrollTo);
                        else if ("scrollBy"in h)
                            n += parseInt(a.scrollBy);
                        else if ("destroy"in h) {
                            c.remove();
                            g.remove();
                            b.unwrap();
                            return
                        }
                        m(n, !1, !0)
                    }
                } else {
                    a.height = "auto" == a.height ? b.parent().height() : a.height;
                    n = f("<div></div>").addClass(a.wrapperClass).css({position: "relative",
                        overflow: "hidden", width: a.width, height: a.height});
                    b.css({overflow: "hidden", width: a.width, height: a.height});
                    var g = f("<div></div>").addClass(a.railClass).css({width: a.size, height: "100%", position: "absolute", top: 0, display: a.alwaysVisible && a.railVisible ? "block" : "none", "border-radius": a.railBorderRadius, background: a.railColor, opacity: a.railOpacity, zIndex: 90}), c = f("<div></div>").addClass(a.barClass).css({background: a.color, width: a.size, position: "absolute", top: 0, opacity: a.opacity, display: a.alwaysVisible ?
                                "block" : "none", "border-radius": a.borderRadius, BorderRadius: a.borderRadius, MozBorderRadius: a.borderRadius, WebkitBorderRadius: a.borderRadius, zIndex: 99}), q = "right" == a.position ? {right: a.distance} : {left: a.distance};
                    g.css(q);
                    c.css(q);
                    b.wrap(n);
                    b.parent().append(c);
                    b.parent().append(g);
                    a.railDraggable && c.bind("mousedown", function(a) {
                        var b = f(document);
                        y = !0;
                        t = parseFloat(c.css("top"));
                        pageY = a.pageY;
                        b.bind("mousemove.slimscroll", function(a) {
                            currTop = t + a.pageY - pageY;
                            c.css("top", currTop);
                            m(0, c.position().top, !1)
                        });
                        b.bind("mouseup.slimscroll", function(a) {
                            y = !1;
                            p();
                            b.unbind(".slimscroll")
                        });
                        return!1
                    }).bind("selectstart.slimscroll", function(a) {
                        a.stopPropagation();
                        a.preventDefault();
                        return!1
                    });
                    g.hover(function() {
                        v()
                    }, function() {
                        p()
                    });
                    c.hover(function() {
                        x = !0
                    }, function() {
                        x = !1
                    });
                    b.hover(function() {
                        s = !0;
                        v();
                        p()
                    }, function() {
                        s = !1;
                        p()
                    });
                    b.bind("touchstart", function(a, b) {
                        a.originalEvent.touches.length && (z = a.originalEvent.touches[0].pageY)
                    });
                    b.bind("touchmove", function(b) {
                        k || b.originalEvent.preventDefault();
                        b.originalEvent.touches.length &&
                                (m((z - b.originalEvent.touches[0].pageY) / a.touchScrollStep, !0), z = b.originalEvent.touches[0].pageY)
                    });
                    w();
                    "bottom" === a.start ? (c.css({top: b.outerHeight() - c.outerHeight()}), m(0, !0)) : "top" !== a.start && (m(f(a.start).position().top, null, !0), a.alwaysVisible || c.hide());
                    C()
                }
            });
            return this
        }});
    jQuery.fn.extend({slimscroll: jQuery.fn.slimScroll})
})(jQuery);




/*!
 * iCheck v1.0.2, http://git.io/arlzeA
 * ===================================
 * Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization
 *
 * (c) 2013 Damir Sultanov, http://fronteed.com
 * MIT Licensed
 */

(function($) {

  // Cached vars
  var _iCheck = 'iCheck',
    _iCheckHelper = _iCheck + '-helper',
    _checkbox = 'checkbox',
    _radio = 'radio',
    _checked = 'checked',
    _unchecked = 'un' + _checked,
    _disabled = 'disabled',
    _determinate = 'determinate',
    _indeterminate = 'in' + _determinate,
    _update = 'update',
    _type = 'type',
    _click = 'click',
    _touch = 'touchbegin.i touchend.i',
    _add = 'addClass',
    _remove = 'removeClass',
    _callback = 'trigger',
    _label = 'label',
    _cursor = 'cursor',
    _mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent);

  // Plugin init
  $.fn[_iCheck] = function(options, fire) {

    // Walker
    var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]',
      stack = $(),
      walker = function(object) {
        object.each(function() {
          var self = $(this);

          if (self.is(handle)) {
            stack = stack.add(self);
          } else {
            stack = stack.add(self.find(handle));
          }
        });
      };

    // Check if we should operate with some method
    if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) {

      // Normalize method's name
      options = options.toLowerCase();

      // Find checkboxes and radio buttons
      walker(this);

      return stack.each(function() {
        var self = $(this);

        if (options == 'destroy') {
          tidy(self, 'ifDestroyed');
        } else {
          operate(self, true, options);
        }

        // Fire method's callback
        if ($.isFunction(fire)) {
          fire();
        }
      });

    // Customization
    } else if (typeof options == 'object' || !options) {

      // Check if any options were passed
      var settings = $.extend({
          checkedClass: _checked,
          disabledClass: _disabled,
          indeterminateClass: _indeterminate,
          labelHover: true
        }, options),

        selector = settings.handle,
        hoverClass = settings.hoverClass || 'hover',
        focusClass = settings.focusClass || 'focus',
        activeClass = settings.activeClass || 'active',
        labelHover = !!settings.labelHover,
        labelHoverClass = settings.labelHoverClass || 'hover',

        // Setup clickable area
        area = ('' + settings.increaseArea).replace('%', '') | 0;

      // Selector limit
      if (selector == _checkbox || selector == _radio) {
        handle = 'input[type="' + selector + '"]';
      }

      // Clickable area limit
      if (area < -50) {
        area = -50;
      }

      // Walk around the selector
      walker(this);

      return stack.each(function() {
        var self = $(this);

        // If already customized
        tidy(self);

        var node = this,
          id = node.id,

          // Layer styles
          offset = -area + '%',
          size = 100 + (area * 2) + '%',
          layer = {
            position: 'absolute',
            top: offset,
            left: offset,
            display: 'block',
            width: size,
            height: size,
            margin: 0,
            padding: 0,
            background: '#fff',
            border: 0,
            opacity: 0
          },

          // Choose how to hide input
          hide = _mobile ? {
            position: 'absolute',
            visibility: 'hidden'
          } : area ? layer : {
            position: 'absolute',
            opacity: 0
          },

          // Get proper class
          className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio,

          // Find assigned labels
          label = $(_label + '[for="' + id + '"]').add(self.closest(_label)),

          // Check ARIA option
          aria = !!settings.aria,

          // Set ARIA placeholder
          ariaID = _iCheck + '-' + Math.random().toString(36).substr(2,6),

          // Parent & helper
          parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''),
          helper;

        // Set ARIA "labelledby"
        if (aria) {
          label.each(function() {
            parent += 'aria-labelledby="';

            if (this.id) {
              parent += this.id;
            } else {
              this.id = ariaID;
              parent += ariaID;
            }

            parent += '"';
          });
        }

        // Wrap input
        parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert);

        // Layer addition
        helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent);

        // Finalize customization
        self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide);
        !!settings.inheritClass && parent[_add](node.className || '');
        !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id);
        parent.css('position') == 'static' && parent.css('position', 'relative');
        operate(self, true, _update);

        // Label events
        if (label.length) {
          label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) {
            var type = event[_type],
              item = $(this);

            // Do nothing if input is disabled
            if (!node[_disabled]) {

              // Click
              if (type == _click) {
                if ($(event.target).is('a')) {
                  return;
                }
                operate(self, false, true);

              // Hover state
              } else if (labelHover) {

                // mouseout|touchend
                if (/ut|nd/.test(type)) {
                  parent[_remove](hoverClass);
                  item[_remove](labelHoverClass);
                } else {
                  parent[_add](hoverClass);
                  item[_add](labelHoverClass);
                }
              }

              if (_mobile) {
                event.stopPropagation();
              } else {
                return false;
              }
            }
          });
        }

        // Input events
        self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) {
          var type = event[_type],
            key = event.keyCode;

          // Click
          if (type == _click) {
            return false;

          // Keydown
          } else if (type == 'keydown' && key == 32) {
            if (!(node[_type] == _radio && node[_checked])) {
              if (node[_checked]) {
                off(self, _checked);
              } else {
                on(self, _checked);
              }
            }

            return false;

          // Keyup
          } else if (type == 'keyup' && node[_type] == _radio) {
            !node[_checked] && on(self, _checked);

          // Focus/blur
          } else if (/us|ur/.test(type)) {
            parent[type == 'blur' ? _remove : _add](focusClass);
          }
        });

        // Helper events
        helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) {
          var type = event[_type],

            // mousedown|mouseup
            toggle = /wn|up/.test(type) ? activeClass : hoverClass;

          // Do nothing if input is disabled
          if (!node[_disabled]) {

            // Click
            if (type == _click) {
              operate(self, false, true);

            // Active and hover states
            } else {

              // State is on
              if (/wn|er|in/.test(type)) {

                // mousedown|mouseover|touchbegin
                parent[_add](toggle);

              // State is off
              } else {
                parent[_remove](toggle + ' ' + activeClass);
              }

              // Label hover
              if (label.length && labelHover && toggle == hoverClass) {

                // mouseout|touchend
                label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass);
              }
            }

            if (_mobile) {
              event.stopPropagation();
            } else {
              return false;
            }
          }
        });
      });
    } else {
      return this;
    }
  };

  // Do something with inputs
  function operate(input, direct, method) {
    var node = input[0],
      state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked,
      active = method == _update ? {
        checked: node[_checked],
        disabled: node[_disabled],
        indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false'
      } : node[state];

    // Check, disable or indeterminate
    if (/^(ch|di|in)/.test(method) && !active) {
      on(input, state);

    // Uncheck, enable or determinate
    } else if (/^(un|en|de)/.test(method) && active) {
      off(input, state);

    // Update
    } else if (method == _update) {

      // Handle states
      for (var each in active) {
        if (active[each]) {
          on(input, each, true);
        } else {
          off(input, each, true);
        }
      }

    } else if (!direct || method == 'toggle') {

      // Helper or label was clicked
      if (!direct) {
        input[_callback]('ifClicked');
      }

      // Toggle checked state
      if (active) {
        if (node[_type] !== _radio) {
          off(input, state);
        }
      } else {
        on(input, state);
      }
    }
  }

  // Add checked, disabled or indeterminate state
  function on(input, state, keep) {
    var node = input[0],
      parent = input.parent(),
      checked = state == _checked,
      indeterminate = state == _indeterminate,
      disabled = state == _disabled,
      callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
      regular = option(input, callback + capitalize(node[_type])),
      specific = option(input, state + capitalize(node[_type]));

    // Prevent unnecessary actions
    if (node[state] !== true) {

      // Toggle assigned radio buttons
      if (!keep && state == _checked && node[_type] == _radio && node.name) {
        var form = input.closest('form'),
          inputs = 'input[name="' + node.name + '"]';

        inputs = form.length ? form.find(inputs) : $(inputs);

        inputs.each(function() {
          if (this !== node && $(this).data(_iCheck)) {
            off($(this), state);
          }
        });
      }

      // Indeterminate state
      if (indeterminate) {

        // Add indeterminate state
        node[state] = true;

        // Remove checked state
        if (node[_checked]) {
          off(input, _checked, 'force');
        }

      // Checked or disabled state
      } else {

        // Add checked or disabled state
        if (!keep) {
          node[state] = true;
        }

        // Remove indeterminate state
        if (checked && node[_indeterminate]) {
          off(input, _indeterminate, false);
        }
      }

      // Trigger callbacks
      callbacks(input, checked, state, keep);
    }

    // Add proper cursor
    if (node[_disabled] && !!option(input, _cursor, true)) {
      parent.find('.' + _iCheckHelper).css(_cursor, 'default');
    }

    // Add state class
    parent[_add](specific || option(input, state) || '');

    // Set ARIA attribute
    if (!!parent.attr('role') && !indeterminate) {
      parent.attr('aria-' + (disabled ? _disabled : _checked), 'true');
    }

    // Remove regular state class
    parent[_remove](regular || option(input, callback) || '');
  }

  // Remove checked, disabled or indeterminate state
  function off(input, state, keep) {
    var node = input[0],
      parent = input.parent(),
      checked = state == _checked,
      indeterminate = state == _indeterminate,
      disabled = state == _disabled,
      callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
      regular = option(input, callback + capitalize(node[_type])),
      specific = option(input, state + capitalize(node[_type]));

    // Prevent unnecessary actions
    if (node[state] !== false) {

      // Toggle state
      if (indeterminate || !keep || keep == 'force') {
        node[state] = false;
      }

      // Trigger callbacks
      callbacks(input, checked, callback, keep);
    }

    // Add proper cursor
    if (!node[_disabled] && !!option(input, _cursor, true)) {
      parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
    }

    // Remove state class
    parent[_remove](specific || option(input, state) || '');

    // Set ARIA attribute
    if (!!parent.attr('role') && !indeterminate) {
      parent.attr('aria-' + (disabled ? _disabled : _checked), 'false');
    }

    // Add regular state class
    parent[_add](regular || option(input, callback) || '');
  }

  // Remove all traces
  function tidy(input, callback) {
    if (input.data(_iCheck)) {

      // Remove everything except input
      input.parent().html(input.attr('style', input.data(_iCheck).s || ''));

      // Callback
      if (callback) {
        input[_callback](callback);
      }

      // Unbind events
      input.off('.i').unwrap();
      $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i');
    }
  }

  // Get some option
  function option(input, state, regular) {
    if (input.data(_iCheck)) {
      return input.data(_iCheck).o[state + (regular ? '' : 'Class')];
    }
  }

  // Capitalize some string
  function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  // Executable handlers
  function callbacks(input, checked, callback, keep) {
    if (!keep) {
      if (checked) {
        input[_callback]('ifToggled');
      }

      input[_callback]('ifChanged')[_callback]('if' + capitalize(callback));
    }
  }
})(window.jQuery || window.Zepto);







function applyClientValidations() {};




//KANBAN
$(function () {
    var kanbanCol = $('.panel-body');
    kanbanCol.css('max-height', (window.innerHeight - 150) + 'px');

    var kanbanColCount = parseInt(kanbanCol.length);
    //$('.container-fluid').css('min-width', (kanbanColCount * 350) + 'px');

    draggableInit();

    $('.panel-heading').click(function() {
        var $panelBody = $(this).parent().children('.panel-body');
        $panelBody.slideToggle();
    });
});

function draggableInit() {
    var sourceId;

    $('[draggable=true]').bind('dragstart', function (event) {
        sourceId = $(this).parent().attr('id');
        event.originalEvent.dataTransfer.setData("text/plain", event.target.getAttribute('id'));
    });

    $('.panel-body').bind('dragover', function (event) {
        event.preventDefault();
    });

    $('.panel-body').bind('drop', function (event) {
        var children = $(this).children();
        var targetId = children.attr('id');

        if (sourceId != targetId) {
            var elementId = event.originalEvent.dataTransfer.getData("text/plain");
            //$('#processing-modal').modal('toggle'); //before post
            // Post data 
            setTimeout(function () {
                var element = document.getElementById(elementId);
                children.prepend(element);
                //$('#processing-modal').modal('toggle'); // after post
            }, 10);
        }
        event.preventDefault();
    });
}

function handleSwapTab(link) {
	if (document.getElementById("pageStatus") == undefined || document.getElementById("pageStatus").value == "READ") {
		doShowWaitPopup();
		window.location = link.href;
	} else {
		var lastForm = document.forms.length - 1;
		document.forms[lastForm].action = link.href;
		if (document.forms[lastForm].onsubmit()) {
			resetInputNumbers();
			document.forms[lastForm].submit();
		}
	}
	return false;
}
