$(document).ready(function() {
	
	$('a#btn_add_survey').click(function() {
		var stype = $('#survey_create_type').find('option:selected').val();
		if(stype != '') {
			if(!confirm('You have chosen to create a new survey based on data from the selected option. Are you sure you want to do this?')) {
				return false;
			}
		}
		window.location.href = '/admin/surveys/add/'+stype;
		return false;
	});
	
	$(".masked-currency").blur(function(){ 
		$(this).val(formatCurrency($(this).val()));
	});
	
	$(".masked-number").blur(function(){ 
		$(this).val(formatNumber($(this).val()));
	});
	
	$('table.scrollable').scrollable(200, 500);
	
	$("#accordion").accordion({ 
		header: "h3",
		alwaysOpen: false,
		autoHeight: false,
		animated: false
	});
	
	$("#send_reminder_form").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: 500
	});
	
	$("#criteria_editor").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: 400
	});
	
	$(".survey-input").live("click", function(){
		var table = $(this).parents('table:first');
		if($(this).attr('type') == 'radio') {
			$(table).find('input[type="checkbox"]').each(function(){  
				this.checked = false;											  
			});
		} else {
			$(table).find('input[type="radio"]').each(function(){  
				this.checked = false;											  
			});
		}
	});
	
	$(".btn-send-reminder").live("click", function(){
		if(confirm('Are you sure?')) {
			$('.ajax-load').show();
			$.post("/agency/send_reminder", { 
				id: $('#campaign_id').val(),
				email_subject: $('#send-reminder-subject').val(),
				email_text: $('#send-reminder-text').val()
			}, function(data){
				$('.ajax-load').hide();
				displayError(data);
				$('.msg-send-reminder').fadeIn(1000).fadeTo(3000, 1).fadeOut(1000);
			});
		}
		return false;
	});
	
	$(".btn-edit-criteria").live("click", function(){
		$('#criteria_editor').dialog('open');
		return false;
	});
	
	$(".btn-send-reminder-dialog").live("click", function(){
		$('#send_reminder_form').dialog('open');
		return false;
	});
	
	$(".btn-save-criteria").live("click", function(){
		var criteria = JSON.stringify($('form#submitted_criteria').serializeArray());
		var id;
		$('.ajax-load').show();
		$.post("/admin/surveys/update_criteria", { 
			id: $('#survey_id').attr('id'),
			criteria: criteria
		}, function(data){
			displayError(data);
			$('.ajax-load').hide();
			$('.msg-save-criteria').fadeIn(1000).fadeTo(3000, 1).fadeOut(1000);
			$("form#submitted_criteria input").each(function(i){
				id = $(this).attr('id').replace('editcriterion_','');
				$('div#criterium_'+id+' h3 a').html('Criterion '+(i+1)+': '+$(this).val());
			});
		});
		return false;
	});
	
	// SURVEY BUILDER FUNCTIONS
	$(".btn-question-delete").live("click", function(){
		var tr = $(this).parents('tr:first');
		var id = $(tr).attr('id').replace('question_','');
		if(confirm('DELETE QUESTION: Are you sure?')) {
			$('.ajax-load').show();
			$.post("/admin/surveys/delete_question", { 
				id: id
			}, function(data){
				$('.ajax-load').hide();
				displayError(data);
				if(data=='ok') {
					$(tr).remove();
				}
			});
		}
		return false;
	});
	
	$(".btn-question-add").live("click", function(){
		var table = $(this).parents('table:first');
		var tr = $(this).parents('tr:first');
		var content = $(tr).find('input#question_content_new').val();
		var score = $(tr).find('input#score_new').val();
		var section_id = $(table).attr('id').replace('section_','');
		var question_rows = $(table).find('tbody');
		var clonedRow = '<tr class="question" id=""><td><input type="text" id=">" class="question_content_entry" value="" /></td><td><input type="text" id="" class="score_entry" value="" /></td><td class="actions" style="text-align: center;"><a href="#" class="btn-question-delete">Delete</a></td></tr>';
		$('.ajax-load').show();
		$.post("/admin/surveys/add_question", { 
			content: content,
			score: score,
			section_id: section_id
		}, function(data){
			$('.ajax-load').hide();
			if(IsNumeric(data)) {
				$(question_rows).append(clonedRow);
				clonedRow = $(question_rows).find('tr:last');
				$(clonedRow).attr('id','question_'+data);
				$(clonedRow).find('input.question_content_entry').attr('id','question_content_'+data);
				$(clonedRow).find('input.question_content_entry').val(content);
				$(clonedRow).find('input.score_entry').attr('id','score_'+data);
				$(clonedRow).find('input.score_entry').val(score);
				$(tr).find('input#question_content_new').val('');
				$(tr).find('input#score_new').val('');
				bindAllStaticEvents();
			} else {
				displayError(data);
			}
		});
		return false;
	});
	
	$(".btn-section-delete").live("click", function(){
		var table = $(this).parents('table:first');
		var id = $(table).attr('id').replace('section_','');
		if(confirm('DELETE SECTION: Are you sure?')) {
			$('.ajax-load').show();
			$.post("/admin/surveys/delete_section", { 
				id: id
			}, function(data){
				$('.ajax-load').hide();
				displayError(data);
				if(data=='ok') {
					$(table).remove();
				}
			});
		}
		return false;
	});
	
	$(".btn-section-add").live("click", function(){
		var div = $(this).parents('div.criterium:first');
		var criterium_id = $(div).attr('id').replace('criterium_','');
		var sectionsdiv = $(div).find('div.sections');
		var clonedSection;
		var newsectiontable = '<table class="section" id="section_3" cellspacing="0" cellpadding="0"><thead><tr><th colspan="4" class="actions"><label>Question</label><input type="text" id="section_name_3" class="section_name_entry" value="" /></th></tr><tr class="questions"><td style="width: 520px;"><label>Answers</label></td><td style="width: 30px;">Score</td><td colspan="2">&nbsp;</td></tr></thead><tbody></tbody><tfoot><tr class="questions question_new"><td><input type="text" id="question_content_new" class="question_content_entry_new" /></td><td><input type="text" id="score_new" class="score_entry_new" /></td><td class="actions" style="text-align: center;"><a href="#" class="btn-question-add">Add</a></td></tr><tr><td colspan="4" class="actions" style="padding:10px; background:#fcf8ea;"><a href="#" class="btn-section-delete">Delete Question</a></td></tr></tfoot></table>';
		$('.ajax-load').show();
		$.post("/admin/surveys/add_section", { 
			criterium_id: criterium_id
		}, function(data){
			$('.ajax-load').hide();
			if(IsNumeric(data)) {
				$(sectionsdiv).append(newsectiontable);
				clonedSection = $(sectionsdiv).find('table.section:last');
				$(clonedSection).attr('id','section_'+data);
				$(clonedSection).find('input.section_name_entry').attr('id','section_name_'+data);
				bindAllStaticEvents();
			} else {
				displayError(data);
			}
		});
		return false;
	});
	
	bindAllStaticEvents();
});

function focusColor() {
	$(this).parents('tr:first').addClass('active');
	return false;
}
function blurColor() {
	$(this).parents('tr:first').removeClass('active');
	return false;
}
function sectionNameBlur() {
	var id = $(this).attr('id').replace('section_name_','');
	var content = $(this).val();
	$.post("/admin/surveys/save_section_name", { 
		id: id, 
		content: content
	}, function(data){
		displayError(data);
	});
	return false;
}
function questionContentBlur() {
	var id = $(this).attr('id').replace('question_content_','');
	var content = $(this).val();
	var score = $('#score_'+id).val();
	$.post("/admin/surveys/save_question", { 
		id: id, 
		content: content,
		score: score
	}, function(data){
		displayError(data);
	});
	return false;
}
function scoreBlur() {
	var id = $(this).attr('id').replace('score_','');
	var content = $('#question_content_'+id).val();
	var score = $(this).val();
	$.post("/admin/surveys/save_question", { 
		id: id, 
		content: content,
		score: score
	}, function(data){
		displayError(data);
	});
	return false;
}

function bindAllStaticEvents() {
	$("table.section input, table.section a").bind("focus", focusColor);
	$("table.section input, table.section a").bind("blur", blurColor);
	$(".section_name_entry").bind("blur", sectionNameBlur);
	$(".question_content_entry").bind("blur", questionContentBlur);
	$(".score_entry").bind("blur", scoreBlur);
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.,$";
   var IsNumber = true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
      {
      	IsNumber = false;
      }
   }
   if(sText.length == 0) {
   		IsNumber = false;
   }
   return IsNumber;
}

function formatCurrency(data) {
	if(IsNumeric(data)) {
		data = String(data).replace(/[\$,]/g,'');
		var temp = data.split(".");
		if(temp[1] && temp[1].length>2)
			temp[1]=temp[1].substr(0,2);
	 
		var output="";
		var re=/(\d{1,3})$/;
		while( temp[0].match( re ) )
		{
			output = "," + RegExp.$1 + output;
			temp[0] = temp[0].replace( re, '' );
		}
		if("undefined" !== typeof(temp[1]) )
		{
			output += "." + String(temp[1]);
		}
		output = output.substring(1);
		return "$" + output;
	} else {
		return data;
	}
}

function formatNumber(data) {
	if(IsNumeric(data)) {
		data = String(data).replace(/[\$,]/g,'');
		var temp = data.split(".");
		if(temp[1] && temp[1].length>2)
			temp[1]=temp[1].substr(0,2);
	 
		var output="";
		var re=/(\d{1,3})$/;
		while( temp[0].match( re ) )
		{
			output = "," + RegExp.$1 + output;
			temp[0] = temp[0].replace( re, '' );
		}
		if("undefined" !== typeof(temp[1]) )
		{
			output += "." + String(temp[1]);
		}
		output = output.substring(1);
		return output;
	} else {
		return data;
	}
}


function displayError(code) {
	if(code=='ok')	{
		
	} else if(code=='noauth') {
		alert('Your login session has expired. You will now be redirect to the login page.');
		window.location.href='/admin/';
	} else {
		//alert(code);
	}
}