$(function(){
	$("#loading").ajaxStart(function(){
		$(".loadingImg", this).show();
		var dh = $(document).height();
		var wh = $(window).height();
		$(this).show().height(dh > wh ? dh : wh);
	}).ajaxStop(function(){
		$(this).hide();
	});

	$("#accountMenu").navMenu({container:"#mainContent1"});
	
	initPage();
});

function toggleCheckeBox(checkBox, inputName, checkVal, uncheckVal){
	var jInput = $("#applayForm").find("[name="+inputName+"]");
	if(checkBox.checked) jInput.val(checkVal || "1");
	else jInput.val(uncheckVal || "0");
}

function closeDialog(){
	$.closeDialog('#dialogBox');
}

function generateVerify(id){
//	$(id).attr("src", "/validationCode.do?method=generate&timestamp=" + new Date().getTime());
	$(id).html("<img src='/validationCode.do?method=generate&timestamp=" + new Date().getTime() +"'/>");
}

function iframeCallback(form, callback){
	if(!$(form).valid()) {return false;}
	window.donecallback = $.isFunction(callback) ? callback : iframeDone;
	if ($("#callbackframe").size() == 0) { 
		$("<iframe id='callbackframe' name='callbackframe' src='about:blank' style='display:none'></iframe>").appendTo("body");
	}
	form.target = "callbackframe";
}
function iframeDone(response){
	if (response["statusCode"] == 300) {
		if (response["message"]) alertMsg.error(response["message"]);
	} else if (response["statusCode"] == 301) {
		alertMsg.error(response["message"], {okCall:function(){
			window.location = "/render.do?method=login";
		}});
	} else {
		if (response["message"]) alertMsg.correct(response["message"]);
	}
}

function validateCallback(form, callback, $params) {
	try{
		if (!$(form).valid()) {
			alertMsg.error("There are errors occurred. Please correct errors before proceeding.");
			return false;
		}
		if (!jQuery.isFunction(callback)) {callback = jsonMsgDone;}
		
		var params = $(form).serializeArray();
		for ( var key in $params ){
			params[params.length] = { name: key, value: $params[key]};
		}

		$.post(form.action, params, callback, "json");
	} catch (e){}
	return false;
}


function jsonMsgDone(json){
	if(json.statusCode == 200) {
		if(json.message) alertMsg.correct(json.message);
	} else if (json.statusCode == 301) {
		alertMsg.error("Session Timeout! Please re-sign in.", {okCall:function(){
			window.location = "/render.do?method=login";
		}});
	} else {
		if(json.message) alertMsg.error(json.message);
	};
}



function uploadMcDocDone(response){
	iframeDone(response);
	if(response["statusCode"] == 200) {
		$("#mcList").loadUrl("/myaccount/render.do?method=listMc");
	};
}

function mcDone(json){
	jsonMsgDone(json);
	if(json.statusCode == 200) {
		$("#mcList").loadUrl("/myaccount/render.do?method=listMc");
		$.closeDialog('#dialogBox');
	};
}

function updMc(mcId){
	$.openDialog('#dialogBox',{url:'/myaccount/render.do?method=updMc&mcId='+mcId,title:'Edit'})
} 


function removeMc(mcId){
	alertMsg.confirm('Are you sure you want to remove this certificate?', {
		okCall: function(){
			$.post("/myaccount/user.do?method=removeMc",{mcId:mcId},mcDone,"json");
		}
	});
} 

function delMcDocument(fileId){
	alertMsg.confirm('Are you sure you want to remove this document?', {
		okCall: function(){
			$.post("/myaccount/content.do?method=remove", {fileId:fileId}, mcDone, "json");
		}
	});
}


function uploadQasDocDone(response){
	iframeDone(response);
	if(response["statusCode"] == 200) {
		$("#qasDocList").loadUrl("/myaccount/render.do?method=listQasDoc");
	};
}


function uploadCpdDocDone(response){
	iframeDone(response);
	if(response["statusCode"] == 200) {
		$("#cpdList").loadUrl("/myaccount/render.do?method=listCpd");
	};
}

function searchEas(form){
	$('#container').loadUrl(form.action, $(form).serializeArray());
	return false;
}
function sortEas(orderField, reverse){
	if (reverse) orderField = orderField+"_DESC";
	filterEas({orderField:orderField});
}
function jumpEasPage(jumpBut){
	var pageNum = $(jumpBut).parent().find(":text").val();
	if (pageNum && pageNum.isDigits() && pageNum>0){
		filterEas({pageNum:pageNum})
	}
}
function filterEas(args){
	var form = $("#pagerForm").get(0);
	if(args["username"])form.username.value = args["username"];
	if(args["postcode"])form.postcode.value = args["postcode"];
	if(args["role"])form.role.value = args["role"];
	if(args["pageNum"])form.pageNum.value = args["pageNum"];
	if(args["numPerPage"])form.numPerPage.value = args["numPerPage"];
	searchEas(form);
}



function updCpd(cpdId){
	$.openDialog('#dialogBox',{url:'/myaccount/render.do?method=updCpd&cpdId='+cpdId,title:'Edit CPD'})
} 

function removeCpd(cpdId){
	alertMsg.confirm('Are you sure you want to remove this record?', {
		okCall: function(){
			$.post("/myaccount/user.do?method=removeCpd",{cpdId:cpdId},apply4ForCpdDone,"json");
		}
	});
} 

function apply4ForCpdDone(json){
	jsonMsgDone(json);
	if(json.statusCode == 200) {
		$("#cpdList").loadUrl("/myaccount/render.do?method=listCpd");
		$.closeDialog('#dialogBox');
	};
}

function updPa(paId){
	$.openDialog('#dialogBox',{url:'/myaccount/render.do?method=updPa&paId='+paId,title:'Edit Records'})
} 

function removePa(paId){
	alertMsg.confirm('Are you sure you want to remove this records?', {
		okCall: function(){
			$.post("/myaccount/user.do?method=removePa",{paId:paId},apply4ForPaDone,"json");
		}
	});
} 

function apply4ForPaDone(json){
	jsonMsgDone(json);
	if(json.statusCode == 200) {
		$("#paList").loadUrl("/myaccount/render.do?method=listPa");
		$.closeDialog('#dialogBox');
	}else{
		$.closeDialog('#dialogBox');
	}
}


function delQasDocument(fileId){
	alertMsg.confirm('Are you sure you want to remove this document?', {
		okCall: function(){
			$.post("/myaccount/content.do?method=remove", {fileId:fileId}, uploadQasDocDone, "json");
		}
	});
}

function delCpdDocument(fileId){
	alertMsg.confirm('Are you sure you want to remove this document?', {
		okCall: function(){
			$.post("/myaccount/content.do?method=remove", {fileId:fileId}, apply4ForCpdDone, "json");
		}
	});
}


function showChecked(checkBox, boxId){
	if(checkBox.checked) $(boxId).show().find(":input").removeClass("ignore");
	else $(boxId).hide().find(":input").addClass("ignore");
}

function ctrCpdBox(checkBox, boxId){
	if(checkBox.checked) $(boxId).find(":input").addClass("required");
	else $(boxId).find(":input").removeClass("required");
}

function chkAppType(checkBox, box$){
	var $box = $(checkBox).parent().find(box$);
	if(checkBox.checked) $box.show().find(":input").removeClass("ignore");
	else $box.hide().find(":input").addClass("ignore");
}

function registerDone(json){
	jsonMsgDone(json);
	if(json.statusCode == 200) {
		$("#container").loadUrl("/render.do?method=registerDone&email="+json.objectId);
	};
}




function applyDone(json){
	jsonMsgDone(json);
	if(json.statusCode == 200) {
		if (json.step) loadApply(json.step);
		else $("#container").loadUrl("/myaccount/render.do?method=submit");
	};
}
function submitApplay(){
	validateCallback($('#applayForm').get(0), applyDone);
}
function loadApply(step){
	$("#container").loadUrl("/myaccount/render.do?method=apply", {step:step});
}

function applyReviewPayment(form){
	if(!$(form).valid()) return false;
	$.post(form.action, $(form).serializeArray(), function(html){
		$("#reviewFormBox").show().html(html);
		$("#paymentFormBox").hide();
		initPage($("#reviewFormBox"));
	});
	return false;
}
function switchPayment(){
	$("#reviewFormBox").hide();
	$("#paymentFormBox").show();
}

function cpCompanyInfo(checkBox, formId){
	var _cpVal = function (src, desc){
		$form.find("[name="+desc+"]").val($form.find("[name="+src+"]").val());
	}
	var _clearVal = function(src){
		$form.find("[name="+src+"]").val("");
	}
	var $form = $(formId);
	if(checkBox.checked){
		_cpVal("domCompanyName","ndomCompanyName");
		_cpVal("domTradingName","ndomTradingName");
		_cpVal("domCompanyAddress1","ndomCompanyAddress1");
		_cpVal("domCompanyAddress2","ndomCompanyAddress2");
		_cpVal("domCompanyAddress3","ndomCompanyAddress3");
		_cpVal("domTown","ndomTown");
		_cpVal("domCounty","ndomCounty");
		_cpVal("domPostcode","ndomPostcode");
		_cpVal("domCompanyNumber","ndomCompanyNumber");
		_cpVal("domVatNumber","ndomVatNumber");
		_cpVal("domBusinessType","ndomBusinessType");
		_cpVal("domPositionHeld","ndomPositionHeld");
		_cpVal("domTelephoneNumber","ndomTelephoneNumber");
		_cpVal("domFaxNumber","ndomFaxNumber");
		_cpVal("domWebsite","ndomWebsite");
	} else {
		_clearVal("ndomCompanyName");
		_clearVal("ndomTradingName");
		_clearVal("ndomCompanyAddress1");
		_clearVal("ndomCompanyAddress2");
		_clearVal("ndomCompanyAddress3");
		_clearVal("ndomTown");
		_clearVal("ndomCounty");
		_clearVal("ndomPostcode");
		_clearVal("ndomCompanyNumber");
		_clearVal("ndomVatNumber");
		_clearVal("ndomBusinessType");
		_clearVal("ndomPositionHeld");
		_clearVal("ndomTelephoneNumber");
		_clearVal("ndomFaxNumber");
		_clearVal("ndomWebsite");
	}
}



/* Find lodgement address */
function addressList(form){
	if (!$(form).valid()) {
		return false;
	}
	$.post(form.action, $(form).serializeArray(), function(html){
		$("#addressSeleter").html(html);
	});
	return false;
}

function selectAddress(addrType){
	var form = $("#applyForm");
	var addressId = $("#addressSeleter").val();
	if (!addressId) return false;
		
	if (addrType == "companyAddr"){
		$.getJSON("/lodgeAddress.do?method=depcAddress", {addressId:addressId}, function(json){
			form.find("[name=domCompanyAddress1]").val(json.address1);
			form.find("[name=domCompanyAddress2]").val(json.address2);
			form.find("[name=domCompanyAddress3]").val(json.address3);
			form.find("[name=domPostcode]").val(json.postcode);
			form.find("[name=domTown]").val(json.town);
			closeDialog();
		});
	} else if (addrType == "companyNdAddr") {
		$.getJSON("/lodgeAddress.do?method=ndepcAddress", {addressId:addressId}, function(json){
			form.find("[name=ndomCompanyAddress1]").val(json.address1);
			form.find("[name=ndomCompanyAddress2]").val(json.address2);
			form.find("[name=ndomCompanyAddress3]").val(json.address3);
			form.find("[name=ndomPostcode]").val(json.postcode);
			form.find("[name=ndomTown]").val(json.town);
			closeDialog();
		});
	} else if (addrType == "homeAddr") {
		$.getJSON("/lodgeAddress.do?method=depcAddress", {addressId:addressId}, function(json){
			form.find("[name=address1]").val(json.address1);
			form.find("[name=address2]").val(json.address2);
			form.find("[name=address3]").val(json.address3);
			form.find("[name=postcode]").val(json.postcode);
			form.find("[name=town]").val(json.town);
			closeDialog();
		});
	}
	
}

