var current_dg_field_name = "";
var current_dg_group_name = "date_columns_array";

(function(fn){
    if (!fn.map) fn.map=function(f){var r=[];for(var i=0;i<this.length;i++)r.push(f(this[i]));return r}
    if (!fn.filter) fn.filter=function(f){var r=[];for(var i=0;i<this.length;i++)if(f(this[i]))r.push(this[i]);return r}
})(Array.prototype);

function HandleEnterKey(e, submitid)
{
	var keycode = (e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode));
	if (keycode == 13)
	{
		if(submitid != "")
			$("#" + submitid).click();
		return false;
	}
	return true;
}
function string_length_check(value, colname) 
{
	len = value.length;
	if (len < 6) 
	   return [false, colname + ": Please enter atleast 6 characters."];
	else 
	   return [true,""];
}
$(function()
{
	custom_field_array = custom_field_array.map(function(elem) { return elem.toLowerCase(); }); 
	
	$(window).bind('resize', function() {fixGridSizes();}).trigger('resize');
	
	$("#SetupPane").bind('resize', function() {fixGridSizes();}).trigger('resize');
	
	$('#SetupTabPane').tabs();
	
	$("#ui_delete_field").button().click(function() 
	{
		createCustomField("delete");
	});
	
	$("#ui_display_column_update").button().click(function() 
	{
		updateDisplayColumns();
	});
	
	$("#refresh_dg_domain_table").button().click(function() 
	{
		refreshDisplayGroupTable();
	});
	
	$("#ui_add_field").button().click(function() 
	{
		createCustomField("insert");
	});
	
	$("#field_name").change(function() 
	{
		customFieldNameChanged();
	});
	
	$("#field_type").change(function() 
	{
		var ftype = $("#field_type").val().toLowerCase();
		if(ftype == "varchar")
		{
			$("#field_width").removeAttr("disabled");
			var fw = $("#field_width").val();
			if(fw == "")
				$("#field_width").val("128");
		}
		else
		{
			$("#field_width").attr("disabled",true);
		}
	});
	
	$("#field_name").keydown(function(event) 
	{
		if(!HandleEnterKey(event, "ui_add_field"))
			return false;
	});
	
	makeCustomFieldListSelectable();
	makeDisplayGroupColumnList();
	customFieldNameChanged();
	
	$("#display_group_name").change(function() 
	{
		refreshDisplayGroupTable();
	});
	
	$("#lookuplist :checkbox").map(function() {
		$('#'+this.id).change(function() {updateDefaultLookups();});
    });
	
	$("#lupreflist :checkbox").map(function() {
		$('#'+this.id).change(function() {updatePreferredLookups();});
    });
	
	$("#ui_set_license").button().click(function() 
	{
		var licensecode = $('#license_key_code').val();
		setMasterOption("license_key_code", encodeURIComponent(licensecode), false);
	});
	
	$("#ui_set_cliauthkey").button().click(function() 
	{
		var licensecode = $('#cli_auth_key_code').val();
		setMasterOption("cli_auth_key_code", encodeURIComponent(licensecode), false);
	});
	
	$("#ui_theme").change(function() 
	{
		var theme = $('#ui_theme').val();
		setMasterOption("ui_theme", theme, false);
	});
	
	$("#home_page_link").change(function() 
	{
		var entry = $('#home_page_link').val();
		setMasterOption("home_page_link", entry, false);
	});
	
	$("#product_page_link").change(function() 
	{
		var entry = $('#product_page_link').val();
		setMasterOption("product_page_link", entry, false);
	});
	
	$("#support_page_link").change(function() 
	{
		var entry = $('#support_page_link').val();
		setMasterOption("support_page_link", entry, false);
	});
	
	$("#contact_page_link").change(function() 
	{
		var entry = $('#contact_page_link').val();
		setMasterOption("contact_page_link", entry, false);
	});
	
	$("#main_logo_image").change(function() 
	{
		var entry = $('#main_logo_image').val();
		setMasterOption("main_logo_image", entry, false);
	});
	
	$("#custom_tools_file").change(function() 
	{
		var entry = $('#custom_tools_file').val();
		setMasterOption("custom_tools_file", entry, false);
	});
	
	$("#ui_set_licensee_name").button().click(function() 
	{
		var entry = $('#legal_licensee_name').val();
		setMasterOption("legal_licensee_name", entry, false);
	});
	
	$("#config_subdomain_entry").change(function() 
	{
		var entry = $('#config_subdomain_entry').val();
		setMasterOption("config_subdomain_entry", entry, false);
	});
	
	$("#default_sub_domains").change(function() 
	{
		var entry = $('#default_sub_domains').val();
		setMasterOption("default_sub_domains", entry, false);
	});
	
	$("#home_page_max_redirs").change(function() 
	{
		var entry = $('#home_page_max_redirs').val();
		setMasterOption("home_page_max_redirs", entry, false);
	});
	
	$("#do_dns_record_lookup").change(function() 
	{
		var entry = $("#do_dns_record_lookup").attr('checked') ? 1 : 0;
		setMasterOption("do_dns_record_lookup", entry, false);
	});
	
	$("#requeue_on_empty_whois").change(function() 
	{
		var entry = $("#requeue_on_empty_whois").attr('checked') ? 1 : 0;
		setMasterOption("requeue_on_empty_whois", entry, false);
	});
	
	$("#fix_host_domain_names").change(function() 
	{
		var entry = $("#fix_host_domain_names").attr('checked') ? 1 : 0;
		setMasterOption("fix_host_domain_names", entry, false);
	});
	
	$("#auth_timeout_minutes").change(function() 
	{
		var entry = $("#auth_timeout_minutes").val();
		setMasterOption("auth_timeout_minutes", entry, false);
	});
	
	$("#max_login_attempts").change(function() 
	{
		var entry = $("#max_login_attempts").val();
		setMasterOption("max_login_attempts", entry, false);
	});
	
	$("#login_lockout_minutes").change(function() 
	{
		var entry = $("#login_lockout_minutes").val();
		setMasterOption("login_lockout_minutes", entry, false);
	});
	
	$("#cell_date_format").change(function() 
	{
		var entry = $("#cell_date_format").val();
		setMasterOption("cell_date_format", entry, false);
	});
	
	$("#ui_set_user_info").button().click(function() 
	{
		var username = $('#admin_user_name').val();
		var pass01 = $('#admin_password').val();
		var pass02 = $('#admin_password_repeat').val();
		if(username == "")
		{
			custom_alert("<p>Missing username. The password protection will be disabled.</p>", "Warning"); 
		}
		if((pass01 != pass02 && pass01 != "") || (pass01.length < 6 && username != ""))
			custom_alert("<p>Passwords don't match or password length is too small.</p>", "Problem");
		else
		{
			setUserNameAndPassword(username, pass01);
		}
	});
	
	$("#multi_server_global_settings").change(function() 
	{
		var entry = $("#multi_server_global_settings").attr('checked') ? 1 : 0;
		setMasterOption("multi_server_global_settings", entry, false);
	});
	
	$("#domain_grid_search").change(function() 
	{
		var entry = $("#domain_grid_search").attr('checked') ? 1 : 0;
		setMasterOption("domain_grid_search", entry, false);
	});
	
	$("#submitemailsetup").button().click(function(event) 
	{
		event.preventDefault();
		updateEmailSettings();
	});
	
	$("#email_send_method").change(function() 
	{
		HideShowSMTPSettings();
	});
	
	HideShowSMTPSettings();
});

function HideShowSMTPSettings()
{
	var ftype = $("#email_send_method").val().toLowerCase();
	if(ftype == "smtp")
		$("#smtpsetup").show();
	else
		$("#smtpsetup").hide();
}

function updateEmailSettings()
{
	var emaildata = $("#email-setup-form").serialize();
	var turl = "appsetup.php?emset";
	var request = $.ajax({type: "POST",	url: turl, data: emaildata});
	request.done(function(msg) 
	{  
		var x = jQuery.parseJSON(msg);
		if(x.status == "done" && x.count > 1)
		{
			$('#em_status_img').attr('src','lib/css/img/success.png');
		}
		else
			$('#em_status_img').attr('src','lib/css/img/error.png');
	});
	request.fail(function(jqXHR, textStatus) {$('#em_status_img').attr('src','lib/css/img/error.png');});
	
}

function setUserNameAndPassword(username, password)
{
	setMasterOption("admin_user_name", username, false);
	setMasterOption("admin_password", password, (username == "" ? false : true));
}

function updateDefaultLookups()
{
	var checkedIds = $("#lookuplist :checkbox:checked").map(function() {
        return this.id;
    }).get();
	
	var colsetup = "";
	var length = checkedIds.length;
    var columns = new Array();
	for (var i = 0; i < length; i++) 
	{
	  columns[i] = checkedIds[i].replace("cb-lu-", "");
	  colsetup += columns[i];
	  if(i != (length-1))
		colsetup += ",";
	}
	if(colsetup == "")
		colsetup = "-";
	setMasterOption('default_lookup_types', colsetup, false);
}

function updatePreferredLookups()
{
	var checkedIds = $("#lupreflist :checkbox:checked").map(function() {
        return this.id;
    }).get();
	
	var colsetup = "";
	var length = checkedIds.length;
    var columns = new Array();
	for (var i = 0; i < length; i++) 
	{
	  columns[i] = checkedIds[i].replace("cb-luh-", "");
	  colsetup += columns[i];
	  if(i != (length-1))
		colsetup += ",";
	}
	setMasterOption('high_preference_lookups', colsetup, false);
}

function setMasterOption(fname, fvalue, dologout)
{
	var turl = "appsetup.php?opset=" + fname;
	var datastr = "value=" + fvalue;
	/* License key may contain "+" which will get mangled. So send it raw */
	if(fname.toLowerCase() != "license_key_code")
		datastr = "value=" + encodeURIComponent(fvalue);
	var request = $.ajax({type: "POST",	url: turl, data: datastr});
	request.done(function(msg) 
	{  
		if(dologout == true)
			window.location = "lib/php/login.php?logout&redir=" + encodeURIComponent("appsetup.php#auth");
		if(fname == "ui_theme")
		{
			window.location.href = "appsetup.php#interface";
			location.reload();
		}
	});
	request.fail(function(jqXHR, textStatus) {});
}

function customFieldNameChanged()
{
	var fname = $('#field_name').val();
	var fwidth = $('#field_width').val();
	var ftype = $('#field_type').val();
	fname = fname.replace(/ /g, "_").toLowerCase();
	var found = false;
	var custom_field = false;
	if(jQuery.inArray(fname,custom_field_array) != -1)
		custom_field = true;
	else if(jQuery.inArray(fname,domain_field_array) != -1)
		found = true;
	if(custom_field && fname != "")
	{
		$("#field_type").attr("disabled",true);
		$("#field_width").attr("disabled",true);
		$( "#ui_add_field" ).button( "option", "disabled", true );
		$( "#ui_delete_field" ).button( "option", "disabled", false );
	}
	else if(found || fname == "")
	{
		$("#field_type").attr("disabled",true);
		$("#field_width").attr("disabled",true);
		$( "#ui_delete_field" ).button( "option", "disabled", true );
		$( "#ui_add_field" ).button( "option", "disabled", true );
	}
	else if(fname != "")
	{
		$("#field_type").attr("disabled",false);
		$("#field_width").attr("disabled",false);
		$( "#ui_delete_field" ).button( "option", "disabled", true );
		$( "#ui_add_field" ).button( "option", "disabled", false );
		//alert(ftype);
		if(fwidth == "" && ftype == "varchar")
			$('#field_width').val("128");
	}
}

function refreshDisplayGroupTable()
{
	var gname = $("#display_group_name").val().toLowerCase();
	{
		var turl = "appsetup.php?dghtml=" + gname;
		var request = $.ajax({type: "POST",	url: turl});
		request.done(function(msg) 
		{  
			var x = jQuery.parseJSON(msg);
			$("#tablecolumns").html(x.chtml);
			makeDisplayGroupColumnList();
		});
		request.fail(function(jqXHR, textStatus) {});
	}
	current_dg_group_name = gname;
}

function updateDisplayColumns()
{
	var checkedIds = $("#tablecolumns :checkbox:checked").map(function() {
        return this.id;
    }).get();
	
	var colsetup = "";
	var length = checkedIds.length;
    var columns = new Array();
	for (var i = 0; i < length; i++) 
	{
	  columns[i] = checkedIds[i].replace("cb-", "");
	  colsetup += columns[i];
	  if(i != (length-1))
		colsetup += ";";
	}

	var turl = "appsetup.php?dgset=" + current_dg_group_name;
	var datastr = "entry=" + colsetup;
	var request = $.ajax({type: "POST",	url: turl, data: datastr});
	request.done(function(msg) 
	{  
	});
	request.fail(function(jqXHR, textStatus) {});
	
	// Save any current setting changes (label & width)
	saveColumnLabelAndWidth("", current_dg_field_name, $('#column_label').val(), $('#column_width').val());
}

function makeCustomFieldListSelectable()
{
	$( "#domaincolumns" ).selectable(
	{
		stop: function() 
		{
			$('#domaincolumns li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() 
			{
				$(this).addClass('ui-state-highlight');
				$('#field_name').val($(this).text());
				var cindex = jQuery.inArray($(this).text().toLowerCase(),custom_field_array);
				
				if(cindex >= 0 && cindex < custom_field_types.length)
				{
					//alert(custom_field_types[cindex]);
					$('#field_type').val(custom_field_types[cindex]);
					var width = custom_field_lengths[cindex];
					if(width == "0")
						width = "";
					$('#field_width').val(width);
				}
				customFieldNameChanged();
			});
		},
		selecting: function (e, ui) {
            // force single selection
            $(e.target).find('.ui-selectee.ui-selecting').not(ui.selecting).removeClass('ui-selecting');
            $(e.target).find('.ui-selectee.ui-selected').not(ui.selecting).removeClass('ui-selected');
        }
    });
}

function makeDisplayGroupColumnList()
{
	$( "#tablecolumns" ).sortable();
	$( "#tablecolumns" ).sortable({ handle: ".handle" })
	.selectable({
		selecting: function (e, ui) 
		{
            // force single selection
            $(e.target).find('.ui-selectee.ui-selecting').not(ui.selecting).removeClass('ui-selecting');
            $(e.target).find('.ui-selectee.ui-selected').not(ui.selecting).removeClass('ui-selected');
        },
		stop: function() 
		{
			$('#tablecolumns li').each(function() {
				$(this).removeClass('ui-state-highlight');
			});
			$( ".ui-selected", this ).each(function() 
			{
				var oldfield = current_dg_field_name;
				var oldlabel = $('#column_label').val();
				var oldwidth = $('#column_width').val();
				
				$(this).addClass('ui-state-highlight');
				var field = $(this).text();
				$('#selectedcolumn').html(field);

				var datastr = "slabel=" + oldlabel + "&swidth=" + oldwidth + "&sfield=" + oldfield + "&gfield=" + field;
				var turl = "appsetup.php";

				current_dg_field_name = field;
				
				var request = $.ajax({type: "POST",	url: turl, data: datastr});
				request.done(function(msg) 
				{  
					var x = jQuery.parseJSON(msg);
					if(x.status == "done")
					{
						$('#column_label').val(x.label);
						$('#column_width').val(x.width);
					}
				});
				request.fail(function(jqXHR, textStatus) {});
			});
		}
	})
    .find("li")
	.addClass( "ui-corner-all" )
	.prepend( "<div class='handle'><span class='ui-icon grip-drag-action-button'></span></div>" );
}

function saveColumnLabelAndWidth(gfield, sfield, slabel, swidth)
{
	var datastr = "slabel=" + encodeURIComponent(slabel) + "&swidth=" + swidth + "&sfield=" + sfield + "&gfield=" + gfield;
	var turl = "appsetup.php";
	var request = $.ajax({type: "POST",	url: turl, data: datastr});
	request.done(function(msg) 
	{  
		var x = jQuery.parseJSON(msg);
		if(x.status == "done")
		{
		}
	});
	request.fail(function(jqXHR, textStatus) {});
}

function createCustomField(acttype)
{
	var fieldname = $("#field_name").val();
	var fieldtype = $("#field_type").val();
	var fieldsize = $("#field_width").val();
	var datastr = 'field_name=' + encodeURIComponent(fieldname);
	datastr += '&field_type=' + fieldtype;
	datastr += '&field_size=' + fieldsize;
	var turl = "appsetup.php?fieldset";
	if(acttype == "delete")
		turl += "=delete";
	else
		turl += "=insert";
	var request = $.ajax({type: "POST",	url: turl, data: datastr});
	request.done(function(msg) 
	{  
		var x = jQuery.parseJSON(msg);
		if(x.status == "done")
		{
			$('#allnames').html(x.allnames);
			$('#status_img').attr('src','lib/css/img/success.png');
			makeCustomFieldListSelectable();
			custom_field_array = x.custom;
			custom_field_array = custom_field_array.map(function(elem) { return elem.toLowerCase(); }); 
			custom_field_lengths = x.cwidths;
			custom_field_types = x.ctypes;
			domain_field_array = x.domcolumns;
			customFieldNameChanged();
		}
		else
			$('#status_img').attr('src','lib/css/img/error.png');
	});
	request.fail(function(jqXHR, textStatus) {$('#status_img').attr('src','lib/css/img/error.png');});
	
}

function fixGridSizes()
{
	var dheight = $(window).height();
	jQuery("#SetupTabPane").width($("#SetupPane").width()-27, true); 
	jQuery("#SetupTabPane").height(dheight-96, true); 
	jQuery(".currentfields").height(dheight-96-115, true); 
	jQuery("#displaylist").height(dheight-96-205, true); 
	jQuery(".interfaceinfobox").height(dheight-96-100, true); 
	jQuery(".lumiscbox").height(dheight-96-75, true); 
	jQuery("#lookuplist").height(dheight-96-280, true); 
	jQuery("#lupreflist").height(dheight-96-300, true); 
}