var G_SET = {container:"#container",mainContent:"#mainContent"};

$(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();
	});

	initPage();
});


function validateForm(form){
	if(!$(form).valid()) {return false;}
}
function closeDialog(){
	$.closeDialog('#dialogBox');
}
function validateCallBack(form, callback, $params) {
	try{
		if (!$(form).valid()) {
			alertMsg.error(Msg.get('validation.failed'));
			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);
		if (json.furl) $("#container").loadUrl(json.furl);
	} else if (json.statusCode == 301) {
		alertMsg.error(Msg.get('session.timeout'), {okCall:function(){
			window.location = "/render.do?method=login";
		}});
	} else {
		if(json.message) alertMsg.error(json.message);
	};
}
function dialogAjaxDone(json){
	jsonMsgDone(json);
	if (json.statusCode == 200){
		closeDialog();
	}
}
function ifarmeCallback(form, callback){
	if(!$(form).valid()) {return false;}
	window.donecallback = $.isFunction(callback) ? callback : jsonMsgDone;
	if ($("#callbackframe").size() == 0) { 
		$("<iframe id='callbackframe' name='callbackframe' src='about:blank' style='display:none'></iframe>").appendTo("body");
	}
	form.target = "callbackframe";
}



function delReportDocument(fileId){
	alertMsg.confirm(Msg.get('document.del.confirm'), {
		okCall: function(){
			$.post("/myaccount/content.do?method=remove", {fileId:fileId}, uploadReportDocDone, "json");
		}
	});
}
function uploadReportDocDone(response){
	jsonMsgDone(response);
	if(response["statusCode"] == 200) {
		_loadReport(response["objectId"], {step:"DOCUMENT"});
	};
}

function showChecked(checkBox, boxId){
	if(checkBox.checked) $(boxId).show("slow");
	else $(boxId).hide("slow");
}
function toggleCheckeBox(checkBox, inputName, checkVal, uncheckVal){
	var jInput = $("#reportForm").find("[name="+inputName+"]");
	if(checkBox.checked) jInput.val(checkVal || "1");
	else jInput.val(uncheckVal || "0");
}
function repToggleChecked(checkBox, inputNames){
	for (var i = 0; i<inputNames.length; i++){
		var jInput = $("#reportForm").find("[name="+inputNames[i]+"]");
		if (checkBox.checked) {
			jInput.attr("disabled", false);
		} else {
			jInput.attr("disabled", true);
		}
	}
}
//function toggleImprovement(checkBox, index){
//	var namePrex = "improvement("+index+").";
//	var jNote = $("#reportForm").find("[name="+namePrex+"note]");
//	var jSaving = $("#reportForm").find("[name="+namePrex+"saving]");
//	var jSap = $("#reportForm").find("[name="+namePrex+"sapChange]");
//	var jEi = $("#reportForm").find("[name="+namePrex+"eiChange]");
//	if(checkBox.checked) {
//		jNote.attr("disabled", true).addClass("disabled").parent().find("> span.error").hide();
//		jSaving.show();
//		jSap.show();
//		jEi.show();
//	} else {
//		jNote.attr("disabled", false).removeClass("disabled");
//		jSaving.hide();
//		jSap.hide();
//		jEi.hide();
//	}
//}

function showBedf(){
	var $form = $("#reportForm");
	$.openDialog('#dialogBox',{url:"/myaccount/report.do?method=bedf", data:$form.serializeArray(), title:"View Boiler Details", width:680, height:380});
}
function processReport($param, isNext){
	var form = $("#reportForm").get(0);
	if (isNext && !$(form).valid()) {
		alertMsg.error(Msg.get('validation.failed'));
		return false;
	}
	if ($param.step) form.step.value = $param.step;
	$.post(form.action, $(form).serializeArray(), processReportDone, "json");
}
function processReportDone(json){
	jsonMsgDone(json);
	if(json.statusCode == 200) {
		_loadReport(json.objectId, {step:json.step, tabNav:json.tabNav});
	};
}

function calculateEnergyRating(){
	var form = $("#reportForm").get(0);
	$.post("/myaccount/report.do?method=calculateRating", {reportId:form.reportId.value, step:"IM"}, function (json){
		jsonMsgDone(json);

		if(json.statusCode == 200) {
			_loadReport(json.objectId, {step:json.step, edit:true});
		}
		
	}, "json");
}
function reCalculateRating(tabNav){
	var form = $("#reportForm").get(0);
	var url = "/myaccount/report.do?method=reCalculateRating&step=IM";
	if (tabNav) url += "&tabNav="+tabNav;
	$.post(url, $(form).serializeArray(), processReportDone, "json");
}

function closeReportWindow(isNotPersist){
	if (isNotPersist) {
		alertMsg.confirm(Msg.get('window.close.confirm'), {
			okCall: function(){
				_closeReportWindow();
			}
		});
	} else {
		_closeReportWindow();
	}
	function _closeReportWindow(){
		$("#container").loadUrl("/myaccount/render.do?method=listReport&closeReprt=1");
	}
}
function _getSelectedReportId(){
	var reportId = $("#reportListForm").get(0).reportId.value;
	if (!reportId) {
		alertMsg.error(Msg.get('report.select'));
		return false;
	}
	return reportId;
}
function loadEditReport(step){
	var reportId = _getSelectedReportId();
	if (reportId) _loadReport(reportId, {edit:true, step:step, bHistory:true});
}
function copyReport(){
	var reportId = _getSelectedReportId();
	if (!reportId) return false;
	alertMsg.confirm(Msg.get('report.copy.confirm'), {
		okCall: function(){
			$.post("/myaccount/report.do?method=copyReport", {reportId:reportId}, _reloadReport_, "json");
		}
	});
}
function loadAddReport(){
	$("#container").loadUrl("/myaccount/render.do?method=addReport");
}
function _loadReport(reportId, options){
	var op = $.extend({ edit: false, step:"", tabNav:"", bHistory: false}, options);
	var url = "/myaccount/render.do?method=processReport&reportId="+reportId;
	if (op.edit) url += "&editReport=1";
	if (op.step) url += "&step=" + op.step;
	if (op.tabNav) url += "&tabNav=" + op.tabNav;
	
	if (op.bHistory) $("#container").loadHistory(url);
	else $("#container").loadUrl(url);
}
function _reloadReport_(json){
	jsonMsgDone(json);
	if(json.statusCode == 200) {
		_loadReport(json.objectId, {step:json.step, edit:true});
	};
}
function delReport(){
	var reportId = _getSelectedReportId();
	if (!reportId) return false;
	alertMsg.confirm(Msg.get('report.del.confirm'), {
		okCall: function(){
			$.post("/myaccount/report.do?method=delReport", {reportId:reportId}, opReportDone, "json");
		}
	});
}
function cancelReport($reportId){
	var reportId = $reportId || _getSelectedReportId();
	if (!reportId) return false;
	alertMsg.confirm(Msg.get('report.cancel.confirm'), {
		okCall: function(){
			$.post("/myaccount/report.do?method=cancelReport", {reportId:reportId}, opReportDone, "json");
		}
	});
}
function createEpc($reportId){
	var reportId = $reportId || _getSelectedReportId();
	if (reportId)
		$.post("/myaccount/report.do?method=createEpc", {reportId:reportId}, $reportId ? _reloadReport_ : opReportDone, "json");
}
function lodgeReport($reportId){
	var reportId = $reportId || _getSelectedReportId();
	if (reportId)
		$.post("/myaccount/report.do?method=lodgeReport", {reportId:reportId}, $reportId ? _reloadReport_ : opReportDone, "json");
}
function opReportDone(json){
	jsonMsgDone(json);
	filterReports({}, true);
}

//function copyToOtherFloors($tableId, $index){
//	var groundIndex = $index || 0;
//
//	var jTRs = $($tableId + ">tbody>tr");
//	var jGroundInput = jTRs.eq(groundIndex).find("[type=text]");
//	var aData = [];
//	for (var i=0; i<3; i++){
//		aData[i] = jGroundInput.eq(i).val();
//	}
//	jTRs.each(function(index){
//		
//		if (index > groundIndex){
//			var jInput = $(this).find("[type=text]");
//			if (jInput.size() > 2) {
//				jInput.each(function(inputIndex){
//					$(this).val(aData[inputIndex]);
//				});
//			}
//		}
//	});
//}

function depcAddressList(postcodeId){
	var postcode = $(postcodeId).val();
	if (postcode) $.post('/lodgeAddress.do?method=depcAddressList', {postcode:postcode}, function(json){
		var html = "";
		$.each(json, function(i,n){
			html += '<option value="'+n.tempId+'">'+n.addressLine+'</option>';
		});
		$("#addressSeleter").html(html);
	}, "json");
}
function selectAddress(formId, addressId){
	var form = $(formId);
	if (addressId) $.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);
//		form.find("[name=county]").val(json.address4);
		form.find("[name=uprn]").val(json.uprn);
	});
}

function searchReports(form){
	$("#container").loadUrl(form.action, $(form).serializeArray());
	return false;
}

function advancedExportReports(){
	var form = $("#reportSearchForm").get(0);
	var url = "/myaccount/render.do?method=advancedExportReports&"+$(form).serialize();
	window.location = url;
}

function exportReports(){
	var form = $("#reportSearchForm").get(0);
	var url = "/myaccount/render.do?method=exportReports&"+$(form).serialize();
	window.location = url;
}

function advancedExportReportsByQa(){
	var form = $("#reportSearchForm").get(0);
	var url = "/myaccount/render.do?method=advancedExportReportsByQa&"+$(form).serialize();
	window.location = url;
}
function exportReportsByQa(){
	var form = $("#reportSearchForm").get(0);
	var url = "/myaccount/render.do?method=exportReportsByQa&"+$(form).serialize();
	window.location = url;
}

function sortReports(orderField, reverse){
	if (reverse) orderField = orderField+"_DESC";
	filterReports({orderField:orderField});
}
function filterReports(args){
	var form = $("#pagerReportForm").get(0); 
	if (!form) return;
	if(args["pageNum"])form.pageNum.value = args["pageNum"];
	if(args["numPerPage"])form.numPerPage.value = args["numPerPage"];
	if(args["orderField"])form.orderField.value = args["orderField"];
	searchReports(form);
}

function opBaseReportDone(json){
	jsonMsgDone(json);
	filterBaseReports({}, true);
}

function cancelEclsReport(reportId){
	if (!reportId) return false;
	alertMsg.confirm(('Are you sure you want to cancel the report?'), {
		okCall: function(){
			$.post("/myaccount/eclsReport.do?method=cancel", {reportId:reportId}, opReportDone, "json");
		}
	});
}




function eaRequestQa(){
	var reportId = _getSelectedReportId();
	if (reportId)
		$.post("/myaccount/report.do?method=eaRequestQa", {reportId:reportId}, opReportDone, "json");
}

function qaRequestQa(){
	var reportId = _getSelectedReportId();
	if (reportId)
		$.post("/myaccount/report.do?method=qaRequestQa", {reportId:reportId}, opReportDone, "json");
}
function eaConfirmQa(reportId){
	if (reportId)
		$.post("/myaccount/report.do?method=eaConfirmQa", {reportId:reportId}, jsonMsgDone, "json");
}
function qaReportCheckDone(json){
	jsonMsgDone(json);
	if(json["statusCode"] == 200) {
		_loadReport(json["objectId"], {edit:true, step:"DOCUMENT"});
		$.closeDialog('#dialogBox');
	};
}

function qaCloseReportWindow(){
	$("#container").loadUrl("/myaccount/render.do?method=listBaseReport&closeReprt=1");
}
// Control Panel
function toControlPanel(){
	$("#container").loadUrl("/myaccount/render.do?method=overview");
}

function loadInsurance(){
	$("#container").loadUrl('/myaccount/render.do?method=insurancePolicies');	
}
function delInsurance(insuranceId){
	alertMsg.confirm(Msg.get('insurance.del.confirm'), {
		okCall: function(){
			$.post("/myaccount/user.do?method=delInsurance", {insuranceId:insuranceId}, opInsuranceDone , "json");
		}
	});
}

function setDefaultInsurance(insuranceId){
	$.post("/myaccount/user.do?method=setDefaultInsurance", {def:insuranceId}, function(){} , "json");
}
function opInsuranceDone(json){
	jsonMsgDone(json);
	if(json["statusCode"] == 200) {
		loadInsurance();
	};
}

function copyBillToDelivery(check,formId){
	var form = $(formId).get(0);
	if(check.checked){
		form.deliveryFirstName.value  = form.billFirstName.value;
		form.deliveryLastName.value   = form.billLastName.value;
		form.deliveryAddress1.value   = form.billAddress1.value;
		form.deliveryAddress2.value   = form.billAddress2.value;
		form.deliveryCity.value 	  = form.billCity.value;
		form.deliveryPostcode.value   = form.billPostcode.value;
	}else{
		form.deliveryFirstName.value = "";
		form.deliveryLastName.value  = "";
		form.deliveryAddress1.value  = "";
		form.deliveryAddress2.value  = "";
		form.deliveryCity.value 	 = "";
		form.deliveryPostcode.value  = "";
	}
}


function submitBillAndReview(form) {
	if (!$(form).valid()) {
		alertMsg.error(Msg.get('validation.failed'));
		return false;
	}
	$.post(form.action, $(form).serializeArray(), function(html){
		$("#container").html(html);
		initPage($("#container"));
	});
	return false;
}

function searchBills(form){
	$("#container").loadUrl(form.action,$(form).serializeArray());
	return false;
}
function sortBill(orderField, reverse){
	if (reverse) orderField = orderField+"_DESC";
	filterEas({orderField:orderField});
}

function filterBills(args){
	var form = $("#pagerbillForm").get(0);
	if(args["startDate"])form.keywords.value = args["startDate"];
	if(args["endDate"])form.keywords.value = args["endDate"];
	if(args["pageNum"])form.pageNum.value = args["pageNum"];
	if(args["numPerPage"])form.numPerPage.value = args["numPerPage"];
	if(args["orderField"])form.orderField.value = args["orderField"];
	searchBills(form);
}

function changeCreditType(o){
	$("#priceTable").loadUrl("/myaccount/bill.do?method=changePriceTable",{creditType:o.value});
	if (o.value == 'RdSAP' || o.value == 'SAP'){
		$("#credits").attr("min",10);
	} else {
		$("#credits").removeAttr("min");
	}
}

function lodgeAndReview(form) {
	if (!$(form).valid()) {
		alertMsg.error(Msg.get('validation.failed'));
		return false;
	}
	$.post(form.action, $(form).serializeArray(), function(html){
		$("#container").html(html);
		initPage($("#container"));
	});
	return false;
}

function lodgeAndReviewCallback(form, callback){
	
	if(!form.dataGather.checked && !form.tick.checked){
		alertMsg.error("Please tick the box if you didn't visit this building personally!");
		return false;
	}
	ifarmeCallback(form, callback);
}


function lodgeAndReviewDone(json){
	if (json.statusCode == 200) {
		$("#container").loadUrl("/myaccount/eclsReport.do?method=lodgeAndReview",{path:json.objectId,dataGather:json.furl});
	}
	if (json.statusCode == 300) {
		if (json.message) alertMsg.error(json.message);
	}
}

function lodgeEclsReport(form){
	$.post(form.action,$(form).serializeArray(),lodgeEclsReportDone,"json");
	return false;
}

function lodgeEclsReportDone(json){
	jsonMsgDone(json);
	$("#container").loadUrl("/myaccount/render.do?method=eclsLodge");
}
