function Go (w) {
	if (!w) {
		w = location.href;
		
	}
		
	window.location.href = w;
	
}


function submitForm(f) {
	$(f).submit();
}

function GoPop (win) {
	if (!win) {
		win = location.href;
		
	}
	var pc = 90;
	var h = ((screen.height / 100 ) * pc)
	var w = ((screen.width / 100 ) * pc);
	window.open(win,"OpenWindow","height="+h+",width="+w+",resizable=1,scrollbars=1");
	OpenWindow.moveTo(w/2,h/2);
}

function doExternalLinks () {
	var links = $$('a');
	
	for (x = 0; x < links.length; x++) {
		var link = $(links[x]);
		
		if (link.href.indexOf(document.domain) == -1 && (link.href.indexOf('http://') != -1 || link.href.indexOf('https://') != -1)) {
			link.writeAttribute('target','_blank');
			
		}
		
	}
	
}

function clearNonNumber (e) {	
	$(e).value = $(e).getValue().replace(/([^\d]+)/gi,'');
	
}

function showMessageBox (s) {
	var str = s;
	var box = new Object();
	box.width = 500;
	
	if (arguments[1]) {
		box.height = arguments[1].height;	
		box.width = arguments[1].width;			
		
	}
	
	var s = document.viewport.getDimensions();
	var o = document.viewport.getScrollOffsets();
	
	var l = ((s.width+o.left)/2)-(box.width/2);
	var t = o.top+200;
	
	$('windowboxbg').removeClassName('none').setStyle({
		height: (s.height+o.top)+'px',
		zIndex: 5000
		
	});
	
	$('windowbox').removeClassName('none').setStyle({
		left: l+'px',
		top: t+'px',
		zIndex: 5001
	
	});
	
	$('windowboxinner').update(str).setStyle({
		left: l+'px',
		top: t+'px',
		width: box.width+'px',
		zIndex: 5002
		
	});
	
	new Draggable('windowbox');
	
	//toggleScrollbars(false);
	
}

function updateMessageBox (s) {
	$('windowboxinner').update(s);
	
}

function closeMessageBox () {
	$('windowboxbg').addClassName('none');	
	$('windowbox').addClassName('none');
	$('windowboxinner').update('');
	
	//toggleScrollbars(true);
		
}

function resizeMessageBox (w) {	
	var s = document.viewport.getDimensions();
	var o = document.viewport.getScrollOffsets();
	
	var l = ((s.width+o.left)/2)-(w/2);
	
	$('windowbox').setStyle({
		left: l+'px'
		
	});
	
	$('windowboxinner').setStyle({
		width: w+'px'
	
	});
	
	var box = $('windowboxinner').getHeight() + o.top;
	var bg = $('windowboxbg').getHeight();
	
	if (box > bg) {
		$('windowbox').setStyle({
			top: '200px'
			
		});
		
		$('windowboxbg').setStyle({
			height: box+'px'
			
		});
		
		new Effect.ScrollTo('windowbox');
		
	}
	
}

function doConfirm (w, m) {
	var what = w.split('=');
	var opt;
	var str;
	
	switch (what[0]) {
		case 'loc':
		opt = '<a href="javascript:;" onclick="hideMessageBox()">Cancel</a> &mdash; or &mdash; <a href="'+what[1]+'">Continue</a>';
		
		break;
		
		case 'js':
		opt = '<a href="javascript:;" onclick="hideMessageBox()">Cancel</a> &mdash; or &mdash; <a href="javascript:;" onclick="'+what[1]+'">Continue</a>';
		
		break;
		
	}
	
	str = '<p>'+m+'</p><p class="centre">'+opt+'</p>';
	
	showMessageBox(s);
	
}

function showAlert (t, c, e) {
	if (e === true) {
		return '<div class="highlight'+c+'">'+t+'</div>';
		
	} else {
		$(e).update(t).className = 'highlight'+c;
	
	}
	
}

function hideAlert (el) {
	$(el).update('').className = 'none';
	
}

function makeVisible (el) {
	if($(el + '-form').getStyle('display') == 'none')
	{
		$(el + '-form').setStyle({ display: 'block' })
		$(el + '-add').setStyle({ display: 'none' })
	} else {
		$(el + '-form').setStyle({ display: 'none' })
		$(el + '-add').setStyle({ display: 'block' })
	}
}

function populateForm (form, data) {
	var keys = Object.keys(data);
	var vals = Object.values(data);
	var el;
	var cl;
	
	$(form).reset();
	
	for (x = 0; x < keys.length; x++) {
		if ($(form+keys[x])) {
			el = $(form+keys[x]);
			
			if (vals[x].indexOf('disabled__') == 0) {
				el.disable();
				
				vals[x] = vals[x].replace('disabled__','');
				
			} else {
				el.enable();
				
			}
			
			if (el.className == 'form_select') {
				cl = el.descendants();
				
				for (y = 0; y < cl.length; y++) {
					if ($(cl[y]).value == vals[x]) {
						$(cl[y]).selected = true;
						
					}
					
				}
				
			} else {
				el.value = vals[x];
				
			}
			
		}
		
	} 
	
	if (arguments[2]) {
		var ekeys = Object.keys(arguments[2]);
		var evals = Object.values(arguments[2]);
		
		for (x = 0; x < ekeys.length; x++) {
			$(ekeys[x]).value = evals;
			
		}
		
	}
	
}

function showHelp (target) {
	new Ajax.Request('/widgets/showhelp.php',{
		method: 'post',
		parameters: 'indentifier='+target,
		onCreate: function (r) {
			showMessageBox(showAlert('Please wait...','loading',true));
			
		},
		onComplete: function (r) {
			resizeMessageBox(500);
			
			updateMessageBox(r.responseText);
			
		}
		
	});
	
}

function toggleScrollbars (s) {
	var textareas = $$('textarea');
	var selects = $$('select');
	
	for (x = 0; x < textareas.length; x++) {
		if (!s) {
			$(textareas[x]).setStyle({ overflow: 'hidden' });
			
		} else {
			$(textareas[x]).setStyle({ overflow: 'auto' });
			
		}
		
	}
	
	for (x = 0; x < selects.length; x++) {
		if (!s) {
			$(selects[x]).setStyle({ overflow: 'hidden' });
			
		} else {
			$(selects[x]).setStyle({ overflow: 'auto' });
			
		}
		
	}
	
}

//Event.observe(window,'mousemove',function(){ setTimeout(removeMessage, 2000); }); 

function removeMessage(){ 
	
	$('messagesHead').fade('', { duration:30 });
	$('messagesForm').fade('', { duration:30 });
}


function autocompleter (el, type, intWidth)
{
	new Autocomplete(el.id, { 
		serviceUrl:'/widgets/autocompleter.php?type=' + type,
		minChars: 3,
		maxHeight: 400,
		width: intWidth
	});
}

function autocompleterTitle (el, type, intWidth)
{
	new Autocomplete(el.id, { 
		serviceUrl:'/widgets/autocompleter.php?type=' + type,
		minChars: 1,
		maxHeight: 400,
		width: intWidth
	});
}

function ajaxActions (id, container, action, master_id, el)
{
	new Ajax.Request('/widgets/ajaxActions.php',{
		method: 'post',
		parameters: 'id=' + id + '&action=' + action + '&container=' + container + '&master=' + master_id,
		onCreate: function (r) {
			el.src = '/images/icons/hourglass.png';
		},
		onComplete: function (r) {
			//alert(r.responseText);
			refreshList(container, action, master_id);
		}
	});
}

// There may be instances where you require more than one action to be performed for a particular page or section
// Therefore by have master_action has an extra parameter solves the problem of being forced to only using one
// action per template/page/section!
function ajaxActionsV2(id, container, action, master_id, master_action, el)
{
	new Ajax.Request('/widgets/ajaxActions.php',{
		method: 'post',
		parameters: 'id=' + id + '&action=' + action + '&container=' + container + '&master=' + master_id,
		onCreate: function (r) {
			el.src = '/images/icons/hourglass.png';
		},
		onComplete: function (r) {
			refreshList(container, master_action, master_id);
		}
	});	
}

function ajaxActionsV3(id, container, action, master_id, el)
{
	new Ajax.Request('/widgets/ajaxActions.php',{
		method: 'post',
		parameters: 'id=' + id + '&action=' + action + '&container=' + container + '&master=' + master_id,
		onCreate: function (r) {
			el.src = '/images/icons/hourglass.png';
		},
		onComplete: function (r) {
			refreshListInclJavascript(container, action, master_id);
		}
	});	
}

function ajaxActionsV4(id, container, action, master_id, master_action, el)
{
	new Ajax.Request('/widgets/ajaxActions.php',{
		method: 'post',
		parameters: 'id=' + id + '&action=' + action + '&container=' + container + '&master=' + master_id,
		onCreate: function (r) {
			el.src = '/images/icons/hourglass.png';
		},
		onComplete: function (r) {
			refreshListInclJavascript(container, master_action, master_id);
		}
	});	
}

function ajaxConfirmDelete (id, container, action, master_id, el)
{
	var result = confirm('Are you sure you wish to delete?');
	
	if( result == true )
	{
		ajaxActionsV3(id, container, action, master_id, el);
	}	
}

function ajaxTogglePageContent (id, container, action, name, value, el) {
	
	new Ajax.Request('/widgets/ajaxActions.php',{
		method: 'post',
		parameters: 'id=' + id + '&action=' + action + '&container=' + container + '&' + name + '=' + value,
		onCreate: function (r) {
			el.src = '/images/icons/hourglass.png';
		},
		onComplete: function (r) {
			//alert(r.responseText);
			refreshList(container, action, '');
		}
	});	
}

function collapseTable(id, collapse)
{
	if( !collapse )
	{
		$('bulletLink' + id).onclick = function(){ collapseTable(id, true); }
		$('bulletToggle' + id).src = "/images/icons/bullet_delete.png";
		$('subsOfParent' + id).show();

	}
	else
	{
		$('bulletLink' + id).onclick = function(){ collapseTable(id, false); }
		$('bulletToggle' + id).src = "/images/icons/bullet_add.png";
		$('subsOfParent' + id).hide();	
	}
}

function collapseAdminTable(id, collapse)
{
	var param = "";
	if( !collapse )
	{
		$('bulletLink' + id).onclick = function(){ collapseAdminTable(id, true); }
		$('bulletToggle' + id).src = "/images/icons/bullet_delete.png";
		var children = document.getElementsByClassName('subsOfParent' + id);
		for(var i = 0; i < children.length; i++)
		{
			children[i].show();
		}
		param = "show";
		
	}
	else
	{
		$('bulletLink' + id).onclick = function(){ collapseAdminTable(id, false); }
		$('bulletToggle' + id).src = "/images/icons/bullet_add.png";
		var children = document.getElementsByClassName('subsOfParent' + id);
		for(var i = 0; i < children.length; i++)
		{
			children[i].hide();
		}	
		param = "hide";
	}
	
	new Ajax.Request('/widgets/ajaxSessions.php',{
		method: 'post',
		parameters: 'c=' + param + '&id=' + id,
		onComplete: function (r) {
			var d = r.responseText.split('|');
			//alert(r.toSource());
		}
	});
}

function collapseTextarea(id, collapse)
{
	if( !collapse )
	{
		$('bulletLink' + id).onclick = function(){ collapseTextarea(id, true); }
		//$('row' + id).onclick = function(){ collapseTextarea(id, true); }
		$('bulletToggle' + id).src = "/images/icons/bullet_delete.png";
		$('textarea' + id).show();
		$('plainContent' + id).hide();
		$('plainText' + id).hide();
		$('customHeading' + id).show();

	}
	else
	{
		$('bulletLink' + id).onclick = function(){ collapseTextarea(id, false); }
		//$('row' + id).onclick = function(){ collapseTextarea(id, false); }
		$('bulletToggle' + id).src = "/images/icons/bullet_add.png";
		$('plainContent' + id).show();
		$('textarea' + id).hide();	
		$('customHeading' + id).hide();
		$('plainText' + id).show();
	}
	
			
	bkLib.onDomLoaded(function() { 
		nicEditors.allTextAreas();	
	});
}

function refreshList (container, action, idx) {
	new Ajax.Updater(container,'/widgets/ajaxTables.php',{
		method: 'post',
		parameters: 'db=' + action + '&idx=' + idx
	});
}

function refreshListInclJavascript (container, action, idx) {
	new Ajax.Updater(container,'/widgets/ajaxTables.php',{
		method: 'post',
		parameters: 'db=' + action + '&idx=' + idx,
		onComplete: function (r) {
			
			bkLib.onDomLoaded(function() { 
				nicEditors.allTextAreas();	
			});
		},
		evalScripts: true,
		asynchronous: true
	});
}

function submitAjaxForm (f, el, container, getList, master, closeWindow) {
	$(f).request({
		onCreate: function (r) {
			el.src = '/images/icons/hourglass.png';
		},
		onComplete: function (r) {
			var d = r.responseText.split('|');

			if (d[0] > 0) {
				refreshList(container, getList, master);
				if (closeWindow == 1)
				{
					closeMessageBox();
				}
				else
				{
					if (d[2] > 0)
					{
						editItem ( d[3], d[4], container, getList, master );
					}
				}
			} else {
				alert(d[1]);
				el.src = '/images/icons/accept.png';
			}
		}
		
	});
	
}

function updateCheckbox (contact_id, option_id, section){
	new Ajax.Request('/widgets/ajaxSaves.php',{
		method: 'post',
		parameters: 'section=' + section + '&option_id=' + option_id + '&contact_id=' + contact_id,
		onComplete: function (r) {
			var d = r.responseText.split('|');
			
			if (d[0] < 1) {
				alert(d[1]);
			}
		}
	});
}

function ajaxEdit (idx, section, container, getList, master_id){
	new Ajax.Updater(section + idx,'/widgets/ajaxForms.php',{
		method: 'post',
		parameters: 'section=' + section + '&container=' + container + '&getList=' + getList + '&master=' + master_id + '&idx=' + idx
	});
}


// ------------------------------------------------------------------------------------------------------------------------------------
//
//  ADMIN FUNCTIONS
//
// ------------------------------------------------------------------------------------------------------------------------------------
function editItem ( type, idx, container, getList, content_id )
{
	new Ajax.Request('/widgets/ajaxForms.php',{
	method: 'post',
	parameters: 'section=' + type + '&idx=' + idx + '&container=' + container + '&getList=' + getList + '&content_id=' + content_id,
	onComplete: function (r) {
		
			showMessageBox(r.responseText);
		}
	});
}

function removeItem ( type, idx )
{
	var decision = confirm ( 'Are you sure you want to remove this item?' );
	
	if ( decision == true )
	{
		new Ajax.Request('/widgets/ajaxSaves.php',{
		method: 'post',
		parameters: 'section=' + type + '-DELETE&idx=' + idx,
		onComplete: function (r) {
			var d = r.responseText.split('|');
			
				if (d[0] > 0)
				{	
					$(type + idx).hide();
				}
			}
		});
	}
}

function updateCharCounter( field, counterField, maxlimit )
{
	$(counterField).value = maxlimit - $(field).value.length;
}

function textCounter( field, counterField, maxlimit )
{	
	// if text becomes too long...trim it!
	if ( $(field).value.length > maxlimit )
	{
		$(field).value = $(field).value.substring( 0, maxlimit );
	}
	// otherwise, update 'characters left' counter
	else
	{
		updateCharCounter( field, counterField, maxlimit );
	}
}

function stripslashes( str ) 
{
	return ( str + '' ).replace( /\\(.?)/g, function ( s, n1 )
	{
		switch( n1 )
		{
			case '\\':
				return '\\';
		
			case '0':
				return '\0';
		
			case '':
				return '';
		
			default:
				return n1;
		}
	});
}

function replaceOneChar(s,c,n)
{
	var re = new RegExp('^(.{'+ --n +'}).(.*)$','');
	return s.replace(re,'$1'+c+'$2');
}

function friendlyUrl( strTitle )
{
	var urlTitle;
	strTitle = strTitle.strip();
	strTitle = stripslashes( strTitle );
	strTitle = strTitle.toLowerCase();
	strTitle = strTitle.replace(/ \\/g, " ");
	urlTitle = strTitle.replace(/ /g, "-");
	//urlTitle = urlTitle.replace(/[^a-z0-9-]+/g, "");
	urlTitle = urlTitle.replace("&", "and");
	if(strTitle.indexOf("{location}") >= 0)
	{
		// landing page location
		urlTitle = urlTitle.replace("{location}", "{LOCATION}");
		urlTitle = urlTitle.replace(/[^a-z0-9-({LOCATION})]+/g, "");
		for(var i = 0; i < urlTitle.length; i++)
		{
			if(urlTitle.charAt(i) == "{")
			{
				if(urlTitle.charAt(i+1) != "L")
				{
					replaceOneChar(urlTitle, "?", i);
				}
			}
			if(urlTitle.charAt(i) == "}")
			{
				if(urlTitle.charAt(i-1) != "N")
				{
					replaceOneChar(urlTitle, "?", i);
				}
			}
		}
		urlTitle.replace("?","");
	}
	else
	{
		urlTitle = urlTitle.replace(/[^a-z0-9-]+/g, "");
	}
	urlTitle = urlTitle.replace("--", "-");
	return urlTitle;
}

function generateMetaTitle( siteName, strTitle )
{
	var siteTitle  = ( strTitle != '' ) ? " - " + siteName : siteName;
	var metaTitle  = strTitle + siteTitle;
	
	return metaTitle;
}

function tasksForTitle( siteName, strTitle )
{	
	$('url').value        = friendlyUrl( strTitle );
	$('meta_title').value = generateMetaTitle( siteName, strTitle );
}

function imageswap( intID, on, current )
{
	if(on)
	{
		var form = "on";
	}
	else
	{
		var form = "off";
	}
	switch (intID)
	{
			case 1:
				var image = "url(/images/menu-"+form+"_01.gif)";
			break;
			case 2:
				var image = "url(/images/menu-"+form+"_02.gif)";
			break;
			default:
				var image = "url(/images/menu-"+form+"_03.gif)";
			break;
	}
	//alert($('menu'+intID));
	$('menu'+intID).setStyle({backgroundImage:""});
	$('menu'+intID).setStyle({backgroundImage:image});
	if(current > 0)
	{
		var image = image.replace("off", "on");
		$('menu'+current).setStyle({backgroundImage:image});
	}
}

function preloader() 
{
	// counter
    var i = 0;
	// create object
    imageObj = new Image();
    // set image list
    images = new Array();
    images[0]="/images/menu-on_01.gif";
    images[1]="/images/menu-off_01.gif";
    images[2]="/images/menu-on_02.gif";
    images[3]="/images/menu-off_02.gif";
	images[4]="/images/menu-on_03.gif";
    images[5]="/images/menu-off_03.gif";

    // start preloading
    for(i=0; i<=5; i++) 
    {
         imageObj.src=images[i];
    }
}
