// constants to define the title of the alert and button text.
/*var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";

// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts
if(document.getElementById) {
	window.alert = function(txt) {
		createCustomAlert(txt);
	}
}

function createCustomAlert(txt) {
	// shortcut reference to the document object
	d = document;

	// if the modalContainer object already exists in the DOM, bail out.
	if(d.getElementById("modalContainer")) return;

	// create the modalContainer div as a child of the BODY element
	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	 // make sure its as tall as it needs to be to overlay all the content on the page
	mObj.style.height = document.documentElement.scrollHeight + "px";

	// create the DIV that will be the alert 
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "alertBox";
	// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	// center the alert box
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

	// create an H1 element as the title bar
	h1 = alertObj.appendChild(d.createElement("h1"));
	h1.appendChild(d.createTextNode(ALERT_TITLE));

	// create a paragraph element to contain the txt argument
	msg = alertObj.appendChild(d.createElement("p"));
	msg.innerHTML = txt;
	
	// create an anchor element to use as the confirmation button.
	btn = alertObj.appendChild(d.createElement("a"));
	btn.id = "closeBtn";
	btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
	btn.href = "#";
	// set up the onclick event to remove the alert when the anchor is clicked
	btn.onclick = function() { removeCustomAlert();return false; }
}*/

//Table2CSV
jQuery.fn.table2CSV = function(options) {
    var options = jQuery.extend({
        separator: ',',
        header: [],
        delivery: 'popup' // popup, value
    },
    options);

    var csvData = [];
    var headerArr = [];
    var el = this;

    //header
    var numCols = options.header.length;
    var tmpRow = []; // construct header avalible array

    if (numCols > 0) {
        for (var i = 0; i < numCols; i++) {
            tmpRow[tmpRow.length] = formatData(options.header[i]);
        }
    } else {
        $(el).filter(':visible').find('th').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
    }

    row2CSV(tmpRow);

    // actual data
    $(el).find('tr').each(function() {
        var tmpRow = [];
        $(this).filter(':visible').find('td').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
        row2CSV(tmpRow);
    });
    if (options.delivery == 'popup') {
        var mydata = csvData.join('\n');
        return popup(mydata);
    } else {
        var mydata = csvData.join('\n');
        return mydata;
    }

    function row2CSV(tmpRow) {
        var tmp = tmpRow.join('') // to remove any blank rows
        // alert(tmp);
        if (tmpRow.length > 0 && tmp != '') {
            var mystr = tmpRow.join(options.separator);
            csvData[csvData.length] = mystr;
        }
    }
    function formatData(input) {
    	input = input.trim();
        // replace " with “
        var regexp = new RegExp(/["]/g);
        var output = input.replace(regexp, "“");
        //HTML
        var regexp = new RegExp(/\<[^\<]+\>/g);
        var output = output.replace(regexp, "");
        if (output == "") return '';
        return '"' + output.trim() + '"';
    }
    function popup(data) {
        var generator = window.open('', 'csv', 'height=400,width=600');
        generator.document.write('<html><head><title>CSV</title>');
        generator.document.write('</head><body >');
        generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
        generator.document.write(data);
        generator.document.write('</textArea>');
        generator.document.write('</body></html>');
        generator.document.close();
        return true;
    }
};

function checkExpiryDate(field, rules, i, options){
	var exp = new RegExp("^((0[1-9])|(1[0-2]))[\/]*((0[8-9])|(1[1-9])|(2[0-9]))$");
	if (!exp.test(field.val())) return "Please enter a valid Expiry Date (e.g.: 06/16)";
}

//CC Validation
function isValidCreditCard(value, param) {
	var cardName = param;

	var cards = new Array();
	cards[0] = { cardName: "Visa", lengths: "13,16", prefixes: "4", checkdigit: true };
	cards[1] = { cardName: "MasterCard", lengths: "16", prefixes: "51,52,53,54,55", checkdigit: true };
	cards[2] = { cardName: "DinersClub", lengths: "14,16", prefixes: "305,36,38,54,55", checkdigit: true };
	cards[3] = { cardName: "CarteBlanche", lengths: "14", prefixes: "300,301,302,303,304,305", checkdigit: true };
	cards[4] = { cardName: "AmEx", lengths: "15", prefixes: "34,37", checkdigit: true };
	cards[5] = { cardName: "Discover", lengths: "16", prefixes: "6011,622,64,65", checkdigit: true };
	cards[6] = { cardName: "JCB", lengths: "16", prefixes: "35", checkdigit: true };
	cards[7] = { cardName: "enRoute", lengths: "15", prefixes: "2014,2149", checkdigit: true };
	cards[8] = { cardName: "Solo", lengths: "16,18,19", prefixes: "6334, 6767", checkdigit: true };
	cards[9] = { cardName: "Switch", lengths: "16,18,19", prefixes: "4903,4905,4911,4936,564182,633110,6333,6759", checkdigit: true };
	cards[10] = { cardName: "Maestro", lengths: "12,13,14,15,16,18,19", prefixes: "5018,5020,5038,6304,6759,6761", checkdigit: true };
	cards[11] = { cardName: "VisaElectron", lengths: "16", prefixes: "417500,4917,4913,4508,4844", checkdigit: true };
	cards[12] = { cardName: "LaserCard", lengths: "16,17,18,19", prefixes: "6304,6706,6771,6709", checkdigit: true };

	var cardType = -1;
	for (var i = 0; i < cards.length; i++) {
		if (cardName.toLowerCase() == cards[i].cardName.toLowerCase()) {
			cardType = i;
			break;
		}
	}
	if (cardType == -1) { return false; } // card type not found

	value = value.replace(/[\s-]/g, ""); // remove spaces and dashes
	if (value.length == 0) { return false; } // no length

	var cardNo = value;
	var cardexp = /^[0-9]{13,19}$/;
	if (!cardexp.exec(cardNo)) { return false; } // has chars or wrong length

	cardNo = cardNo.replace(/\D/g, ""); // strip down to digits

	if (cards[cardType].checkdigit) {
		var checksum = 0;
		var mychar = "";
		var j = 1;

		var calc;
		for (i = cardNo.length - 1; i >= 0; i--) {
			calc = Number(cardNo.charAt(i)) * j;
			if (calc > 9) {
				checksum = checksum + 1;
				calc = calc - 10;
			}
			checksum = checksum + calc;
			if (j == 1) { j = 2 } else { j = 1 };
		}

		if (checksum % 10 != 0) { return false; } // not mod10
	}

	var lengthValid = false;
	var prefixValid = false;
	var prefix = new Array();
	var lengths = new Array();

	prefix = cards[cardType].prefixes.split(",");
	for (i = 0; i < prefix.length; i++) {
		var exp = new RegExp("^" + prefix[i]);
		if (exp.test(cardNo)) prefixValid = true;
	}
	if (!prefixValid) { return false; } // invalid prefix

	lengths = cards[cardType].lengths.split(",");
	for (j = 0; j < lengths.length; j++) {
		if (cardNo.length == lengths[j]) lengthValid = true;
	}
	if (!lengthValid) { return false; } // wrong length

	return true;
}

// removes the custom alert from the DOM
function removeCustomAlert() {
	document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

function IsNumeric(input) {
	return (input - 0) == input && input.length > 0;
}

function validateABN(value) {
	value = value.replace(/[ ]+/g, '');
	if (!value.match(/\d{11}/)) {
		return false;
	}

	var weighting = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
	var tally = (parseInt(value.charAt(0)) - 1) * weighting[0];











	for (var i = 1; i < value.length; i++) {
		tally += (parseInt(value.charAt(i)) * weighting[i]);
	}
	return (tally % 89) == 0;
};

function validateACN(value) {
	value = value.replace(/[ ]+/g, '');

	if (!value.match(/\d{9}/)) {
		return false;
	}

	var weighting = [8, 7, 6, 5, 4, 3, 2, 1];
	var tally = 0;
	for (var i = 0; i < weighting.length; i++) {
		tally += (parseInt(value.charAt(i)) * weighting[i]);
	}

	var check = 10 - (tally % 10);
	check = check == 10 ? 0 : check;

	return check == parseInt(value.charAt(i));
};

//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=getcouncil&pc=6102&suburb=bentley
function getCouncilFromSuburbPostcode(idState, idRegion, idCouncil, suburb, postcode) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getcouncil&pc=" + postcode + "&suburb=" + suburb;
	var state = $(idState);
	var region = $(idRegion);
	var council = $(idCouncil);

	state.val('');
	region.val('');
	council.val('');
	$.getJSON(theSource, function(data) {
		state.val(data.state);
		region.val(data.region);
		council.val(data.value);
		council.attr("councilid", data.councilid)
	});
}

//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=availablecategoriesinpostcode&postcode=6102&term=carpet
function getAvailableCategoriesInPostcodeAutoComplete(id, postcode) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=availablecategoriesinpostcode&postcode=" + postcode;

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	});
}

function getOpenJobsInPostcode(id, postcode, category) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=openjobsinpostcode&category=" + category + "&postcode=" + postcode;
	var select = $(id);

	select.empty();
	$.getJSON(theSource, function(data) {
		$.each(data, function(key, val) {
			select.append("<div class='slItem' >" +
					"<h3><a href='http://atonce.com:8080/supplierdashboard' >" + val.category + " job in " + val.suburb + "</a></h3>" +
					"<p class='subTxt' >" + val.details + "</p>" +
					"<p class='time' >" + val.time + "</p>" +
					"</div>");
		});
	});
}

//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=availablecapabilities&category=Carpet%20Stores&postcode=6102
//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=availablecapabilities&category=Abrasive Blasting&postcode=6101&grouptype=franchise&groupid=23401
function getAvailableCapabilitiesSelect(id, category, postcode, pc1, pc2, pc3, pc4) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=capabilities&category=" + category + "&id=atonce_capabilities";
	var select = $(id);

	select.empty();
	$.getJSON(theSource, function(data) {
		$.each(data, function(key, val) {
			select.append("<div class='listItem'><input type='radio' name='r-scat' id='r-scat-" + key + "' value='" + val.value + "' category='" + val.id + "' postcode='" + postcode + "' pc1='" + pc1 + "' pc2='" + pc2 + "' pc3='" + pc3 + "' pc4='" + pc4 + "' /><label for='r-scat-" + key + "'>" + val.label + "</label></div>");
		});
	});
}

//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&term=auto&postcode=6101&grouptype=franchise&groupid=23401&widgetid=12
function getFranchiseCategoriesClosed(id, postcode, franchiseId, widgetId) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&postcode=" + postcode + "&grouptype=franchise&groupid=" + franchiseId + "&widgetid=" + widgetId;

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	});
}

//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&term=auto&postcode=6101&widgetid=12
function getLimitedCategoriesClosed(id, postcode, widgetId) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&postcode=" + postcode + "&widgetid=" + widgetId;

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	});
}

//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&term=auto&postcode=6101&grouptype=franchise&groupid=23401
function getFranchiseCategories(id, postcode, franchiseId) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&postcode=" + postcode + "&grouptype=franchise&groupid=" + franchiseId;

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	});
}

//http://localhost:8080/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&term=auto&postcode=6101
function getLimitedCategories(id, postcode) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getgroupservicewithinpostcode&postcode=" + postcode;

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	});
}

function getOrganisationCategories(id) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getorganisationcategories";

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getOrganisationTypes(id) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getorganisationtypes";

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
/*	$.ajax({
        type: "GET",
	    url: "/html/portlet/ext/organizationtype.xml",
    	dataType: "xml",
    	success: function(xml) {
    		var select = $(id);
    		select.children().remove().end().append("<option value=''>--Please make a selection--</option>");
       		$(xml).find('menuitem').each(function(){
            	var value = $(this).find('value').text();  
             	var title = $(this).find('label').text();                
            	select.append("<option value='"+value+"'>"+title+"</option>");
        	});         
    	},
		error: function() {
			alert("Failed to get Organisation Types list");
		}
	});*/
}

function getServices(id) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getservices";

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,

		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}


function getCommunities(id) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=getcommunities";

	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getSuburbs(thePostcode, ctrlId, updatePostcode) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=postcode&id=atonce_codes";
	if (thePostcode.length == 4) {
		theSource += "&pc=" + thePostcode;
	}
	$(ctrlId).autocomplete({
		source: theSource,
		minChars: 0,
		mustMatch: true,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id;
				if (updatePostcode) {
					if ((IsNumeric(arr[0])) && (IsNumeric(arr[1])) && (IsNumeric(arr[2])) && (IsNumeric(arr[3]))) {
						$("input[id*='tbPostcode4']").val(arr[3]);
						$("input[id*='tbPostcode3']").val(arr[2]);
						$("input[id*='tbPostcode2']").val(arr[1]);
						$("input[id*='tbPostcode1']").val(arr[0]);
					}
				}
			}
			catch(err) {
				$(ctrlId).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getAOSCategoriesList(id, userId) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=aoscategories&id=" + userId;
	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getCategoriesList(id, capId, isSelect) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=categories&id=atonce_capabilities";
	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(capId).val('');
			}
		//}, search: function(event, ui) { 
		//	YUI().use('node', function(Y) {
		//		Y.get('body').setStyle('cursor', 'wait');
		//	}); 
		//},  open: function(event, ui) { 
		//	YUI().use('node', function(Y) {
		//		Y.get('body').setStyle('cursor', 'default');
		//	}); 
		},
		select: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
				if (isSelect) {
					getCapabilitiesListSelect(capId, arr);
				}
				else {
					if (capId != null) {
						$(capId).val('');
						getCapabilitiesList(capId, arr);
					}
				}
			}
			catch(err) {
				$(id).val('');
				$(id).focus();
				alert("Invalid Service selection!");
			}
		}
	}).focus(function(){
		/* if (this.value == "") $(this).trigger('keydown.autocomplete'); */
	});
}

function getCapabilitiesList(id, category) {
	var a = location.pathname.split("/");
	category = category.replace("&", "%26");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=capabilities&category=" + category + "&id=atonce_capabilities";
	$(id).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var arr = ui.item.id; //test for invalid string
			}
			catch(err) {
				$(id).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getCategoriesListSelect(id) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=categories&id=atonce_capabilities";
	var select = $(id);

	select.empty();
	$.getJSON(theSource, function(data) {
		$.each(data, function(key, val) {
			select.append("<option value='" + val.label + "'>" + val.value + "</option>");
		});
	});
}

function getCapabilitiesListSelect(id, category) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=capabilities&category=" + category + "&id=atonce_capabilities";
	var select = $(id);

	select.empty();
	$.getJSON(theSource, function(data) {
		$.each(data, function(key, val) {
			select.append("<option value='" + val.label + "'>" + val.value + "</option>");
		});
	});
}

function getLRC(idLoc, idReg, idCou) {
	getLRCStep1(idLoc, idReg, idCou);
}

function getLRCStep1(idLoc, idReg, idCou) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&step=l&id=atonce_codes";
	$(idLoc).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var loc = ui.item.value; //test for invalid string
				getLRCStep2(loc, idReg, idCou);
			}
			catch(err) {
				$(idLoc).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getLRCStep2(loc, idReg, idCou) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&step=r&id=atonce_codes&state=" + loc;
	$(idReg).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var reg = ui.item.value; //test for invalid string
				getLRCStep3(loc, reg, idCou);
			}
			catch(err) {
				$(idReg).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getLRCStep3(loc, reg, idCou) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&step=c&id=atonce_codes&state=" + loc+ "&region=" + reg;
	$(idCou).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var cou = ui.item.value; //test for invalid string
			}
			catch(err) {
				$(idCou).val('');
			}
		}
	});
}

function getLRCAll(idLoc, idReg, idCou) {
	getLRCAllStep1(idLoc, idReg, idCou);
}

function getLRCAllStep1(idLoc, idReg, idCou) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&all=all&step=l&id=atonce_codes";
	$(idLoc).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var loc = ui.item.value; //test for invalid string
				getLRCAllStep2(loc, idReg, idCou);
			}
			catch(err) {
				$(idLoc).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
	getLRCAllStep2("", idReg, idCou);
}

function getLRCAllStep2(loc, idReg, idCou) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&all=all&step=r&id=atonce_codes&state=" + loc;
	$(idReg).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var reg = ui.item.value; //test for invalid string
				getLRCAllStep3(loc, reg, idCou);
			}
			catch(err) {
				$(idReg).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
	getLRCAllStep3(loc, "", idCou);
}



function getLRCAllStep3(loc, reg, idCou) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&all=all&step=c&id=atonce_codes&state=" + loc+ "&region=" + reg;
	$(idCou).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var cou = ui.item.value; //test for invalid string
			}
			catch(err) {
				$(idCou).val('');
			}
		}
	});
}

function getLocation(idLoc) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&step=l&id=atonce_codes";
	$(idLoc).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var loc = ui.item.value; //test for invalid string
			}
			catch(err) {
				$(idLoc).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getRegion(idReg) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&step=r&id=atonce_codes";
	$(idReg).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 0,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var reg = ui.item.value; //test for invalid string
			}
			catch(err) {
				$(idReg).val('');
			}
		}
	}).focus(function(){
		if (this.value == "")
			$(this).trigger('keydown.autocomplete');
	});
}

function getCouncil(idCou) {
	var a = location.pathname.split("/");
	var theSource = a[0] + "/dashMember-portlet/widgetfeeder/do?type=lrc&step=c&id=atonce_codes";
	$(idCou).autocomplete({
		source: theSource,
		mustMatch: true,
		minLength: 2,
		change: function(event, ui) { //ui.item -> id, label, value
			try {
				var cou = ui.item.value; //test for invalid string
			}
			catch(err) {
				$(idCou).val('');
			}
		}
	});
}

// ====================== Businessware Technologies =========================
(function(global) {
  var atOnce = {
    VERSION: '0.0.1',
    Description: 'atOnce client side library. Copyright Businessware Technologies',
    feedEntry: function(id,url,feedName,description,loadingMessage,data){
	if(id) {this.id=id} else {throw "id is required for feedEntry";}
	if(url) {this.url=url} else {throw "url is required for feedEntry";}
	if ("undefined" != typeof feedName) this.feedName=feedName;
	if ("undefined" != typeof description) this.description=description;
	if ("undefined" != typeof loadingMessage) {this.loadingMessage=loadingMessage;} else{this.loadingMessage="loading Please wait....";}
	if ("undefined" != typeof data) this.data=data;	
	},
	sleep: function (milliseconds) {
		var start = new Date().getTime();
		while ((new Date().getTime() - start) < milliseconds){
			// Do nothing
		}
	},
	fileTypeAllowed: function ( fileName, fileTypes ) {
		if (!fileName) return;

		dots = fileName.split(".")
		//get the part AFTER the LAST period.
		fileType = "." + dots[dots.length-1];

		return (fileTypes.join(".").indexOf(fileType) != -1);	// ?
		//alert('That file is OK!') :
		//alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
	}
};

atOnce.feeds = {
	configuration: [
	{id:"categories",
	 url:"/dashMember-portlet/widgetfeeder/do?type=categories&id=atonce_capabilities",
	 feedName:"Business Categories",
	 description: "Business Categories",
	 loadingMessage: "Please wait while the Business Categories are being loaded...",
	 data:null
	},
	{id:"communities",
	 url:"/dashMember-portlet/widgetfeeder/do?type=getorganisationcategories",
	 feedName: "Community Categories",
 	 description: "Community Categories",
	 loadingMessage: "Please wait while the Community Categories are being loaded...",
	 data:null
	},
	{id:"jobscategories",
	 url:"/dashMember-portlet/widgetfeeder/do?type=postedjobscategories",
	 feedName: "Posted Jobs Categories",
 	 description: "Posted Jobs Categories",
	 loadingMessage: "List of jobs categories against which jobs have been posted...",
	 data:null
	},
	{id: "postcodes",
	 url: "/dashMember-portlet/widgetfeeder/do?type=postcode&id=atonce_codes",
	 feedName: "Suburbs",
	 description: "Suburbs",
	 loadingMessage: "Please wait while the Postcode and Suburbs information is being loaded...",
	 data:null
	}],

	getFeed: function (id,parameters,callback,refresh) {		
		var callbackId = id;		
		for (i=0; i< atOnce.feeds.configuration.length; i++) {
			if (id.toLowerCase() == atOnce.feeds.configuration[i].id) {
				if (undefined == atOnce.feeds.configuration[i].data || null == typeof atOnce.feeds.configuration[i].data || "" == atOnce.feeds.configuration[i].data || refresh) {
					YUI().use('io', function (Y) {
						var request = Y.io(atOnce.feeds.configuration[i].url, {
						    method: 'GET',
						    data: parameters ? encodeURI(parameters) : '',
						    sync: true,
						    on: {
							success: function (id, result) {
								atOnce.feeds.configuration[i].data = JSON.parse(result.responseText);
								if ("function" == typeof callback) { callback(JSON.parse(result.responseText),callbackId); }
							},
							failure: function (id, result) {
								alert('failed to retrieve feed');
							}
						    }
						});
					});
				}
				else {
					if ("function" == typeof callback) { callback(atOnce.feeds.configuration[i].data,id); }				
				}
			}
		}
	},
	getById: function (id) {
		for (var i=0; i < atOnce.feeds.configuration.length; i++) {
			if (id.toLowerCase()==atOnce.feeds.configuration[i].id) return atOnce.feeds.configuration[i];		
		}	
	},
	addFeed: function(feedEntry){
		atOnce.feeds.configuration.push(feedEntry);		//TODO - add check for existing entry - duplicate key.
	}
}

atOnce.AC=[];
atOnce.widget={};
atOnce.widget.generatorTemplate = "<div style='width: [$container_width$];'> <script type='text/javascript' src='http://uwa.netvibes.com/js/c/UWA/UWA_Embedded.js'></script> 	<div id='atonce_com_Widget_Container'></div> <script type='text/javascript'> function _XXXTemp() { if (typeof UWA == 'undefined') { setTimeout('_XXXTemp()', 750); } else {var MyWidget = new UWA.Embedded('http://atonce.com/w/widget.html', {'displayHeader':false, 'displayFooter':false, container: 'atonce_com_Widget_Container', data : { color1: '[$color1$]', color2: '[$color2$]', widgetID: [$widgetID$], theParams: [$theParams$] }} ); } } 	_XXXTemp(); </script> </div> ";


 if (typeof global.atOnce == "undefined") {
    global.atOnce = atOnce;
  }


})(typeof window === 'undefined' ? this : window);


function forceAutoCompleteSelection(item) {
	$(item).live("blur", function(event) {
	     var autocomplete = $(this).data("autocomplete");
	     var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
	     var myInput = $(this);
	     autocomplete.widget().children(".ui-menu-item").each(function() {
		 var item = $(this).data("item.autocomplete");
		 if (matcher.test(item.label || item.value || item)) {
			 autocomplete.selectedItem = item;
		     return;
		 }
	     });
	     if (autocomplete.selectedItem) {
		 autocomplete._trigger("select", event, {item: autocomplete.selectedItem});
	     } else {
		 // $(this).validationEngine('showPrompt', 'Please type 3 characters and select an item from suggestion list.', 'load');
		 $(this).val('');
	     } 
	});
}

function autoCompletePrompt(field, rules, i, options){
      if (field.val() == "") {
         // this allows the use of i18 for the error msgs
         return "* Please type 3 characters and select an item from suggestion list.";
      }
    }


