
/**
 * This file contains core functions and bindings used
 * across all pages.
 */

/**
 * Event bindings
 */

$(document).ready(function() {
	/**
	 * Standard ajax events and warnings.
	 */
	$('#WarningSimple').ajaxError(function() {
		$('#warningSimpleMessage').text('Ajax error.');
		$(this).show();
	});
	
	$('#loader').ajaxStart( function() {
		$(this).fadeIn();
	});
	
	$('#loader').ajaxStop(function() {
		$(this).fadeOut();
	});
	
});

/**
 *	function declarations
 */

/**
 * Simple warning message box.
 * @param message	string warning message.
 */
function show_warning(message) {
	$('#warningSimpleMessage').text(message);
	$('#WarningSimple').show();
	$('#WarningSimple').css('z-index', 2000);
}

/**
 * Does autocompletes for a Organisation and Contact pair.
 * 
 * Will autofill related ID fields for both. If Organisation
 * field is filled contact autocomplete will only search contacts 
 * in that organisation. When contact field is filled Organisation
 * field will be autocompleted with contact's organisation.
 * @param orgInput
 * @param orgIDInput
 * @param contactInput
 * @param contactIDInput
 * @return
 */
function org_contact_autocomplete(orgInput, orgIDInput, contactInput, contactIDInput) {
	
	orgInput.autocomplete('content/autofill.php', {
		extraParams: { type: 'orgs' },
		minChars: 2,
		mustMatch: true
	}).result(function(event, data, formatted) {
		if (data) {
			if(orgIDInput.val() != data[1]) {
				orgIDInput.val(data[1]);
				contactInput.val('');
				contactIDInput.val('');
			}
		} else {
			orgIDInput.val('');
		}
	});
	contactInput.autocomplete('content/autofill.php', {
		extraParams: { type: 'contact', oid: function() { return orgIDInput.val(); } },
		minChars: 2,
		mustMatch: true,
		formatItem: function(row, i, max, term) {
			return  row[0].replace(new RegExp("(" + term + ")", "gi"), "<strong>$1</strong>") + "<br>" +
					"<span style='font-size: 80%;'>"+row[2] + "</span><br>" +
					"<span style='font-size: 70%;'>"+row[3]+"</span>";
		},
		cacheLength: 1
	}).result(function(event, data, formatted) {
		if (data) {
			contactIDInput.val(data[1]);
			orgIDInput.val(data[4]);
			orgInput.val(data[2]);
			
		}
	});
	
	
}

function org_autocomplete(orgInput, orgIDInput) {
	
	orgInput.autocomplete('content/autofill.php', {
		extraParams: { type: 'orgs' },
		minChars: 2,
		mustMatch: true
	}).result(function(event, data, formatted) {
		if (data) {
			if(orgIDInput.val() != data[1]) {
				orgIDInput.val(data[1]);
			}
		} else {
			orgIDInput.val('');
		}
	});
	
	
	
}

function org_autocomplete_secondary(orgInput, orgIDInput,branchName,branchsel) {
	
	orgInput.autocomplete('content/autofill.php', {
		extraParams: { type: 'orgs' },
		minChars: 2,
		mustMatch: false
	}).result(function(event, data, formatted) {
		if (data) {
			if(orgIDInput.val() != data[1]) {
				orgIDInput.val(data[1]);
			}
		} else {
			orgIDInput.val('');
			
		}
		branchName.show();
		branchsel.hide();
		branchsel.val(0);
	}).flushCache(function(event,data,formatted){
		data=null;
	});
	
	
	
}

/**
 * Sets up a imperial/metric input pair to allow toggling and
 * auto converting between them
 * @param dropdown		dropdown selector of unit type
 * @param input_imperial
 * @param input_metric
 * @param type			type of measure (land/building)
 * @return
 */
function measure_auto_convert(dropdown, input_imperial, input_metric, type) {
	
	dropdown.unbind();
	input_metric.unbind();
	input_imperial.unbind();
	
	input_metric.hide();
	input_imperial.show();
	
	dropdown.bind('change', function() {
		switch(parseInt($(this).val())) {
		case 1:
			input_imperial.show();
			input_metric.hide();
			break;
		case 2:
		default:
			input_imperial.hide();
			input_metric.show();
			break;
		}
	});
	
	input_imperial.bind('blur', function() {
		input_metric.val( number_format( imperial_to_metric( number_unformat($(this).val()), type)));
	});
	input_metric.bind('blur', function() {
		input_imperial.val( number_format( metric_to_imperial( number_unformat($(this).val()), type)));
	});
	
}

/**
 * Converts an imperial value into a metric one.
 * @param s		int imperial value
 * @param type	type of measure (land/building)
 * @return		int metric value
 */
function imperial_to_metric(s, type) {
	if(s == '')
		return '';
	if(s == 0)
		return 0;
	switch(parseInt(type)) {
	case 2:
		return acres_to_ha(s);
	case 1:
	default:
		return sqfeet_to_sqm(s);
	}
}

/**
 * Converts a metric value into an imperial one
 * @param s		int metric value
 * @param type	type of measure
 * @return		int imperial value
 */
function metric_to_imperial(s, type) {
	if(s == '')
		return '';
	if(s == 0)
		return 0;
	switch(parseInt(type)) {
	case 2:
		return ha_to_acres(s);
	case 1:
	default:
		return sqm_to_sqfeet(s);
	}
}

/**
 * Conversion from square feet to square metres
 * @param feet	int square feet
 * @return		int square metres
 */
function sqfeet_to_sqm(feet) {
	return Math.round(feet * 0.09290304);
}

/**
 * Conversion from square metres to square feet
 * @param m		int square metres
 * @return		int square feet
 */
function sqm_to_sqfeet(m) {
	//return Math.round(m * 10.7639104);
	return Math.round(m * 10.7639104);
}

/**
 * Conversion from acres to hectares
 * @param acres	
 * @return	hectares
 */
function acres_to_ha(acres) {
	return Math.round(acres * 0.404685642);
}

/**
 * Conversion from hectares to acres
 * @param ha
 * @return	acres
 */
function ha_to_acres(ha) {
	return Math.round(ha * 2.47105381);
}

/**
 * Formats a number with thousands separators
 * @param nStr
 * @return
 */
function number_format(nStr)
{
	nStr += '';
	if(nStr == '')
		return '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1].substr(0, 2) : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function size_format(nStr)
{
	nStr += '';
	if(nStr == '')
		return '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1].substr(0, 2) : '.00';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	
	return x1 + x2;
}


function size_unformat(str) {
	var x = str.split('.');
	var n = 0;
	if(x.length > 1)
		n = parseInt(x[1].substr(0, 2)) / 100;
	if(x.length > 0) {
		var y = parseInt(x[0].replace(/,/g,''));
		if(!isNaN(y))
			n = n + y;
	} else {
		return '';
	}
	
	return n;
}

/**
 * Converts a number formatted with number_format 
 * back to an integer.
 * @param str
 * @return
 */
function number_unformat(str) {
	var x = str.split('.');
	var n = 0;
	if(x.length > 1)
		n = parseInt(x[1].substr(0, 2)) / 100;
	if(x.length > 0) {
		var y = parseInt(x[0].replace(/,/g,''));
		if(!isNaN(y))
			n = n + y;
	} else {
		return '';
	}
	
	return n;
}

/**
 * 
 * @param nStr
 * @return
 */
function integer_format(nStr) {
	
	nStr += '';
	if(nStr == '')
		return '';
	x = nStr.split('.');
	x1 = x[0];
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	
	return x1;
}

/**
 * Creates a string formatted representation of a size,
 * showing both imperial and metric values
 * @param t		type of measure (land/building)
 * @param size	integer size
 * @param per	boolean - if 'per' should be added (optional)
 * @param curr	string currency to add (optional)
 * @return
 */
function area_format(t, size, per, curr) {
	size = parseInt(size);
	t = parseInt(t);
	if(isNaN(size))
		return '';
	var f = '';
	var p = '';
	var c = '';
	if(per)
		p = 'per ';
	if(curr)
		c = curr;
	if(t == 1) {
		//f = integer_format(size) + c +' '+p+'sq/ft (';
		f = c +' '+integer_format(size) + ' '+p+'sq.ft (';
		//f += integer_format(sqfeet_to_sqm(size))+ c + ' '+p+'sq/m)';
		f += c +' '+integer_format(sqfeet_to_sqm(size))+  ' '+p+'sq.m)';
	} else {
		//f = integer_format(size) + c + ' '+p+'ac. (';
		f = c + ' '+integer_format(size) + ' '+p+'ac (';
		//f += integer_format(acres_to_ha(size)) + c + ' '+p+'ha).';
		f += c +' '+integer_format(acres_to_ha(size)) +  ' '+p+'ha)';
	}
	return f;
}

function price_format(t, price, per, curr) {
	price = parseInt(price);
	t = parseInt(t);
	if(isNaN(price))
		return '';
	var f = '';
	var p = '';
	var c = '';
	if(per)
		p = 'per ';
	if(curr)
		c = curr;
	if(t == 1) {
		f = c +' '+integer_format(price) + ' '+p+'sq/ft (';
		f += c +' '+integer_format(price_sqfeet_to_sqm(price))+  ' '+p+'sq/m)';
	} else {
		f = c + ' '+integer_format(price) + ' '+p+'ac (';
		f += c +' '+integer_format(price_acres_to_hect(price)) +  ' '+p+'ha)';
	}
	return f;
}

function price_sqfeet_to_sqm(price){
	return (price/0.09290304);;
}

function price_acres_to_hect(price){
	return (price/0.404685642);
}


/**
 * Converts the integer value of a unit status to it's
 * string value.
 * @param s
 * @return
 */
function status_name(s) {
	
	switch(parseInt(s)) {
	case 1: return 'Live'; break;
	case 2: return 'Under offer'; break;
	case 3: return 'Let'; break;
	case 4: return 'Sold'; break;
	case 5: return 'Off Market'; break;
	case 6: return 'Dead'; break;
	case 7: return 'Tentative'; break;
	}
}

function grade_name(s,type) {
	if(type==1)
		switch(parseInt(s)) {
		case 1: return 'New build - Pre-let'; break;
		case 2: return 'New build - Under Construction'; break;
		case 3: return 'New build - Shell & Core'; break;
		case 4: return 'New build - Completed'; break;
		case 5: return 'Grade A'; break;
		case 6: return 'Second-hand Grade A'; break;
		case 7: return 'Grade B'; break;
		case 8: return 'Second-hand Grade B'; break;
		default: return '';break;
		}
	else if(type==2)
	switch(parseInt(s)){
		case 1: return 'Site'; break;
		case 2: return 'Application'; break;
		case 3: return 'Consent Granted'; break;
		case 4: return 'Refused Application'; break;
		case 5: return 'Lapsed'; break;
		default: return '';break;
		}
	
}

function land_status_name(s) {
	
	switch(parseInt(s)) {
	case 1: return 'Site'; break;
	case 2: return 'Application'; break;
	case 3: return 'Consent Granted'; break;
	case 4: return 'Refused Application'; break;
	case 5: return 'Lapsed'; break;
	default: return '';break;
	}
}

function fillcountry(comboId, country){
	$.getJSON('content/json.reqs.php', {action: 'getCountry'}, function(resp) {
		$(comboId).html("");
		$.each(resp.country, function(i, val) {
			if(val.cname==country)$("<option selected='selected'>"+val.cname+"</option>").appendTo(comboId)
			else $("<option >"+val.cname+"</option>").appendTo(comboId);
		});
	});
}

function filldepartment(comboId, country){
	$.getJSON('content/json_new_orgs.php', {action: 'getDepartment'}, function(resp) {
		$(comboId).html("");
		$.each(resp.department, function(i, val) {
			if(val.id==country)$("<option selected='selected' value='"+val.id+"'>"+val.dname+"</option>").appendTo(comboId)
			else $("<option value='"+val.id+"'>"+val.dname+"</option>").appendTo(comboId);
		});
	});
}

function category_name(s) {
	
	switch(parseInt(s)) {
	case 1: return 'Investment'; break;
	case 2: return 'Development'; break;
	case 3: return 'Investment & Development'; break;
	default: return ''; break;
	}
}
function unit_instruction(s) {
	
	switch(parseInt(s)) {
	case 2: return 'Tentative'; break;
	case 1: return 'Yes'; break;
	case 0: return 'No'; break;
	default: return ''; break;
	}
}
// for property
function convert_metrics(ptype,stype ,size){
	//ptype= property type (1: building ; 2:Land)
	//stype = conversion type (sqmt to sqf or ac to ha depending on ptype)
	//size = size value
	var res='';
	if(ptype==1){
		switch(stype){
			case '1':
				res = sqm_to_sqfeet(size);
				break;
			case '2':
			default:
				res = sqfeet_to_sqm(size);
				break;
			
		}
	}
	else if (ptype==2){
		
		switch(stype){
			case '1':
				res = ha_to_acres(size);
				break;
			case '2':
			default:
				res = acres_to_ha(size);
				break;
			
		}
		
	}
	return res;
}
//convert_to_hec_price

function convert_to_metric_price(ptype,stype ,price){
	//ptype= property type (1: building ; 2:Land)
	//stype = conversion type (sqmt to sqf or ac to ha depending on ptype)
	//size = size value
	var res='';
	if(ptype==1){
		switch(stype){
			case '1':
				//res = sqm_to_sqfeet(size);
				res = Math.round(price*0.09290304);
				break;
			case '2':
			default:
				res = (price/0.09290304);
				break;
			
		}
	}
	else if (ptype==2){
		
		switch(stype){
			case '1':
				//res = ha_to_acres(size);
				res = Math.round(price*0.404685642);
				break;
			case '2':
			default:
				res = (price/0.404685642);
				break;
			
		}
		
	}
	return res;
}


// for properties
function format_size(resp){
	
		if(resp.size!=0.00)
		resp.sizename = area_format(resp.type, resp.size);
		else resp.sizename='';
		if(resp.size_to!=0.00)
		resp.sizetoname = area_format(resp.type, resp.size_to);
		else resp.sizetoname='N/A';
		//added as per bob - size format
		resp.sizeformat1='';
		resp.sizeformat2='';
		var metric1='';
		var metric2='';
		if(resp.type==1){
			metric1= 'sq.ft';
			metric2= 'sq.m';
		}else{
			metric1= 'ac.';
			metric2= 'hc.';
		}
		//alert(resp.size_to);
		if(resp.size!=0.00){
		var sto = integer_format(resp.size_to);
		resp.sizeformat1 = integer_format(resp.size) +(sto ==0 || resp.size==resp.size_to?' '+metric1:' - '+sto+' '+metric1);
		var sf = imperial_to_metric(resp.size,resp.type);
		var st = imperial_to_metric(resp.size_to,resp.type);
		var stf = integer_format(st);
		if(sf!=0)
			resp.sizeformat2 = integer_format(sf) +(stf ==0 || resp.size==resp.size_to?' '+metric2:' - '+stf+' '+metric2);
		}
		
		//end  size format
		
		if(resp.freehold_per!=0)
		resp.freeholdname = price_format(resp.type, resp.freehold_per);
		else 	resp.freeholdname='N/A';
		if(resp.leasehold_per!=0)
		resp.leaseholdname = price_format(resp.type, resp.leasehold_per,'per');
		else 	resp.leaseholdname='N/A';
		if(resp.longleasehold_per!=0)
		resp.longleaseholdname = price_format(resp.type, resp.longleasehold_per,'per');
		else 	resp.longleaseholdname='N/A';
		if(resp.leasehold_per){
			if(resp.type == 1) {
					resp.leasehold_format1 = resp.currency + integer_format(resp.leasehold_per) +' per sqft';
					resp.leasehold_format2 = resp.currency + integer_format(price_sqfeet_to_sqm(resp.leasehold_per)) + ' per sqmt';
				} else {
					resp.leasehold_format1 = resp.currency + integer_format(resp.leasehold_per) +' per  ac.';
					resp.leasehold_format2 = resp.currency + integer_format(price_acres_to_hect(resp.leasehold_per)) + ' per hc.';
				}
				
		}else {
			resp.leasehold_format1 = 'N/A';
			resp.leasehold_format2 = 'N/A';
		}
		
	return resp;
}

function fill_size_dropDown(comboId,type){
	$(comboId+' option').remove();//
	var options;
	switch(parseInt(type)) {
	case 1:
		options = ['sq/f', 'sq/m'];
		break;
	case 2:
	default:
		options = ['ac.', 'ha.'];
	}
	$.each(options, function(i,val) {
		$(comboId).append('<option value="'+(i+1)+'">'+ val +'</option>');
	});
}

// for requirements
function format_size_req(resp){
	
		if(resp.size_from!=0)
		resp.sizefname = area_format(resp.type, resp.size_from);
		else 	resp.sizefname='';
		if(resp.size_to!=0)
		resp.sizetname = area_format(resp.type, resp.size_to);
		else 	resp.sizeftname='';
		resp = reqsize_format_new(resp);
		
	return resp;
		
	
}


function clearBox (val){
	$(val + " input[type=text]").val(" ");
	$(val + " textarea").val(" ");
	$(val +' option').removeAttr('selected');
	$(val + " input[type=checkbox]").attr('checked', false);
	$('.disabled1,.disabled2,.disabled3').attr('disabled','disabled');
	$(val + " input[type=file]").val("");
	$(val + " input[type=hidden]").val("");
	//def_radio
	$('.def_radio').attr('checked', 'checked');
}



function CTypeName(id){
	var result='';
	switch(parseInt(id)){
	case 1:
		result='Client';
		break;
	case 2:
		result='Agent';
		break;
	case 3:
		result='Applicant';
		break;
	}
return result;
}


function sortBypsize(a, b) {
     var x = parseInt(a.size);
    var y = parseInt(b.size);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBypsizeDESC(a, b) {
     var x = parseInt(a.size);
    var y = parseInt(b.size);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortBypdate(a, b) {
    var x = a.pdate.toLowerCase();
    var y = b.pdate.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBypdateDESC(a, b) {
    var x = a.pdate.toLowerCase();
    var y = b.pdate.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
function sortBypname(a, b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBypnameDESC(a, b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByplocation(a, b) {
    var x = a.location.toLowerCase();
    var y = b.location.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByplocationDESC(a, b) {
    var x = a.location.toLowerCase();
    var y = b.location.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortBylocation(a, b) {
    var x = a.postcode.toLowerCase();
    var y = b.postcode.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBylocationDESC(a, b) {
    var x = a.postcode.toLowerCase();
    var y = b.postcode.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortBypown(a, b) {
    var x = a.owner.toLowerCase();
    var y = b.owner.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBypownDESC(a, b) {
    var x = a.owner.toLowerCase();
    var y = b.owner.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}


function sortByusize(a, b) {
     var x = parseInt(a.size);
    var y = parseInt(b.size);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByusizeDESC(a, b) {
     var x = parseInt(a.size);
    var y = parseInt(b.size);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByuname(a, b) {
    var x = (a.name==null?'':a.name.toLowerCase());
    var y = (b.name==null?'':b.name.toLowerCase());
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByunameDESC(a, b) {
    var x = (a.name==null?'':a.name.toLowerCase());
    var y = (b.name==null?'':b.name.toLowerCase());
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
function sortByuproperty(a, b) {
    var x = a.property.toLowerCase();
    var y = b.property.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByupropertyDESC(a, b) {
    var x = a.property.toLowerCase();
    var y = b.property.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByulocation(a, b) {
    var x = a.location.toLowerCase();
    var y = b.location.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByulocationDESC(a, b) {
    var x = a.location.toLowerCase();
    var y = b.location.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
function sortByudate(a, b) {
    var x = a.udate.toLowerCase();
    var y = b.udate.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByudateDESC(a, b) {
    var x = a.udate.toLowerCase();
    var y = b.udate.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}


function sortBymdate(a, b) {
    var x = a.mdate.toLowerCase();
    var y = b.mdate.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
//
function sortBymdateDESC(a, b) {
    var x = a.mdate.toLowerCase();
    var y = b.mdate.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByutenant(a, b) {
    var x = a.tenant.toLowerCase();
    var y = b.tenant.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByutenantDESC(a, b) {
    var x = a.tenant.toLowerCase();
    var y = b.tenant.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByuagent(a, b) {
    var x = a.agent.toLowerCase();
    var y = b.agent.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByuagentDESC(a, b) {
    var x = a.agent.toLowerCase();
    var y = b.agent.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}


function sortByuowner(a, b) {
    var x = a.owner.toLowerCase();
    var y = b.owner.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByuownerDESC(a, b) {
    var x = a.owner.toLowerCase();
    var y = b.owner.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByugrade(a, b) {
    var x = a.gradename.toLowerCase();
    var y = b.gradename.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByugradeDESC(a, b) {
    var x = a.gradename.toLowerCase();
    var y = b.gradename.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}


function sortByuOrgType(a,b){
	 var x = a.orgtype.toLowerCase();
    var y = b.orgtype.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByuOrgTypeDESC(a, b) {
    var x = a.orgtype.toLowerCase();
    var y = b.orgtype.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}


function sortByfreehold(a, b) {
     var x = parseInt(a.freehold_total);
    var y = parseInt(b.freehold_total);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByfreeholdDESC(a, b) {
     var x = parseInt(a.freehold_total);
    var y = parseInt(b.freehold_total);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByllhold(a, b) {
     var x = parseInt(a.longleasehold_total);
    var y = parseInt(b.longleasehold_total);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByllholdDESC(a, b) {
     var x = parseInt(a.longleasehold_total);
    var y = parseInt(b.longleasehold_total);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortBylholdper(a, b) {
     var x = parseInt(a.leasehold_per);
    var y = parseInt(b.leasehold_per);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBylholdperDESC(a, b) {
     var x = parseInt(a.leasehold_per);
    var y = parseInt(b.leasehold_per);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}






function sortByCmp(a, b) {
   var x = a.name.toLowerCase();
   var y = b.name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
   //alert(parseFloat(x) - parseFloat(y));
   
}
function sortByCmpDESC(a, b) {
   var x = a.name.toLowerCase();
   var y = b.name.toLowerCase();
   return ((x > y) ? -1 : ((x < y) ? 1 : 0));
   
}

function sortBySector(a, b) {
    var x = a.sector.toLowerCase();
    var y = b.sector.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBySectorDESC(a, b) {
    var x = a.sector.toLowerCase();
    var y = b.sector.toLowerCase();
   return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByType(a, b) {
     var x = parseInt(a.type);
    var y = parseInt(b.type);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByTypeDESC(a, b) {
     var x = parseInt(a.type);
    var y = parseInt(b.type);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByWeb(a, b) {
    var x = a.web.toLowerCase();
    var y = b.web.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByWebDESC(a, b) {
    var x = a.web.toLowerCase();
    var y = b.web.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByCname(a, b) {
    var x = a.fname.toLowerCase();
    var y = b.fname.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCnameDESC(a, b) {
    var x = a.fname.toLowerCase();
    var y = b.fname.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByCorg(a, b) {
    var x = a.oname.toLowerCase();
    var y = b.oname.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByCorgDESC(a, b) {
    var x = a.oname.toLowerCase();
    var y = b.oname.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByCbranch(a, b) {
    var x = a.bname.toLowerCase();
    var y = b.bname.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCbranchDESC(a, b) {
    var x = a.bname.toLowerCase();
    var y = b.bname.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByCwork(a, b) {
    var x = a.work.toLowerCase();
    var y = b.work.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCworkDESC(a, b) {
    var x = a.work.toLowerCase();
    var y = b.work.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByCemail(a, b) {
    var x = a.email.toLowerCase();
    var y = b.email.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCemailDESC(a, b) {
    var x = a.email.toLowerCase();
    var y = b.email.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByCmob(a, b) {
    var x = a.mob.toLowerCase();
    var y = b.mob.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCmobDESC(a, b) {
    var x = a.mob.toLowerCase();
    var y = b.mob.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByCddi(a, b) {
    var x = a.ddi.toLowerCase();
    var y = b.ddi.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCddiDESC(a, b) {
    var x = a.ddi.toLowerCase();
    var y = b.ddi.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}



function sortByudet(a, b) {
    var x = (a.catName==null?'':a.catName.toLowerCase());
    var y = (b.catName==null?'':b.catName.toLowerCase());
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByudetDESC(a, b) {
    var x = (a.catName==null?'':a.catName.toLowerCase());
    var y = (b.catName==null?'':b.catName.toLowerCase());
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}



// requirements start


function sortByrsize(a, b) {
     var x = parseInt(a.size_from);
    var y = parseInt(b.size_from);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByrsizeDESC(a, b) {
     var x = parseInt(a.size_from);
    var y = parseInt(b.size_from);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByrdate(a, b) {
    var x = a.date.toLowerCase();
    var y = b.date.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByrdateDESC(a, b) {
    var x = a.date.toLowerCase();
    var y = b.date.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
function sortByrstatus(a, b) {
    var x = a.status.toLowerCase();
    var y = b.status.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByrstatusDESC(a, b) {
    var x = a.status.toLowerCase();
    var y = b.status.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByrloc(a, b) {
    var x = a.location.toLowerCase();
    var y = b.location.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByrlocDESC(a, b) {
    var x = a.location.toLowerCase();
    var y = b.location.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByragent(a, b) {
    var x = a.agent_oname.toLowerCase();
    var y = b.agent_oname.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByragentDESC(a, b) {
    var x = a.agent_oname.toLowerCase();
    var y = b.agent_oname.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByrapp(a, b) {
    var x = a.org_name.toLowerCase();
    var y = b.org_name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByrappDESC(a, b) {
    var x = a.org_name.toLowerCase();
    var y = b.org_name.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByrapplicant(a, b) {
    var x = a.app_name.toLowerCase();
    var y = b.app_name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByrapplicantDESC(a, b) {
    var x = a.app_name.toLowerCase();
    var y = b.app_name.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function sortByref(a, b) {
     var x = parseInt(a.id);
    var y = parseInt(b.id);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByrefDESC(a, b) {
     var x = parseInt(a.id);
    var y = parseInt(b.id);
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}





// requirements end


function fill_useClass(controlId,useclass){
	
removeItems(document.getElementById(controlId));
   if(useclass!=undefined && useclass!='' && useclass!=null && useclass!='null'){
        var uclass = useclass.split(',');
        //alert(uclass);
        $.each(uclass, function(i, val) {
            if(val!=' ' && val!=''){
              $.each(property_use_cases,function(j, res){
		//alert(val.trim());
                     if(val.trim()==res.code)
                            $("<option>"+res.name+"</option>").appendTo("#"+controlId);
              });
               
            }
        });
   }
   else{
	 $("#"+controlId).html('');
	
   }
	
}

function removeItems(selectbox)
{
	var i;
	for(i=selectbox.options.length-1;i>=0;i--)
	{
		selectbox.remove(i);
	}
}

function create_location(array,separator){
	
	if(!separator)
		separator ="<br />";
	var result='';
	var j=0;
		$.each(array,function(i,val){
			if(val.name.trim()!='' && val.name!=null){
				if(j==0){
					result = val.name.trim();
					j++;
				}
				else{
					result = result + separator+ val.name.trim();
				}
			}	
		});
		
	return result;
	
}


function SelectUse(uclassId,useClassDiv,hiddenId,row_prefix){
	var val = "";
	var count = 15;
	var num   = 1;
	var hidValue='';
	var count=0;
	while( num <= 15){
		
		if ($('#'+row_prefix+'use_' + num).is(":checked")){
			var uclassValue = $('#'+row_prefix+'use_' + num).val();
			$.each(property_use_cases,function(i,resp){
				if(resp.code== uclassValue){
					if(count==0){
						hidValue = resp.code;
						val += "<option value=\""+resp.code+"\">" + resp.name + "</option>";
						count++;
					}
					else{
						hidValue = hidValue + ","+resp.code;
						val += "<option value=\""+resp.code+"\">" + resp.name + "</option>";
					}
				}
			});
		} 
		num ++;
	}
	if(val == ""){
		val += "<option value=\"1\">Double Click To Select Use Class</option>";
	}
		
	//alert(hidValue);
	$(uclassId).html(val);
	$(useClassDiv).hide();
	$(hiddenId).val(hidValue);
}

function show_use(infoMenu,uclass,row_prefix){
	Loadsmalltpl(infoMenu,'useClass',row_prefix);
	if(uclass=='')
		return;
	var uClassArray = uclass.split(',');

	
	$(infoMenu+ " input:checkbox").removeAttr('checked');
	$.each(uClassArray,function(i,val){
		
		if(val!=''){
			$.each($(infoMenu+ " input:checkbox"),function(i,res){
				//alert(res);
				if($(this).val()==val.trim())
					$(this).attr('checked','checked');
			});
		}
		});
	
	
}
function ClearHtml(id){
	$(id).html('');
	$(id).removeAttr('checked');
	
}

function format_reqsize(resp){
	if(resp.size_from!=0.00)
		resp.sizefrname = area_format(resp.type, resp.size_from);
		else 	resp.sizefrname='';
		if(resp.size_to!=0.00)
		resp.sizetoname = area_format(resp.type, resp.size_to);
		else resp.sizetoname='';
	return resp;	
}


function format_unit(val){
	
	if(val.type == 1) {
		val.typename = 'building';
		if(val.size!=0)
			val.sizename = area_format(val.type, val.size);
		else 	val.sizename='';
		if(val.sizeto!=0)
			val.sizetoname = area_format(val.type, val.size_to);
		else 	val.sizetoname='';
				
		} else {
			val.typename = 'land';
			if(val.size!=0)
				val.sizename = area_format(val.type, val.size);
			else 	val.sizename='';
			if(val.sizeto!=0)
				val.sizetoname = area_format(val.type, val.size_to);
			else 	val.sizetoname='';
		}
	
	return val;
}

function ShowGradeHtml(grade,type,ContorlId){
	
	if(grade==null) return;
	var gArr = grade.split(',');
	$(ContorlId).html('');
	$.each(gArr,function(i,val){
		if(val!='')
			$(ContorlId).append("<option >" +grade_name(val,type)+ "</option>");
	});
	
}


function ShowdatesHtml(date,ContorlId){
	if(date==null) return;
	var gArr = date.split(',');
	$(ContorlId).html('');
	$.each(gArr,function(i,val){
		if(val!='')
			$(ContorlId).append("<option >" +val+ "</option>");	
	});
	
}

if(typeof String.prototype.trim !== 'function') { 
  String.prototype.trim = function() { 
    return this.replace(/^\s+|\s+$/g, '');  
  } 
} 


function Loadsmalltpl(loadDiv,template,row_prefix){
	var resp="{\"response\":\"empty\",\"page\":\"1\",\"row_prefix\":\""+row_prefix+"\",\"total\":\"0\"}";
	var myobj = (new Function("return " + resp))() ;
	$(loadDiv).removeTemplate();
	$(loadDiv).setTemplate(contentLoad.get_template_by_id(template));
	$(loadDiv).processTemplate(myobj);	
}


function emailClick(){
	$('.email').unbind().css('cursor','pointer').click(function(){	
		var email = $(this).html();
		//window.open(email,'emailWindow');
	});
}

function size_format_new(resp){
	if(resp.size!=0)
		resp.sizefname = area_format(resp.type, resp.size);
		else 	resp.sizefname='';
		if(resp.sizeto!=0)
		resp.sizetname = area_format(resp.type, resp.sizeto);
		else 	resp.sizeftname='';
		
		resp.sizeformat1='';
		resp.sizeformat2='';
		var metric1='';
		var metric2='';
		if(resp.type==1){
			metric1= 'sq.ft';
			metric2= 'sq.m';
		}else{
			metric1= 'ac.';
			metric2= 'hc.';
		}
		if(resp.size!=0.00){
		var sto = integer_format(resp.sizeto);
		resp.sizeformat1 = integer_format(resp.size) +(sto ==0 ?' '+metric1:' - '+sto+' '+metric1);
		var sf = imperial_to_metric(resp.size,resp.type);
		var st = imperial_to_metric(resp.sizeto,resp.type);
		var stf = integer_format(st);
		//if(sf!=0)
			resp.sizeformat2 = integer_format(sf) +(stf ==0 ?' '+metric2:' - '+stf+' '+metric2);
		//}
		}
	return resp;
}

function reqsize_format_new(resp){
	resp.sizeformat1='';
		resp.sizeformat2='';
		var metric1='';
		var metric2='';
		if(resp.type==1){
			metric1= 'sq.ft';
			metric2= 'sq.m';
		}else{
			metric1= 'ac.';
			metric2= 'hc.';
		}
		if(resp.size_from!=0.00){
		var sto = integer_format(resp.size_to);
		resp.sizeformat1 = integer_format(resp.size_from) +(sto ==0 || resp.size_from==resp.size_to?' '+metric1:' - '+sto+' '+metric1);
		var sf = imperial_to_metric(resp.size_from,resp.type);
		var st = imperial_to_metric(resp.size_to,resp.type);
		var stf = integer_format(st);
		//if(sf!=0)
			resp.sizeformat2 = integer_format(sf) +(stf ==0 || resp.size_from==resp.size_to?' '+metric2:' - '+stf+' '+metric2);
		//}
		}
		return resp;
}

function getlogtype(type){
	var res='';
	switch(type){
		case "1":
			res='Telephone';
			break;
		case "2":
			res ='Email';
			break;
		case "3":
			res = 'Letter';
			break;
		case "4":
			res ='Visit';
			break;
		case "5":
			res = 'status changed';
			break;
		case "6":
			res = 'Updated';
			break;
		default:
			res='Other';
			break;
	}
	return res;
}

function fill_useClassTemplate(useclass){
	var result='';
	//removeItems(document.getElementById(controlId));
	   if(useclass!=undefined && useclass!='' && useclass!=null && useclass!='null'){
		var uclass = useclass.split(',');
		$.each(uclass, function(i, val) {
		    if(val!=' ' && val!=''){
		      $.each(property_use_cases,function(j, res){
			     if(val.trim()==res.code)
				   // $("<option>"+res.name+"</option>").appendTo("#"+controlId);
				    result+= "<option>"+res.name+"</option>";
		      });
		       
		    }
		});
	   }
	return result;
}

function postData(postURL,requestAction,params,callback){
       var data = new Object();
       $.each(params,function(i,val){
              data[i]=val;
       });
      $.post(postURL+"?action="+requestAction, {'json' : JSON.stringify(data)}, function(resp) {
			callback(resp);
		}, 'json');
}
