$(function() {
	
	$('.survey-table tr:even td').addClass('zebra');
	
	$('.datepicker').datepicker();
	
	$(".addSecondayQuestion").click(function(){
		if ($(this).attr('checked')) {
        	$(this).closest('div').next('div').slideDown('normal');
			//$('.a1-sqg').slideDown('normal');
        } else {
            //$('.a1-sqg').slideUp('normal');
			$(this).closest('div').next('div').slideUp('normal');
        };
	});
	
	$("#create-new-survey-radio input").click(function(){
		if ($(this).val() == "1" ) {
        	$('#clientNameEditInput').attr('title','');
			$('#existingClientID').attr('title','Pick an existing Client');
			$('#existing-client').slideDown('normal');
        	$('#new-client').slideUp('normal');
        } else {
			$('#clientNameEditInput').attr('title','Client Name');
            $('#existingClientID').attr('title','');
			$('#new-client').slideDown('normal');
            $('#existing-client').slideUp('normal');
        };
	});
	
	$(".socialThankYou").click(function() {
		if ($(this).val() == "1" ) {
			$('#custom-thank-you').show();
		} else {
			$('#custom-thank-you').hide();
		}
	});
	
	$('input#bgColor').ColorPicker({
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val(hex);
			$(el).ColorPickerHide();
		},
		onBeforeShow: function () {
			$(this).ColorPickerSetColor(this.value);
		}
	})
	.bind('keyup', function(){
		$(this).ColorPickerSetColor(this.value);
	});
	
	//**************************** Thank you social functions ****************//
	$('.share-twitter, .share-fb').click(function() {
		var clickSharedElement = $(this);
		var shareStatement = $('#feedback-text-social').val();
		var customStatementId = 0;
		
		//Inser the new statement, return the statement id
		$.ajax({
			url: 'includes/ajaxFiles/enterCustomShareThis.php',
			async: false,
			type: "POST",
			data: "statement="+shareStatement+"&whichService="+$(this).attr('class'),
			success: function(msg) {
				customStatementId = msg;
			}
		});
		
		//Set the link body for each type
		var customLinkType = $(this).attr('class');
		if(customLinkType == "share-twitter") {
			$(this).attr('href','http://twitter.com/home?status='+shareStatement);
		} else {
			$(this).attr('href','http://www.facebook.com/sharer.php?u=http://'+surveyDomain+'?fbid='+customStatementId+'&t='+shareStatement);
		} 
		
	});
});

//Cufon.replace('h2');
//Cufon.replace('#admin-area');

///////////////////////////////////////Validate Form//////////////////////////////////////////////////
function validateForm(aform) {
	var el = aform.elements;
	var errorMsg = '';
	var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
	
	for(var i = 0 ; i < el.length ; ++i) {
		var googleToolbar = el[i].title;
		
		if(googleToolbar.substr(0,11) == "Your Google") {continue;}
		
		if(el[i].name == 'url') {
			var surveyID = document.getElementById('surveyID').value;
			
			var isUrlUnique = '';
			isUrlUnique = ajaxFunction('../../includes/ajaxFiles/checkForUniqueUrl.php?url='+el[i].value+'&surveyID='+surveyID,'');
			//If url is not unique, than post error msg ///////
			if(isUrlUnique == "n") {
				errorMsg += 'The URL you entered is currently in use. Either enter a different URL or archive the survey that is using this Url.' + '\n';
			}
		}
		
		if(el[i].name == 'email') {
			if((String(el[i].value).search (isEmail_re) != -1) == false) {
				errorMsg += 'Invalid Email' + '\n';
			}
		} else if (el[i].type == 'select-one') {
			if(el[i].selectedIndex < 1 && el[i].title.length > 0) {
				errorMsg += el[i].title + '\n';
			}
		} else if (el[i].title.length > 0) {
			if(el[i].value.length == 0) {
				errorMsg += el[i].title + '\n';
			}
		}
	}
	
	if(errorMsg.length > 0) {
		errorMsg = 'Please complete all required fields below:\n'+errorMsg;
		alert(errorMsg);
		return false;
	} else {
		return true;
	}
	
	return false;
}

///////////////////////////////////// Survey Questions Functions //////////////////////////////////////
function updateNumberOfAnswers(questionID,numAnswers) {
	
	//if(verifySave('updateNumQuestions')) {
		ajaxFunction('question-answers.php?id='+questionID+'&numAnswers='+numAnswers,'answerContainer');
		
		/////////////////// Have to recall these jquery selectors since the content is being refreshed ////////////
		$(function() {
		
			$(".addSecondayQuestion").click(function(){
				if ($(this).attr('checked')) {
					$(this).closest('div').next('div').slideDown('normal');
					//$('.a1-sqg').slideDown('normal');
				} else {
					//$('.a1-sqg').slideUp('normal');
					$(this).closest('div').next('div').slideUp('normal');
				};
			});
			
			$('#surveyDetailForm input, #surveyQuestionListForm input, input.answerInput, input.addSecondayQuestion').click(function() {
				inputClickedOn = true;
			});			
		});
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//}
}

function updateNumberOfSecondaryAnswers(secondaryQuestionID,numAnswers,counter) {
	//if(verifySave('updateNumQuestions')) {
		ajaxFunction('secondary-question-answers.php?secondaryQuestionID='+secondaryQuestionID+'&secondaryNumAnswers='+numAnswers+'&currentKey='+counter,'secondaryQuestionsContainer_'+counter);
		
		/////////////////// Have to recall these jquery selectors since the content is being refreshed ////////////
		$(function() {
			$('#surveyDetailForm input, #surveyQuestionListForm input, input.answerInput, input.addSecondayQuestion').click(function() {
				inputClickedOn = true;
			});	
		});
		////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	//}
}

///////////////////////////////////// Ajax Function ///////////////////////////////////////////////////
//The base ajax function 
function ajaxFunction(url,divID) {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	
	//Add a random id to the end of the url
	url = url+"&sid="+Math.random();
	//alert(url);
	xmlHttp.open("GET",url,false);
	xmlHttp.send(null);
	
	if(divID.length) {
		document.getElementById(divID).innerHTML = xmlHttp.responseText
	} else {
		return xmlHttp.responseText;
	}
}

////////////////////////// Protect user from leaving page without saving first /////////
var inputClickedOn = false;

$(function() {

	//$('#surveyDetailForm input, #surveyQuestionListForm input, input.answerInput, input.addSecondayQuestion').click(function() {
	$('#surveyDetailForm input, #surveyQuestionListForm input').click(function() {
		inputClickedOn = true;
	});	
});

function verifySave(type) {
	var response;
	
	if(inputClickedOn == true) {
		if(type == 'surveyDetail') {
			response = confirm('Are you sure want to navigate away from this page without saving your Survey Data first. Please click on "Cancel" and then "Submit Survey" or "Reorder Questions" to save your data first or click on "OK" if do not want to save any changes you made.');
		} /*else if (type == "updateNumQuestions") {
			response = confirm('Warning: This will erase all changes that you just made to these answers. Please click on "Cancel" and then "Submit" to save your data first or click on "OK" if do not want to save any changes you made.');
		}*/
		return response;
	} else {
		return true;
	}
}
/////////////////////////////////////////////////////////////////////////////////////////

////////////// Front end - Secondary Questions /////////////////////////////////////////
function checkForSecondaryQuestion(value,checked,type,questionID) {
	ajaxFunction('includes/ajaxFiles/getSubQuestion.php?questionID='+questionID+'&answerID='+value+'&type='+type+'&checked='+checked,'subQuestionContainer_'+questionID);
	
	$(function() {
		if(value == 1) {
			$('#otherAnswerContainer_'+questionID).css('display','');
		} else if(type != "checkbox") {
			$('#otherAnswerContainer_'+questionID).css('display','none');
		} else if(type == "checkbox" && value == "1" && !checked) {
			$('#otherAnswerContainer_'+questionID).css('display','none');
		}
	});
}

////////////// Front end - Save the Secondary Questions Value to Session (no divID to update) /////////////////////////////////////////
function saveSelectionInSession(value,checked,type,questionID) {
	ajaxFunction('includes/ajaxFiles/getSubQuestion.php?questionID='+questionID+'&answerID='+value+'&type='+type+'&checked='+checked,'');
}
