/**
* Author: (Soham Dave and 6482503)
* Purpose: External Javascript file used for XMLHTTP Object Creation
* CREATED: 1 SEPTEMBER 2009
* LAST UPDATED: 1 SEPTEMBER 2009 
*/
/*
*Function to Request for Program XML Data
*/

var xhrProgram=createRequest();
var xhrNewsLetter=createRequest();
var xhr=createRequest();
/*
*Summary: THis function will fetch the data regarding Programs that are clicked using AJAX
*Parameter: Program Data to be fetched from Programs XML File
*Return: AJAX request response which is Program description Data to be printed on HTML Page
*Author: Soham Dave
*/
function getProgramData(programFetch)
{
	var url = "program.php?whichprogram=" + programFetch + "&sid="+Math.random();
	xhrProgram.open("GET", url, true); 
	xhrProgram.setRequestHeader("Content-Type", "text/html" ); //use this if no response required 
	xhrProgram.onreadystatechange = function()
	{
		if ((xhrProgram.readyState == 4) &&(xhrProgram.status == 200))    
		{
			document.getElementById("content_data").innerHTML=xhrProgram.responseText;			
   		}
	}  
	xhrProgram.send(null); 
}
/*
*Summary: THis function will fetch the data regarding Newletter based on just issued year or All of them in depository
*Parameter: Program Data to be fetched from Newsletter XML File that is styled by News_letter XSLT File
*Return: AJAX request response which is Newletter description and Link Data to be printed on HTML Page
*Author: Soham Dave
*/
function getNewsLetterData(divID,newsLetterYear)
{
	//check for the request made is just one newletter or for all of them
	if(newsLetterYear == "one")
	{
		var url = "program.php?News_Letter_All=all&whichyear=one&sid="+Math.random();
	}
	else
	{
		var url = "program.php?whichyear=one&sid="+Math.random();
	}
	xhrNewsLetter.open("GET", url, true); 
	//setting the OUtput headers to be HTML rather than XML
	xhrNewsLetter.setRequestHeader("Content-Type", "text/html" ); //use this if no response required 
	xhrNewsLetter.onreadystatechange = function()
	{
		if ((xhrNewsLetter.readyState == 4) &&(xhrNewsLetter.status == 200))    
		{
			//Print the Data received on HTML File styled by XSLT 
			document.getElementById(divID).innerHTML=xhrNewsLetter.responseText;
   		}
	}  
	xhrNewsLetter.send(null); 
}
/*
*Summary: THis function reads the cookie information passed
*Parameter: reads the cookie value you want
*Return: returns cookie information
*Author: Soham Dave
*/
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
/*
*Summary: This function will Hide the HTML Element Clicked
*Parameter: Passing Sourced Division tag that trigger and Division that is to be Hidden 
*Return: Will Hide the Section by clearing All Data in it.
*Author: Soham Dave
*/
function HideSection(srcDIV,div)
{
	document.getElementById(div).innerHTML="";
	document.getElementById(srcDIV).innerHTML="";
	/*document.getElementById(srcDIV).innerHTML="Latest Events &gt;&gt;&gt;&gt;&gt;";
	var obj= document.getElementById(srcDIV);
	removeEvent(obj,"click",HideSection);
	addEvent(obj,"click",function() { XML_XSL_Transform('News_Events.xsl','data/News_Events.xml','news-box') });*/
}
/*
*Summary: THis function will OPen the download File dialog for the File the to be Downloaded.
*Parameter: URL of the Document to be Downloaded
*Return: Will open the File save Dialog
*Author: Soham Dave
*/
function DownloadFile(url)
{
	var pieces= url.split("/").pop();
	var location_URL="fileloader.php?fileName="+url+"&file_is=" + pieces;
	oIFrm = document.getElementById('myIFrm');
	oIFrm.src = location_URL;
}
/*
*Summary: This Function will issues the Admin Task Request and prints the response from PHP File corresspondingly
*Parameter: Which task you want to Do.
*Return: AJAX request response which is Admin response corressponding to registering Form Elements on HTML Page
*Author: Soham Dave
*/
function DataAddition(what)
{
	if(what=="events_addition")
	{
		url="addition=" + "add_delete"+ "&sid=" + Math.random();
		xhr.open("POST", "admin.php", true);		    
	}
	else if(what=="addition")
	{
		url="event_addition=" + "event"+ "&sid=" + Math.random();
		xhr.open("POST", "admin.php", true);	
	}
	else if(what=="deletion")
	{
		XML_XSL_Transform('Delete_Activity.xsl','data/News_Events.xml','requestData');
		return 0;
	}
	else if(what=="activity_addition")
	{
		url="addition=" + "activity"+ "&sid=" + Math.random();
		xhr.open("POST", "admin.php", true);	
	}
	else if(what=="Newsletter_addition")
	{
		url="newsletter_addition=" + "newsletter"+ "&sid=" + Math.random();
		xhr.open("POST", "admin.php", true);	
	}
	else if(what=="Newsletter_deletion")
	{
		XML_XSL_Transform('Delete_Newsletter.xsl','data/News_Letter.xml','requestData');
		return 0;
	}
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.onreadystatechange = function()
	{	
		// Check the Status of xhr object
		if (xhr.readyState == 4 && xhr.status==200)
		{
			if(xhr.responseText.indexOf("radio") != -1)
			{
				document.getElementById("more_activity").innerHTML=xhr.responseText;
			}
			else
			{
				document.getElementById("requestData").innerHTML=xhr.responseText;
			}
		}
	}
	xhr.send(url);
}
/*
*Summary: This function will Transform the XML File requested with XSLT information and will o/p on HTML Tags
*Parameter: Name of XML File and XSLT File and where Styled Information is output.
*Return: Will Return Styled informaiton on Data of XML File using XSL File
*Author: Soham Dave
*/
function XML_XSL_Transform(xslfile,xmlfile,divID)
{ 
	if(window.document.title.indexOf("Admin") != -1)
	{
		var CookieUserName=getCookie("UserName");
		if(CookieUserName == null || CookieUserName == "")
		{
			alert("You must be Logged in to Use this Administrator Facility");
			window.location="login.html";
			return;
		}		
	}
	if(divID!=null)
	{
		if (window.ActiveXObject) 
		{
			// Load XML
			var xml = new ActiveXObject("Microsoft.XMLDOM");
			xml.async = false;
			xml.load(xmlfile);
			// Load XSL
			var xsl = new ActiveXObject("Microsoft.XMLDOM");
			xsl.async = false;
			xsl.load(xslfile);
			// Transform
			var fragment = xml.transformNode(xsl);
    	    document.getElementById(divID).innerHTML="";
		    document.getElementById(divID).innerHTML=fragment;	
		}
		else if (window.XMLHttpRequest) 
		{
			var xsltProc = new XSLTProcessor();
			xslSS = document.implementation.createDocument("", "doc", null);
			xslSS.async = false;
			xslSS.load(xslfile);
			xsltProc.importStylesheet(xslSS);
		
			var xmlDoc = document.implementation.createDocument("", "doc", null);
			xmlDoc.async = false;
			xmlDoc.load(xmlfile);
			// Transform
			var fragment = xsltProc.transformToFragment(xmlDoc, document);
    	    document.getElementById(divID).innerHTML="";
		    document.getElementById(divID).appendChild(fragment);	
		}	
	}
	else
	{
		alert("Sorry XML-XSL Transformation can not be performed as HTML element doesn't exsist");
	}
	
}
/*
*Summary: This function will Hide and Toggle the HTML Section clicked based on Style information of HTML Elements 
*Parameter: Passing Sourced Division tag that trigger and Division that is to be Hidden 
*Return: Will Toggle and Hide the Section
*Author: Soham Dave
*/
function ShowHidden(divID)
{
  var ele=document.getElementById(divID);
  if(!ele) return true;
  if(ele.style.display=="none")
  {
      ele.style.display="block";
	  if(divID=="more_news")
	  {
		  XML_XSL_Transform('News_Events_All.xsl','data/News_Events.xml','more_news');
	  }	
  }
  else
  {
      ele.style.display="none";
  } 
  return true;
}
/*
*Summary: This function will Check the Form fields for empty or not
*Parameter: Form field to be checked for empty/null or not
*Return: Will return false for null or true otherwise for further processing.
*Author: Soham Dave
*/
function checknotempty(field)
{
	if(field==null || field=='')
	{
		return false;
	}
	else
	{
		return true;
	}		
}
/*
*Summary: This function will Disbale Enter key for the form elements so Data entered in field is not transfered to other fields.
*Parameter: Form field for disable enter key and corressponding Event registered with Field
*Return: Will Disable Enter key 
*Author: Soham Dave
*/
function handleEnter (field, event) 
{
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	//Enter key's ASCII Code
	if (keyCode == 13) 
	{
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
			break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();
			return false;
	} 
	else
		return true;
}     
/*
*Summary: This function will Validate the Form Fields
*Parameter: Passing which form is to be validated 
*Return: Will Message User for further Action if Form is not validated
*Author: Soham Dave
*/
function checkfields(activity)
{
	var messages='';
	messages1='Please follow the following instructions to submit the Form successfully: \n';
	var frm=document.forms["admin_form"];
	if(activity=="event")
	{
		dateVal=frm.date.value;	
        timeVal=frm.time.value;
        locationVal=frm.location_val.value;
		contactName=frm.contact_name.value;
        contactVal=frm.contact_val_no.value;
        desc=frm.desc.value;
        var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; 
        if(frm.date.value != '' && !frm.date.value.match(re)) 
        { 
             messages= messages + "Invalid date format.\n please specify in dd/mm/yyyy format. \n"; 
        }           
        var reg = /^\d{1,2}:\d{2}([ap]m)?$/; 
        if(frm.time.value != '' && !frm.time.value.match(reg)) 
        { 
             messages=messages+ "Invalid time format.please specify in 12 Hour Format eg. 12:00am or 12:00pm. \n"; 
        }       
        if(checknotempty(locationVal)==false)
	    {
			  messages=messages+'Enter a Location. \n';
	    }
		if(checknotempty(contactName)==false)
	    {
			  messages=messages+'Enter a Contact Name. \n';
		}
		else
		{
			  if(checkAlphaNumeric(contactName)==false)
			  {
					messages=messages+'Enter the Contact name in Alphabetic Format only it should not contain any Numbers. \n';
			  }
		}
        if(checknotempty(contactVal)==false)
	    {
			messages=messages+'Enter a Contact Number. \n';
		}
		else
		{
			if(isNaN(contactVal))
			{
				messages=messages+'Enter Contact number in Numeric Only. \n';
			}
        }       
        if(checknotempty(desc)==false)
	    {
		      messages=messages+'Enter a Description. \n';
	    }	
	}
	else if(activity=="newsletter")
	{
		nameVal=frm.name_news.value;	
        volumeVal=frm.volume_news.value;
		volumeNo=frm.volume_no.value;
        news_description=frm.news_desc.value;
		if(checknotempty(nameVal)==false)
	    {
			  messages=messages+'Enter a Name of News Letter File. \n';
	    }
        if(checknotempty(volumeVal)==false)
	    {
		      messages=messages+'Enter a Volume of News Letter File. \n';
        }
		else
		{
			 if(checkAlphaNumeric(volumeVal)==false)
			  {
					messages=messages+'Enter the Volume name in Alphabetic Format only it should not contain any Numbers. \n';
			  }
		}
		if(checknotempty(volumeNo)==false)
	    {
		      messages=messages+'Enter a Volume No of News Letter File. \n';
        }       
		else
		{
			if(isNaN(volumeNo))
			{
				messages=messages+'Enter Volume number in Numeric Only. \n';
			}
		}
        if(checknotempty(news_description)==false)
	    {
		      messages=messages+'Enter a Description of News Letter. \n';
	    }			
	}
	if(messages!='')
	{		
		alert(messages1+messages,'Error','Soham Dave');
		return false;
	}	
}
/**
*Summary: Check for the respective fields if that contains valid Alphanumeric Data or not
*Parameter: Passing Form field that is to be Validated for Alpha numeric
*Return: Inform the User weather form field contains any Alphanumeric or not
*Author: Soham Dave
*/
function checkAlphaNumeric(field)
{
	var reg= /^[a-z\ A-Z.,;:"']+$/;
	if(field.match(reg))
	{
		return true;
	}
	else
	{
		return false;
	}	
}

/*
*Summary: This function will Add the Form Data to corressponding XML File
*Parameter: Passing XMl File where Data to be Added and Form from which Data to be Added.
*Return: Inform the User about the Activity Done.
*Author: Soham Dave
*/
function AddXMLData(xmlfile,activity)
{
  var frm=document.forms["admin_form"];
  if(checkfields(activity)==false)
  {
       alert("please validate all fields");
  }
  else if(activity=="event")
  {
       dateVal=frm.date.value;	
       timeVal=frm.time.value;
       locationVal=frm.location_val.value;
	   contactName=frm.contact_name.value;
       contactVal=frm.contact_val_no.value;
       desc=frm.desc.value;
       url="Date_Event=" + encodeURIComponent(dateVal) + "&Time_Event=" + encodeURIComponent(timeVal) + "&Location_Event=" + encodeURIComponent(locationVal) + "&Contact_Event1=" + encodeURIComponent(contactName) + + "&Contact_Event2=" + encodeURIComponent(contactVal) + "&Desc_Event=" + encodeURIComponent(desc) + "&XML_File=" + encodeURIComponent(xmlfile) + "&sid=" + Math.random();
	   xhr.open("POST", "admin.php", true);	
	   xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	   xhr.onreadystatechange = function()
 	   {	
		 // Check the Status of xhr object
		 if (xhr.readyState == 4 && xhr.status==200)
		 {
		 	alert(xhr.responseText);
			window.location.reload(true);
		 }
	   }
	   xhr.send(url);
   }
   else if(activity=="newsletter")
   {
	   	nameVal=frm.name_news.value;	
        volumeVal=frm.volume_news.value;
		volumeNo=frm.volume_no.value;
        news_description=frm.news_desc.value;
		filelist=frm.news_file.value;
		url="Name_Newsletter=" + encodeURIComponent(nameVal) + "&Volume_Newsletter1=" + encodeURIComponent(volumeVal) +"&Volume_Newsletter2=" + encodeURIComponent(volumeNo) + "&Desc_Newsletter=" + encodeURIComponent(news_description) + "&XML_File=" + encodeURIComponent(xmlfile) + "&File_list=" + encodeURIComponent(filelist) + "&sid=" + Math.random();
	   xhr.open("POST", "fileupload.php", true);	
   	   xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	   xhr.onreadystatechange = function()
 	   {	
		 // Check the Status of xhr object
		 if (xhr.readyState == 4 && xhr.status==200)
		 {
		 	alert(xhr.responseText);
			window.location.reload(true);
		 }
	   }
	   xhr.send(url);
   }
}
/*
*Summary: This function will handle the Deletion of Admin Task.
*Parameter: Which element to be deleted from corressponding XML File defined in PHP File handling admin request.
*Return: Will retuen AJAX-PHP response.
*Author: Soham Dave
*/
function DeleteEvent(id)
{
	url="Delete_Event=" + encodeURIComponent(id) + "&sid=" + Math.random();
	xhr.open("POST","admin.php", true);	
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.onreadystatechange = function()
	{	
		// Check the Status of xhr object
		if (xhr.readyState == 4 && xhr.status==200)
		{
			alert(xhr.responseText);
		}
	}
	xhr.send(url);	
}