/**
 * This is the JS file that is included in every file no matter what. It handles most of the functionality sitewide
 * the exception to this is the main editor in /mason/index.php as it has its own unique js code.
 *
 * Most of it is well documented so check it out
 */
var mouseX = 0;
var mouseY = 0;
var windowX = 1000;
var windowY = 740;
var has_preview = false;
var what = 'PM_row';
var expired = false;
var main_url = '/';
var ajax_url = main_url + 'landing-ajax.php';
var g_page_id;

var activity_indicator = '<P>&nbsp;</P><P align="center"><IMG src="images/indicator.gif" width=32 height=32 vspace="10"><br />Please wait while loading...</P><P>&nbsp;</P>';
var img = new Image;
img.src = 'images/indicator.gif';

/**
* This function will poll the server every minute to see if the users session has expired
* If it has expired it will execute some javascript which will redirect them to the login page
*/
new PeriodicalExecuter(function(pe)
{
	exp = new Ajax.Request(main_url + 'login.php?PM_check_logout=true', {evalScripts: true, method: 'get'});
}, 300);

Event.observe(window, 'load', function()
{
	if ($('chosen_template'))
	{
		if (document.viewport.getHeight() > 650)
		{
			$('chosen_template').setStyle({ position: 'fixed' });
		}
	}
});

/**
* This function will set an event watch for triggering the help container to expand or collapse.
* If Left or Up is pressed the container will expand, if Down or Right is pressed it will collapse.
* If F1 is pressed it will do the opposite of what it currently is
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	void
*/
Event.observe(document, 'keypress', function(event)
{
	if($('PM_help_text').style.display == 'none' && event.keyCode == Event.KEY_LEFT)
	{
		show_help();
	}
	if($('PM_help_content').style.width != '1px' && event.keyCode == Event.KEY_RIGHT)
	{
		hide_help();
	}
	if(event.keyCode == 112)
	{
		click_help();
	}
});


Event.observe(window, 'resize', function(event)
{
	get_window_dimensions();

	if ($('PM_help_text').style.display != 'none')
	{
		$('PM_help_content').style.width = windowX - 90 + 'px';
	}
});

/**
* This function will show the progress indicator
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	show_indicator();
*/
function show_indicator()
{
	$('PM_activity_indicator').style.display = 'block';
}

/**
* This function will hide the progress indicator
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	hide_indicator();
*/
function hide_indicator()
{
	$('PM_activity_indicator').style.display = 'none';
}

/**
* This function will log where the mouse goes every time it moves.
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	void
*/
Event.observe(document, 'mousemove', function(event)
{
	mouseX = Event.pointerX(event);
	mouseY = Event.pointerY(event) - document.body.scrollTop;
	if(has_preview)
	{
		set_preview(mouseX, mouseY);
	}
});

/**
* This function will find out the viewable size for the specific browser window
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	get_window_dimensions();
*/
function get_window_dimensions()
{
	if(document.layers || (document.getElementById && !document.all))
	{
		windowX = window.outerWidth;
		windowY = window.outerHeight;
	}
	else if(document.all)
	{
		windowX = document.body.clientWidth;
		windowY = document.body.clientHeight;
	}
	else
	{
		windowX = 1000;
		windowY = 740;
	}


}

/**
* This function will set the DOM display style to block for the DOM id passed as an arguement
*
* @param	DOM id	what
* @return	void
* @author 	Scott Roach
* @example 	showit('element_info');
*/
function showit(what)
{
	if($(what))
	{
		$(what).style.display = 'block';
	}
}

/**
* This function will set the DOM display style to none (hiding the block) for the DOM id passed as an arguement
*
* @param	DOM id	what
* @return	void
* @author 	Scott Roach
* @example	hideit('element_info');
*/
function hideit(what)
{
	if($(what))
	{
		$(what).style.display = 'none';
	}
}

/**
* This function will hide the layouts box, show the templates box, and call the show_templates function to fetch the templates from the server
*
* @param	string	what
* @return	void
* @author 	Scott Roach
* @example	chooseit('oneleft');
*/
function chooseit(what)
{
	$('PM_layouts').hide();
	show_templates("all", "type", what);
	$('PM_templates').show();
}

/**
* This function will grab all templates from the server that match the given parameters
*
* @param	string	sortby (all|rating|category|type)
* @param 	string	limitby	(array id that matches compare)
* @param 	string	compare (value that limitby must match)
* @return	void
* @author 	Scott Roach
* @example	show_tempaltes('all', 'type', 'oneleft'); show all "oneleft" templates
*/
function show_templates(sortby, limitby, compare)
{
	var qs  = 'action=templates&sortby=' + sortby;

	if(limitby != "")
	{
		qs += '&limitby=' + limitby;
	}
	if(compare != "")
	{
		qs += '&compare=' + compare;
	}

	var myAjax = new Ajax.Updater('PM_template_holder', ajax_url, {method: 'get', parameters: qs});
}

/**
* This function will actually choose a template from the list of templates
*
* @param	template id
* @return	void
* @author 	Stanislav Misiurev
* @example	choose_template(1); choose the template "Blog"
*/
function choose_template(template)
{
	window.location = main_url + 'template.php?template=' + template + '&path=' + $F('path');
}

/**
* This function just sets the border to 1 pixel wide and solid black for the DOM id "sitename",
* This is for if the person doesnt enter a sitename and chooses a template
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	clear_alert();
*/
function clear_alert()
{
	$('sitename').style.border = '1px solid black';
}

/**
* This function redirects the user to their newly created site
*
* @param	Object	originalRequest
* @return	void
* @author 	Scott Roach
* @example	edit_template(ajax_object);
*/
function edit_template(originalRequest)
{
	site_details = originalRequest.responseText.split('_');
	window.location = '/mason/index.php?site_id=' + site_details[0] + '&page_id=' + site_details[1];
}


/**
* This function will show the preview DOM id so that it appears. It does this by changing the CSS styling
*
* @param	string what (image uri)
* @return	void
* @author 	Scott Roach
* @example	preview('http://www.somesite.com/someimage.jpg');
*/
function preview(what)
{
/*	$('PM_preview').style.position = 'absolute';
	$('PM_preview').style.background = 'url(' + what + ') center no-repeat #EEE';
	$('PM_preview').style.display = 'block';
	$('PM_preview').style.width = '400px';
	$('PM_preview').style.height = '400px';
	$('PM_preview').style.border = '1px solid #666';
	$('PM_preview').style.top = (window.pageYOffset + 100) + 'px';
	$('PM_preview').style.left = '250px';
	$('PM_preview').style.marginTop = '3px 0 0 0';
*/
}

/**
* This function will hide the preview that was set with preview();
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	clear_preview();
*/
function clear_preview()
{
/*
	$('PM_preview').style.width = '0px';
	$('PM_preview').style.height = '0px';
	$('PM_preview').style.border = 'none';
	$('PM_preview').style.background = 'none';
	$('PM_preview').style.display = 'none';
*/
	$('PM_preview_content').style.width = '0px';
	$('PM_preview_content').style.display = 'none';
}

/**
* This function will show the preview DOM id so that it appears. It does this by changing the CSS styling
*
* @param	string what (image uri)
* @return	void
* @author 	Scott Roach
* @example	preview('http://www.somesite.com/someimage.jpg');
*/
function quicksite_preview(el)
{

	$('PM_preview').style.backgroundImage = $(el).getStyle('background-image');
	$('PM_preview').style.backgroundRepeat = 'no-repeat';
	$('PM_preview').style.width = '400px';
	$('PM_preview').style.height = '400px';
	$('PM_preview').style.border = '1px solid #666';
}

function quicksite_select_template(el)
{
	$(el).addClassName('selected');
	$$('.thumb').each(
		function(e)
		{
			if(e != el)
			{
				$(e).removeClassName('selected');
			}
		});
}

/**
* This function will hide the preview that was set with preview();
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	clear_preview();
*/
function quicksite_clear_preview(el)
{

	$('PM_preview').style.width = '0px';
	$('PM_preview').style.height = '0px';
	$('PM_preview').style.border = 'none';
	$('PM_preview').style.background = 'none';
}

/**
* This function will search through the HelpText array for any elements that match the string what.
* Ones that do not match will be hidden, those that do will stay visible.
*
* @param	string 	what
* @return	void
* @author 	Scott Roach
* @example	findit('Add a new page');
*/
function findit(what)
{
	what   = what.toLowerCase();
	finds  = new Array();
	if(HelpText.length == 0)
	{
		alert('No results');
	}
	else
	{
		found = 0;
		for(var i=0; i<HelpText.length; i++)
		{
			TopicText[i].style.display = 'none';
			finds = what.split(" ");
			wasfound = true;
			for(var j=0; j<finds.length;j++)
			{
				if(SearchText[i].indexOf(finds[j]) < 1 && finds[j] != "")
				{
					wasfound = false;
				}
			}
			if(wasfound)
			{
				HelpText[i].style.display = 'block';
				finds[found] = i;
				found++;
			}
			else
			{
				//Effect.Fade(HelpText[i]);
				HelpText[i].style.display = 'none';

			}
		}
		if(found < 4)
		{
			for(var i=0; i<TopicText.length; i++)
			{
				//Effect.SlideDown(TopicText[i]);
				TopicText[i].style.display = 'block';
				$('PM_toggle_' + TopicText[i].id.replace(/PM_help_topic_/, '')).style.background = 'url(images/app/bullet_toggle_minus.png) top left no-repeat';
			}
		}
		else
		{
			for(var i=0; i<TopicText.length; i++)
			{
				//Effect.SlideDown(TopicText[i]);
				$('PM_toggle_' + TopicText[i].id.replace(/PM_help_topic_/, '')).style.background = 'url(images/app/bullet_toggle_plus.png) top left no-repeat';
			}
		}
//		$('PM_no_search_results').style.display = found == 0 ? 'block' : 'none';
//		hide_indicator();
	}
}

/**
* This function will toggle the descriptions for help categories from visible to hidden and back.
*
* @param	string	what (where what is the help topic title)
* @return	void
* @author 	Scott Roach
* @example	toggle_help('AddPage');
*/
function toggle_help(what)
{
	$('PM_help_topic_' + what).toggle();
	$('PM_toggle_' + what).style.background = $('PM_help_topic_' + what).style.display == 'block' ? 'url(images/app/bullet_toggle_minus.png) center left no-repeat' : 'url(images/app/bullet_toggle_plus.png) center left no-repeat';
}

/**
* This function will take the Helpers array and format it on the help page so that it is visually presentable, as well as prepare it for searching.
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	load_help();
*/
function load_help()
{
	var i = 0;
	for (item in Helpers)
	{
		if (item == 'each') break;
		$('PM_help_topics').innerHTML += '<div class="PM' + '_help_text"><a href="javascript:to' + 'ggle_help(\'' + item + '\');"><h5 clas' + 's="PM_help_topic" id="PM_toggle_' + item + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + item + '</h5></a><p class="PM_h' + 'elp_toggle" id="PM_help_topic_' + item + '" style="display: none;">' + Helpers[item] + '</p></div>' + "\n";
		SearchText[i] = '  ' + item.toLowerCase().stripTags() + ' ' + Helpers[item].toLowerCase().stripTags();
		i++;
	}
/*	show_indicator();
	var hash = $H(Helpers);
	topic = hash.keys();
	definition = hash.values();
	for(var i=0; i<topic.length; i++)
	{
		$('PM_help_topics').innerHTML += '<div class="PM' + '_help_text"><a href="javascript:to' + 'ggle_help(\'' + topic[i] + '\');"><h5 clas' + 's="PM_help_topic" id="PM_toggle_' + topic[i] + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + topic[i] + '</h5></a><p class="PM_h' + 'elp_toggle" id="PM_help_topic_' + topic[i] + '" style="display: none;">' + definition[i] + '</p></div>' + "\n";
		SearchText[i] = '  ' + topic[i].toLowerCase().stripTags() + ' ' + definition[i].toLowerCase().stripTags();
	}
	$('PM_help_topics').innerHTML += '<h3 id="PM_no_search_results" style="display: none;">Your search did not return any matches</h3>';
*/
	HelpText = document.getElementsByClassName('PM_help_text', 'PM_help_topics');
	TopicText = document.getElementsByClassName('PM_help_toggle', 'PM_help_topics');
//	hide_indicator();
}

/**
* This function will popup a window. It is used for the filemananger
*
* @param	string	url
* @return	void
* @author 	Scott Roach
* @example	popUp('http://www.google.com');
*/
function popup(URL)
{
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=580,height=600,left=20,top=20');");
}

/**
* This function will add rollover triggers to all DOM ids that have help topics.
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	set_helpers();
*/
function set_helpers()
{
	id_to_Helper = new Array();
	Helper_to_id = new Array();
	id_to_Helper[0] = 'DropDownGoTo';
	Helper_to_id[0] = 'PM_pages';
	id_to_Helper[1] = 'AddSite';
	Helper_to_id[1] = 'PM_addsite';
	id_to_Helper[2] = 'DeleteSite';
	Helper_to_id[2] = 'PM_deletesite';
	id_to_Helper[3] = 'EditSite';
	Helper_to_id[3] = 'PM_editsite';
	id_to_Helper[4] = 'ImportSite';
	Helper_to_id[4] = 'PM_importsite';
	id_to_Helper[5] = 'PublishSite';
	Helper_to_id[5] = 'PM_publishsite';
	id_to_Helper[6] = 'FileManager';
	Helper_to_id[6] = 'PM_filemananger';
	id_to_Helper[7] = 'ChangeLoginInformation';
	Helper_to_id[7] = 'PM_changelogin';
	id_to_Helper[8] = 'Help';
	Helper_to_id[8] = 'PM_help';
	id_to_Helper[9] = 'PageMasonLogo';
	Helper_to_id[9] = 'PM_pm_logo';
	id_to_Helper[10] = 'LunarpagesLogo';
	Helper_to_id[10] = 'PM_lp_logo';
	id_to_Helper[11] = 'ChooseTemplateLayout';
	Helper_to_id[11] = 'PM_choose';
	id_to_Helper[12] = 'ChooseTemplate';
	Helper_to_id[12] = 'PM_templates';
	id_to_Helper[13] = 'OneLeft';
	Helper_to_id[13] = 'PM_oneleft';
	id_to_Helper[14] = 'OneTop';
	Helper_to_id[14] = 'PM_onetop';
	id_to_Helper[15] = 'OneRight';
	Helper_to_id[15] = 'PM_oneright';
	id_to_Helper[16] = 'TwoLeft';
	Helper_to_id[16] = 'PM_twoleft';
	id_to_Helper[17] = 'TwoRight';
	Helper_to_id[17] = 'PM_tworight';
	id_to_Helper[18] = 'ChooseLayout';
	Helper_to_id[18] = 'PM_layouts';
	id_to_Helper[19] = 'SiteName';
	Helper_to_id[19] = 'sitename';
	id_to_Helper[20] = 'EditSites';
	Helper_to_id[20] = 'PM_edit_sites';

	for(var i=0; i<Helper_to_id.length; i++)
	{
		if($(Helper_to_id[i]))
		{
			add_listener(Helper_to_id[i], Helpers[id_to_Helper[i]]);
			$(Helper_to_id[i]).onmouseout = function(){default_editable();};
		}
	}
/*	Helper_to_id[21] = '';
	id_to_Helper[21] = '';
	Helper_to_id[22] = '';
	id_to_Helper[22] = '';
	Helper_to_id[23] = '';
	id_to_Helper[23] = '';
	Helper_to_id[24] = '';
	id_to_Helper[24] = '';
	Helper_to_id[25] = '';
	id_to_Helper[25] = '';
	Helper_to_id[26] = '';
	id_to_Helper[26] = '';
	Helper_to_id[27] = '';
	id_to_Helper[27] = '';
	Helper_to_id[28] = '';
	id_to_Helper[28] = '';
	Helper_to_id[29] = '';
	id_to_Helper[29] = '';*/
}

/**
* This function will add will add a function to a specific DOM id element that will call the editable() function with the value of text
*
* @param	string DOM id	element
* @return	string 	text (value of the text to pass to editable())
* @author 	Scott Roach
* @example	add_listener('PM_addsite', 'Clicking this will let you add a new site');
*/
function add_listener(element, text)
{
	$(element).onmouseover = function() {editable(text);};
}

/**
* This function will indicate that there is help info for a certain item, and it will set the help area content to the help info.
*
* @param	string	what (help content)
* @return	void
* @author 	Scott Roach
* @example	editable("Clicking Add Site will allow you to create a new site");
*/
function editable(what)
{
	$('PM_help_text').innerHTML = what;
	$('PM_help_right').style.background = 'url(images/PM_help_right_over.png) top right no-repeat';
}

/**
* This function will reset the style of the help area to show that there is no specific help context for the item the user is looking at.
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	default_editable();
*/
function default_editable()
{
	$('PM_help_right').style.background = 'url(images/PM_help_right.png) top right no-repeat';
}

/**
* This function will expand the help area
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	show_help();
*/
function show_help()
{
	get_window_dimensions();
	new Rico.Effect.Size( 'PM_help_content', (windowX - 90), null, 500, 10,
	{complete:function() {new Effect.Appear('PM_help_text')}} );
	setcookie('PM_helper', 'open', 30);
}

/**
* This function will collapse the help area.
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	hide_help();
*/
function hide_help()
{
	new Effect.Fade('PM_help_text', {afterFinish: function(){new Rico.Effect.Size( 'PM_help_content', 1, null, 500, 10);}});
	setcookie('PM_helper', 'closed', 30);
}

/**
* This function will make the help area the opposite of what it currently is. If it is collpased it will call show_help(), if it is expanded it will call hide_help()
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	click_help();
*/
function click_help()
{
	if($('PM_help_text').style.display == 'none')
	{

		show_help();
	}
	else
	{
		hide_help();
	}
}

/**
* This function will make javascript set a cookie with the name "name", value "value" and set it to expire in "days" days
*
* @param	string	name
* @param 	string 	value
* @param 	int/string	days
* @return	void
* @author 	Scott Roach
* @example	setcookie('has_loaded_page', 'true', 365);
*/
function setcookie(name, value, days)
{
	expires = "";
	if(days != "" && days != null)
	{
		date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

/**
* This function will get the value for the desired cookie "name"
*
* @param	string	name
* @return	string 	cookie_value
* @author 	Scott Roach
* @example	read_cookie('has_loaded_page'); // returns "true" from previous example
*/
function readcookie(name)
{
	eval('regex = /' + name + '=(.+?)(;|$)/');
	matches = document.cookie.match(regex);
	if(matches == null)
	{
		return false;
	}
	return matches[1];
}

/**
* This function will set the original style of the help area. If there is a cookie set that the help area is collapsed, it will load collapsed.
* If there is not cookie, or the cookie is set as expanded the help area will be loaded as being expanded.
*
* @param	void
* @return	void
* @author 	Scott Roach
* @example	adjust_helper();
*/
function adjust_helper()
{
	$('PM_help_right').style.background = 'url(images/PM_help_right.png) top right no-repeat';
	cookie = readcookie('PM_helper');
	if (cookie == 'open' || cookie == false)
	{
		get_window_dimensions();
		$('PM_help_content').style.width = (windowX - 90) + 'px';
		$('PM_help_text').style.display = 'block';
	}
	else
	{
		$('PM_help_content').style.width = '1px';
		$('PM_help_text').style.display = 'none';
	}
}

/**
* This function will toggle a div and also change the image of the toggler from a + to a -
*
* @param	string toggle_id
* @param	string plus_id
* @return	void
* @author 	Scott Roach
* @example	edit_toggle('dunno', 'rawr');
*/
function edit_toggle(toggle_id, plus_id)
{
	if($(toggle_id).style.display != 'none')
	{
		$(plus_id).style.background = 'url(images/app/bullet_toggle_plus.png) center left no-repeat';
	}
	else
	{
		$(plus_id).style.background = 'url(images/app/bullet_toggle_minus.png) center left no-repeat';
	}
	new Effect.toggle(toggle_id, 'appear');
}


function cancel_submit(what)
{
	Effect.Fade(what);
}

/*
* This function will position the prompt for different options.
*
* @param	id element (id elemet to position)
* @param	int width (width of the item to position)
* @param	int height (height of the item to position)
* @return 	void
* @author	Scott Roach
* @example	position('PM_mount_point_dlg', 200, 200);
*/
function position(element, width)
{
	get_window_dimensions();
	midX = mouseX + 5;//Math.floor((windowX / 2) - (width / 2));
	midY = mouseY + 5;//Math.floor((mouseY) - (height / 2));
	$(element).style.position = 'absolute';
	$(element).style.width = width + "px";
//	$(element).style.height = height + "px";
	$(element).style.top = midY + "px";
	$(element).style.left = midX + "px";
	$(element).style.border = '1px solid #B2ACAB';
	$(element).style.background = '#F3F3F3';
//	$(element).style.padding = '15px';
}

/*
* This function will bring up the prompt to edit a page title
*
* @param	int page_id
* @param	string page_title (current page_title)
* @return 	void
* @example	edit_title(3, 'My contact page');
*/
function edit_title(page_id, page_title, flag)
{
	position('PM_edit_page_title', 250);
	$('PM_edit_title_page_id').value = page_id;
	if ($('PM_new_page_title').value == '' || flag)
	{
		$('PM_new_page_title').value = page_title;
	}
	Effect.Appear('PM_edit_page_title');
}

/*
* This function will bring up the prompt to edit a page name
*
* @param	int page_id
* @param	string page_name (current page_name)
* @return 	void
* @example	edit_page_name(3, contact);
*/
function edit_page_name(page_id, page_name, flag)
{
	if (page_name == 'index')
	{
		alert('You cannot rename index page!');
		return;
	}

	position('PM_edit_page_name', 250);
	$('PM_edit_name_page_id').value = page_id;
	if ($('PM_new_page_name').value == '' || flag)
	{
		$('PM_new_page_name').value = page_name;
	}
	Effect.Appear('PM_edit_page_name');
}

/*
* This function will bring up the promt to edit a site's name
*
* @param	int site_id
* @param	string site_name (current site_name)
* @return 	void
* @author	Scott Roach
* @example	edit_site_name(0, 'Dentist Site');
*/
function edit_site_name(site_id, site_name)
{
	position('PM_edit_site_name', 250);
	$('PM_edit_site_id').value = site_id;
	$('PM_new_site_name').value = site_name;
	Effect.Appear('PM_edit_site_name');
}

/*
* This function will bring up the prompt to clone a page
*
* @param	int page_id
* @return 	void
* @example	clone_page(3);
*/
function clone_page(page_id)
{
	position('PM_clone_page', 250);
	$('PM_clone_page_id').value = page_id;
	Effect.Appear('PM_clone_page');
}

function edit_mount_point()
{
	position('PM_mount_point_dlg', 400);
	Effect.Appear('PM_mount_point_dlg');
}

/*
* This function will actually edit a page title from the prompt that was put up by edit_title()
*
* @return 	void
* @author	Scott Roach
* @example	submit_page_title();
*/
function submit_page_title(flag)
{
	url = ajax_url + '?action=edittitle&page_id=' + $F('PM_edit_title_page_id') + '&site_id=' + $F('PM_edit_title_site_id') + '&page_title=' + $F('PM_new_page_title') + '&_=1&flag=' + flag;
	var myAjax = new Ajax.Updater('PM_edit_sites', url, {method: 'get', evalScripts: true});
	cancel_submit('PM_edit_page_title');
}

/*
* This function will actually add a cloned page from the prompt that was placed by clone_page()
*
* @return 	void
* @author	Scott Roach
* @example	submit_cloned_page();
*/
function submit_cloned_page(flag)
{
	url = ajax_url + '?action=clonepage&page_id=' + $F('PM_clone_page_id') + '&page_name=' + $F('PM_cloned_page_name') + '&_=1&flag=' + flag;
	var myAjax = new Ajax.Updater('PM_edit_sites', url, {method: 'get', evalScripts: true});
	cancel_submit('PM_clone_page');
}

/*
* This function will actually edit a page name from the prompt that was put up by edit_page_name()
*
* @return 	void
* @author	Scott Roach
* @example	submit_page_name();
*/
function submit_page_name(flag)
{
	url = ajax_url + '?action=pagename&page_id=' + $F('PM_edit_name_page_id') + '&site_id=' + $F('PM_edit_name_site_id') + '&page_name=' + $F('PM_new_page_name') + '&_=1&flag=' + flag;
	var myAjax = new Ajax.Updater('PM_edit_sites', url, {method: 'get', evalScripts: true});
	cancel_submit('PM_edit_page_name');
}

/*
* This function will actually edit a site name from the prompt that was put up edit_site_name()
*
* @return 	void
* @author	Scott Roach
* @example	submit_site_name();
*/
function submit_site_name()
{
	var url = ajax_url + '?action=sitename&site_id=' + $F('PM_edit_site_id') + '&site_name=' + $F('PM_new_site_name') + '&_=1';
	var myAjax = new Ajax.Updater('PM_edit_sites', url, {method: 'get', evalScripts: true});
	cancel_submit('PM_edit_site_name');
}

function submit_mount_point()
{
	var url = ajax_url + '?action=mountpoint&path=' + $F('PM_mount_point_path') + '&_=1';
	var myAjax = new Ajax.Updater('PM_mount_point', url, {method: 'get', evalScripts: true});
	cancel_submit('PM_mount_point_dlg');
}

function init()
{
	get_window_dimensions();
	editable(Helpers['InitialHelper']);
	set_helpers();
	adjust_helper();
}

function IEfix(height, overflow)
{
	if(nav_type.indexOf('msie') + 1)
	{
		thehtml = document.getElementsByTagName('html')[0];
		thehtml.style.height = height;
		thehtml.style.overflow = overflow;
		thebody = document.getElementsByTagName('body')[0];
		thebody.style.height = height;
		thebody.style.overflow = overflow;
		window.scrollTo(0, 0);
	}
}

function find_sites()
{
	var url = main_url + 'getsites.php';
	var myAjax = new Ajax.Updater('sites', url, {onComplete: function(){close_editor();}});
}


function show_sites(originalRequest)
{
	$('sites').innerHTML = originalRequest.responseText;
	close_editor();
}


function find_pages(site_id)
{
	g_site_id = site_id;
	var url = main_url + 'getpages.php?site_id=' + g_site_id;
	var myAjax = new Ajax.Request(url, {onComplete: show_pages});
}


function show_pages(originalRequest)
{
	//$('pages').innerHTML = originalRequest.responseText;
	close_editor();
}


function load_page(page_id)
{
	g_page_id = page_id;
	$('page_content').hide();
	$('PM_loading').show();
	var url = ajax_url + '?action=getpage&page_id=' + page_id;
	var myAjax = new Ajax.Updater('page_content', url, { evalScripts: false, onComplete: show_page });
}


function show_page()
{
	set_CSS_file();
	set_page_details();

	$('PM_loading').hide();
	$('page_content').show();
}

function show_dialog(name, title, url, width, height)
{
	if (!FCKeditorAPI)
	{
		return false;
	}

	if (!FCKeditorAPI.GetInstance('fckmain'))
	{
		return false;
	}

	if (!FCKeditorAPI.GetInstance('fckmain').EditorWindow)
	{
		return false;
	}
	FCKeditorAPI.GetInstance('fckmain').EditorWindow.parent.FCKConfig.FloatingPanelsZIndex = 5000;
	FCKeditorAPI.GetInstance('fckmain').EditorWindow.parent.FCKDialog.OpenDialog( name, title, url, width, height );
}


function custom_events(name, custom_id, link, title, helper)
{
	if ($('PM_' + name + custom_id))
	{
		add_listeners('PM_' + name + custom_id, helper)

		Event.observe($('PM_' + name + custom_id), 'click', function () {
			show_dialog( 'FCKDialog_' + name, 'Edit ' + title, link, '400', '350' );
		});
	}
}


//function set_page_details(site_name, page_name, page_title)
function set_page_details()
{
	var url = ajax_url + '?action=getpagecontent&page_id=' + g_page_id;
	new Ajax.Updater('PM_content', url);

	window.document.title = $F('page_title');

	Event.observe($('PM_content'), 'click', function () {
		show_dialog( 'FCKDialog_Main', 'Edit Content', '/fckeditor.php?page_id=' + g_page_id, '800', '400' ) ;
	});
	Event.observe($('mason-header'), 'click', function () {
		show_dialog( 'FCKDialog_Header', 'Edit Header', 'pm_header.php', '450', '150' );
	});
	Event.observe($('mason-footer'), 'click', function () {
		show_dialog( 'FCKDialog_Footer', 'Edit Footer', '/fckeditor_editable.php?id=footer', '450', '200' );
	});
	add_listeners('PM_content', 'EditPageContent');
	add_listeners('mason-header', 'EditHeader');
	add_listeners('mason-footer', 'EditFooter');
	custom_events('menu', 1, 'pm_menu.php?menu=1', 'Menu', 'EditMenuItem');
	custom_events('menu', 2, 'pm_menu.php?menu=2', 'Menu', 'EditMenuItem');
	custom_events('menu', 3, 'pm_menu.php?menu=3', 'Menu', 'EditMenuItem');
	custom_events('editable', 1, '/fckeditor_editable.php?id=1', 'Section', 'EditEditable');
	custom_events('editable', 2, '/fckeditor_editable.php?id=2', 'Section', 'EditEditable');
	custom_events('editable', 3, '/fckeditor_editable.php?id=3', 'Section', 'EditEditable');
	override_links('PM_content');
	override_links('mason-footer');
	override_links('PM_editable1');
	override_links('PM_editable2');
	override_links('PM_editable3');
	override_links('PM_editable4');
	override_links('PM_editable5');
}

function save_page(content)
{
	new Ajax.Updater('page_content', ajax_url, {
		parameters:  { action: 'editpage', page_id: g_page_id, content: content },
		onComplete: set_page_details
	});
}


function save_editable(id, content)
{
	new Ajax.Updater('PM_editable' + id, ajax_url, {
		evalScripts: true,
		parameters:  { action: 'editable', editable_id: id, newcontent: content }
	});
}

function save_header(str)
{
	new Ajax.Updater('mason-header', ajax_url, {
		parameters: {action: 'sitename', newname: str},
		method: 'post'
	});
}

function save_footer(str)
{
	new Ajax.Updater('mason-footer', ajax_url, {
		parameters: {action: 'sitefooter', newtext: str},
		method: 'post',
		onComplete: function () {
			override_links('mason-footer');
		}
	});
}

function save_menu(menu_id, items_str)
{
	new Ajax.Updater('PM_menu' + menu_id, ajax_url, {
		parameters: { action: 'editmenu', menu_id: menu_id, items: items_str},
		method: 'post'
	});
}


function add_listeners(id, helperid)
{
	Event.observe(id, 'mouseover', function () {
		editable(Helpers[helperid]);
	});

	Event.observe(id, 'mouseout', function() {
		default_editable();
	});

	$(id).style.cursor = 'pointer';
}

function encode_html(s)
{
        var str = new String(s);
        str = str.replace(/&/g, "&amp;");
        str = str.replace(/</g, "&lt;");
        str = str.replace(/>/g, "&gt;");
        str = str.replace(/\"/g, "&quot;");
        return str;
}


function override_links(what)
{
	if (!$(what))
	{
		return false;
	}

	var r = new RegExp('href=', 'gi');
	$(what).innerHTML.replace(r, 'xref=');
}


function rewrite_links(what)
{
	return what.replace(/xref=/gi, 'href=');
}

function set_CSS_file()
{
	var sheets;
	if(!window.ScriptEngine && navigator.__ice_version)
	{
		sheets = document.styleSheets;
	}
	if(document.getElementsByTagName)
	{
		sheets = document.getElementsByTagName('link');
	}
	else if(document.styleSheets && document.all)
	{
		sheets = document.all.tags('LINK');
	}
	tempstr = '';
	for(i=0; i<sheets.length;i++)
	{

		if(sheets[i].title == ('page' + g_page_id) || sheets[i].title == 'main' || sheets[i].title == 'menu')
		{
			sheets[i].disabled = false;
		}
		else
		{
			sheets[i].disabled = true;
		}
	}
}

function add_page(site_id)
{
	position('PM_add_page', 300);
	$('PM_add_page_site_id').value = site_id;
	Effect.Appear('PM_add_page');
}

function submit_add_page(flag)
{
	var page_name = $F('PM_add_page_name');
	var page_title = $F('PM_add_page_title');


	if(page_name != "" && page_name != null && page_name.length > 3)
	{
		if ($('PM_edit_sites'))
		{
			$('PM_edit_sites').innerHTML = activity_indicator;
		}

		var myAjax = new Ajax.Request(ajax_url, {
			parameters: { action: 'addpage', name: page_name, title: page_title, selected: 'true', flag: flag, tomenu: $F('PM_add_page_menu') },
			method: 'post',
			evalScripts: true,
			onComplete: function(o)
			{
				if (o.responseText != '0')
				{
					var response = o.responseText.split('::', 2);
					if ($('PM_edit_sites'))
					{
						$('PM_edit_sites').innerHTML = response[1];
					}

					if (response[0] == 'exists')
					{
						alert("Page " + page_name + ".html already exists.");
					}
					else if (confirm("The page was successfully created!\nWould you like to be taken to it?"))
					{
						window.location = 'page.php?page_id=' + response[0];
					}
				}
			}
		});
		cancel_submit('PM_add_page');
	}
	else if (page_name != null)
	{
		alert("The page name must be at least 4 characters in length\nPlease try again.");
	}
}


function delete_page(page_id, flag, page_name)
{
	if (page_name == 'index')
	{
		alert('You cannot delete index page!');
		return;
	}

	var confirmit = confirm("Are you sure you want to delete this page?");
	if(confirmit)
	{
		var url = ajax_url + '?action=rmpage&page_id=' + page_id;
		if (flag)
		{
			var myAjax = new Ajax.Request(url, {method: 'get', onComplete: function(){window.location = 'index.php';}});
		}
		else
		{
			$('PM_edit_sites').innerHTML = activity_indicator;
			var myAjax = new Ajax.Updater('PM_edit_sites', url, {method: 'get', evalScripts: true});
		}
	}
}


function save_site(site_id)
{
	var confirmit = confirm("Are you sure that you want to save your site?");
	if(confirmit)
	{
		var url = ajax_url + '?action=savesite&site_id=' + site_id + '&_=1';
		var myAjax = new Ajax.Request(url, {method: 'get', onComplete: function(){alert('Your site has been saved')}});
	}
}

function alert_to_save(site_id)
{

}

function publish_site(site_id)
{
	$('PM_published_pages').innerHTML = activity_indicator;
	var url = ajax_url + '?action=publish&site_id=' + site_id;
	var myAjax = new Ajax.Request(url, {method: 'get', onComplete: function(o){$('PM_published_pages').innerHTML = o.responseText;}});
}

function goto_page()
{
	if ($F('PM_pages') > 0)
	{
		window.location = 'page.php?page_id=' + $F('PM_pages');
	}
}


function select_tutorial(value)
{
	if (value != '')
	{
		$('PM_swf').innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="600" height="500"><param name="movie" value="tutorials/' + value + '" /><param name="quality" value="high" /><embed src="tutorials/' + value + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="600" height="500"></embed></object>';

	}
}

function set_css(new_color, template_rating)
{
        indicator_loader();
        var css = $('PM_selectedpreview').readAttribute('css');
        var new_src = $('PM_selectedpreview').readAttribute('image').replace(css, new_color);

        $('PM_selectedpreview_img').src = new_src;
        $('PM_selectedpreview_img').observe('load', preview_loader);

        $('PM_selectedpreview').writeAttribute('css', new_color);
        $('PM_selectedpreview').writeAttribute('image', new_src);
        $('change_template_area').style.display = 'block';
        //var template_id = $('change_template').readAttribute('template_id');
       // $('change_template').writeAttribute('href', 'template.php?template='+template_id+'&css='+new_color);
        //$('template_rating').innerHTML = template_rating;
        $('template_css').value = new_color;
}

function load_themes(css_files)
{
        var colorTemplate = new Template("<span class='color_theme' style='background: #{color};' onClick=\"set_css('#{color}', null);\" alt='Use #{color} color scheme'></span>");
        var content = '';
        css_files.each(function(c){
                content += colorTemplate.evaluate({color: c});
        });
        $('color_chooser').update(content);
}

function indicator_loader()
{
        $('PM_selectedpreview_img').style.display = 'none';
        $('PM_selectedpreview_loader').style.display = 'block';
}

function select_pm_template(el)
{
	indicator_loader();

	$$('.PM_thumb_placer').each(function(e)
	{
		if(e != el)
		{
			$(e).removeClassName('PM_thumb_selected');
		}
		else
		{
			var baseURL = document.URL.replace(/template.php/, '');
			//Select The box
			$(el).addClassName('PM_thumb_selected');

			//Set the template for the page
			var template_id = el.readAttribute('template_id');
			var template_name = el.readAttribute('template_name');
			var template_location = el.readAttribute('template_folder');
			var thumbnail = el.readAttribute('template_thumbnail');
			var css_files = el.readAttribute('css').split(',');
			var template_rating = el.readAttribute('template_rating');
			var thumbstyle = el.readAttribute('thumbstyle');

			set_css(css_files[0], template_rating);
			load_themes(css_files);

			$('template_name').innerHTML = template_name;
			$('PM_selectedpreview_img').src = template_location+'/'+thumbnail;
			$('PM_selectedpreview').writeAttribute('image', template_location+'/'+thumbnail);
			$('PM_selectedpreview_img').observe('load', preview_loader);
			/*
			$('change_template').writeAttribute('template_id', template_id);
			$('change_template_area').style.display = 'block';
			$('change_template').writeAttribute('href', 'template.php?template='+template_id+'&css='+css_files[0]);
			*/
			$('template_id').value = template_id;
			$('template_css').value = css_files[0];
		}
	});
}

function preview_loader()
{
        $('PM_selectedpreview_loader').style.display = 'none';
        $('PM_selectedpreview_img').style.width = '400px';
        $('PM_selectedpreview_img').style.height = '300px';
        $('PM_selectedpreview_img').style.display = 'block';
}



function editfilename( e )
{
	if( e.value == '' )
		return;

	var filename = e.value.toLowerCase().replace(/[^0-9a-zA-Z.\-[\]\^_\s+~]/ig, ""); // Replace invalid characters
	$('PM_add_page_name').value = filename.replace(/\s/ig, "_");
}

// Checks if all field filled
function feedback_form()
{
	if ($F('fullname') == '')
	{
		alert('Please enter your name');
		$('fullname').focus();
		return false;
	}

	if ($F('email') == '')
	{
		alert('Please enter your e-mail');
		$('email').focus();
		return false;
	}

	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test($F('email')))
	{
		alert('Please enter valid e-mail address');
		$('email').focus();
		return false;
	}

	if ($F('msg') == '')
	{
		alert('Please enter your message');
		$('msg').focus();
		return false;
	}

	return true;
}
