// JavaScript Document
////////////////////////////////////////////////////////////////////////////////////////
///Quired QGS v 1.1.022////////////////////////////////////////////////////////////////
///functions.js///////////////////////////////////////////////////////////////////////
///written by Tim McLain on 12/16/08/////////////////////////////////////////////////
///modified by Tim McLain on 04/06/10///////////////////////////////////////////////
///previous version: v1-1-018//////////////////////////////////////////////////////
///This script declares functions for the different javascript procedures/////////
///that will be used by the QGS./////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//set some universal variables for use with the system
var browserCodeName=navigator.appCodeName;
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
var ajax_div = 'content_div';
var ajax_div_2 = 'dashboard_image_div';
var expanded_link = "";
var active_login_box_button = "login_box_follow_div";
//create the request object
var http = f_create_request_object();
var http2 = f_create_request_object();
var ajax_div_2 = 'dashboard_image_div';
//function for centering the site in the user's browser
function f_position_copyright(){
	//push the copyright div underneath the main div
	//if it exists
	if(document.getElementById('copyright_div')){
		var content_div = document.getElementById('main_content_div');
		var content_height = content_div.offsetHeight;
		var cp_div = document.getElementById('copyright_div');
		//get the style sheets
		var top=0;
		if(typeof document.styleSheets != "undefined"){
			var style_sheet = document.styleSheets[0];
			var my_rules = null;
			if(typeof style_sheet.rules != "undefined"){
				my_rules = style_sheet.rules;
			}else{
				my_rules = style_sheet.cssRules; 
			}
			
			//loop through rules
			if(my_rules != null){
				for(var i=0; i<my_rules.length; i++)
				{
					if(my_rules[i].selectorText.toLowerCase() == '.main_content_div'){
						var my_split = my_rules[i].style.top.split("px");
						top = parseFloat(my_split[0]);
					}
				}
			}
		}
		cp_div.style.position = "absolute";
		var new_top = (content_height+top) + "px";
		if(new_top != cp_div.style.top){
			cp_div.style.top = new_top;
		}else{
			clearInterval(intervalID);
		}
	}
}

//function for getting the window width and height
function f_get_window_size(){
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
	myWidth = window.innerWidth;
	myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	//IE 6+ in 'standards compliant mode'
	myWidth = document.documentElement.clientWidth;
	myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	//IE 4 compatible
	myWidth = document.body.clientWidth;
	myHeight = document.body.clientHeight;
	}
	var sizes = new Array(myWidth, myHeight);
	return sizes;
}


//function for writing values to the content area
function f_write_check(element, value){
	document.getElementById(element).innerHTML += value;
}

//functions for creating an AJAX content change
function f_create_request_object(){
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	return request_o; //return the object
}

//send and receive ajax information
function f_get_ajax_response(url, sendVars, div){
		//set the div that the content should be written into
		if(div != "undefined"){
			ajax_div = div;
		}else{
			ajax_div = 'content_div';
		}
		//tell the request object to send all the information via post
		http.open('POST', url);
		//set the request header to send the information in a post friendly format
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//set the function that will be used to listen for the response
		http.onreadystatechange = f_load_content;
		//send the information over to the processing script
		http.send(sendVars);
}

//listen for the ajax response and do the appropriate action when it is received
function f_load_content(){
	if(http.readyState == 4){ //Finished loading the response
		//close the status box if it is open
		var response = http.responseText;
		//determine what to do based upon what type
		//of form has been loaded
		switch(ajax_div)
		{
			case 'summary_span':
				//create new textarea 
				var my_split = response.split("~~~~");
				var html = "Please insert the summary that you would like to appear above the list of child pages that will be seen by the user when this page is clicked.<br />";
				html += "<textarea id='summary' class='form_textarea'>"+my_split[0]+"</textarea>";
				html += "Please insert the headline for the summary list(generic headline will be generated if left blank):<br />";
				html += "<input id='summary_headline' name='summary_headline' class='form_textfield' value='"+my_split[1]+"' /><br />";
				html += "Please insert the meta-title for the summary list(generic title will be generated if left blank):<br />";
				html += "<input id='summary_title' name='summary_title' class='form_textfield' value='"+my_split[2]+"'><br />";
				html += "Please insert the meta-description for the summary list(generic description will be generated if left blank):<br />";
				html += "<textarea id='summary_description' class='form_textarea'>"+my_split[3]+"</textarea><br />";
				html += "Please insert the keywords for the summary list(generic keywords will be generated if left blank):<br />";
				html += "<textarea id='summary_keywords' class='form_textarea'>"+my_split[4]+"</textarea><br />";
				response = html;
				break;
			default:
				break;
		}
		if(response == "session-cache-cleared"){
			f_reload_menu();
			f_draw_dashboard_image();			
		}else{
			document.getElementById(ajax_div).innerHTML = response;
		}
		if(ajax_div != "post_comment_div" && ajax_div != "summary_span"){
			window.scrollTo(0, 0);
		}
	}
}	

//listen for the ajax response and do the appropriate action when it is received
function f_load_content_2(){
	if(http2.readyState == 4){ //Finished loading the response
		var response = http2.responseText;
		document.getElementById(ajax_div_2).innerHTML = response;
	}
}

//listen for the ajax response and do the appropriate action when it is received
function f_load_content_3(){
	if(http.readyState == 4){ //Finished loading the response
		var response = http.responseText;
		var element = document.getElementById(ajax_div);
		f_add_error_message(element, response);
	}
}

//check to see if a field value is available
function f_check_exists(field,type,cur_val){
	
	//remove any error spans that are already there
	var errorSpans = document.getElementsByTagName("span");
	for(var e=(errorSpans.length-1); e >= 0; e--){
		var spanClass = errorSpans[e].className;
		var spanArray = spanClass.split(" ");
		spanClass = spanArray[0];
		var spanParent = errorSpans[e].parentNode;
		var spanPattern = /^form_error_message_text$/;
		if(spanPattern.test(spanClass)){
			spanParent.removeChild(errorSpans[e]);	
		}
	}
	 
	//remove the error br tags
	var errorBrs = document.getElementsByTagName("br");
	for(var e=(errorBrs.length-1); e >= 0; e--){
		var brClass = errorBrs[e].className;
		var brParent = errorBrs[e].parentNode;
		var brPattern = /^.*error_br.*$/;
		if(brPattern.test(brClass)){
			brParent.removeChild(errorBrs[e]);
		}
	}
	
	
	var element;
	var message;
	var pass=false;
	var hold=false;
	var hold_words = new Array("privacy-policy","profile","tips","agreement","summary","blog","followers","service","product","event","individual","business","group","form");
	//get the element
	if(document.getElementById(field)){
		element = document.getElementById(field);
		//is the value the same as the cur_value
		if(element.value == cur_val){
			message = "The value has not been changed from it's current setting. So it is available.";
			f_add_error_message(element, message);
		}else{
			//check to make sure that the 
			//input passes the validation
			var elements = new Array();
			elements[0] = element;
			pass = f_validate_form(elements);
			//check to make sure that the value
			if(pass){
				for(var i=0; i<hold_words.length; i++)
				{
					if(element.value == hold_words[i]){
						hold = true;
						break;
					}
				}
				if(hold != true){
					var url = "/PHP/process/p_check_exists.php";
					var sendVars = "field="+type+"&value="+element.value;
					//set the div that the content should be written into
					ajax_div = field;
					//tell the request object to send all the information via post
					http.open('POST', url);
					//set the request header to send the information in a post friendly format
					http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					//set the function that will be used to listen for the response
					http.onreadystatechange = f_load_content_3;
					//send the information over to the processing script
					http.send(sendVars);
				}else{
					message = "The word you have entered cannot be used because it has been reserved by the system to reference another page.";
					f_add_error_message(element, message);
				}
			}
		}
	}else{
		message = "There was an error finding the element that you are checking the availability for.";
		f_add_error_message("content_div", message);
	}
	
}

//validate the elements of a form
function f_validate_form(elements){
	
	//remove any error spans that are already there
	var errorSpans = document.getElementsByTagName("span");
	for(var e=(errorSpans.length-1); e >= 0; e--){
		var spanClass = errorSpans[e].className;
		var spanArray = spanClass.split(" ");
		spanClass = spanArray[0];
		var spanParent = errorSpans[e].parentNode;
		var spanPattern = /^form_error_message_text$/;
		if(spanPattern.test(spanClass)){
			spanParent.removeChild(errorSpans[e]);	
		}
	}
	 
	//remove the error br tags
	var errorBrs = document.getElementsByTagName("br");
	for(var e=(errorBrs.length-1); e >= 0; e--){
		var brClass = errorBrs[e].className;
		var brParent = errorBrs[e].parentNode;
		var brPattern = /^.*error_br.*$/;
		if(brPattern.test(brClass)){
			brParent.removeChild(errorBrs[e]);
		}
	}
	
	var pass = true;
	//var elementStr;
	for(var i=0; i < elements.length; i++){
		if(elements[i].id != undefined){
			//pull the className from the element to determine what type of validation to use
			var useElementArray = elements[i].className.split(" ");
			var useElement = useElementArray[0];
			var required = false;
			var maxlength;
			var minlength;
			var elementlength = elements[i].value.length;
			var message;
			var requiredPattern = /^.*required.*$/;
			if(requiredPattern.test(elements[i].className)){
				var required = true;
			}
			var pattern = "";
			//use a switch to determine what type of 
			switch(useElement){
				case "duration":
					pattern = /^(\d+:)?(\d+:)?(\d+)$/;
					message = "This field must only contain a valid timecode duration: (ex 1:20:30 for 1hour 20mins and 30secs or 22:30 for 22mins and 30secs)";
					break;
				case "USD":
				case "usd":
					//limit to only USD
					pattern = /^\$?([0-9]+)\.?([0-9][0-9])?$/;
					message = "This field must only contain a valid USD currency amount. (ex. 10.00, $10 or $10.00)"; 
					break;
				case "fullName":
					//limit to only letters
					pattern = /^([A-Z][A-Za-z]*) ([A-Za-z\.])? ?([A-Z][A-Za-z]+)$/;
					message = "This field must only contain a first and last name. (ex. John Doe or Jane M. Doe)"; 
					break;
				case "lettersSpaces":
					//limit to only letters
					pattern = /^[a-zA-Z\- ]+$/;
					message = "This field must only contain letters. "; 
					break;
				case "lettersOnly":
					//limit to only letters
					pattern = /^[a-zA-Z\-]+$/;
					message = "This field must only contain letters. "; 
					break;
				case "uppersOnly":
					//limit to only uppercase letters
					pattern = /^[A-Z\-]$/;
					message = "This field must only contain uppercase letters. "; 
					break;
				case "lowersOnly":
					//limit to only lowercase letters
					pattern = /^[a-z\-]$/;
					message = "This field must only contain lowercase letters. "; 
					break;
				case "lettersDigits":
					//limit to only letters and digits
					pattern = /^[a-zA-Z0-9\-]+$/;
					message = "This field must only contain letters and digits. "; 
					break;
				case "lettersDigitsSpaces":
					//limit to only letters and digits
					pattern = /^[a-zA-Z0-9\- ]+$/;
					message = "This field must only contain letters and digits. "; 
					break;
				case "digitsOnly":
					//limit to only digits
					pattern = /^[0-9]+$/;
					message = "This field must only contain digits. "; 
					break;
				case "email":
					//make sure that the email is a valid email
					pattern = /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/;
					message = "This field must contain a valid email (ex. name@domain.com). ";
					break;
				case "url":
					//make sure that the input is a valid url
					pattern = /^[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.?[A-Za-z0-9-_%&\?\/.=#]+$/;
					message = "This field must contain a valid url (ex. http://www.trigonstaff.com, http://domain.com, http://sub.domain.com). ";
					break;
				case "phone":
					//make sure that the input is a valid phone
					pattern = /^(\(?\d+\)? ?)-?(\d+[\- ])*\d+$/;
					message = "This field must contain a valid phone number (ex. (555)555-5555). ";
					break;
				case "security_input_text":
					//make sure that the input is a valid phone
					pattern = /^[A-Za-z]+$/;
					message = "This field must contain the code that you see in the image. ";
					break;
				default:
					break;
			}
			
			if(required || (elements[i].value != "" && elements[i].type != 'checkbox' && elements[i].type != 'hidden')){
				//test the pattern against the value to make sure that the input is valid
				if(pattern != "" && !pattern.test(elements[i].value)){
					pass = false;
					f_add_error_message(elements[i], message);
				}
				
				var split_ele = elements[i].id.split("_");
				var num = split_ele[split_ele.length-1];
				//test the length against the maximum length
				if(document.getElementById('maxlength_'+num)){
					maxlength = document.getElementById('maxlength_'+num).value;
					if(elementlength > maxlength){
						pass = false;
						message = "This field cannot contain more than "+ maxlength + " characters. ";
						f_add_error_message(elements[i], message);
					}
				}
				//test the length against the minimum length
				if(document.getElementById('minlength_'+num)){
					minlength = document.getElementById('minlength_'+num).value;
					if(elementlength < minlength){
						pass = false;
						message = "This field cannot contain less than "+ minlength + " characters.";
						f_add_error_message(elements[i], message);	
					}
				}
				
				//give error for check box not being checked
				if(elements[i].type == 'checkbox'){
					if(!elements[i].checked){
						pass = false;
						message = "This box must be checked to proceed!";
						f_add_error_message(elements[i], message);
					}
				}
			}
			//make sure that any required filed is filled out
			if(required && elementlength <= 0 && elements[i].type != "checkbox"){
				pass = false;
				message = "This field cannot be left blank.";
				f_add_error_message(elements[i], message);	
			}
		}
	}
	return pass;
}

//add error messages to a form
function f_add_error_message(element, message){
	element.focus();		
	var errorMessage = document.createTextNode(message);
	var parent = element.parentNode;
	var myMessage = document.createElement("span");
	var errorName = "error";
	var br = document.createElement("br");
	br.setAttribute("className", "");
	br.className = "error_br";
	myMessage.setAttribute("className", "");
	myMessage.setAttribute("id", errorName);
	myMessage.appendChild(errorMessage);
	myMessage.className = "form_error_message_text";
	parent.insertBefore(myMessage, element);
	parent.insertBefore(br, element);
}


//submit a form
function f_submit_form(form_name){
	var elements = document.forms[form_name].elements;
	var pass = f_validate_form(elements);
	var url;
	var div;
	if(pass){
		var sendVars = "";
		//loop through each element and build the sendVars
		for(var i=0; i < elements.length; i++){
			var my_encode = Url.encode(elements[i].value);
			if(elements[i].type != "checkbox" || form_name == 'upload_form'){
				if((elements[i].type != "checkbox") || (elements[i].type == 'checkbox' && elements[i].checked)){
					sendVars += elements[i].id+"="+my_encode+"&";
				}
			}else{
				sendVars += elements[i].id+"="+elements[i].checked+"&";
			}
		}
		
		switch(form_name){
			case 'start_following_box':
				url = "/PHP/process/p_special_form.php?type=start_following";
				div = 'login_box_content_div';
				break;
			case 'post_comment_form':
				url = "/PHP/process/p_special_form.php?type=post_comment";
				div = "post_comment_div";
				break;
			case 'update_profile_image':
				url = "/PHP/process/p_special_form.php?type=update_profile_image";
				div = "update_profile_image";
				sendVars += "&action=process";
				//add the value of the selected image
				for(var i=0; i<elements.length;i++)
				{
					if(elements[i].type == "checkbox" && elements[i].checked)
					{
						sendVars += "&image_id="+elements[i].value;
						break;
					}
				}
				break;
			case 'request_info_form_div':
			case 'request_info_form':
				url = "/PHP/process/p_special_form.php?type=request_info";
				div = "request_info_form_div";
				break;
			default:
				url = "/PHP/process/p_process_form.php";
				div = "content_div";
				break;
		}
				
		if(form_name != "upload_form"){
			f_get_ajax_response(url, sendVars, div);
		}
	}
	
}

//special processing for saving a draft
function f_save_draft(type){
	var form_name = "";
	switch(type)
	{
		case "edit":
			form_name= "edit_thread";
			break;
		case "add":
			form_name = "add_thread";
			break;
	}
	var elements = document.forms[form_name].elements;
	var pass = f_validate_form(elements);
	var url;
	var div;
	if(pass){
		var sendVars = "";
		//loop through each element and build the sendVars
		for(var i=0; i < elements.length; i++){
			var my_encode = Url.encode(elements[i].value);
			if(elements[i].type != "checkbox" || form_name == 'upload_form'){
				if((elements[i].type != "checkbox") || (elements[i].type == 'checkbox' && elements[i].checked)){
					sendVars += elements[i].id+"="+my_encode+"&";
				}
			}else{
				sendVars += elements[i].id+"="+elements[i].checked+"&";
			}
		}
		
		sendVars += "save_draft=1";
		
		url = "/PHP/process/p_process_form.php";
		div = "content_div";
		
		if(form_name != "upload_form"){
			f_get_ajax_response(url, sendVars, div);
		}
	}
	
}



//function for embedding the menu
function f_draw_menu(){
	//embed the menu with SWFobject	
	var menuURL = portal_url+'/flash/menu/sa_menu_qgs_v2-12.swf';
	var expressURL = portal_url+"/flash/expressInstall.swf";
	var menuDiv = "menu_div";
	
	var flashVars = {};
	flashVars.requestURL = portal_url;
	if(clicked_button != 0){
		flashVars.startClickedBtn = clicked_button;
	}
	var params = {};
	params.wmode = "transparent";
	params.menu = "false";
	params.allowfullscreen = "false";
	params.quality = "high";
	params.allowscriptaccess = "always";
	
	var attributes = {};
	attributes.id = "myMenu";
	
	//set some menu sizes based off the 
	var m_percent = 198/270;
	var m_width = 198;
	var m_height = Math.round(586*m_percent);
	//set the height and width of the menu
	if(menu_width != 198){
		percent = menu_width/198;
		menu_height = Math.round(m_height*percent);
	}else{
		menu_width = Math.round(m_width);
		menu_height = Math.round(m_height);
	}
	swfobject.embedSWF(menuURL, menuDiv, menu_width, menu_height, "10.0.0", expressURL, flashVars, params, attributes);
}

//function for embedding the menu
function f_draw_order_tool(){
	if(document.getElementById("order_tool_div")){
		//embed the menu with SWFobject	
		var toolURL = portal_url+'/flash/order_tool/order_tool_qgs_v1-0.swf';
		var expressURL = portal_url+"/flash/expressInstall.swf";
		var toolDiv = "order_tool_div";
		
		var flashVars = {};
		flashVars.portal_url = portal_url;
		flashVars.sc = sc;
		flashVars.table = table;
		flashVars.item_id = item_id;
		flashVars.modifier = modifier;
		var params = {};
		params.wmode = "opaque";
		params.menu = "false";
		params.allowfullscreen = "false";
		params.quality = "high";
		params.allowscriptaccess = "always";
		
		var attributes = {};
		attributes.id = "ordering_tool";
		
		swfobject.embedSWF(toolURL, toolDiv, 300, 500, "10.0.0", expressURL, flashVars, params, attributes);
	}
}

//function for embedding the menu
function f_draw_upload(){
	//embed the menu with SWFobject	
	var uploadURL = 'http://test.quired.com/flash/upload_tool/sa_upload_qgs_v1-0.swf';
	var expressURL = portal_url+"/flash/expressInstall.swf";
	var uploadDiv = "upload_div";
	
	var flashVars = {};
	flashVars.sc = sc;
	flashVars.ip = ip;
	flashVars.user_id = uid;
	flashVars.upload_type = upload_type;
	if(upload_type == "upload"){
		flashVars.my_profile = my_profile;
		flashVars.uploaded_by = uploaded_by;
	}else if(upload_type == "download"){
		flashVars.item_id = download_id;
		flashVars.download_type = download_type;
		flashVars.referer_address = referer_address;
		flashVars.browser = browser;
	}
	var params = {};
	params.menu = "false";
	params.allowfullscreen = "false";
	params.quality = "high";
	params.allowscriptaccess = "always";
	
	var attributes = {};
	attributes.id = "upload_tool";
	swfobject.embedSWF(uploadURL, uploadDiv, 350, 150, "10.0.0", expressURL, flashVars, params, attributes);
}



//function for embedding the menu
function f_draw_media_player(my_media_id){
	//embed the menu with SWFobject	
	var mediaURL = portal_url+'/flash/media_player/sa_media_player_qgs_v1-0.swf';
	var expressURL = portal_url+"/flash/expressInstall.swf";
	var mediaDiv = "media_holder_div";
	
	var flashVars = {};
	flashVars.requestID = my_media_id;
	flashVars.requestURL = portal_url;
	flashVars.aPlay = "autoPlay";
	
	var params = {};
	params.wmode = "opaque";
	params.menu = "false";
	params.allowfullscreen = "true";
	params.quality = "high";
	params.allowscriptaccess = "always";
	var attributes = {};
	attributes.id = "myMediaPlayer";
	
	//set the height and width of the player
	if(media_width != 298){
		percent = media_width/298;
		media_height = 192*percent;
	}else{
		media_width = 298;
		media_height = 192;
	}
	
	swfobject.embedSWF(mediaURL, mediaDiv, media_width, media_height, "10.0.0", expressURL, flashVars, params, attributes);
}

//function that loads the media information into the media_info div
function f_load_media_info(media_id){
	if(media_info){
		var url = "/PHP/process/p_get_media_items.php";
		var sendVars = "action=media_info&media_id="+media_id;
		//set the div that the content should be written into
		ajax_div = 'media_info_div';
		//tell the request object to send all the information via post
		http.open('POST', url);
		//set the request header to send the information in a post friendly format
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//set the function that will be used to listen for the response
		http.onreadystatechange = f_load_content;
		//send the information over to the processing script
		http.send(sendVars);
	}
}

function f_draw_media_selector(type, profile_id){
	if(!document.getElementById('media_selector_div')){
		var media_selector_div = document.createElement("div");
		media_selector_div.setAttribute("id", "media_selector_div");
		media_selector_div.className = "media_selector_div";
		document.getElementsByTagName("body")[0].appendChild(media_selector_div);
		
		//align the div
		var my_left = 10;
		var my_top = 5;
		
		media_selector_div.style.position = "absolute";
		media_selector_div.style.left = my_left+"px";
		media_selector_div.style.top = my_top+"px";
	}
	
	var url = "/PHP/process/p_get_media_items.php";
	
	var sendVars = "action=media_selector&type=";
	
	switch(type){
		case 'video':
			sendVars += "0";
			break;
		case 'audio':
			sendVars += "2";
			break;
		case 'photos':
			sendVars += "3";
			break;
		case 'all':
		default:
			sendVars += "all";
			break;
	}
	
	sendVars += "&profile_id="+profile_id;
	
	//set the div that the content should be written into
	ajax_div = 'media_selector_div';
	//tell the request object to send all the information via post
	http.open('POST', url);
	//set the request header to send the information in a post friendly format
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//set the function that will be used to listen for the response
	http.onreadystatechange = f_load_content;
	//send the information over to the processing script
	http.send(sendVars);
}

function f_draw_update_profile_image(profile_id,sc,ip){
	if(!document.getElementById('update_image_div')){
		var update_image_div = document.createElement("div");
		update_image_div.setAttribute("id", "update_image_div");
		update_image_div.className = "media_selector_div";
		document.getElementsByTagName("body")[0].appendChild(update_image_div);
		
		//align the div
		var my_left = 10;
		var my_top = 5;
		
		update_image_div.style.position = "absolute";
		update_image_div.style.left = my_left+"px";
		update_image_div.style.top = my_top+"px";
	}
	
	var url = "/PHP/process/p_special_form.php?type=update_profile_image";
	var sendVars = "action=draw_form";
	sendVars += "&profile_id="+profile_id;
	sendVars += "&sc="+sc+"&ip="+ip;
	//set the div that the content should be written into
	ajax_div = 'update_image_div';
	//tell the request object to send all the information via post
	http.open('POST', url);
	//set the request header to send the information in a post friendly format
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//set the function that will be used to listen for the response
	http.onreadystatechange = f_load_content;
	//send the information over to the processing script
	http.send(sendVars);
}

function f_update_media_player(my_media_id){
	var parent;
	if(document.getElementById("myMediaPlayer")){
		var swf = document.getElementById("myMediaPlayer");
		parent = swf.parentNode;
		parent.removeChild(swf);
	}
	
	if(document.getElementById('media_holder_div')){
		var div = document.getElementById('media_holder_div');
		parent = div.parentNode;
		parent.removeChild(div);
	}
	
	if(document.getElementById('media_player_div')){
		parent = document.getElementById('media_player_div');
	}else{
		parent = document.createElement("div");
		parent.setAttribute("id","media_player_div");
		parent.className = "media_player_div";
		var nest;
		if(document.getElementById("left_div"))
		{
			nest = document.getElementById("left_div");	
		}
		else if(document.getElementById("right_div"))
		{
			nest = document.getElementById("right_div");	
		}
		else if(document.getElementById("content_div"))
		{
			nest = document.getElementById("content_div");
		}
		else
		{
			nest = document.body;
		}
		nest.apendChild(parent);
	}
	
	var media_holder_div = document.createElement("div");
	media_holder_div.setAttribute("id", "media_holder_div");
	media_holder_div.className = "media_holder_div";

	
	parent.appendChild(media_holder_div);
	
	f_draw_media_player(my_media_id);
	
	
}

function f_draw_image(media_id){
	if(!document.getElementById('view_image_div')){
		var view_image_div = document.createElement("div");
		view_image_div.setAttribute("id", "view_image_div");
		view_image_div.className = "media_selector_div";
		document.getElementsByTagName("body")[0].appendChild(view_image_div);
		
		//align the div
		var my_left = 10;
		var my_top = 5;
		
		view_image_div.style.position = "absolute";
		view_image_div.style.left = my_left+"px";
		view_image_div.style.top = my_top+"px";
	}
	
	
	var url = "/PHP/process/p_get_media_items.php";
		
	var sendVars = "action=draw_image&media_id="+media_id;
	//set the div that the content should be written into
	ajax_div = 'view_image_div';
	//tell the request object to send all the information via post
	http.open('POST', url);
	//set the request header to send the information in a post friendly format
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//set the function that will be used to listen for the response
	http.onreadystatechange = f_load_content;
	//send the information over to the processing script
	http.send(sendVars);
}


/////////////////////////////////////////////
//Functions for attaching event listeners///
///////////////////////////////////////////

function f_attach_listeners(){
	if(document.getElementById("login_box_login_div")){
		var login_image = document.getElementById("login_box_login_div");
		f_attach_event_listener(login_image, "mouseover", f_rollover_button, false);
		f_attach_event_listener(login_image, "mouseout", f_rollover_button, false);
		f_attach_event_listener(login_image, "click", f_click_button, false);
	}
	if(document.getElementById("login_box_follow_div")){
		var follow_image = document.getElementById("login_box_follow_div");
		f_attach_event_listener(follow_image, "mouseover", f_rollover_button, false);
		f_attach_event_listener(follow_image, "mouseout", f_rollover_button, false);
		f_attach_event_listener(follow_image, "click", f_click_button, false);
	}
	if(document.getElementById("follow_checkbox")){
		var checkbox = document.getElementById("follow_checkbox");
		f_attach_event_listener(checkbox, "change", f_check_follow, false);
	}
}


function f_attach_event_listener(target, eventType, functionRef, capture){
	if(typeof target.addEventListener != "undefined")
	{
		target.addEventListener(eventType, functionRef, capture);
	}
	else if(typeof target.attachEvent != "undefined")
	{
		target.attachEvent("on"+eventType, functionRef);
	}
	else
	{
		eventType = "on" + eventType;
		if(typeof target[eventType] == "function")
		{
			var oldListener = target[eventType];
			
			target[eventType] = function()
			{
				oldListener();
				return functionRef();
			};
		}
		else
		{
			target[eventType] = functionRef;
		}
	}
}

function f_detach_event_listener(target, eventType, functionRef, capture){
	if(typeof target.removeEventListener != "undefined"){
		target.removeEventListener(eventType, functionRef, capture);
	}else if(typeof target.detachEvent != "undefined"){
		target.detachEvent("on"+eventType, functionRef);
	}else{
		target["on" + eventType] = null;
	}
}

function f_get_event_target(event){
	var targetElement = null;
	if(typeof event.target != "undefined"){
		targetElement = event.target;
	}else{
		targetElement = event.srcElement;
	}
	
	while(targetElement.nodeType == 3 && targetElement.parentNode != null){
		targetElement = targetElement.parentNode;
	}
	
	return targetElement;
}

function f_stop_event(event){
	if(typeof event.stopPropagation != "undefined"){
		event.stopPropagation();
	}else{
		event.cancelBubble = true;
	}
}


//////////////////////////////////////////////
///event functions///////////////////////////
////////////////////////////////////////////
function f_rollover_button(event){
	if(typeof event == "undefined"){
		event = window.event;
	}
	var target = f_get_event_target(event);
	if(target.id != active_login_box_button){
		//get the className of the target
		var pattern = /_inactive/g;
		
		var class_name = target.className;
		var my_class;
		if(pattern.test(class_name)){
			my_class = class_name.replace(pattern, "");
		}else{
			my_class = class_name+"_inactive";
		}
		target.className = my_class;
	}
}

function f_click_button(event){
	if(typeof event == "undefined"){
		event = window.event;
	}
	var target = f_get_event_target(event);
	if(target.id != active_login_box_button){
		var current_active = document.getElementById(active_login_box_button);
		current_active.className += "_inactive";
		
		//get the className of the target
		var pattern = /_inactive/g;
		
		var class_name = target.className;
		var my_class = class_name.replace(pattern, "");
		target.className = my_class;
		
		active_login_box_button = target.id;
		f_change_login_box_content(target);
	}
}

function f_check_follow(event){
	if(typeof event == "undefined"){
		event = window.event;
	}
	var target = f_get_event_target(event);
	
	if(target.checked == true){
		if(!document.getElementById("agreement_span")){
			var span = document.createElement("span");
			span.setAttribute("id", "agreement_span"); 
			var html = "<br /><span class='form_link'><a href='http://newdeal1-0.quired.com/agreement'>Read Our Terms of Agreement</a></span><br /><input id='agreement' name='agreement' type='checkbox' class='agreement required text_class' />&nbsp;I have read and agree to the terms of agreement";
			span.innerHTML = html;
			var code = document.getElementById("code");
			var parent = code.parentNode;
			parent.insertBefore(span, code.nextSibling);
		}
	}else{
		if(document.getElementById("agreement_span")){
			var span = document.getElementById("agreement_span");
			var parent = span.parentNode;
			parent.removeChild(span);
		}
	}
}

function f_change_login_box_content(target){
	var html = "";
	switch(target.id)
	{
		case 'login_box_follow_div':
			if(is_following){
				html += "<span class='module_small_text'>";
				html += "You are currently a follower of this website.";
				html += "</span>";
				html += "<form style='margin-top:5px;' action='"+portal_url+"/form/follow/stop' method='POST' target='_self'><input type='submit' value='STOP FOLLOWING' name='submit' /></form>";
			}else{
				html += "<span class='module_small_text'>";
				html += "<form name='start_following' id='start_following' method='POST' action='Javascript:f_submit_form(\"start_following\");' ><table class='form_table'><tr><td><span class='module_small_text'>Enter your email address here to recieve regular updates from this website:</span><br /><input type='text' name='email' id='email' class='email required form_textfield' value='' /><input type='hidden' value='1' id='sent' name='sent' /></td></tr><tr><td><input type='submit' value='Submit' name='submit' /></td></tr></table></form>";
				html += "</span>";
			}
			break;
		case 'login_box_login_div':
			if(logged_in){
				html += "<span class='module_small_text'>";
				html += "You are currently logged in.";
				html += "</span>";
				html += "<form style='margin-top:5px;' action='"+portal_url+"/logout' method='POST' target='_self'><input type='submit' value='LOGOUT' name='submit' /></form>";
			}else{
				html += "<span class='module_small_text'>";
				html += "<form name='login_form' id='login_form' method='POST' action='/PHP/process/p_login.php' ><table class='form_table'><tr><td><span class='form_error_message_text'>*&nbsp;</span><span class='module_small_text'>Enter your username or email here:</span><br /><input type='text' name='value_0' id='value_0' class='lettersDigits required form_textfield' value='' /><input type='hidden' value='username' id='field_0' name='field_0' /><input type='hidden' id='maxlength_0' name='maxlength_0' value='25' /><input type='hidden' id='minlength_0' name='minlength_0' value='0' /><input type='hidden' id='table_0' name='_0' value='users' /></td></tr><tr><td><span class='form_error_message_text'>*&nbsp;</span><span class='module_small_text'>Enter your password here:</span><br /><input type='password' name='value_1' id='value_1' class='lettersDigits required form_textfield' value='' /><input type='hidden' value='password' id='field_1' name='field_1' /><input type='hidden' id='maxlength_1' name='maxlength_1' value='25' /><input type='hidden' id='minlength_1' name='minlength_1' value='0' /><input type='hidden' id='table_1' name='_1' value='users' /></td></tr><input type='hidden' name='db_table_0' id='db_table_0' value='users' />	<tr><td><span class='module_small_text'></span><input type='hidden' name='form_name' id='form_name' value='login_form' /><input type='submit' value='Submit' name='submit' /></td></tr></table></form><span class='form_link'><a href='/form/follow/start'>Create An Account</a>  |  <a href='/form/forgot_password'>Forgot Password?</a></span>";
				html += "</span>";
			}
			break;
	}
	
	document.getElementById('login_box_content_div').innerHTML = html;
}

function f_show_tool_tip(btnTitle){
	var menuDiv = document.getElementById('menu_div');
	tipText = btnTitle;
	f_attach_event_listener(menuDiv, 'mousemove', f_show_tool_tip_div, false);
}

function f_hide_tool_tip(){
	var menuDiv = document.getElementById('menu_div');
	f_detach_event_listener(menuDiv, 'mousemove', f_show_tool_tip_div, false);
	
	var myDivs = document.getElementsByTagName("div");
	for(var i=0; i < myDivs.length; i++){
		var curDiv = myDivs[i];
		var relAttr = curDiv.className;
		if(relAttr == "toolTip"){
			var parentNode = curDiv.parentNode;
			parentNode.removeChild(curDiv);	
		}
	}
}

function f_show_tool_tip_div(event){
	if(!document.getElementById('toolTip')){
		var tip = document.createElement("div");
		tip.setAttribute("id", "toolTip");
		tip.className = "tool_tip";
		tip.innerHTML = "<span class='contentText'>"+tipText+"</span>";
		
		var scrollingPosition = f_get_scrolling_position();
	
		var cursorPosition = [0, 0];
		if(typeof event.pageX != "undefined" && typeof event.x != "undefined"){
			cursorPosition[0] = event.pageX;
			cursorPosition[1] = event.pageY;
		}else{
			cursorPosition[0] = event.clientX + scrollingPosition[0];
			cursorPosition[1] = event.clientY + scrollingPosition[1];
		}
		
		tip.style.position = "absolute";
		tip.style.left = cursorPosition[0] + 10 + "px";
		tip.style.top =  cursorPosition[1] + 10 + "px";
		document.getElementsByTagName("body")[0].appendChild(tip);
	}else{
		hideToolTip();
		var tip = document.createElement("div");
		tip.setAttribute("id", "toolTip");
		tip.className = "toolTip";
		tip.innerHTML = "<span class='contentText'>"+tipText+"</span>";
		
		var scrollingPosition = f_get_scrolling_position();
	
		var cursorPosition = [0, 0];
		if(typeof event.pageX != "undefined" && typeof event.x != "undefined"){
			cursorPosition[0] = event.pageX;
			cursorPosition[1] = event.pageY;
		}else{
			cursorPosition[0] = event.clientX + scrollingPosition[0];
			cursorPosition[1] = event.clientY + scrollingPosition[1];
		}
		
		tip.style.position = "absolute";
		tip.style.left = cursorPosition[0] + 10 + "px";
		tip.style.top =  cursorPosition[1] + 10 + "px";
		document.getElementsByTagName("body")[0].appendChild(tip);
	}
}

function f_get_scrolling_position(){
	var position = [0, 0];
	
	if(typeof window.pageYOffset != 'undefined'){
		position = [window.pageXOffset,
					window.pageYOffset];
	}else if(typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0 || document.documentElement.scrollLeft > 0){
		position = [
					document.documentElement.scrollLeft,
					document.documentElement.scrollTop
					];
	}else if(typeof document.body.scrollTop != 'undefined'){
		position = [
					document.body.scrollLeft,
					document.body.scrollTop
					];
	}
	
	return position;
}


function f_close_div(div_id){
	var div = document.getElementById(div_id);
	var parent = div.parentNode;
	parent.removeChild(div);
}

/////////////////////////////////////////////////////////////////////
///functions for updating or addding UI Elements////////////////////
///////////////////////////////////////////////////////////////////

function f_draw_dashboard_image(){
	var width = "200";
	//make sure that the styleSheet 
	//DOM element is available
	if(typeof document.styleSheets != "undefined"){
		//loop through each styleSheet
		for(var i=0; i < document.styleSheets.length; i++)
		{
			//pull the rules for each
			//stylesheet
			var rules;
			var break_out = false;
			if(typeof document.styleSheets[i].rules != "undefined"){
				rules = document.styleSheets[i].rules;
			}else{
				rules = document.styleSheets[i].cssRules;
			}
			
			if(rules.length > 0){
				//look through the rules for
				//the left_div rule
				for(var b=0; b < rules.length; b++)
				{
					if(rules[b].selectorText != "undefined" && typeof rules[b].selectorText != "undefined"){
						if(rules[b].selectorText.toLowerCase() == '.login_image_div')
						{
							width = rules[b].style.width;
							if((width=="")||(width==0))
							{
								width="200";
							}
							break_out = true;
							break;
						}
					}
				}
			}
			//stop the loop
			//if the width
			//was found
			if(break_out){
				break;
			}
		}
	}
	
	//remove the px suffix
	//from the width
	var pattern = /px/g;
	width = width.replace(pattern, "");
	
	//check to see if the image div exists
	//and create it if not
	var use_class="";
	if(!document.getElementById('dashboard_image_div')){
		var my_div = document.createElement("div");
		my_div.setAttribute("id", "dashboard_image_div");
		my_div.className = "dashboard_image_div";
		//append the new div above the menu div
		var menu_div;
		if(document.getElementById('menu_div')){
			menu_div = document.getElementById('menu_div');
		}else{
			menu_div = document.getElementById('myMenu');
		}
		//get the parent
		var parent = menu_div.parentNode;
		//insert the new div
		parent.insertBefore(my_div, menu_div);
	}else{
		var my_div = document.getElementById('dashboard_image_div');
		var classes = my_div.className.split(" ");
		use_class=classes[1];
	}
	//use AJAX to pull the HTML for the image
	//and to place it inside the div
	var url = "/PHP/process/p_dashboard_image.php";
		
	var sendVars = "&width="+width+"&ids="+use_class;
	//set the div that the content should be written into
	ajax_div_2 = 'dashboard_image_div';
	//tell the request object to send all the information via post
	http2.open('POST', url);
	//set the request header to send the information in a post friendly format
	http2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//set the function that will be used to listen for the response
	http2.onreadystatechange = f_load_content_2;
	//send the information over to the processing script
	http2.send(sendVars);
	
}


////////////////////////////////////////////////////////////////////
/////functions for expanding and collapsing link options///////////
//////////////////////////////////////////////////////////////////

//listen for the ajax response and do the appropriate action when it is received
function f_parse_links(){
	if(http.readyState == 4){ //Finished loading the response
		var response = http.responseText;
		element = document.getElementById(expanded_link);
		//determine whther or not a special case 
		//link has been clicked
		var hold_links = new Array();
		var pattern;
		var url;
		//split the response at the delimiter
		var split_up = response.split("~~");
		var links = new Array();
		for(var i in split_up)
		{
			var split_split = split_up[i].split("|");
			
			links[i] = new Array();
			links[i]['title'] = split_split[0];
			links[i]['link'] = split_split[1];
			
		}
		
		for(var i in links)
		{
			//get the parent node of the original
			//element
			var parent = element.parentNode;
			
			//create a break node
			var new_br = document.createElement("br");
			new_br.setAttribute("className","db_expanded_link");
			new_br.className = "db_expanded_link";
			parent.insertBefore(new_br, element.nextSibling);
			//set the element variable to the last
			//added <br />
			element = new_br;
			
			//setup a variable for the link
			pattern = /^Javascript:.+$/;
			if(pattern.test(links[i]['link'])){
				url = links[i]['link'];
			}else{
				url = portal_url + links[i]['link'];
			}
			
			//create the new anchor element
			var new_link = document.createElement('a');
			var href = document.createAttribute('href');
			new_link.setAttribute("href", url);
			new_link.setAttribute("className", "");
			new_link.className = "db_expanded_link";
			new_link.innerHTML += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+links[i]['title'];
			//insert the new element
			parent.insertBefore(new_link, element.nextSibling);
			//set the element variable to the last
			//added anchor
			element = new_link;
		}
	}
}


//expand a link
function f_expand_link(id, parent_id, item_id){
	//define an array to hold the links that
	//should be parented underneath the main
	//link
	var links = new Array();
	var element;
	if(document.getElementById(id)){
		element = document.getElementById(id);
		//collapse any expanded links
		f_collapse_links(element);
		if(expanded_link != id){
			expanded_link = id;
			//use ajax to get the appropriate information
			var url = "/PHP/process/p_link_options.php";
			//tell the request object to send all the information via post
			http.open('POST', url);
			//set the request header to send the information in a post friendly format
			http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			//set the function that will be used to listen for the response
			http.onreadystatechange = f_parse_links;
			//create the sendVars variable
			var sendVars = "parent_id="+parent_id+"&item_id="+item_id;
			//send the information over to the processing script
			http.send(sendVars);
		}else{
			expanded_link = "";
		}
	}
}

//collapse a link
function f_collapse_links(element){
	
	var links = document.getElementsByTagName("a");
	var pattern = /^.*db_expanded_link.*$/;
	if(links.length > 0){
		for(var i=links.length-1; i >= 0 ; i--)
		{
			if(pattern.test(links[i].className))
			{
				var parent = links[i].parentNode;
				parent.removeChild(links[i]);
			}
		}
	}
	
	var brs = document.getElementsByTagName("br");
	if(brs.length > 0){
		for(var i=brs.length-1; i >=0; i--)
		{
			if(pattern.test(brs[i].className))
			{
				var parent = brs[i].parentNode;
				parent.removeChild(brs[i]);
			}
		}
	}
}

//update a form when an item changes
function f_mod_form(params){
	table = params[0];
	//what form are we dealing with
	switch(table)
	{
		case 'page_categories':
			var parent;
			var summary;
			var summary_exists = false;
			//see if the summary is present
			if(document.getElementById('summary')){
				summary_exists = true;
			}
			if(document.getElementById('field_3')){
				if(document.getElementById('field_3').value == "summary"){
					summary_exists = true;
				}
			}
			//check to see if the element is already there
			if(summary_exists){
				if(!document.getElementById("value_2_array[]").checked){
					//remove any summary elements that were added by Javascript
					if(document.getElementById('summary_span')){
						summary = document.getElementById('summary_span');
						parent = summary.parentNode;
						parent.removeChild(summary);
					}
					
					//remove any summary elements that were added by PHP
					for(var i=2; i<=6; i++)
					{
						if(document.getElementById('row_'+i)){
							summary = document.getElementById('row_'+i);
							parent = summary.parentNode;
							parent.removeChild(summary);
						}
					}
				}
			}else{
				if(document.getElementById("value_2_array[]").checked){
					//get the elements
					var insert_element = document.getElementById('submit');
					//create a span to hold 
					var span = document.createElement("div");
					span.id = "summary_span";
					parent = insert_element.parentNode;
					if(parent.insertBefore(span, insert_element)){
						ajax_div = "summary_span";
						//use ajax to get the appropriate information
						var url = "/PHP/process/p_form_js.php";
						//tell the request object to send all the information via post
						http.open('POST', url);
						//set the request header to send the information in a post friendly format
						http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						//set the function that will be used to listen for the response
						http.onreadystatechange = f_load_content;
						//create the sendVars variable
						var sendVars = "table="+table+"&type="+params[1]+"&item_id="+params[2];
						//send the information over to the processing script
						http.send(sendVars);
					}
				}
			}
			break;
		case 'profiles':
			var parent;
			var element;
			switch(params[1])
			{
				case "summary":
					if(document.getElementById("value_13_array[]")){
						element = document.getElementById("value_13_array[]");
						if(element.checked){
							if(!document.getElementById("summary_span")){
								var span = document.createElement("span");
								span.id = "summary_span";
								span.name = "summary_span";
								span.innerHTML = "<br />";
								parent = element.parentNode;
								if(parent.appendChild(span)){
									ajax_div = "summary_span";
									//use ajax to get the appropriate information
									var url = "/PHP/process/p_form_js.php";
									//tell the request object to send all the information via post
									http.open('POST', url);
									//set the request header to send the information in a post friendly format
									http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
									//set the function that will be used to listen for the response
									http.onreadystatechange = f_load_content;
									//create the sendVars variable
									var sendVars = "table="+table+"&type="+params[1]+"&item_id="+params[2];
									//send the information over to the processing script
									http.send(sendVars);
								}
							}
						}else{
							//remove the summary_content text field
							if(document.getElementById("summary_span")){
								element = document.getElementById("summary_span");
								parent = element.parentNode;
								parent.removeChild(element);
							}
						}
					}
					break;
				default:
					var price_exists=false;
					if(document.getElementById("price")){
						price_exists = true;
					}else if(document.getElementById("value_9")){
						element = document.getElementById("value_9");
						var my_class = element.className.split(" ");
						if(my_class[0] == "USD"){
							price_exists = true;
						}
					}
					//does the price element exist
					if(price_exists){
						//remove any elements that shouldn't be there
						if(!document.getElementById("value_8_array[]").checked){
							var elements = new Array('element_holder','price','tax','shipping','purchase_link','purchase_link_title','row_8','row_9','row_10','row_11','row_12');
							//loop through and remove each element
							for(var i=0; i < elements.length; i++)
							{
								if(document.getElementById(elements[i])){
									element = document.getElementById(elements[i]);
									parent = element.parentNode;
									parent.removeChild(element);
								}
							}
							
							var spans = document.getElementsByTagName("span");
							//remove those that are attached to the form elements
							for(i=spans.length-1; i >= 0; i--)
							{
								if(spans[i].className == "module_content_text"){
									switch(spans[i].innerHTML)
									{
										case "Price(USD):":
										case "Tax(USD):":
										case "Shipping(USD):":
										case "Link to external shopping cart (leave blank if you want a Paypal button to be created):":
										case "Text that will appear for the shopping cart link(leave blank if you want a Paypal button to be created):":
											parent = spans[i].parentNode;
											parent.removeChild(spans[i]);
											break;
									}
								}
							}
						}
					}else{
						if(document.getElementById("value_8_array[]").checked){
							var elements = new Array('price','tax','shipping','purchase_link','purchase_link_title');
							//loop through and build html for each
							var html = "";
							var my_class;
							var text;
							for(var i=0; i < elements.length; i++)
							{
								switch(elements[i])
								{
									case 'price':
										text = "Price(USD):";
										my_class = "class='USD form_textfield'";
										break;
									case 'tax':
										text = "Tax(USD):";
										my_class = "class='USD form_textfield'";
										break;
									case 'shipping':
										text = "Shipping(USD):";
										my_class = "class='USD form_textfield'";
										break;
									case 'purchase_link':
										text = "Link to external shopping cart (leave blank if you want a Paypal button to be created):";
										my_class = "class='url form_textfield'";
										break;
									case 'purchase_title_link':
										text = "Text that will appear for the shopping cart link(leave blank if you want a Paypal button to be created):";
										my_class = "class='lettersDigitsSpaces form_textfield'";
										break;
								}
								html += "<div style='margin-top:10px;'><span class='module_content_text'>"+text+"</span><br /><input type='text' "+my_class+" id="+elements[i]+" name="+elements[i]+" /></div>";
							}
							//get the sellable field
							var sellable = document.getElementById("value_8_array[]");
							parent = sellable.parentNode;
							var sibling = sellable.nextSibiling;
							var span = document.createElement("div");
							span.id = "element_holder";
							span.innerHTML = html;
							parent.insertBefore(span,sibling);
						}
					}
					break;
			}
			break;
	}
}

//annotation functions
function closeAnnotation(){
	/*
	if(document.getElementById("annotationDiv")){
		var annotationDiv = document.getElementById("annotationDiv");
		var parent = annotationDiv.parentNode;
		.media_selector_div {
			width: 640px;
			height: 480px;
			background-color:#FFFFFF;
			margin-top: 0px;
			margin-left: 6px;
			margin-bottom: 0px;
			margin-right: 0px;
			padding-top: 0px;
			padding-left: 0px;
			padding-bottom: 0px;
			padding-right: 0px;
			border: 1px solid #000000;
		}
	}
	*/
}

/*
function alignAnnotation(){
	var annotationDiv = document.getElementById("annotationDiv");
	
	var my_left;
	var my_top;
	
	if(browser == "Microsoft Internet Explorer"){
		my_left = (document.body.clientWidth/2)-(annotationDiv.style.width/2)-(300*scalePercent);
		my_top = (document.body.clientHeight/2)-(annotationDiv.style.height/2)-(100*scalePercent);
	}else{
		my_left = (window.innerWidth/2)-(annotationDiv.style.width/2)-(300*scalePercent);
		my_top = (window.innerHeight/2)-(annotationDiv.style.height/2)-(100*scalePercent);
	}
	annotationDiv.style.position = "absolute";
	annotationDiv.style.left = my_left+"px";
	annotationDiv.style.top = my_top+"px";
}

function getAnnotationContent(id){
		http4.open('get', '/MediaPlayer/getAnnotationContent.php?id='+id);
		http4.onreadystatechange = loadAnnotationContent; 
		http4.send(null);
}
*/

function f_clear_session_cache(){
	//use ajax to get the appropriate information
	var url = "/PHP/process/p_clear_session.php";
	var sendVars = "";
	//tell the request object to send all the information via post
	http.open('POST', url);
	//set the request header to send the information in a post friendly format
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//set the function that will be used to listen for the response
	http.onreadystatechange = f_load_content;
	//create the sendVars variable
	//send the information over to the processing script
	http.send(sendVars);
}

function f_reload_menu(){
	if(document.getElementById("myMenu")){
		var menu = document.getElementById("myMenu");
		var parent = menu.parentNode;
		var menu_div = document.createElement("div");
		menu_div.className = "menu_div";
		menu_div.id = "menu_div";
		if(parent.replaceChild(menu_div,menu)){
			f_draw_menu();
		}
	}
}

function f_update_media_form_groups(item_id){
	var elements = document.forms['upload_form'].elements;
	var pattern = /^groups.*$/;
	for(var i=0; i<elements.length; i++)
	{
		if((pattern.test(elements[i].id)) && (elements[i].type == "checkbox")){
			if((elements[i].checked == true) && (elements[i].value != item_id)){
				elements[i].checked = false;
			}
		}
	}
}

function f_update_profile_image_form(item_id){
	var elements = document.forms['update_profile_image'].elements;
	var pattern = /^img.*$/;
	for(var i=0; i<elements.length; i++)
	{
		if((pattern.test(elements[i].id)) && (elements[i].type == "checkbox")){
			if((elements[i].checked == true) && (elements[i].value != item_id)){
				elements[i].checked = false;
			}
		}
	}
}

function f_clear_field(form_name, id, value){
	var elements = document.forms[form_name].elements;
	for(var x=0; x < elements.length; x++)
	{
		if(elements[x].id == id)
		{
			if(elements[x].value == value)
			{
				elements[x].value = "";
			}
			break;
		}
	}
}

//DHTML menu functions

var branch;

function dropdownMenu(navid)
{
  var isie = typeof document.all != 'undefined'
     && typeof window.opera == 'undefined'
     && navigator.vendor != 'KDE';

  if (typeof document.getElementById == 'undefined'
      || (navigator.vendor == 'Apple Computer, Inc.'
      && typeof window.XMLHttpRequest == 'undefined')
      || (isie && typeof document.uniqueID == 'undefined'))
  {
    return;
  }

  var rollover = new Image;
  rollover.src = 'right-red.gif';
  rollover = new Image;
  rollover.src = 'down-red.gif';

  var tree = document.getElementById(navid);
  if (tree)
  {
    branch = tree;
    var items = tree.getElementsByTagName('li');
    for (var i = 0; i < items.length; i++)
    {
      dropdownTrigger(tree, items[i], navid, isie);
    }
  }
}

function dropdownTrigger(tree, li, navid, isie)
{
  var opentime, closetime;
  var a = li.getElementsByTagName('a')[0];
  var menu = li.getElementsByTagName('ul').length > 0
      ? li.getElementsByTagName('ul')[0] : null;
  var horiz = tree.className.indexOf('horizontal') != -1;
  var issub = li.parentNode.id == navid;

  if (menu)
  {
    li.className += (li.className == '' ? '' : ' ') + 'hasmenu';
  }

  attachEventListener(li, 'mouseover', function(e)
  {
    if (unwantedTextEvent()) { return; }
    clearTimeout(closetime);
    if (branch == li) { branch = null; }

    a.className += (a.className == '' ? '' : ' ') + 'rollover';

    var target = typeof e.target != 'undefined' ? e.target : window.event.srcElement;
    while (target.nodeName.toUpperCase() != 'LI')
    {
      target = target.parentNode;
    }
    if (target != li) { return; }

    if (menu)
    {
      opentime = window.setTimeout(function()
      {
        if (branch)
        {
          clearMenus(branch);
          branch = null;
        }

        menu.style.left = horiz
            ? (isie ? li.offsetLeft + 'px' : 'auto')
            : '0';

        menu.style.top = horiz && issub
            ? (isie ? a.offsetHeight + 'px' : 'auto')
            : (isie ? li.offsetTop + 'px' : '0');

        repositionMenu(menu);

        if (typeof document.uniqueID != 'undefined')
        {
          createIframeLayer(menu);
        }
      }, 250);
    }
  }, false);

  attachEventListener(li, 'mouseout', function(e)
  {
    if (unwantedTextEvent()) { return; }

    var related = typeof e.relatedTarget != 'undefined' ? e.relatedTarget : window.event.toElement;
    if (!li.contains(related))
    {
      clearTimeout(opentime);
      branch = li;

      a.className = a.className.replace(/ ?rollover/g, '');
      if (menu)
      {
        closetime = window.setTimeout(function()
        {
          menu.style.left = '-100em';

          if (toggleSelects('visible') && tree.contains(related))
          {
            toggleSelects('hidden');
          }
          else
          {
            removeIframeLayer(menu);
          }

        }, 600);
      }
    }
  }, false);

  if (!isie)
  {
    li.contains = function(node)
    {
      if (node == null) { return false; }
      if (node == this) { return true; }
      else { return this.contains(node.parentNode); }
    };
  }
  
}

function clearMenus(root)
{
  var menus = root.getElementsByTagName('ul');
  for (var i = 0; i < menus.length; i++)
  {
    menus[i].style.left = '-100em';
    removeIframeLayer(menus[i]);
  }
}

function unwantedTextEvent()
{
  return (navigator.vendor == 'Apple Computer, Inc.'
      && (event.target == event.relatedTarget.parentNode
      || (event.eventPhase == 3
      && event.target.parentNode == event.relatedTarget)));
}

function getRoughPosition(ele, dir)
{
  var pos = dir == 'x' ? ele.offsetLeft : ele.offsetTop;
  var tmp = ele.offsetParent;
  while (tmp != null)
  {
    pos += dir == 'x' ? tmp.offsetLeft : tmp.offsetTop;
    tmp = tmp.offsetParent;
  }
  return pos;
}

function getViewportSize()
{
  var size = [0,0];

  if (typeof window.innerWidth != 'undefined')
  {
    size = [
        window.innerWidth,
        window.innerHeight
    ];
  }
  else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth != 'undefined'
      && document.documentElement.clientWidth != 0)
  {
    size = [
        document.documentElement.clientWidth,
        document.documentElement.clientHeight
    ];
  }
  else
  {
    size = [
        document.getElementsByTagName('body')[0].clientWidth,
        document.getElementsByTagName('body')[0].clientHeight
    ];
  }

  return size;
}

function repositionMenu(menu)
{
  var extent = [
      getRoughPosition(menu, 'x') + menu.offsetWidth + 25,
      getRoughPosition(menu, 'y') + menu.offsetHeight + 25
  ];
  var viewsize = getViewportSize();

  if (extent[0] > viewsize[0])
  {
    var offset = menu.offsetWidth
        + menu.parentNode.parentNode.offsetWidth;
    var inset = menu.parentNode.offsetWidth
        - menu.offsetLeft;

    menu.style.left = (0 - offset + (inset * 2)) + 'px';
  }

  if (extent[1] > viewsize[1])
  {
    var current = parseInt(menu.style.top, 10);
    var difference = extent[1] - viewsize[1];

    menu.style.top = (current - difference) + 'px';
  }
}

function createIframeLayer(menu)
{
  if (!toggleSelects('hidden'))
  {
    var layer = document.createElement('iframe');
    layer.tabIndex = '-1';
    layer.src = 'javascript:false;';
    menu.parentNode.appendChild(layer);

    layer.style.left = menu.offsetLeft + 'px';
    layer.style.top = menu.offsetTop + 'px';
    layer.style.width = menu.offsetWidth + 'px';
    layer.style.height = menu.offsetHeight + 'px';
  }
}

function removeIframeLayer(menu)
{
  if (!toggleSelects('visible'))
  {
    var layers = menu.parentNode.getElementsByTagName('iframe');
    while (layers.length > 0)
    {
      layers[0].parentNode.removeChild(layers[0]);
    }
  }
}

function toggleSelects(vis)
{
  if (typeof document.uniqueID != 'undefined'
      && typeof document.body.style.scrollbarTrackColor == 'undefined')
  {
    var selects = document.getElementsByTagName('select');
    for (var i = 0; i < selects.length; i++)
    {
      selects[i].style.visibility = vis;
    }

    return true;
  }

  return false;
}

function attachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.addEventListener != 'undefined')
  {
    target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != 'undefined')
  {
    target.attachEvent('on' + eventType, functionRef);
  }
  else
  {
    eventType = 'on' + eventType;

    if (typeof target[eventType] == 'function')
    {
      var oldListener = target[eventType];

      target[eventType] = function()
      {
        oldListener();

        return functionRef();
      }
    }
    else
    {
      target[eventType] = functionRef;
    }
  }

  return true;
}

function addLoadListener(fn)
{
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener('load', fn, false);
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener('load', fn, false);
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent('onload', fn);
  }
  else
  {
    var oldfn = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = fn;
    }
    else
    {
      window.onload = function()
      {
        oldfn();
        fn();
      };
    }
  }
}
