var C_ADD = "a";
var C_QUERY = "q";
var C_VIEW = "v";
var C_LIST = "l";
var C_DOWNLOAD = "dl";

var C_OK = "0";
var C_INFO = "6";
var C_INVALID = "7";
var C_CONFIRM = "8";
var C_ERROR = "9";

var record_obj = null;
var upload_form = null;
var m_filename = "";
var m_file = "";

$(document).ready(function () {
	$('#uploading').hide();
	$('#view_doc').hide();

	$('#txtDoc').on('change', function () {
		upload_form = this.form;
	});
	$('#viewDoc').on('change', function () {
		upload_form = this.form;
	});
});

function clearEntry() {
	$('#txtCompanyName').val("");
	$('#txtCompanyUEN').val("");
	$('#txtCompanyPhone').val("");
	$('#txtContactName').val("");
	$('#txtContactNumber').val("");	
	$('#txtContactEmail').val("");
	$('#txtItemSelling').val("");
	$('#txtEventPeriod').val("");
	$('#txtEquipments').val("");
	record_obj = null;
	upload_form = null;
	m_filename = "";
	m_file = "";
	$('#uploading').hide();
	$('#view_doc').hide();
}

function addRecord() {
	saveRecord(C_ADD);
}

function saveRecord(type) {
	if (validateRecord()) {
		var data = {
			"type": type,

			"companyname": $('#txtCompanyName').val(),
			"companyuen": $('#txtCompanyUEN').val(),
			"companyphone": $('#txtCompanyPhone').val(),
			"contactname": $('#txtContactName').val(),
			"contactnumber": $('#txtContactNumber').val(),
			"contactemail": $('#txtContactEmail').val(),

			"itemselling": $('#txtItemSelling').val(),
			"eventperiod": $('#txtEventPeriod').val(),
			"equipment": $('#txtEquipments').val(),

			"base64file": $('#txtAddProspectAttachmentFileBase64').html(),
			"extension": $('#txtAddProspectAttachmentFileExt').val(),
			"name": $('#txtAddProspectAttachmentFilename').val()
		};
		var url = "addprospect.pzx?c=" + add_url + "&d=" + new Date().getTime();
		callServer(url, "json", data, onResponse, record_obj);
	}else{
		return
	}
}
function onResponse(obj, resp) {
	if(resp.status != C_OK){
		alert(resp.mesg);
		return;
	}
	if (resp.status == C_OK) {
		if (resp.type == C_ADD) {
			alert(resp.mesg);
			clearEntry();
		}
	}
}
function validateRecord() {
	if ($('#txtCompanyName').blank()) {
		alert("Company Name cannot be blank!");
		$('#txtCompanyName').focus();
		return false;
	}
	if ($('#txtCompanyUEN').blank()) {
		alert("Company UEN cannot be blank!");
		$('#txtCompanyUEN').focus();
		return false;
	}
	if ($('#txtCompanyPhone').blank()) {
		alert("Company Phone cannot be blank!");
		$('#txtCompanyPhone').focus();
		return false;
	}
	if ($('#txtContactName').blank()) {
		alert("Contact Name cannot be blank!");
		$('#txtContactName').focus();
		return false;
	}
	if ($('#txtContactNumber').blank()) {
		alert("Contact Number cannot be blank!");
		$('#txtContactNumber').focus();
		return false;
	}
	if ($('#txtContactEmail').blank()) {
		alert("Contact Email cannot be blank!");
		$('#txtContactEmail').focus();
		return false;
	} else if(!($('#txtContactEmail').blank())){
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		if(emailReg.test($('#txtContactEmail').val()) ==false){
			alert("Not a valid Email");
			$('#txtContactEmail').focus();
			return false;
		}
	}
	return true;
}

function hasExtensionAddProspect(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function getFileExtensionAddProspect(filename){
	var ext = /^.+\.([^.]+)$/.exec(filename);
	return ext == null ? "" : ext[1];
}


function encodeImageFileAsURLAddProspect(event) {
    var filesSelected = document.getElementById("txtAddProspectAttachment").files;
	if (!hasExtensionAddProspect('txtAddProspectAttachment', ['.jpg', '.jpeg', '.png','.pdf'])) {
		alert("The image format have to be in 'jpg', 'jpeg', 'png' , 'pdf");
		$("#txtAddProspectAttachment").val("");
		return;
	}

    if (filesSelected.length > 0) {
       	var fileToLoad = filesSelected[0];
	   	var fileExt = getFileExtensionAddProspect(filesSelected[0].name);
		  
      	var fileReader = new FileReader();

      	fileReader.onload = function(fileLoadedEvent) {
			var srcData = fileLoadedEvent.target.result; // <--- data: base64
			// var base64String = window.btoa(srcData);
			$('#txtAddProspectAttachmentFileBase64').html(srcData);
			$('#txtAddProspectAttachmentFileExt').val(fileExt);
			$('#txtAddProspectAttachmentFilename').val(filesSelected[0].name);
      	}
      fileReader.readAsDataURL(fileToLoad);
    }

	src= URL.createObjectURL(event.target.files[0])
	$('#view_doc').show();
	$('#frame').attr('src', src);
	$('#viewDoc').html(filesSelected[0].name);
	
}

function openPreview(){
	var iframe = $("#frame"); 
	var newWindow = window.open(iframe.attr(src), 'Dynamic Popup', 'height=800, width=800, scrollbars=auto, resizable=no, location=no, status=no');
	newWindow.document.write(iframe[0].outerHTML);
	newWindow.document.close();
}

function onAddProspectImageResponse(obj,resp) {
	if (resp.status != C_OK ) {
        alert(resp.mesg);
        return false;
    }
}

