/*
 * Copyright 2010-2011, Softnik Technologies
 * http://www.softnik.com/
 */


function clear_form_elements(ele) {
    $(ele).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
}

/////////////////////////////////////////////////////////////////////////////////////////

$(function() 
{
	$("#dialog-add-domains").dialog(
	{
		resizable: false,
		autoOpen: false,
		width: 400,
		modal: true,
		buttons: {
			Clear: function() {
				clear_form_elements("#dialog-add-domains");
				$("#data").focus();
			},
			'OK': function() {
				$(this).dialog('close');
				var user_entry_data = $("#domain-entry-form").serialize();
				var catid = lastsel_categoryrow_id;
				if($("#catadd").attr('checked') == false && catid > 1)
					catid = 0;
				if($("#catempty").attr('checked') == true && catid > 1 && is_an_admin_user)
					empty_cat_and_add_domains(user_entry_data, catid);
				else
					add_domains(user_entry_data, catid);
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#dialog-user-admin").dialog(
	{
		resizable: false,
		autoOpen: false,
		modal: true,
		buttons: {
			Clear: function() {
				clear_form_elements("#dialog-user-admin");
				$("#data").focus();
			},
			'OK': function() {
				var user_entry_data = $("#user-selfadmin-form").serialize();
				var p1 = $("#new_pwd_1").val();
				var p2 = $("#new_pwd_2").val();
				if(p1.length < 8)
				{
					$("#selfadmerror").html("Password is too short");
					return;
				}
				else if(p1 != p2)
				{
					$("#selfadmerror").html("Passwords don't match!");
					return;
				}
				$.ajax({
					type: "POST",
					cache: false,
					dataType: 'text',
					url: "lib/php/selfadmin.php",
					data: user_entry_data,
					success: function(msg)
					{
						$("#selfadmerror").html(msg);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) 
					{ 
						if(XMLHttpRequest.status == 403)
							$("#selfadmerror").html("Access Denied! No permission.");
						else
							$("#selfadmerror").html("Error: " + errorThrown); 
					} 
				});
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#dialog-add-subdomains").dialog(
	{
		resizable: false,
		autoOpen: false,
		modal: true,
		buttons: {
			Clear: function() {
				clear_form_elements("#dialog-add-subdomains");
				$("#ui_subdomains").focus();
			},
			'OK': function() {
				$(this).dialog('close');
				var user_entry_data = $("#ui_subdomains").val();
				var selids = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
				if(selids.length > 0 && selids != null)
				{
					$.ajax({
						type: "POST",
						cache: false,
						dataType: 'json',
						url: grid_url_base + "?mode=ah",
						data: "data=" + user_entry_data + "&id=" + selids,
						success: function(html)
						{
							$("#SubDomainTable").trigger("reloadGrid"); 
						}
					});
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	
	
	$("#dialog-lookup-what").dialog(
	{
		resizable: false,
		autoOpen: false,
		modal: true,
		buttons: {
			'OK': function() {
				// LOOKUP_DOMAIN_WHOIS | LOOKUP_DOMAIN_IP | LOOKUP_HTTP_HOMEPAGE | LOOKUP_ALEXA_DATA | LOOKUP_GOOGLE_PR | LOOKUP_MX_RECORDS | LOOKUP_PING_RESPONSE | LOOKUP_IP_WHOIS | LOOKUP_GOOGLE_INDEX;
				var luw = 0;
				luw |= $('#luwhois').is(':checked') ? LOOKUP_DOMAIN_WHOIS : 0;
				luw |= $("#ludns").is(':checked') ? LOOKUP_DOMAIN_IP : 0;
				luw |= $("#luhttp").is(':checked') ? LOOKUP_HTTP_HOMEPAGE : 0;
				luw |= $("#lualexa").is(':checked') ? LOOKUP_ALEXA_DATA : 0;
				luw |= $("#lugpr").is(':checked') ? LOOKUP_GOOGLE_PR : 0;
				luw |= $("#lumx").is(':checked') ? LOOKUP_MX_RECORDS : 0;
				luw |= $("#luping").is(':checked') ? LOOKUP_PING_RESPONSE : 0;
				luw |= $("#luipwhois").is(':checked') ? LOOKUP_IP_WHOIS : 0;
				luw |= $("#lugindex").is(':checked') ? LOOKUP_GOOGLE_INDEX : 0;
				luw |= $("#lusubdom").is(':checked') ? LOOKUP_SUB_DOMAINS : 0;
				var luint = $("#luint").val();
				if(luint == "")
					luint = 1440;
				if(luw != 0)
				{
					DoLookups(luw, luint);
					$(this).dialog('close');
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#dialog-parse-whois").dialog(
	{
		resizable: false,
		autoOpen: false,
		width: 400,
		modal: true,
		buttons: 
		{
			'OK': function() {
				var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
				var lurl = "lib/php/whoisreparse.php?" + "id=" + rowKey;
				$.ajax({
					type: "GET",
					cache: false,
					url: lurl,
					success: function(html)
					{
						jQuery("#"+domain_table_grid_id).trigger("reloadGrid"); 
					}
				});
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#dialog-bulk-action").dialog(
	{
		resizable: false,
		autoOpen: false,
		width: 400,
		modal: true,
		buttons: 
		{
			Clear: function() {
				clear_form_elements("#bulk-action-form");
				$("#bt-notes-a").focus();
			},
			'OK': function() {
				var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
				var lurl = "lib/php/bulktool.php?" + "id=" + rowKey;
				lurl += "&notes_a=" + $("#bt-notes-a").val();
				lurl += "&notes_b=" + $("#bt-notes-b").val();
				lurl += "&notes_c=" + $("#bt-notes-c").val();
				lurl += "&notes_d=" + $("#bt-notes-d").val();
				lurl += "&cat_add=" + $("#bt-cat-add").val();
				lurl += "&cat_delete=" + $("#bt-cat-delete").val();
				lurl += "&bt-field-set=" + $("#bt-field-set").val(); 
				lurl += "&field_set=" + $("#field_set").val(); 
				$.ajax({
					type: "GET",
					cache: false,
					url: lurl,
					success: function(html)
					{
						jQuery("#"+domain_table_grid_id).trigger("reloadGrid"); 
					}
				});
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#dialog-csv-upload").dialog(
	{
		resizable: false,
		autoOpen: false,
		width: 450,
		
		modal: true,
		buttons: {
			'Clear': function() {
				$("#csverrors").html("&nbsp;")
			},
			'Upload': function() {
				//$(this).dialog('close');
				uploadCSVFile();
			},
			'Close': function() {
				$(this).dialog('close');
			}
			
		},
		open: function ()
        {
			$('input[type="file"]').blur();
        }
	});
	
	$("#dialog-csv-download").dialog(
	{
		resizable: false,
		autoOpen: false,
		width: 450,
		
		modal: true,
		buttons: {
			'Download': function(event) {
				event.preventDefault();
				downloadRows($("#csv-download-radio :radio:checked").attr('id'));
			},
			'Cancel': function() {
				$(this).dialog('close');
			}
			
		}
	});
	
	$("#dialog-regalias-editor").dialog(
	{
		resizable: false,
		autoOpen: false,
		width: 350,
		modal: true,
		open: function(event, ui) 
		{
			$("#ra-error").html("&nbsp;");
			var html = $("#dialog-regalias-editor").data('info');
			var x = jQuery.parseJSON(html);
			var sid = x.id;
			jQuery("#ra-real-name").html('<p><b>' + x.name + '</b></p>');
			jQuery("#ra-regalias").val(x.alias);
		},
		buttons: {
			'OK': function() {
				var alias = jQuery("#ra-regalias").val();
				submitRegistrarAlias(sid, alias);
			},
			'Close': function() {
				$(this).dialog('close');
			}
		}
	});
	
	$("#regalias-form").submit(function() {
		var alias = jQuery("#ra-regalias").val();
		var rowKey = jQuery("#"+domain_table_grid_id).getGridParam("selarrrow"); 
		if(rowKey.length == 1)
		{
			sid = rowKey[0];
			submitRegistrarAlias(sid, alias);
		}
		return false;
	});
	
	showQueueInfo();
	
	$( "#csv-download-radio" ).buttonset();
});

function submitRegistrarAlias(id, alias)
{
	if(alias != "")
	{
		$.ajax({
			type: "GET",
			cache: false,
			url: "lib/php/regalias.php?id=" + id + "&alias=" + jQuery("#ra-regalias").val(),
			success: function(html)
			{
				var x2 = jQuery.parseJSON(html);
				if(x2.status == "OK")
				{
					setRegistrarAlias(x2.registrar, jQuery("#ra-regalias").val());
					if(hasColumnInModel("registrar"))
					{
						$("#"+domain_table_grid_id).trigger( 'reloadGrid' );
					}
					jQuery('#dialog-regalias-editor').dialog('close');
				}
			}
		});
	}
	else
		$("#ra-error").html("<p>Alias can't be empty</p>");
}


function show_queue_count() 
{
	$.ajax({
		type: 'POST',
		url: 'lib/php/ajxinfo.php?q',
		cache: false,
		contentType: false,
		processData: false
	}).done(function(data) {
		var x = jQuery.parseJSON(data);
		$("#queue_count").html("<h3>Current Lookup Queue Size: " + x.queue_size + "</h3>");
		$("#queue_last_proc").html("<h3>Last Processed At: " + x.last_queue_proc + "</h3>");
		$("#server_time").html("<h3>Server Time: " + x.server_time + "</h3>");
		$("#qb-ipw").attr('value', 'IP Whois (' + x.ipw_size + ')');
		$("#qb-all").attr('value', 'All (' + x.queue_size + ')');
		$("#qb-alexa").attr('value', 'Alexa (' + x.alexa_size + ')');
		$("#qb-http").attr('value', 'Home Page (' + x.http_size + ')');
		$("#qb-dw").attr('value', 'Domain Whois (' + x.dw_size + ')');
		$("#qb-ping").attr('value', 'Ping (' + x.ping_size + ')');
		$("#qb-gpr").attr('value', 'Google PR (' + x.gpr_size + ')');
		$("#qb-mx").attr('value', 'MX (' + x.mx_size + ')');
		$("#qb-sdw").attr('value', 'Registrar Whois (' + x.sdw_size + ')');
		$("#qb-ssl").attr('value', 'SSL (' + x.ssl_size + ')');
		$("#qb-dns").attr('value', 'Sub Domains (' + x.dns_size + ')');
		$("#qb-ip").attr('value', 'Domain IP (' + x.ip_size + ')');
		$("#qb-gindex").attr('value', 'Google Index (' + x.gi_size + ')');
	}).fail(function(jqXHR,status, errorThrown) {
		if(jqXHR.status == 403)
			alert("Access Denied! No permission to edit.");
		else if(jqXHR.status == 400)
			alert("Invalid Session. Please login again.");
		else if(jqXHR.status == 408)
			alert("Session timeout. Please login again.");
	});
}
	
function showQueueInfo()
{
	show_queue_count();
	var switcher;
	switcher = setInterval(show_queue_count, 60000);
	$("#queue_refresh").click(function(e){show_queue_count();e.preventDefault();});
}

function uploadCSVFile()
{
	$("#csverrors").css("height", "150px");
	data = new FormData($('#csv-upload')[0]);
	$("#csverrors").html("Please wait...");
	if(data != "")
	{
		$.ajax({
			type: 'POST',
			url: 'lib/php/uploadcsv.php?CategoryID=' + lastsel_categoryrow_id,
			data: data,
			cache: false,
			contentType: false,
			processData: false
		}).done(function(data) {
			var x = jQuery.parseJSON(data);
			$("#csverrors").html(x.msg);
			$("#"+domain_table_grid_id).trigger("reloadGrid");
		}).fail(function(jqXHR,status, errorThrown) {
			//console.log(errorThrown);
			//console.log(jqXHR.responseText);
			//console.log(jqXHR.status);
			if(jqXHR.status == 403)
				alert("Access Denied! No permission to edit.");
			else if(jqXHR.status == 400)
				alert("Invalid Session. Please login again.");
			else if(jqXHR.status == 408)
				alert("Session timeout. Please login again.");
		});
	}
	else
		$("#csverrors").html("Nothing to upload!");
}

function add_domains(user_entry_data, catid)
{
	$.ajax({
		type: "POST",
		cache: false,
		dataType: 'json',
		url: grid_url_base + "?mode=ad",
		data: user_entry_data + "&CategoryID=" + catid,
		success: function(html)
		{
			$("#"+domain_table_grid_id).trigger("reloadGrid"); 
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) 
		{ 
			if(XMLHttpRequest.status == 403)
				alert("Access Denied! No permission to add domains.");
			else
				alert("Error: " + errorThrown); 
		} 
	});
}

function empty_cat_and_add_domains(user_entry_data, catid)
{
	$.ajax({
		type: "POST",
		cache: false,
		dataType: 'json',
		url: "lib/php/bulktool.php",
		data: "cat=" + catid,
		success: function(html)
		{
			add_domains(user_entry_data, catid); 
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) 
		{ 
			if(XMLHttpRequest.status == 403)
				alert("Access Denied! No permission to add domains.");
			else
				alert("Error: " + errorThrown); 
		} 
	});
}

