var cur_wid = "";
	function SwitchEditorDevice(dev){

		$(".editor-holder").attr(
			"data-url" , 
			$(".editor-holder").attr("data-editor") + "&section=" + dev
		);

		SaveLayout();

	}
	function SaveLayout(noredir) {

		noredir = noredir || false ;

		var layouts = {};
		var layout = 0;
		var column = 0;
		var count = 0;

		$(".editor-columns").each(function() {

			layout = $(this).attr("data-layout");

			layouts[layout] = {};

			$(this).find(".editor-column").each(function(){

				column = $(this).attr("data-column");

				$(this).find("div.editor-widget").each(function(){
					count ++;

					layouts[layout][count] = { 
						"colum"		: column,
						"widget"	: $(this).attr("data-id"),
						"layout"	: layout
					};
				});
			});
		});

		$.ajax({
			url:"json.php?mod=layouts&sub=editor-save",
			type:'post',
			data:"data=" + JSON.stringify(layouts),
			dataType : 'json',
			success: function(msg){ 
				
				if (noredir) {
					Alert( "Layout saved successfully!");
				} else {
					window.location.href = $(".editor-holder").attr("data-url");
				}
			}
		});

		return false;
		
	}

  $(document).ready(function() {

	$('.widgets-filter-holder .with-tooltip').tooltip({
		placement: 'bottom',
		html: 'true',
		container: "body"
	});


	$(".widgets-filter-holder .reload").click(function() {
		$(".editor-widgets-scroller").load(
			"ajax.php?mod=layouts&sub=widgets" , 
			function() {
				UpdateWidgetSize();
				$('.isotope').isotope();				

				$( ".editor-widgets div.editor-widget" ).draggable({

					appendTo: "body",
					helper: "clone",
					cursor: "move"

				}).disableSelection();


				$("#widget-filter-name").trigger("keyup");
			}
		);
	});
	
	$(".layout-blocks > .widget.Orange > .widget-form div.row").hide();
	$(".layout-blocks > .widget.Orange").first().find("div.row").show();
	$(".layout-blocks > .widget.Orange").first().addClass("opened");

	$(".layout-blocks > .widget.Orange > .widget-head").click(function(){

		$parent = $(this).closest("div.widget.Orange");		
		$parent.toggleClass("opened");

		if ($parent.hasClass("opened")){
			$parent.find("div.row").slideDown();
		} else {
			$parent.find("div.row").slideUp();
		}
	});

	$(document).on(
		"click" , 
		".editor-widget-delete",

//	$(".editor-widget-delete").live(
//		"click",
		function(){

			cur_wid = $(this).closest("div.editor-widget");
			DeleteConfirmCallback("Remove this widget from the layout?", 
				deleteWidget
			);

/*
			if (confirm(
				"Do you want to delete this widget ? \n\n" + $(this).closest("div.editor-widget").text().trim()
				)){

				$(this).closest("div.editor-widget").remove();
			}
			ala 
*/
		}
	);

	function deleteWidget(){
		cur_wid.remove();
	}

	$( ".editor-column-widgets" ).droppable({
	
			activeClass: "editor-column-widgets-active",
			  hoverClass: "", //"ui-state-hover",
			  accept: ":not(.ui-sortable-helper)",
			  drop: function( event, ui ) {

				  var htm = ui.draggable.html();

				$( "<div></div>" )
					.attr("data-id" , ui.helper.attr("data-id"))
					.addClass("editor-widget")
					.html( htm + 
						"<a href='index.php?mod=widgets&sub=widgets&widget_id=" + ui.helper.attr("data-id") + "&action=details&t=u' class='editor-widget-edit' target='_blank'><span class='sign sign-edit'></span></a>" + 
						"<div class='editor-widget-delete'><span class='sign sign-delete'></span></div>")
					.appendTo( this ).find(".editor-widget-drag").remove();
			  }	
	}).sortable({

		//_axis : "y",

		//items: "div",
		sort: function() {
			//$( this ).removeClass( "ui-state-default" );
		},

		stop: function() {
			$(".editor-column-widgets-active").removeClass("editor-column-widgets-active");
		},

		placeholder: "editor-widget-active",

		connectWith: ".editor-column-widgets",

		cursor: "move"

    }).disableSelection();
	
	$( ".editor-widgets div.editor-widget" ).draggable({

		appendTo: "body",
		helper: "clone",
		cursor: "move"

    }).disableSelection();

	//update the size of all widgets
	function UpdateWidgetSize(){

		//fix the affix first

		var editor_wms = 0;

		$('.editor-widgets .editor-widget').matchHeight({ byRow : false}); 
/*
		$('.editor-widgets .editor-widget').each(function() {
			$(this).parent().css("height" , "auto");
		});

		$('.editor-widgets .editor-widget').each(function(){
			if ($(this).height() > editor_wms){
				editor_wms = $(this).height();
			}
		});

		
		$('.editor-widgets .editor-widget').parent().css("height" , (editor_wms + 12) + "px");
*/
	}

	UpdateWidgetSize();

	//$( window ).resize(function() {UpdateWidgetSize() });

	function LoadColumnWidgets(){

		$(".editor-column").each(function(){
			var widgets = $(this).attr("data-widgets");

			if (widgets != ""){
				widgets = widgets.split(",");

				for (i in widgets){

					widget_data = $("#editor-widget-id-"+ widgets[i] );

					if (widget_data.length){

						$( "<div></div>" )
						.attr("data-id" , widget_data.attr("data-id"))
						.addClass("editor-widget")
						.html( 
							widget_data.html() + 
							"<a href='index.php?mod=widgets&sub=widgets&widget_id=" + widget_data.attr("data-id") + "&action=details&t=u' class='editor-widget-edit' target='_blank'><span class='sign sign-edit'></span></a>" + 							
							"<div class='editor-widget-delete'><span class='sign sign-delete'></span></div>")
						.appendTo( $(this).find(".editor-column-widgets") );
					}
				}
			}
		});

	} LoadColumnWidgets();


  });



$(document).ready(function() {

		var qsRegex;

		$( function() {
	  
			  $('.isotope').isotope({
					h_eight: 500,
					resizesContainer: false,
					itemSelector: '.editor-widget-holder',
					layoutMode: "fitRows",
						/*
					layoutMode: 'masonry',
					masonry: {
						gutter: 0,
						columnWidth: 170,
						isFitWidth: true
					}*/

					filter: function () {

						if (qsRegex){
							return $(this).text().match( qsRegex );
						} else {
							return true;
						}

						//return qsRegex ? : true;
					}
			  });

		});


		function debounce( fn, threshold ) {
			var timeout;

			return function debounced() {
				if ( timeout ) {
					clearTimeout( timeout );
				}
	
				function delayed() {
					fn();
					timeout = null;
				}
				setTimeout( delayed, threshold || 100 );
			}
		}



		 var $quicksearch = $('#widget-filter-name').keyup( debounce( function() {

			if ($("#widgets-filter").val()) {
				$("#widgets-filter").val('').trigger("chosen:updated");
			}

			var search = $("#widget-filter-name").val().split(" ");
			//qsRegex = new RegExp( $quicksearch.val(), 'gi' );
             $('.isotope').isotope({
                filter: function() {

					var text = $(this).text().replace("\"" , " ").replace("\"" , " ");

					if ($(this).text().trim() == "Base Module") 	{
						return true;
					}

					if (search.length){

						for (i in search){
							if (!text.match( new RegExp( search[i], 'gi' ) ))
								return false;
						}				

						return true;

					} else {
						return true;
					}

                  }
            });
	    }) );

		//isotope gallery filtering
		$("#widgets-filter").change(function(e){
			var $parent = $(".isotope");
			$parent.isotope({filter : $(this).val()} );

			return false;
		});
/*
		var

		$("#widget-filter-name").keyup(function(e){
			var $parent = $(".isotope");
			$parent.isotope({filter : $(this).val()} );

			return false;
		});
*/

});