// resourceForm Javascript

function initResourceList(){
	YAHOO.util.Connect.asyncRequest('GET', "/files/resourceForm/resources.xml", callback, null); 
	var downloadButton = document.getElementById("downloadButton");
	YAHOO.util.Event.addListener(downloadButton,"click",onDownloadButtonClick);
}

function onDownloadButtonClick(e){
	if(!validateForm()){
		alert("Please properly fill out all fields of the form in order to proceed.")
		return;
	}
	if(! getSelectedDownloads().length > 0)
	{
		alert("You must select at least one document to download.")
		return;
	}
	sendFormData();
}

function sendFormData(){
	var postData = "";
	postData += "referrer="+referrer;
	if(document.getElementById("nameInput") != null) postData += "&name="+document.getElementById("nameInput").value;
	if(document.getElementById("companyInput") != null) postData += "&company="+document.getElementById("companyInput").value;
	if(document.getElementById("zipInput") != null) postData += "&zip="+document.getElementById("zipInput").value;
	if(document.getElementById("emailInput") != null) postData += "&email="+document.getElementById("emailInput").value;
	postData += "&downloads=";
	var downloads = getSelectedDownloads();
	selectedDownloads = downloads;
	for(var i=0;i<downloads.length;i++)
		postData += downloads[i].title+" ("+downloads[i].file+")|";
	YAHOO.util.Connect.asyncRequest('POST', "/files/resourceForm/contact.php", formCallback, postData);
}

var formCallback = {
	success: function(o){showDownloads()},
	failure: function(o){},
	arguments:null
};

var selectedDownloads;
function showDownloads(){
	YAHOO.util.Dom.setStyle(['step1', 'step2'], 'display', "none"); 
	YAHOO.util.Dom.setStyle('step3', 'display', "block"); 
	var html="";
	for(var i=0;i<selectedDownloads.length;i++){
		var currentDocument = selectedDownloads[i];
		html+="<div class=\"documentDownload\">";
		html+="<div class=\"saveFileButton\"><a href=\""+currentDocument.file+"\" target=\"_blank\"><img src=\"/files/resourceForm/images/saveFileButton.jpg\"></a></div>";
		html+="<div class=\"document\"><span class=\"documentTitle\">"+currentDocument.title+"</span>";

		if(currentDocument.description.length > 5) {
			html+="<br/><span class=\"documentDescription\">"+currentDocument.description+"</span>";
		}

		html += "<br/><span class=\"documentMeta\">("+currentDocument.info+")</span>";
		html += "</div></div>";
	}
	var node = document.getElementById('step3resources');
	node.innerHTML = html;
	}


function isRequired(value,minLength){
    if(minLength == null) 
        minLength=1;
    if(value.length < minLength) return false;
    return true;
}     

function isPhone(value,required){
    if(required == null) 
        required = true;
    
    if(!required && value.length == 0) 
        return true;
    
    var requiredDigits = 10; // zero-indexed
    var allowedChars = "-(). +";
    var chars = value.split('');

    for(key in chars) {
        c = chars[key];
        if(parseInt(c)<=9) 
            requiredDigits--;
        else if(allowedChars.indexOf(c) != -1)
            continue;
        else
            return false;
    }
    
    if(requiredDigits <= 0) 
        return true; 
    
    return false;
}

function isEmail(value,required){
    if(required == null) 
        required = true;
    
    if(!required && value.length == 0) 
        return true;
    
    reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return reg.test(value);
}

function isZip(value,required){
    if(required == null) 
        required = true;
    
    if(!required && value.length == 0) 
        return true;
    
    var chars = value.split('');
    var delimiterFound = false;
    
    for(key in chars) {
        c = chars[key];
        if(parseInt(c)<=9) 
            continue;
        else if(!delimiterFound && ( c == "+" || c == "-" ) )
            continue;
        else
            return false;
    }
    
    var isValid = (value.length == 5  || value.length == 6 || value.length == 10) ? true: false;
    
    return isValid;
}
        

function validateForm(){
    var valid=true;
	valid = valid && isRequired(document.getElementById("nameInput").value);
    valid = valid && isZip(document.getElementById("zipInput").value,false);
    valid = valid && isEmail(document.getElementById("emailInput").value);
    return valid;
}


function getSelectedDownloads(){
	var documents = new Array();
	for(var i=0; i<resourceSections.section.length;i++)
	{
		var currentSection = resourceSections.section[i];
		for(var n=0; n<currentSection.document.length;n++)
		{
			var currentDocument = currentSection.document[n];
			var element = document.getElementById("section_"+i+"_document_"+n)
			if(element.checked) documents.push(currentDocument);
		}
	}
	return documents;
}

function renderResourceList(data){
	var section = data.section;
	var html="";
	for(var i=0;i<section.length;i++){
		var title = section[i].title.length!=undefined? section[i].title: '';

		if(title != '')
			html += "<h2>"+title+"</h2>";

		for(var n=0;n<section[i].document.length;n++){
			var currentDocument = section[i].document[n];

			html+="<p class=\"document\">";
			html+="<input type=\"checkbox\" class=\"download\" id=\"section_"+i+"_document_"+n+"\"/>";
			html+="<span class=\"documentTitle\">"+currentDocument.title+"</span>";

			if(currentDocument.description.length > 5) {
				html+="<br/><span class=\"documentDescription\">"+currentDocument.description+"</span><br/>";
			}

			html += "<span class=\"documentMeta\">("+currentDocument.info+")</span>";
			html += "</p>";
		}
	}
	var node = document.getElementById('step2resources');
	node.innerHTML = html;
}

var resourceSections;

var callback = {
	success: function(o) {
		var xml = o.responseText;
		var myobj = xml2json.parser(xml);
		resourceSections = myobj.resources;
		renderResourceList(resourceSections);
	},
	failure: function(o) {
		alert("Could not load resource document list. Please try again later.")
	},
	argument: null
};

YAHOO.util.Event.onDOMReady(initResourceList);