var source_str;
var is_preview=false;//flag to determine if in preview mode
window.onload = function()
	{
		CKEDITOR.replace( 'org_description', {toolbar :[['Bold', 'Italic', 'NumberedList', 'BulletedList', 'Scayt', 'Link']],
		removePlugins : 'elementspath',
		font_style :{
										element		: 'span',
										styles		: { 'font-family' : 'Verdana' },
										overrides	: [ { element : 'font', attributes : { 'face' : null }}]}});
										
										
		CKEDITOR.replace( 'app_instructions', {toolbar :[['Bold', 'Italic', 'NumberedList', 'BulletedList', 'Scayt', 'Link']],
		removePlugins : 'elementspath',
		height:'100px', 
		//width:'350px',
		font_style :{
										element		: 'span',
										styles		: { 'font-family' : 'Verdana' },
										overrides	: [ { element : 'font', attributes : { 'face' : null }}]}});
										
		errorDlg = new YAHOO.widget.SimpleDialog("dlg", { 
		width: "20em", 
		effect:{effect:YAHOO.widget.ContainerEffect.FADE,
	        duration:0.25}, 
		fixedcenter:true,
		visible:false,
		draggable:false });
		errorDlg.setHeader("!");
		errorDlg.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_WARN);
	
		errorDlg.render(document.body);

		
		if (location.href.indexOf('reload')==-1) location.replace(location.href+'?reload')//automatically refreshes page via altering the url
		
	};
	
	function showPreview()
	{
		var org_description = CKEDITOR.instances.org_description.getData();
		var app_instructions = CKEDITOR.instances.app_instructions.getData();
		var app_instructions_label='';
		
		if(app_instructions!='')
			app_instructions_label = "<p><strong>Application Instructions</strong></p>";
			
		is_preview = true;
		
		source_str = org_description+app_instructions_label+app_instructions;
		replaceText();
		removeTags();
			
		var previewDiv = document.getElementById("preview");
		var textElement = document.createElement("textElement");
		textElement.innerHTML = '<label style="font-weight:bold;font-size:11px">Preview</label><br><br><div style="border-style:dotted; border-width:1px; border-color:#BCBCBC; padding:10px;">'+source_str+'</div>';
		previewDiv.appendChild(textElement);
		y=document.getElementsByTagName("textElement")[0]
		previewDiv.replaceChild(textElement, y);
	}
	
	/*sets ckediotr textarea to null/empty*/
	function clearTextArea()
	{
		CKEDITOR.instances.org_description.setData('');
		CKEDITOR.instances.app_instructions.setData('');
	}
	
	function validateEmail()
	{
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var address = document.getElementById("contact_email").value;
		var error_msg;
		
		if(reg.test(address) == false) 
		{
			error_msg="Please supply a valid email address";
			errorDlg.setBody(error_msg);
			errorDlg.show();
		}
		else
		{
			source_str =	CKEDITOR.instances.org_description.getData()+"<p><strong>Application Instructions</strong></p>"+
							CKEDITOR.instances.app_instructions.getData();
			replaceText();
			removeTags();
		}
	}
	
	function validateURL() 
	{ 
		var v = new RegExp(); 
		
		var error_msg;
		
		v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); 
		
		if (!v.test(document.getElementById("org_url").value))
		{
			error_msg="Please supply a valid URL<br>i.e. http://foundationcenter.org";
			errorDlg.setBody(error_msg);
			errorDlg.show();
		}
		else
			validateEmail();
    }  
	
	/*verifies that input fields have been filled in*/
	function validate()
	{
		var error_msg="<strong>Please enter the following:</strong> <br><ul>";
		var missing_fields = false;
		
		if(document.getElementById("job_title").value=='')
		{
			error_msg +="<li>Job Title</li>";
			missing_fields = true;
		}
		
		if(document.getElementById("org_name").value=='')
		{
			error_msg +="<li>Organization Name</li>";
			missing_fields = true;
		}
		
		if(document.getElementById("state").value=='')
		{
			error_msg +="<li>Location: City/State/Other</li>";
			missing_fields = true;
		}
		
		if(document.getElementById("org_url").value=='')
		{
			error_msg +="<li>Organization URL</li>";
			missing_fields = true;
		}
		
		if(document.getElementById("contact_email").value=='')
		{
			error_msg +="<li>Contact E-mail</li>";
			missing_fields = true;
		}
		
		if(CKEDITOR.instances.org_description.getData()=='')
		{
			error_msg +="<li>Job Description</li>";	
			missing_fields = true;
		}
		
		if(CKEDITOR.instances.app_instructions.getData()=='')
		{
			error_msg +="<li>Application Instructions</li>";	
			missing_fields = true;
		}
		
		if(missing_fields)
		{
			error_msg+="</ul>";
			errorDlg.setBody(error_msg);
			errorDlg.show();
		}
		else
			validateURL();
	}
	
	/*strips "span" and "font" tags from data provided in CKEDITOR'S textarea*/ 
	function removeTags()
	{
		var open_tags = new Array("<span", "<font", "<o:p", "<st1:", "</st1:", "<table", "<tbody", "<tr", "<td","<!", "<meta", "<sup", "<link", "<colgroup", "<col");
		var closing_tags = new Array("</span>","</font>", "</o:p>", "</table>", "</tbody>", "</tr>", "</td>", "</sup>", "</colgroup>"); //closing tags in place b/c dynamo dislikes incomplete closing tags. therefore separate array for closing tags are neccessary(at least for tags that dynamo does recognize as legitamate html tags)
			
		index_end_tag = 0;
		tag_end = ">";
		
			for(i=0; i<open_tags.length; i++)
			{
				while(source_str.indexOf(open_tags[i])!=-1)//while tag is found within string/data, remove tag from string.
				{
					index_start_tag = source_str.indexOf((open_tags[i]));
					index_end_tag = source_str.indexOf(tag_end, index_start_tag);
						
					first_str = source_str.substring(0, index_start_tag);
					second_str = source_str.substring(index_end_tag+1);
					source_str = first_str.concat(second_str);
				}
			}//end of for loop
			
			//remove closing tags
				for(i=0; i<closing_tags.length; i++)
				{
					while(source_str.indexOf(closing_tags[i])!=-1)
					{
						index_start_tag = source_str.indexOf(closing_tags[i]);
			
						first_str = source_str.substring(0, index_start_tag);
						second_str = source_str.substring(index_start_tag+(closing_tags[i].length));
						source_str = first_str.concat(second_str);
					}
				}
				removeTagAndContents();
				removeAttributes();
	}
	
	/*removes "style", "class" attributes from CKEDITOR'S data*/
	function removeAttributes()
	{
		var attribute = new Array('style="', 'class="', 'align="');
		var attribute_closing_quote = '"';
		
		for(i=0; i<attribute.length; i++)
		{
				while(source_str.indexOf(attribute[i])!=-1)
				{
					index_start_attribute = source_str.indexOf((attribute[i]));
					
					/*return index of closing '"' starting from the index of attribute's starting position plus the length of the attribute(including the equal and opening quotation i.e. 'style="')*/
					index_end_attribute = source_str.indexOf(attribute_closing_quote, index_start_attribute+(attribute[i].length));
						
					first_str = source_str.substring(0, index_start_attribute);
					second_str = source_str.substring(index_end_attribute+1);
					source_str = first_str.concat(second_str);
				}
		}//end of for loop
		
		
		if(is_preview==false)//if not in preview mode submit form
		{
			CKEDITOR.instances.org_description.setMode('source');
			CKEDITOR.instances.org_description.setData(source_str);	
		
			document.getElementById("submit_form").submit();
		}
		
		is_preview=false;
	}
	
	function removeTagAndContents()
	{
		var attribute = new Array('<style>', '<xml>');
		var attribute_closing_quote;
		
		for(i=0; i<attribute.length; i++)
		{
			var closing_tag = "</"+attribute[i].slice(1);
			
				while(source_str.indexOf(attribute[i])!=-1)
				{
					index_start_attribute = source_str.indexOf((attribute[i]));
					
					/*return index of closing '"' starting from the index of attribute's starting position plus the length of the attribute(including the equal and opening quotation i.e. 'style="')*/
					index_end_attribute = source_str.indexOf(closing_tag, index_start_attribute+(attribute[i].length));
						
					first_str = source_str.substring(0, index_start_attribute);
					second_str = source_str.substring(index_end_attribute+closing_tag.length);
					source_str = first_str.concat(second_str);
				}
		}//end of for loop
	}
	
	function replaceText()
	{
		source_str = source_str.replace(/&lt;/gi, "<");
		source_str = source_str.replace(/&gt;/gi, ">");
		source_str = source_str.replace(/&nbsp;/gi, " ");	
		source_str = source_str.replace(/&middot;/gi, " ");
	}
