function is_touch_device() {
  return 'ontouchstart' in window        // works on most browsers 
      || navigator.maxTouchPoints;       // works on IE10/11 and Surface
};


function humanFileSize(fileSizeInBytes) {

    var i = -1;
    var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);

    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};


function str_replace( r, w , s){
     return s.split(r).join(w);
}


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}	



function formsResize() {
	$(".formLine>.col-md-3, .formLine>.col-md-9").css("min-height" , "auto");
	$(".formLine>.col-md-3").each(function(e){
		if ($(this).height() > $(this).siblings(".col-md-9").height()){
			$(this).siblings(".col-md-9").css("min-height" , $(this).height());
		}
	});
}

$( window ).resize(function() {
	formsResize();
});

$(document).ready(function() {

	$("span.form_preffix").each(function() {
		if ($(this).html() == ""){
			$(this).remove();
		}
	});

	formsResize();

//	if ($(".dashboard-isotope").length){

		$('.dashboard-isotope').isotope({
		  itemSelector : '.isotope-element'
		});

//	}

	$(".form_suffix,.form_prefix").each(function(e){
		if ($(this).html().trim() == ""){
			$(this).remove();
		}
	});


	//design fix
	$(".table tbody tr:nth-child(odd) td").addClass("table-td-odd");

	$(".widget").each(function(){
		if ($(this).children("div:not(.widget-head)").length ){			
		} else {
			$(this).addClass("widget-no-bot-border");
		}
	});


	//$("html").niceScroll();

	$(document).on(
		"click" , 
		".noteCloseButt",
//	$(".noteCloseButt").live(
//		"click",
		function(){
			$(this).closest(".responsebox").slideUp("normal" , function(){ $(this).closest(".responsebox").html(""); })
			return false;
		}
	);

	// Bootstrap Loading button
    $('#loading').click(function () {
        var btn = $(this)
        btn.button('loading')
        setTimeout(function () {
          btn.button('reset')
        }, 3000)
      });
	
	// Bootstrap Dropdown
	$('.dropdown-toggle').dropdown(); 

	//easytabs
	if ($.fn.easytabs) {
		$(".widget-tabs").easytabs({
		  animate: true,
		  defaultTab: "li:first-child",
		  panelActiveClass: "active-content-div",
		  tabActiveClass: "selected",
		  tabs: "> div > ul.tabs > li",
		  updateHash: false
		});
	}

	//table select all function 


	$('input.checkall').click(function() {
		var checkboxes = $(this).closest('table').find(':checkbox');
		if($(this).is(':checked')) {
			checkboxes.prop('checked', true);
		} else {
			checkboxes.prop('checked', false);
		}
	});

	//default ajax processing

	//accordion

	$(".accordion").find(".widget-head").on(
		"click tapone",
		function(){
			var next = $(this).closest(".widget-head").next();

			if (next.hasClass("open")){
				next.slideUp();
			} else {
				next.slideDown();
			}

			next.toggleClass("open");

			return false;
		}	
	);

	$(document).on(
		"tap" , 
		".accordion .widget-head",

//	$(".accordion").find(".widget-head").live(
//		"tap",
		function(){
			var next = $(this).next();

			if (next.hasClass("open")){
				next.slideUp();
			} else {
				next.slideDown();
			}

			next.toggleClass("open");

			return false;
		}	
	);


	//elastic - autogrowing textarea	
	if ($.fn.elastic) {
		$(".elastic").elastic();
	}

	//autocomplete off
	$(".autocomplete_off").attr("autocomplete" , "off");


	//togle menu
	$("#toggle-menu").click( function() {
		$("#main-nav").toggleClass("ipad" );
		$(".rightSection").toggleClass("ipad" );
		$(".backBody").toggleClass("ipad" );

		return false;
	});	


	$("[rel^='prettyPhoto']").prettyPhoto({
		social_tools:false,
		theme: "dark_square",
	});



	//modal
	$("#popup").on("shown.bs.modal", function(e) {


		//var content = $(".modal").find(".modal-content-data");
		if (content.lenght){
			//content.attr("data-width") + 40) + "px"
			//$(".modal-dialog").css("width" , (content.attr("data-width") + 40) + "px");
		}

	});


	$("[data-popup]").click(function(e){

		$(".ui-dialog-title").css("display" , "none");

		var popup = $($(this).attr("data-popup"));
		var _title = $(this).attr("data-popup-title");

		popup.load($(this).attr("href") , function() {
			
			popup.dialog({
				title		:_title,
				//"width"	: $(this).attr("data-width")
				dialogClass : 'cms-confirm-box cms-browse-popup cms-show-close',
//				dialogClass : 'white-content',
				resizable	: false,
				modal		: true,
				width		:'auto',
				position	: { 
						my: "center", 
						at: "center", 
						of: window 
				},

				close		: function(event, ui) {
						$(this).empty().dialog('destroy');
				}
			});
		
		});

		return false;
		
	});


	widgets();



});



function ConfirmRedirect(title , redirect){
	DeleteConfirm(title,redirect);
}

function DeleteConfirm(title , redirect) {
	$("#delete-confirm").html("<p>" + title + "</p>");
    $("#delete-confirm").dialog({
		title		:"",
		dialogClass : 'cms-confirm-box cms-simple-confirm-box',
        resizable	: false,
		draggable	: false,

		width		:'auto',
        modal		: true,
        buttons: [
			{
				text	: "OK",
		        click	: function () {
			        window.location.href = redirect;
				    $(this).dialog("close");
	            },
				class	:	"cms-button-confirm"

			},
			{						
				text	: "Cancel",
				click	: function () {
	                $(this).dialog("close");
		            return false;
			    },
				class	:	"cms-button-close"

			}
        ]
    });    
}

function AlertBox(title) {
	$("#delete-confirm").html("<p>" + title + "</p>");
    $("#delete-confirm").dialog({
		title:"",
		dialogClass : 'cms-confirm-box cms-simple-confirm-box',
        resizable: false,
		width		:'auto',
        modal: true,
        buttons: [
			{
				text	: "OK",
		        click	: function () {
				    $(this).dialog("close");
					return false;
	            },
				class	:	"cms-button-confirm"

			}
        ]
    });    
}

function AlertBoxCallback(title , func) {
	$("#delete-confirm").html("<p>" + title + "</p>");
    $("#delete-confirm").dialog({
		title:"",
		dialogClass : 'cms-confirm-box cms-simple-confirm-box',
        resizable: false,
		width		:'auto',
        modal: true,
        buttons: [
			{
				text	: "OK",
		        click	: function () {
				    $(this).dialog("close");
					func();
					return false;
	            },
				class	:	"cms-button-confirm"

			}
        ]

    });    
}


function ConfirmCallback(title , func , funcCancel) {
	DeleteConfirmCallback(title , func , funcCancel);
}

function DeleteConfirmCallback(title , func , funcCancel) {
	$("#delete-confirm").html("<p>" + title + "</p>");
    $("#delete-confirm").dialog({
		title		:"",
		dialogClass : 'cms-confirm-box cms-simple-confirm-box',
        resizable	: false,
		draggable	: false,

		width		:'auto',
        modal: true,

        buttons: [
			{
				text	: "OK",
		        click	: function () {
					$(this).dialog("close");
					func();
	            },
				class	:	"cms-button-confirm"

			},
			{						
				text	: "Cancel",
				click	: function () {
	                $(this).dialog("close");
					if (typeof funcCancel === 'undefined') { 
						return false; 
					} else {
						funcCancel();
					}
		            return false;
			    },
				class	:	"cms-button-close"

			}
        ]

    });    
}


function Alert(title) {
	$("#delete-confirm").html("<p>" + title + "</p>");
    $("#delete-confirm").dialog({
		title:"",
		dialogClass : 'cms-confirm-box cms-simple-confirm-box',
        resizable: false,
		width		:'auto',
        modal: true,
        buttons: [
			{
				text	: "OK",
		        click	: function () {
				    $(this).dialog("close");
					return false;
	            },
				class	:	"cms-button-confirm"

			}
        ]
    });    
}

function widgets() {

	$("_.widget.collapsed.open").each(function() {
		var parent = $(this);
		var body = $(this).find(".widget-form");
		var siblings = parent.nextUntil(".widget.widget-main");

//		var hasStyle = parent.attr("style") != "";

		body.slideDown(0, function() {
			var cm = body.find(".CodeMirror");

			if (cm.length) {
				cm.each(function(i, el){
					el.CodeMirror.refresh();
				});
			}
		});

		if (siblings.length){
			siblings.each(function() {

				if ($(this).attr("style").trim() != "") {
				} else {
					console.log("x");
					console.log($(this));
					$(this).slideDown(0);
				}
			});
		}
	});

	$(".widget.collapsed .widget-head").click(function(e){

		var parent = $(this).closest(".widget");
		var body = parent.find(".widget-form");
		
		parent.toggleClass("open");			

		
		var siblings = parent.nextUntil(".widget.widget-main");

		if (parent.hasClass("open")) {
			body.slideDown(0,function() {
				var cm = body.find(".CodeMirror");

				if (cm.length) {
					cm.each(function(i, el){
						el.CodeMirror.refresh();
					});
				}

			});

			if (siblings.length){
				siblings.each(function() {
					$(this).slideDown(0 , function() {
					
						if ($(this).attr("old-style")) {
							$(this).attr("style" , $(this).attr("old-style"));
						}
					});					
				})
			}
		} else {
			body.slideUp();
			if (siblings.length){
				siblings.each(function() {
					$(this).attr("old-style", $(this).attr("style"));
					$(this).slideUp(0);
				});
				
			}
		}
	});
}




function BrowseIconFonts(sel , field) {

	$.jGrowl("Loading Icon Library..." , { life: 500 });
	
	var params = {
		"sel"	: sel,
		"t"		: $.now(),
		"mod"	: "tools",
		"sub"	: "browsefonts",
		"field"	: field,
	}

	$("#dialog").html("");
	$("#dialog").load("index.php?" + $.param(params));
    $("#dialog").dialog({
		dialogClass : 'cms-confirm-box cms-browse-popup cms-show-close',
		title		: "Select Icon",
        resizable	: false,
		width		:'884',
		height		: "580",
        modal		:true        
    });    
} 


function BrowsePopup(title , link , width , height) {

	$.jGrowl("Loading..." , { life: 500 });
	
	$("#dialog").html("");
	$("#dialog").load(link);
    $("#dialog").dialog({
		dialogClass : 'cms-confirm-box cms-browse-popup cms-show-close ' + ($(window).width() > width ? "": " cms-popup-fs "),
		title		: title,
        resizable	: true,
		draggable	: false,
        modal		: true,
	    width		: width,
		height		: height,
    });    
}



function FileManager() {

	window.KCFinder = {};
    window.KCFinder.callBack = function(url) {
        // Actions with url parameter here
        window.KCFinder = null;
    };


	var h = 500;
	var w = 900;
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;


    window.open(
		'./3rdparty/filemanager/browse.php?type=upload', 
		'kcfinder_single',
		'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=no,toolbar=no,menubar=no,statusbar=no,status=no,resizable=yes'	
	);


/*
	var finder = new CKFinder();
	finder.basePath = '/admin/3rdparty/ckfinder/';
	finder.Resources = "Files";
	
	finder.width = 700;
	finder.language = 'en';
	finder.popup();	
*/
}


function launchApplication(l_url, l_windowName)
{
  if ( typeof launchApplication.winRefs == 'undefined' )
  {
    launchApplication.winRefs = {};
  }
  if ( typeof launchApplication.winRefs[l_windowName] == 'undefined' || launchApplication.winRefs[l_windowName].closed )
  {
    var l_width = screen.availWidth;
    var l_height = screen.availHeight;

    var l_params = 'status=1,location=1,menubar=1,titlebar=1,toolbar=1' +
                   ',resizable=1' +
                   ',scrollbars=1' +
                   ',width=' + l_width +
                   ',height=' + l_height +
                   ',left=0' +
                   ',top=0';

    launchApplication.winRefs[l_windowName] = window.open(l_url, l_windowName, l_params);
    launchApplication.winRefs[l_windowName].moveTo(0,0);
    launchApplication.winRefs[l_windowName].resizeTo(l_width, l_height);
  } else {
    launchApplication.winRefs[l_windowName].focus()
  }
}

function configureHtmlOutput( ev ) {

    // Ends self closing tags the HTML4 way, like <br>.
    ev.editor.dataProcessor.htmlFilter.addRules(
        {
            elements:
            {
                $: function (element) {
                    // Output dimensions of images as width and height
                    if (element.name == 'img') {
                        var style = element.attributes.style;

                        if (style) {
                            // Get the width from the style.
                            var match = /(?:^|\s)width\s*:\s*(\d+)px/i.exec(style),
                                width = match && match[1];

                            // Get the height from the style.
                            match = /(?:^|\s)height\s*:\s*(\d+)px/i.exec(style);
                            var height = match && match[1];

                            // Get the align from the style

                            var match = /(?:^|\s)float\s*:\s*(left|right)/i.exec(style),
                            align = match && match[1];

                            if (width) {
                                element.attributes.style = element.attributes.style.replace(/(?:^|\s)width\s*:\s*(\d+)px;?/i, '');
                                element.attributes.width = width;
                            }

                            if (height) {
                                element.attributes.style = element.attributes.style.replace(/(?:^|\s)height\s*:\s*(\d+)px;?/i, '');
                                element.attributes.height = height;
                            }

                            if (align) {
                                element.attributes.style = element.attributes.style.replace(/(?:^|\s)float\s*:\s*(left|right);?/i, '');
                                element.attributes.align = align;
                            }
                        }
                    }



                    if (!element.attributes.style)
                        delete element.attributes.style;

                    return element;
                }
            }
        });


}