/*
 * GENERAL INTERFACE FUNCTIONS
 */

$.fn.YFperma_delete = function() {
	if ($('.delete_link').length > 0) {
		$('.delete_link').click(function(e){
			e.preventDefault();
			var object_title = $(this).data('title');
			var object_slug = $(this).data('object_slug');
			var module_name = $(this).data('module_name');
			var uri = $().msg('uri_api')+module_name+'/delete/?slug='+object_slug;
			var yes = confirm($().msg('delete_confirm')+" «"+ object_title + "»?");
			if(yes){
				$.post(uri,function(json) {
					var edit_listing = $().msg('uri_admin')+module_name+'/';
					window.location.href = edit_listing;
				},'json');
			}
			return false;
		});
	}
}

$.fn.YFinterfaceDelete = function(options) {
	var defaults = {
		start_text: $().msg('delete_confirm'),
		title: '',
		module_name: false,
		object_slug: false,
		row_id: false,
		show_empty: true,
		redirect: false,
		end_text: false,
		wrap_title_in_quotes: true
	};
	var opts = $.extend(defaults, options);
	
	// give confirmation alert
	var yes=confirm(opts.start_text+(opts.wrap_title_in_quotes ? " «" : " ")+ opts.title + (opts.wrap_title_in_quotes ? "»" : "")+"?"+(opts.end_text ? " "+opts.end_text : ""));
	var offset = 2;
	if(yes){
		var uri = $().msg('uri_api')+opts.module_name+'/delete/?slug='+opts.object_slug;
		if (opts.redirect) {
			uri += '&redirect=1';
		}  else {
			uri += '&redirect=0';
		}
		if (opts.row_id) {
			var table = $("#"+opts.row_id).parent();
			$(".even").removeClass('even');
			$.post(uri,function(json) {
				$("#"+opts.row_id).slideUp("fast",function(){
					var num_rows = $().YFinterfaceTableGetNumRows(table, offset);
					if ((num_rows == 0) && opts.show_empty) {
						var empty_url = $().msg('url_prefix')+'/'+opts.module_name+'/'+$().msg('uri_empty')+'/';
						$.get(empty_url, false, function(data){ 
							var table_container = table.parent();
							table_container.before('<div class="hidden" id="emptylist">'+data+'</div>');
							table_container.slideUp("slow");
							$("#emptylist").show("slow");
							offset++;
						});
					}
				}).delay(800).remove().YFinterfaceTableZebraRowsInit();;
			},'json');
		} else {
			$.post(uri,function(json) {
				var edit_listing = $().msg('uri_admin')+opts.module_name+'/';
				window.location.href = edit_listing;
			},'json');
		}
        return false;
	} else {
        return false;
	}
}


$.fn.YFconfirmAndSubmitDelete = function( options )
{
	var defaults = {
		alert: 'Are you sure?',
		form_dom_id: false
	};
	var opts = $.extend(defaults, options);
	
	// give confirmation alert
	var yes=confirm(opts.alert);

	if(yes){
		var myForm = document.getElementById(opts.form_dom_id);
		myForm.submit();
	}
	else{
        return false;
	}
}



// Focus first element
// from http://www.gerd-riesselmann.net/development/focus-first-form-field-with-jquery
$.fn.YFinterfaceFormFocusFirstInput = function() {

  var elem = $('input:visible', this).get(0);
  var select = $('select:visible', this).get(0);

  if (select && elem) {
    if (select.offsetTop < elem.offsetTop) {
      elem = select;
    }
  }

  var textarea = $('textarea:visible', this).get(0);

  if (textarea && elem) {
    if (textarea.offsetTop < elem.offsetTop) {
      elem = textarea;
    }
  }

  if (elem && elem.id != 'entry_1') {
    elem.focus();
  }

  return this;
}

$.fn.YFinterfacePopWindow = function(options) {
	var defaults = {
		url: false, 
		width: 60, 
		height: 60, 
		xpos: 60, 
		ypos: 60, 
		toolbar: false, 
		scrollbar: false, 
		resizable: true, 
		name: 'popped',
		status: false,
		titlebar: false,
		directories: false
	};
	var opts = $.extend(defaults, options);
	
    var wspec = "width="  + opts.width  + ",";
    var hspec = "height=" + opts.height + ",";
    var xspec = "screenX=" + opts.xpos + ",left=" + opts.xpos + ",";
    var yspec = "screenY=" + opts.ypos + ",top="  + opts.ypos + ",";

    var toolspec   = (opts.toolbar)   ? "toolbar=yes,"    : "toolbar=no,";
    var scrollspec = (opts.scrollbar) ? "scrollbars=yes," : "scrollbars=no,";
    var resizspec  = (opts.resizable) ? "resizable=yes,"  : "resizable=no,";

    var specs  = wspec + hspec + xspec + yspec;
    specs += toolspec + scrollspec + resizspec;
    specs += "status=no,titlebar=no,directories=no";

    var popper = window.open(opts.url,opts.name,specs);
    if (window.focus) popper.focus();
}

$.fn.YFinterfaceTableZebraRowsInit = function(options) {
	var defaults = {
		tableclass: 'zebra',
		tableid: false,
		classtoadd: 'even',
		parentelement: 'table',
		childelement: 'tr'
	};
	var opts = $.extend(defaults, options);

	if (opts.tableid) {
		$("#"+opts.tableid+" "+opts.childelement).removeClass(opts.classtoadd);
		$("#"+opts.tableid+" "+opts.childelement+":nth-child(even):visible").addClass(opts.classtoadd);
	} else {
		$(opts.parentelement+"."+opts.tableclass+" "+opts.childelement).removeClass(opts.classtoadd);
		$(opts.parentelement+"."+opts.tableclass+" "+opts.childelement+":nth-child(even):visible").addClass(opts.classtoadd);
	}
}

$.fn.YFinterfaceTableGetNumRows = function(table, offset)
{
	var rows = table.children("tr");
	num_rows = rows.length-offset;
	
	return(num_rows);
}

$.fn.YFinterfaceLightboxInit = function()
{
	$("a[rel^='lightbox']").slimbox({counterText: $().msg('slimbox_image_counter')}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
}

$.fn.YFinterfaceTableDragNDropInit = function(options)
{
	var defaults = {
		table_class: false,
		module: false,
		module_name: false
	};

	var opts = $.extend(defaults, options);

	$("."+opts.table_class).tableDnD({
	    onDragClass: "onDrag",
	    dragHandle: "dragger",
	    onDrop: function(table, row) {
			$().YFinterfaceTableOrderSave({'table':table, 'row':row, 'module':opts.module, 'module_name':opts.module_name});
	    }
	});
}

$.fn.YFinterfaceTableOrderSave = function(options) {

	var defaults = {
		table: false,
		row: false,
		module: false,
		module_name: false,
		ref_class: current_module,
		id: false
	};
	var opts = $.extend(defaults, options);
	
	$().YFinterfaceTableZebraRowsInit();
	
    var rows = opts.table.tBodies[0].rows;
    var order_csv = "";
    for (var i=0; i<rows.length; i++) {
        order_csv += rows[i].id.substring(opts.module.length)+",";
    }

	var ref_id 			= $("#"+opts.ref_class+"_id").val();

	var uri = $().msg('uri_api')+opts.module_name+'/setorder/?order='+escape(order_csv);
	console.log(opts.module);
	if (opts.ref_class && !((opts.module == 'category') || (opts.module == 'portfolioitem'))) {
		console.log('this is no good');
		uri += '&ref_class='+opts.ref_class;
	}
	if (ref_id) {
		uri += '&ref_id='+ref_id;		
	}
	if (opts.id) {
		uri += '&id='+opts.id;			
	}
	
	$.getJSON(uri,function(json) { });
}

yf_help_filter_open = Array();

$.fn.YFinterfaceHelpFilterShow = function(classname, inputname)
{
	var origin = $('#'+classname+'_'+inputname);
	var buttontxt = $("#filterhelpbutton"+inputname+" a");
	buttontxt.html($().msg('loading'));

	$("#filterhelpcontent"+inputname).load($().msg('uri_textfilter'), function() { 
		$("#filterhelpcontent"+inputname).css('top', "16px !important");
		var height = $("#filterhelpcontent"+inputname).height()-12;
		var width = origin.css('width').substr(0, 3);
		width = (width-0)+14;
		var xpos = width;
		$("#filterhelpcontent"+inputname).css('position', 'relative');
		$("#filterhelpcontent"+inputname).css('left', xpos+"px");
		$("#filterhelpcontent"+inputname).css('margin-left', "10px");
		$("#filterhelpcontent"+inputname).css('margin-bottom', "-"+height+"px");
		$("#filterhelpcontent"+inputname+" tr:nth-child(even)").addClass("minieven");
		$("#filterhelpcontent"+inputname).fadeIn("fast");
		buttontxt.html($().msg('hide_formatting'));
		yf_help_filter_open[classname+'_'+inputname] = true;
	});	
}

$.fn.YFinterfaceHelpFilterToggle = function(classname, inputname)
{
	if(yf_help_filter_open[classname+'_'+inputname]) {
		$("#filterhelpcontent"+inputname).fadeOut("slow");
		var buttontxt = $("#filterhelpbutton"+inputname+" a");
		buttontxt.html($().msg('show_formatting'));
		yf_help_filter_open[classname+'_'+inputname] = false;
	} else {
		$().YFinterfaceHelpFilterShow(classname, inputname);
	}
}


$.fn.YFinterfaceToggle = function(id)
{
	if($("#"+id+"_toggler").text() == $().msg('toggle_hide')) {
		$("#"+id+"_toggler").text($().msg('toggle_show'));
	} else {
		$("#"+id+"_toggler").text($().msg('toggle_hide'));
	}
	$("#"+id).toggle('blind');
}

$.fn.YFinterfaceLimitChars = function(textarea)
{
	infodiv = $("#charcount_info_"+textarea.attr('id'));
	limit = $("#charcount_max_"+textarea.attr('id')).text();
	if (typeof textarea.attr('data-metadata') == 'undefined') {
		moreinfo = false;
	} else {
		moreinfo = $('<span />', {
			text: textarea.attr('data-metadata')
		});
	}

	var text = textarea.val(); 
	var textlength = text.length;

	if(textlength > parseInt(limit)) {
		diff = textlength - parseInt(limit);
		max_char_alert = $().msg('max_char_alert').replace(/{x}/,limit).replace(/{y}/,diff);
		infodiv.html(max_char_alert);
		if (moreinfo !== false) { infodiv.append(moreinfo); }
		return false;
	} else {
		max_char_status = $().msg('max_char_status').replace(/{x}/,(limit - textlength));
		infodiv.html(max_char_status);
		if (moreinfo !== false) { infodiv.append(moreinfo); }
		return true;
	}
}
