// JavaScript Document

var ed;

//******* ADMIN MENU FUNCTIONS ********//

function expand(obj) {
	jQuery(obj).siblings('.adminModSubMenu').children('.addArea').html('');
	if(jQuery(obj).siblings('.adminModSubMenu').css('display') == 'none') {
		collapse();
		jQuery(obj).siblings('.adminModSubMenu').show();
	} else {
		collapse();
	}
}

function collapse() {
	jQuery('.adminModSubMenu').hide();
}

function reportError(error) {
	jQuery('#error').html(error);
	jQuery('#error').slideDown(250);	
}

function loadModule(posts) {
	if(posts == undefined) {  posts = "";	}
	jQuery('#mainAdminControl').html(ajaxCall(posts));
}

function initializeAdmin(posts)
{
	$('#mainContentEditor').css('width', '70%');
	$('#mainContentEditor').css('height', '70%');
	$('#mainContentEditor').css('top', '15%');
	$('#mainContentEditor').css('left', '15%');
	
	jQuery('#mainMask').click(function() {
		window.location.reload();
	});

	loadModule(posts);
	
	jQuery('#mainMask').fadeTo(500,0.6);
	jQuery('#mainMask').fadeIn(500, function() {
		if(jQuery(window).height() < 300) {
			jQuery('#mainContentEditor').css('position', 'absolute');
		}
		
		jQuery('#mainContentEditor').fadeIn(300);
		//jQuery('#mainContentEditor').show();
	});
}

function windowCancel(Reload)
{
	if (!Reload)
	{
		jQuery('#mainContentEditor').fadeOut(300);
		jQuery('#mainMask').fadeOut(500);
	} else {
		window.location.reload();
	}
}

function clearAdminAreas() {
	jQuery('.addArea').each(function(i) {
		jQuery(this).html('');
	});
	jQuery('.adminMenuCommand').each(function(i) {
		jQuery(this).show();
	});
}

function toggleAdminBtns() {
	jQuery('.adminBtn').toggle();
	if(adminBtnsVisible) {
		adminBtnsVisible = false;
	} else {
		adminBtnsVisible = true;
	}
}

function toggleAdmin() {
	jQuery('#adminModMenu').slideToggle('slow');
	if(jQuery('#adminToggle').css('top') != '0px') {
		jQuery('#adminToggler').text('Expand Admin Menu');
		jQuery('#adminToggle').animate({top:"0px"}, 'slow');
	} else {
		jQuery('#adminToggler').text('Collapse Admin Menu');
		jQuery('#adminToggle').animate({top:"26px"}, 'slow');
	}
}

/////////////////////////////////////
//******* COMMON FUNCTIONS ********//
/////////////////////////////////////

function submitForm(action, returnPost) {
	var posts = '';
	jQuery('.'+action+'FormElem').each(function(i) {
		if ($(this).is('input') && $(this).attr('type') == 'radio' && !$(this).attr('checked')) {
			// don't include it
		} else {
			posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();			
		}
	});
	
	if (returnPost == undefined) {
		loadModule(posts);
	} else {
		return posts;
	}
}

function enableSubmit(obj) {
	if(jQuery(obj).val() != '') {
		jQuery('#adminSubmit').removeAttr('disabled');	
	} else {
		jQuery('#adminSubmit').attr('disabled', 'disabled');
	}
}

function checkAllPages(checkSet) {
	if(checkSet) {
		jQuery('.page_'+checkSet).each(function(i) {
			if(jQuery('#group_name').val() != 'Guest' || checkSet == 'read') {
				jQuery(this).attr('checked', 'checked');
			}
		});
		if(checkSet == 'write')
			checkAllPages('read');
	} else {
		jQuery('.pages').each(function(i) {
			jQuery(this).attr('checked', 'checked');
		});
	}
}

function uncheckAllPages(checkSet) {
	if(checkSet) {
		jQuery('.page_'+checkSet).each(function(i) {
			jQuery(this).removeAttr('checked');
		});
		if(checkSet == 'read')
			uncheckAllPages('write');
	} else {
		jQuery('.pages').each(function(i) {
			jQuery(this).removeAttr('checked');
		});
	}
}

function checkRead(obj, id) {
	if(jQuery(obj).attr('checked')) {
		jQuery('#pageRead'+id).attr('checked', 'checked');
	}
}

function uncheckWrite(obj, id) {
	if(!jQuery(obj).attr('checked')) {
		jQuery('#pageWrite'+id).removeAttr('checked');
	}
}


// Page only functions

//
function addPageItem(action) {
	var posts = '';
	jQuery('.'+action+'FormElem').each(function(i) {
		posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();
	});
	
	if ((result = ajaxCall(posts)) == 1) {
		jQuery("#page"+action+"List").html(ajaxCall("token="+jQuery('#getPageItemToken').val()));
	} else {
		jQuery('#add'+action+'Editor').html(result);
	}
}

//! Used by PageInfo
function editPageItem(action) {
	var posts = '';
	jQuery('.'+action+'FormElem').each(function(i) {
		posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();
	});
	
	if ( (result = ajaxCall(posts)) && result.substr(0,4) == 'http'){
		window.location.href = result;
	} else {
		jQuery('#editPageEditor').html(result);	
	}
}

// Used by PageMenu, PageMeta, PageScript
function deletePageItem(token) {
	if(ajaxCall(token) == 1) {
		jQuery("#page"+action+"List").html(ajaxCall("token="+jQuery('#getPageItemToken').val()));
	}
}

// Used by PageGroup
function editGroupAuth(posts, access) {
	str = '';
	jQuery('.'+access+'Group').each(function(i) {
		if(jQuery(this).attr('checked')) {
			checked = 1;
		} else {
			checked = 0;
		}
		str = setCharAt(str,jQuery(this).attr('name').replace('group_id-', '')-1,checked);
		//alert(str);
	});
	
	if( (result = ajaxCall(posts+"&a="+str)) != 1) {
		alert(result);
	}
}

function setCharAt(str,index,chr) {
	while(index >= str.length) { str = '0' + str; }
    return str.substr(0,(index*-1)) + chr + str.substr((index*-1));
}

function editModuleAuth(token, access) {
	loadModule(token+"&auth="+getModuleAuth(access));
}

function getModuleAuth(access) {
	auth = '1';
	jQuery('.'+access+'Group').each(function(i) {
		if(jQuery(this).attr('checked')) {
			checked = 1;
		} else {
			checked = 0;
		}
		auth = setCharAt(auth,jQuery(this).attr('name').replace('group_id-', '')-1,checked);
	});
	
	return auth
}

function addModuleAttributes(token) {
	var posts = '';
	jQuery('.moduleAttribute').each(function(i) {
		posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();
	});
	
	loadModule(token+posts);
}

function editPermissionAuth() {
	loadModule("alias="+jQuery('#alias').val()+"&auth="+getModuleAuth('read')+"&token="+jQuery('#permissionToken').val());
}


// MAY NO LONGER WORK AFTER REMOVING t+'_view' from loadModule()
function deleteItem(i, t, userPrompt) {
	if(userPrompt) {
		jQuery('#report').html(ajaxCall('i='+i+'&t='+t+'&confirm=1'));
		jQuery('#report').show();
	} else {
		jQuery('#report').hide();
		jQuery('#report').html('');
		if( (result = ajaxCall('i='+i+'&t='+t+'&confirm=0')) == "success") {
			loadModule('');
		} else {
			reportError(result);
		}
	}
}

//!
function editUser() {
	var posts = '';
	jQuery('.editUserFormElem').each(function(i) {
		posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();
	});
	
	posts += "&group=";
	
	jQuery('.checkBox').each(function(i) {
		posts += (jQuery(this).attr('checked') ? jQuery(this).val()+',' : '');
	});
	
	if (posts.substr((posts.length-1),(posts.length-2)) == ',')
	{
		posts = posts.substr(1,(posts.length-2));
	}
	posts += "&subscribe=" + (jQuery('#subscribe').attr('checked') ? 1 : 0);

	loadModule(posts);
}

function installModule() {
	var posts = '';
	jQuery('.attributeField').each(function(i) {
		posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();
	});
	
	loadModule("package="+jQuery('#package').val()+"&module="+jQuery('#module').val()+"&token="+jQuery('#installModuleToken').val()+posts);
}

function searchUsers(terms) {
	jQuery('#users').html(ajaxCall("usr="+terms));
}

function showRegionModule(pageRegion) {
	jQuery('#regionMod-'+pageRegion).show();
}

function tinyInit(width, height)
{
	if (width == undefined)
		width = "60%";
		
	if (height == undefined)
		height = "300";
	
	return new tinymce.Editor('html', {
		mode					: "textareas",
		theme					: "advanced",
		plugins					: "safari,style,inlinepopups,paste,media",
		width					: width,
		height					: height,
		theme_advanced_font_sizes: "10px,12px,13px,14px,16px,18px,20px",
		font_size_style_values	: "10px,12px,13px,14px,16px,18px,20px",
		theme_advanced_buttons1 : "bold,italic,underline,pasteword,forecolor,bullist,numlist,justifyleft,justifycenter,justifyright,link,unlink,image,media,removeformat,code",
		theme_advanced_buttons2 : "formatselect,styleselect,fontsizeselect",
		theme_advanced_blockformats : "p,h1,h2,h3,h4,div,blockquote",
		theme_advanced_styles 	: "Testimonial Author=author;Testimonial=testimonial",
		content_css				: "templates/default/styles/index.css",
		theme_advanced_buttons3 : false,
		relative_urls			: false,
		remove_script_host		: true,
		document_base_url		: protocol+window.location.hostname+"/",
		paste_remove_spans		: true,
		paste_remove_styles		: true,
		fix_table_elements		: true,
		file_browser_callback	: "tinyBrowser",
		extended_valid_elements	: "iframe[*],script[type|lang]"
	});
}

//!
function editContent() {
	jQuery.post(protocol + window.location.hostname + "/ajax.html", {alias:jQuery('#alias').val(), html:escape(ed.getContent()), token:jQuery('#editContentToken').val()},
		function(result) {
			jQuery('#mainAdminControl').html(result);
		}
	);
}

//!
function addModuleContent() {	
	if( (result = ajaxCall("html="+escape(ed.getContent())+"&alias="+jQuery('#alias').val()+'&token='+jQuery('#addContentToken').val())) == 1) {
		windowCancel(true);
	} else {
		jQuery('#mainAdminControl').html(result);
	}
}

//!
function editModuleContent() {
	if( (result = ajaxCall("i="+jQuery('#i').val()+'&token='+jQuery('#editModContentToken').val())) == 1) {
		windowCancel(true);
	} else {
		jQuery('#mainAdminControl').html(result);
	}
}

function editRegionModule() {
	var posts = '';
	jQuery('.attributeField').each(function(i) {
		posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();
	});
	
	loadModule("module="+jQuery('#module').val()+"&publish_date="+jQuery('#publish_date').val()+"&expiration_date="+jQuery('#expiration_date').val()+"&readAccess="+jQuery('#readAccess').val()+"&writeAccess="+jQuery('#writeAccess').val()+"&token="+jQuery('#editRegionModToken').val()+posts);
}

function editRegionModuleAttrs() {
	var posts = '';
	jQuery('.attributeField').each(function(i) {
		posts += "&" + jQuery(this).attr('name') + "=" + jQuery(this).val();
	});
	
	loadModule("token="+jQuery('#editRegionModAttrsToken').val()+posts);
}

function getGroupPages(access) {
	var groupPages = "";
	var first = true;
	
	if(access == 'read') {
		groupPages = getGroupPages('master');
		first = false;
	}
	
	jQuery('.page_'+access).each(function(i) {
		if(jQuery(this).attr('checked') && (groupPages.indexOf(','+jQuery(this).val()+',') == -1 || groupPages.indexOf(jQuery(this).val()+',') != 0 || groupPages.indexOf(','+jQuery(this).val()+',') == groupPages.indexOf(','+jQuery(this).val()+',') != (groupPages.length()-1))) {
			if(!first) {
				groupPages += ",";
			}
			groupPages += jQuery(this).val();
			first = false;
		}
	});
	
	return groupPages;
}


function editGroup() {
	loadModule("rpages="+getGroupPages('read')+"&wpages="+getGroupPages('write')+"&name="+jQuery('#name').val()+"&level="+jQuery('#level').val()+"&token="+jQuery('#adminGroupToken').val());
}

function editItemPages() {
	var itemPages = "";
	var first = true;
	
	jQuery('.pages').each(function(i) {
		if(jQuery(this).attr('checked')) {
			if(!first) {
				itemPages += ",";
			}
			itemPages += jQuery(this).val();
			first = false;
		}
	});

	var posts = "p="+itemPages+"&token="+jQuery('#adminPageItemToken').val();
	loadModule(posts);
}

/////////////////////////////////////
//******* DELETE FUNCTIONS ********//
/////////////////////////////////////

//!
function confirmDelete(posts) {
	if((result = ajaxCall(posts)) == 1) {
		window.location.reload();
	} else {
		reportError(result);	
	}
}

function deleteTemplate(template,userPrompt) {
	if(userPrompt) {
		var data = ajaxCall('tpl='+template+'&confirm=1');
		jQuery('#report').html(data);
		jQuery('#report').show();
	} else {
		jQuery('#report').hide();
		jQuery('#report').html('');
		if( (result = ajaxCall('tpl='+template+'&confirm=0')) && result == "success") {
			loadModule('');
		} else {
			reportError(result);
		}
	}
}


/////////////////////////////////////
//********* GET FUNCTIONS *********//
/////////////////////////////////////

function toggleChildMenu(show) {
	if(show == 'true') {
		$('#parent').show();
		if($('#menus').val() != '') {
			$('#link_parent').show();
		}
	} else {
		$('#menus').val('');
		$('#menu_link').val('');
		$('#parent').hide();
		$('#link_parent').hide();
	}
}

function getMenuLinkList(token, id) {
	$($("#menu_link").children()).remove();
	var data = ajaxCall(token+"&menuID="+id);
	if(data.substring(0,7) == '<option') {
		$('#menu_link').append(data);
	} else {
		reportPageError();
	}
}

//!
function moveItem(token) {
	if((result = ajaxCall(token)) == 1) {
		window.location.reload(true);
	} else {
		reportError(result);	
	}
}

function getModuleAttributes(module,token) {
	jQuery('#moduleAttributes').html(ajaxCall("module="+module+"&token="+token));
}

function popUp(action) {
	switch(action) {
		case 'pageName' :
			msg = "The page name is the URL friendly name that will appear in the address bar of the user when accessing this page. -- ex. http://www.mydomain.com/page_name";
		break;
		
		case 'pageAlias' :
			msg = "The page alias is the full name you would like to give the page. Often times our sites reference the page alias as the headline for the page. Please check with our webmaster to see if this is the case for your website.";
		break;
		
		case 'pageTitle' :
			msg = "The page title appears at the very top of the browser window. The page title is very critical in Search Engine Optimization. If you are paying for Search Engine Optimization (SEO), please consult our webmaster or SEO consultant before changing the titles of any page.";
		break;
		
		case 'alias' :
			msg = "An alias is just a quick name given to an entry so you can reference it later on when editing it or applying the entry to pages";
		break;
		
		case 'analyticCode' :
			msg = "The analytic code is the tracking code you receive from your stat tracking company. Some popular ones are Google, Yahoo and Quancast. Simply paste in the code you receive from the vendors.";
		break;
		
		case 'contentHTML' :
			msg = "This field will contain a snippet of content. You may paste or type in text or insert an image via the toolbar at the bottom.";
		break;
		
		case 'groupLevel' :
			msg = "The group level, a number up to 999, assigns a hierarchy to user groups. User groups with a low group level can only be edited by a group with a higher number. More than one group may have the same number.\r\n \r\nLet's say we have 4 groups of employees -- marketing, which has a group level of 1, sales also with a group level of 1, management level 2 and executive level 3. Marketing and Sales can only see their own group's information because they have the lowest group level and they share the same group level. Management can change marketing and sales permissions since their level is higher than both of those groups. And of course, the executive group, with the highest group level at level 3, can manage all three groups.";
		break;
		
		case 'metaName' :
			msg = "This drop list provides you with the most common valid meta tag names. If you don't see an option you need, let us know and we'll add it to the list.";
		break;
		
		case 'metaContent' :
			msg = "This field should have the value of the content attribute.\r\n\r\n<meta name=\"keyword\" content=\"{CODE TO PASTE INTO THE CONTENT FIELD}\" />";
		break;
		
		case 'scriptLang' :
			msg = "The script language supplies the script tag with the value for the language attribute. E.g., JavaScript 1.0";
		break;
		
		case 'scriptSrc' :
			msg = "The src is where the file resides relative to the scripts directory. Your file must exist on the server before adding the script to the database.";
		break;
		
		case 'scriptType' :
			msg = "Script type supplies the script tag with the value for the type attribute. E.g., text/javascript";
		break;
		
		case 'regionModule':
			msg = "This list displays all modules that have been added to the website. Select one to insert an instance of the selected module into the region slot.";
		break;
		
		case 'pubDate':
			msg = "The publish date determines when a module instance will appear in its assigned region slot.";
		break;
		
		case 'expDate':
			msg = "The expiration date determines when a module instance will disappear from its assigned region slot. Module instances may also expire in a region if another module instance with a later publish date is added.";
		break;
		
		case 'groupAccess':
			msg = "Group access limits the ability for certain user groups to view a module instance. If you don't know how this item is used, we suggest you leave it as is for now. We're currently working on improving the usability of this feature in the future.";
		break;
	}	
	
	alert(msg);
}
