REGION_COOKIE_LABEL = 'region_id';

MKT_date_fmt = "%d-%m-%Y";
DISPLAY_DATE_FORMAT = 'dd-mm-yyyy';
DEFAULT_COUNTRY = 70;
DEFAULT_REGION = 1;
SEARCH_COOKIE_PREFIX = 'mktsearch';

CURRENCY_SYMBOL_ENTITY = '&euro;';
CURRENCY_SYMBOL = '€';
DATE_FORMAT = 'd-m-Y';
TIME_FORMAT = 'g:i A';
var IE_COUNTRY_CODE = '353';

window.selectValues = new Array();

//window.onerror = function(msg, err_url, line) {

function logError(msg, err_url, line) {
	// create the post data string
	var POSTData = 'msg=' + URLEncode(msg) +
				   '&err_url=' + URLEncode(err_url) +
				   '&line=' + URLEncode(line) +
				   '&browser=' + URLEncode(navigator.userAgent);

	new XHR({
		}).send('index.php?option=com_mykidstime&task=error.posterror', POSTData);
};

function FormatCurrency(amt, html, excludeSymbol) //html=true)
{
	//setlocale(LC_MONETARY, 'en_IE');
	amt = Number(amt) ? Number(amt) : 0.00;
	if (excludeSymbol)
		return amt.toFixed(2);

	return (html ? CURRENCY_SYMBOL_ENTITY : CURRENCY_SYMBOL) + amt.toFixed(2); //money_format('%!.2i', amt);
}

function FormatDate(date)
{
	if (date && date > 0) return date(DATE_FORMAT, strtotime(date));
	return '';
}

function FormatTime(time)
{
	dummydate = '01/01/0001 ';
	if (time) return date(TIME_FORMAT, strtotime(dummydate + time));
	return '';
}


function URLEncode (clearString) {
	  var output = '';
	  var x = 0;
	  clearString = clearString.toString();
	  var regex = /(^[a-zA-Z0-9_.]*)/;
	  while (x < clearString.length) {
	    var match = regex.exec(clearString.substr(x));
	    if (match != null && match.length > 1 && match[1] != '') {
	    	output += match[1];
	      x += match[1].length;
	    } else {
	      if (clearString[x] == ' ')
	        output += '+';
	      else {
	        var charCode = clearString.charCodeAt(x);
	        var hexVal = charCode.toString(16);
	        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
	      }
	      x++;
	    }
	  }
	  return output;
	}

function URLDecode (encodedString) {
	  var output = encodedString;
	  var binVal, thisString;
	  var myregexp = /(%[^%]{2})/;
	  while ((match = myregexp.exec(output)) != null
	             && match.length > 1
	             && match[1] != '') {
	    binVal = parseInt(match[1].substr(1),16);
	    thisString = String.fromCharCode(binVal);
	    output = output.replace(match[1], thisString);
	  }
	  return output;
	}

function normalisePhoneNumber( num, international )
{
	num = num.replace(/\D/g, '');

	if (international) {
		switch(num[0]) {
			case '+':
				num = num.substr(1);
				break;
			case '0':
				num = IE_COUNTRY_CODE + num.substr(1);
		}
	}
	else {
		if (num.substr(0, IE_COUNTRY_CODE.length) == IE_COUNTRY_CODE) {
			num = '0' + num.substr(IE_COUNTRY_CODE.length);
		}
	}

	return num;
}

function isIrishMobileNumber(num) {
	return (/^08\d{8}$/.exec(num) != null);
}

function isNumberKey(evt)
{
	var ordPoint = 46;

	evt = new Event(evt);
	var charCode = evt.code; //(evt.which) ? evt.which : event.keyCode;
	var ctrlKey = evt.control; //(evt.which) ? evt.ctrlKey : event.ctrlKey;
	if (!ctrlKey && (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != ordPoint))
		return false;

   return true;
}

function isDateKey(evt)
{
	var ordHyphen = 45;
	var ordColon = 58;

    // Validates key is either digit or a dash
	evt = new Event(evt);
	var charCode = evt.code; //(evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != ordHyphen && charCode != ordColon)
        return false;

    return true;
}

function isPhoneNumberKey(evt)
{
	evt = new Event(evt);
	var charCode = evt.code; //(evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 40 && charCode != 41 && charCode != 43 && charCode != 45)  // 43 = '+'
      return false;

    return true;
}

function disallowPastDate(date) {
	// date is a JS Date object
	now = new Date();
	now.setDate(now.getDate() - 1);
	return ( date < now );
};

function disallowFutureDate(date) {
	// date is a JS Date object
	now = new Date();
	return ( date > now );
};

function getNodeTextByName(node, nodeName)
{

//	var hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;

	children = node.getElementsByTagName(nodeName);

	if (children.length) {
//		if (!hasInnerText)
		if (children[0].textContent != undefined) {
			return children[0].textContent;
		}
		else if (children[0].innerContent != undefined) {
			return children[0].innerText;
		}
		else {
			return children[0].text;
		}
	}

	return '';
}

function getAttrByName(node, attrName)
{
	return node.attributes.getNamedItem(attrName).value;
}

function addCell(row, value) //, colSpan, rowSpan)
{
	var cell = row.insertCell(row.cells.length);
//	if (colSpan > 1) cell.colSpan = colSpan;
//	if (rowSpan > 1) cell.rowSpan = rowSpan;
	cell.innerHTML = value;

	return cell;
}

// Deprecated
function UpdateLocations(regfld, locfld, locations) {

	var reg_id = Number(regfld.value);
	locSelVal = locfld.options[locfld.selectedIndex].value;

	locfld.options.length = 1;
	if (!reg_id) return true;

	var count = 0;
	for ( var i = 0; i < locations.length; i++ ) {
		if (locations[i][2] == reg_id) {
			count++;
			addOption(locfld, locations[i][1], locations[i][0]);
			if (locSelVal == locations[i][0])
				locfld.selectedIndex = count;
		}
	}
	return true;
}

function UpdateRegions(regfld) {
	regSelVal = regfld.options[regfld.selectedIndex].value;

	regfld.options.length = 1;

	var count = 0;
	var regs = window.regions;
	for ( var i = 0; i < regs.length; i++ ) {
		addOption(regfld, regs[i].name, regs[i].id);
		if (regSelVal == regs[i].id)
			regfld.selectedIndex = count;
	}
	return true;
}

function UpdateRegionLocations(regfld, locfld) {
	var reg_id = Number(regfld.value);

	locSelVal = locfld.options[locfld.selectedIndex].value;

	locfld.options.length = 1;
	if (!reg_id) return true;

	var count = 0;
	var locs = window.locations;
	for ( var i = 0; i < locs.length; i++ ) {
		if (locs[i].region_id == reg_id) {
			count++;
			addOption(locfld, locs[i].name, locs[i].id);
			if (locSelVal == locs[i].id)
				locfld.selectedIndex = count;
		}
	}
	return true;
}

function UpdateCategories(typefld, catfld, categories) {

	var listing_type = typefld.value;

	catfld = clearOptions(catfld, true);

	if (!listing_type.length) return true;

	for ( var i = 0; i < categories.length; i++ ) {
		if (categories[i][0] == listing_type) {
//			(type, id, title, parent_id, parent_title) = categories[i];
//			alert(title);
			text = (categories[i][3] ? categories[i][4] + ' -> ' : '') + categories[i][2];
			addOption(catfld, text, categories[i][1]);
		}
	}
	return true;
}

function UpdateVenues(regfld, venfld) {
	venfld.options.length = 1;
	rid = regfld.value;

	for (i = 0; i < window.venues.length; i++) {
		var ven = window.venues[i];
		if (ven.region_id == rid) {
			addOption(venfld, ven.name, ven.id);
		}
	}
}

function VenueSelected() {
	var vid = $('venue_id').value;
	var venue = null;

	for (var i = 0; i < window.venues.length; i++) {
		if (window.venues[i].id == vid) {
			venue = window.venues[i];
			break;
		}
	}

	addressFld = $('address');
	locationFld = $('location_id');
	mapFld = $('map_location');
	if (vid > 0) {
		addressFld.readOnly = true;
		locationFld.readOnly = true;
		mapFld.readOnly = true;

		locationFld.selectedIndex = 0;
		for (i = 0; i < locationFld.options.length; i++) {
			if (locationFld.options[i].value == venue.location_id) {
				locationFld.selectedIndex = i;
				break;
			}
		}
		addressFld.value = venue.address;
		mapFld.value = venue.map_location;

		window.selectValues['location_id'] = locationFld.value;
	}
	else {
		addressFld.readOnly = false;
		locationFld.readOnly = false;
		mapFld.readOnly = false;
	}
}

function selectReadOnly(evt) {

	evt = new Event(evt);

	select = $(evt.target);
	if (select.readOnly) {
		select.value = window.selectValues[select.id];
	}
}

function clearOptions(select, keepFirst)
{
	// Workaround for issue with Mootools 1.11 over-riding remove() function
	elParent = select.parentNode;
	elWidth = select.style.width;
	elId = select.id;
	elName = select.name;
	elClassName = select.className;
	optVal = select.options[0].value;
	optText = select.options[0].text;
//	selVal = select.options[select.selectedIndex].value;

	select.parentNode.removeChild(select);
	select = $(document.createElement("SELECT"));
	select.id = elId;
	select.name = elName;
	select.className = elClassName;
	select.style.width = elWidth;

	if (elParent.childNodes.length)
		elParent.insertBefore(select, elParent.firstChild);
	else
		elParent.appendChild(select);

	if (keepFirst)
		addOption(select, optText, optVal);

	return select;
}

function addOption( selectbox, text, value )
{
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

function varDump(obj)
{
	var debug = '';
	for (var prop in obj) {
		if (typeof(prop) != 'function')
			debug += '(' + typeof(prop) + ') ' + prop + ': ' + obj[prop] + '\r\n';
	}
	alert(debug);
}

function lpad(ContentToSize,PadLength,PadChar)
{
   var PaddedString=ContentToSize.toString();
   for(i=ContentToSize.length+1;i<=PadLength;i++)
   {
       PaddedString=PadChar+PaddedString;
   }
   return PaddedString;
}

// Expects date values in the form dd-mm-yy or dd-mm-yyyy
//
function validDate(value)
{
	mydate = MKTtoDate(value);

	if (!mydate) return false;

	regex = /^([0-9]{1,2})-([0-9]{1,2})-([0-9]{2,4})$/;
	arr = regex.exec(value);
	arr[1] = Number(arr[1]);
	arr[2] = Number(arr[2]) - 1; // reduce by one since JavaScript indexes months from 0!
	arr[3] = Number(arr[3]);

	return (mydate.getDate() == arr[1] && mydate.getMonth() == arr[2] && mydate.getFullYear() == arr[3]);
}

//Expects date values in the form dd-mm-yy or dd-mm-yyyy
//
function MKTtoDate(value)
{
	regex = /^([0-9]{1,2})-([0-9]{1,2})-([0-9]{2,4})$/;
	arr = regex.exec(value);

	if (!arr || arr.length != 4) return false;

	// Handle two digit year
	now = new Date(); // initialise to now
	if (arr[3].length == 3) return false;
	if (arr[3].length == 2) {
		if (arr[3] > (now.getFullYear() % 100 + 10)) {
			arr[3] = Math.floor(now.getFullYear()/100) - 1 + arr[3];
		}
		else {
			arr[3] = Math.floor(now.getFullYear()/100) + arr[3];
		}
	}

	mydate = new Date(arr[2] + '/' + arr[1] + '/' + arr[3] + ' 00:00:00'); // initialise to now

	return mydate;
}

function MySQLtoDate(value)
{
	regex = /^([0-9]{4})-([0-9]{2})-([0-9]{2})/;
	arr = regex.exec(value);

	if (!arr || arr.length != 4) return false;

	mydate = new Date(Number(arr[1]), Number(arr[2]) - 1, Number(arr[3]));

	return mydate;
}

//Expects time values in the form hh24:mi[:ss]
//
function validTime(value)
{
	regex = /^([0-9]{1,2}):([0-9]{2})(:([0-9]{2}))?$/;
	arr = regex.exec(value);

	if (!arr || arr.length < 2) return false;

	hours = arr[1];
	minutes = arr[2];
	seconds = arr[4];

	return (Number(hours) < 24 && Number(minutes) < 60 && (seconds == null || Number(seconds) < 60));
}

function AgesLabel(agefrom, ageto)
{
    var agegroup;

	if (!agefrom.length) {
		if (!ageto.length) {
	    	agegroup = 'All';
		}
		else {
	    	agegroup = 'up to ' + ageto;
		}
	}
	else {
		agegroup = agefrom + (!ageto.length ? '+' : ' to ' + ageto);
	}

    return agegroup;
}

function UpdateSelectOptions(select, optionsvalues) {
	$(select).empty();

  	optionsvalues.each(function(optionvalue) {
    	var text = new Element('option').setHTML(optionvalue.text);
    	text.value = optionvalue.value;
    	text.inject(select);
  	});
}

function getSelectedOptions(select)
{
	selected = new Array();
	for (var i = 0; i < select.options.length; i++)
		if (select.options[i].selected)
			selected.push(select.options[i]);

	return selected;
}

//moveOptionsUp
//
// move the selected options up one location in the select list
//
function moveOptionsUp(selectId) {
	var selectList = document.getElementById(selectId);
	var selectOptions = selectList.getElementsByTagName('option');
	for (var i = 1; i < selectOptions.length; i++) {
		var opt = selectOptions[i];
		if (opt.selected) {
		   selectList.removeChild(opt);
		   selectList.insertBefore(opt, selectOptions[i - 1]);
        }
    }
}

//moveOptionsDown
//
// move the selected options down one location in the select list
//
function moveOptionsDown(selectId) {
	var selectList = document.getElementById(selectId);
	var selectOptions = selectList.getElementsByTagName('option');
	for (var i = selectOptions.length - 2; i >= 0; i--) {
		var opt = selectOptions[i];
		if (opt.selected) {
			var nextOpt = selectOptions[i + 1];
			opt = selectList.removeChild(opt);
			nextOpt = selectList.replaceChild(opt, nextOpt);
			selectList.insertBefore(nextOpt, opt);
     	}
    }
}
function getElementValue(el)
{
	val = null;
	if (el.nodeName == 'INPUT') {
		switch (el.type) {
		case 'checkbox':
			val = el.checked;
			break;
		case 'radio':
			val = getRadioValue(el.form, el.name);
			break;
		default:
			val = el.value;
		}
	}
	if (el.nodeName == 'SELECT') {
		val = el.options[el.selectedIndex].value;
	}
	return val;
}

function setElementValue(el, value)
{
	if (el.nodeName == 'INPUT') {
		switch (el.type) {
		case 'checkbox':
			el.checked = (value == 'true');
			break;
		case 'radio':
			setRadioValue(el.form, el.name, value);
			break;
		default:
			if (value) el.value = value; // Don't assign 'false' to text and hidden fields!
		}
	}
	if (el.nodeName == 'SELECT') {
		$A(el.options).each(function(opt){if (opt.value == value) el.selectedIndex = opt.index;});
	}
	return null;
}

function getRadioValue(form, group)
{
	var choice = null;
	$A(form.elements).each(function(el){
		if (el.type == 'radio' && el.name == group && el.checked) {
			choice = el.value;
		}
	});
	return choice;
}

function setRadioValue(form, group, value)
{
	$A(form.elements).each(function(el){
		if (el.type == 'radio' && el.name == group && el.value == value)
			el.checked = true;
	});
}

function switchRegion(regid, url)
{
	var host = window.location.hostname;
	var domain = host.substr(host.indexOf('mykidstime'));
	domain = domain.length ? domain : host;

//	Cookie.set(REGION_COOKIE_LABEL, regid, {duration: 365 * 5, domain: '.' + domain});
	resetSearchCookies();
	url += '?set_region_id=' + regid;
	window.location = url;
	return false;
}

function resetSearchCookies()
{
	var pairs = document.cookie.split(";");
	var cookies = {};
	for (var i=0; i<pairs.length; i++){
	    var pair = pairs[i].trim().split("=");
	    if (pair[0].substr(0, SEARCH_COOKIE_PREFIX.length) == SEARCH_COOKIE_PREFIX) {
	    	Cookie.remove(pair[0]);
	    }
	    cookies[pair[0]] = unescape(pair[1]);
	}

	return cookies;
}

function parseQueryString()
{
	var query = String(window.location).substr(String(window.location).indexOf('?') + 1).split('&');
	obj = new Object();
	for (i in query) {
		param = String(query[i]).split('=');
		obj[param[0]] = param[1];
	}
	return obj;
}

function calendarSetup(el, params, readonly) { //dateStatusFunc, onUpdateFunc) {
	var btn = new Element('img');
	btn.id = 'btn_' + el.id;
	btn.alt = 'Calendar Icon';
	btn.src = '/templates/system/images/calendar.png';
	btn.addClass('calendar');

	$(el.parentNode).appendChild(btn);

    baseParams =
    	{
            inputField  : el.id,    // ID of the input field
            ifFormat    : MKT_date_fmt,   	// the date format
            button      : btn.id, // ID of the button
            weekNumbers : false
        };
    $extend(baseParams, params);

   	Calendar.setup(baseParams);

	el.readOnly = readonly;
	if (readonly) {
		$(el).addEvent('keydown', function (evt) {
				evt = new Event(evt);
				if (evt.key == 'delete' || evt.key == 'backspace') {
					el.value = '';
					evt.stop();
				}
			});
	}
	else {
		document.formvalidator.setHandler('dateverify', function (value) { return validDate(value); });
		document.formvalidator.setHandler('pastdateverify', function (value) { return (validDate(value) && !disallowFutureDate(MKTtoDate(value))); });
		document.formvalidator.setHandler('futuredateverify', function (value) { return (validDate(value) && !disallowPastDate(MKTtoDate(value))); });
	}
}

function initGeneralTable(table, callback) {
	if (table == null) return;

	resequenceRows(table, 0);
	$A($(table).tBodies[0].rows).each(function(row){initGeneralTableRow(row, callback)});
}

function initGeneralTableRow(row, callback) {
	$(row).addEvent('mouseover', function(){this.addClass('rowhovered');});
	$(row).addEvent('mouseout', function(){this.removeClass('rowhovered');});

	$(row).getElements('td').each(function(cell) {
		if (!cell.hasClass('noselect') && callback) {
		 	cell.onclick = function(){callback(cell.parentNode);};
		}
	});
}

function resequenceRows(table, idx) {
	if (table == null) return;

	$(table).getElements('tr').each(function(row) {
		if (row.rowIndex >= idx) {
			$(row).addClass('row' + row.rowIndex % 2);
			$(row).removeClass('row' + (1 - (row.rowIndex % 2)));
		}
	});
}


String.prototype.ucfirst = function () {
	return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
};

String.prototype.ucwords = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];

  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
