//Controller Object

function ptp_controller(templatePrefix) {
	var that = this;
	
	//assign template variable
	if (templatePrefix != "") {
		this.template = templatePrefix;
	} else {
		this.template = "obama";
	}
	
	this.settingsData;
	this.templateData;
	ptp_options = new Array;
	
	//Imports html template based on value fed to new ptp_controller
	that.loadTemplate();
	$("#previewPane").html(this.templateData);
	//Imports xml file based on value fed to new ptp_controller
	that.loadOptions();			
	
	
	//Create Widgets based on XML Parse
	for(var D=0; D<ptp_options.length; D++) {
		if (ptp_options[D].bool == true){
			var widget = new ptpWidget(ptp_options[D].name, ptp_options[D].label, ptp_options[D].type, ptp_options[D].note);
			$("#editPane").append(widget.html);
			$("#"+widget.label)
				.change(function() {
					var cleanValue = $(this).val();
					cleanValue = cleanValue.replace(/<(.|\n)*?>/gi,"");
					$("#ptp_"+$(this).attr('id')).html(cleanValue).css("background-color", "");
					$(this).val(cleanValue);

				})
				.focus(function() {
					$("#ptp_"+$(this).attr('id')).css("background-color", "#ccffcc");
				})
				.blur(function() {
					$("#ptp_"+$(this).attr('id')).css("background-color", "");
				})
				.val(ptp_options[D].content);
			$("#ptp_"+widget.label).html(ptp_options[D].content);

			var emailFlag = false;			
	
			for (var V=0; V<ptp_options[D].validation.length; V++ ) {
				//alert("attaching validator "+ptp_options[D].validation[V]);
				if((ptp_options[D].validation[V] == "email") || (ptp_options[D].validation[V]=="emails")) {
					emailFlag=true;
				}
				widget.validate(eval("check_"+ptp_options[D].validation[V]), ptp_options[D].validation[V]);
			}

			if (!emailFlag){
				widget.validate(check_strip_tags, "strip_tags");
			}			
		}
	}
	
	
	//Throw webtrends page view code
	_tag.DCSext.email_template=ptp_options.tracking;
	_tag.dcsCollect();
	
	
	//Feed Widgets/HTML to Edit Pane
	//Feed HTML Template to Preview Pane
	//Initialize Preview Pane
	
	this.loadView = function() {
		//Create Widgets based on option's array
		//Feed widgets to Edit Pane
		//Feed HTML Template to Preview Pane
		//Create Editor Object (Public)
		//Run initial validate-all
	
	}
	
	//Create Hidden Inpute for Template Variable	 
	$("form")
		.append('<input type="hidden" id="template" name="template" value="'+this.template+'" />')
		.append('<input type="hidden" id="subject" name="subject" value="'+ptp_options.subject+'" />');
	$("#pageTitle").html(ptp_options.title.text);
	$("#navigation").css({"color":ptp_options.title.color, "background-color":ptp_options.title.background});
	
}

ptp_controller.prototype.loadOptions= function() {
	//alert ("loading options");
	//clear the editPane for new options
	$("#editPane").html("");
	//Search for xml file in named *template.xml in folder called *template
    request = $.ajax({
    	dataType:"xml",
    	async:false,
    	url: "templates/"+this.template+"/"+this.template+".xml",
    	error: function(XMLHttpRequest, textStatus, errorThrown){
		    $('<p></p>')
		   	.html("There was an error with your request")
		   	.appendTo('#previewPane');
		}
    });
    
    
    //parse values and set Options Object
    $(request.responseXML).find('email').each(function(){
    	
    	//Sets the Title
    	ptp_options.title = new Object;
    	ptp_options.title.text = $(this).children('title').text();
    	if ($(this).children('title').attr("color")) {
    		ptp_options.title.color = $(this).children('title').attr("color");
    	} else {
    		ptp_options.title.color = "#FFFFFF";
    	}
    	if ($(this).children('title').attr("background")) {
    		ptp_options.title.background = $(this).children('title').attr("background");
    	} else {
    		ptp_options.title.background = "#003d79";
    	}
		
		//Set Email Subject
		if($(this).children('subject').text()) {
			ptp_options.subject = $(this).children('subject').text();
		} else {
			ptp_options.subject = "Change Your World. Forever.";
		}
		
		//Set Title for tracking
		if($(this).children('tracking').text()) {
			ptp_options.tracking = $(this).children('tracking').text();
		} else {
			ptp_options.tracking = ptp_options.subject;
		}

    	
    	//Activates Options
    	var options = $(this).children('options');
    	var i = 0;
    	options.children('option').each(function(){
    		var validationTests = new Array;
    		var i2 = 0
    		$(this).children('validate').each(function(){    			
    			validationTests[i2] = $(this).attr('type');
    			i2++;	
    		});
    		
    		ptp_options[i] = {
    			name:$(this).attr('name').toString(),
    			type:$(this).attr('type').toString(),
    			bool:$(this).attr('active'),
    			label:$(this).attr("label").toString(),
    			note:$(this).attr("note").toString(),
    			content:$(this).children('content').text(),
    			validation:validationTests};
    		i++;
    	});
	});
    
	return true;
}

ptp_controller.prototype.loadTemplate = function() {
	//alert ("loading template");
	//Feed HTML Template into Preview Pane
	 this.templateData = $.ajax({
    	dataType:"html",
    	async: false,
    	url: "templates/"+this.template+"/"+this.template+".html",
    	error: function(XMLHttpRequest, textStatus, errorThrown){
		    $('<p></p>')
		   	.html("There was an error with your request")
		   	.appendTo('#previewPane');
		}
    }).responseText;
    return true;
}


function sendForm(passForm) {
	document.getElementById('submitButton').disabled = true;
	document.getElementById('progress').innerHTML = '<img src="img/indicatorwhite.gif" width="16" height="16" />';
	
	myForm = $("#"+passForm).serialize();
	myForm = myForm.replace(/<(.|\n)*?>/gi,"");
	
    //var FixedMessage = replacecarriagereturn(passForm.Message.value,'<br/>');
    //var FixedSalutation = replacecarriagereturn(passForm.Salutation.value,'<br/>');
    /*if (passForm.ProgramLink.value == "") {
    	passForm.ProgramLink.value = "http://www.peopletopeople.com/OurPrograms/CAP/Pages/default.aspx";
    }*/
    
    var emails = countEmails($("#"+passForm+" #toAddress").val());
	var fromName = $("#"+passForm+" #yourName").val();
	var fromEmail = $("#"+passForm+" #yourAddress").val();
    

    $.ajax({
    	type:"POST",
    	url:"InviteEmailProcess.aspx",
    	dataType:"text",
    	data: myForm,
    	error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert("There was an error with the program. Please try again later");
    		$("#serverResponse").html("There was an error with the program. Please try again later");
    		document.getElementById('submitButton').disabled = false;
			document.getElementById('progress').innerHTML = "";
    		//displayForm(html);
		},
    	success: function(html){
    		//track email as success
   			pageTracker._trackEvent('Emails', ptp_options.tracking, fromName+" - "+fromEmail, emails);
   			dcsMultiTrack('DCS.dcsuri','/emailConfirm','WT.ti', ptp_options.tracking+'%20Template%20Confirmation','DCSext.sender',fromName+" - "+fromEmail,'DCSext.emailcount',emails);
   			 
    		alert(html);
    		$("#serverResponse").html(html);
    		document.getElementById('submitButton').disabled = false;
			document.getElementById('progress').innerHTML = "";
    		//displayForm(html);
    	}
    });
    
}

function countEmails (text) {
	var text = text.trim();
	var emails = new Array;
	var count;
	emails = text.split(";");
	emails.clean("");
	var count = emails.length;				
	return count;

}

function cleanElements (text) {


}






