$.fn.image = function(src, f){ 
  return this.each(function(){ 
    var i = new Image(); 
    i.src = src; 
    i.onload = f; 
    this.appendChild(i);
  }); 
} 

var Path_Host = "/";

$(document).ready( function() {
    FormToggleRegistration_Init("Student","student");
    FormToggleRegistration_Init("Tutor","tutor");
    FormRegistrationStudent_Init();
    FormProfileStudent_Init();
    FormProfileTutor_Init();
    FormProfileSpreadTheWord_Init();
    UploadButton_Init();
    setConfirmations();
    FormProfileExpertise_Init();
    SetRating_Init();
    FrontPage_Init();
    ViewQuestion_Init();
    FormProfile_Payments_Init();
    ListQuestions_Init();
    FormProfile_Membership_Init();
    FormLogin_Init();
    FormAskQuestion_Init();
    
    $(".ButtonSubmit").click(function(e){
    	form = $(e.target).parents("form");
    	form = form[0];
    	form.submit();
	});

});

function FormProfile_Membership_Init() {
	$("#FormMembership_Period").change(function(e){
		selected = $(e.target).val();
		$(".PeriodPrice").hide();
		$("#FormMembership_PeriodPrice_" + selected).show();
	});
    $(".ButtonSubmitPaypalMembership").click(function(e){
    	form = $(e.target).parents("form");
		selected = $("#FormMembership_Period").val();
		if (selected == 0) return false;
    	form = form[0];
		$(form).append("<input type='hidden' name='amount' value='" + $("#MembershipPrice_"+selected).val() + "' />");
    	form.submit();
	});
}

function ListQuestions_Init() {
	$("#QuestionFilter").change(function(e){
    	form = $(e.target).parents("form");
    	form = form[0];
    	form.submit();
	});
}

function FormProfile_Payments_Init() {
	$("#Button_AddFunds").click(function(){
		$("#Form_WithdrawFunds").hide();
		$("#Form_AddFunds").toggle();
	});
	$("#Button_WithdrawFunds").click(function(){
		$("#Form_AddFunds").hide();
		$("#Form_WithdrawFunds").toggle();
	});
    $(".ButtonSubmitSagepay").click(function(e){
		$(".paypal_field").remove();
    	form = $(e.target).parents("form");
    	form = form[0];
		form.action = $("#sagepay_action").val();
    	form.submit();
//		return false;
	});
    $(".ButtonSubmitPaypal").click(function(e){
		$(".sagepay_field").remove();
    	form = $(e.target).parents("form");
    	form = form[0];
    	form.submit();
	});
}

function FormLogin_Init() {
	$("#FormLogin_ForgotPassword").click(function(){
		$("#FormForgotPassword_Container").show();
	});
	$("#FormForgotPassword_Cancel").click(function(){
		$("#FormForgotPassword_Container").hide();
	});
	$("#FormLogin_Username").keypress(function(k){
		if (k.which == 13 && $("#FormLogin_Username").val() != "" && $("#FormLogin_Password").val() != "") $("#FormLogin").submit();
	});
	$("#FormLogin_Password").keypress(function(k){
		if (k.which == 13 && $("#FormLogin_Username").val() != "" && $("#FormLogin_Password").val() != "") $("#FormLogin").submit();
	});

    if (location.pathname == '/user/login') //only for 'Login' page
    {
      $("#btnLogin").click(function(e){
        form = $(e.target).parents("form");
        form = form[0];
        form.submit();
      });
    }
}

function FormProfileSpreadTheWord_Init() {
	$("#FormProfileSpreadTheWord_See").click(function(){
			message = "<p align='center'><br/>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eleifend eros non tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse elementum. Ut tempus rutrum ante. Phasellus pulvinar.<br /><br/><br/><input type='button' value='OK' class='simplemodal-close' /></p>";
			var modal = $.modal(message, {
				containerCss: {
						height: '200px',
						width: '200px'
				},
				onShow: function() {
					$("#simplemodal-overlay").click(function(){
						modal.close();
					});
				}
			});
	});
}

function FrontPage_Init() {
	$("#FormFrontQuestion_Next").click(function(){

		if ($("#FormFrontQuestion_Text").val().length < 20 ) {
        alert("Your question isn't long enough, it needs to be atleast 20 characters!");
        return;
    }

    $("#FormFrontAskQuestion").submit();
    
		//	message = "<p align='center'><br />Your question isn't long enough, it needs to be atleast 20 characters!<br/><br/><input type='button' value='OK' class='simplemodal-close' /></p>";
		//	var modal = $.modal(message, {
		//		containerCss: {
		//				height: '100px',
		//				width: '200px'
		//		},
		//		onShow: function() {
		//			$("#simplemodal-overlay").click(function(){
		//				modal.close();
		//			});
		//		}
		//	});
		//	return false;
		//}
		
    /*
		$("#FormFrontQuestion_Container").load(Path_Host + "main/front_ask_question", function() {
		var modal = $("#FormFrontQuestion_Container").modal({
			onShow: function() {

				var default_title = $("#FormFrontQuestion_Text").val();
				default_title = default_title.substring(0,65);
				$("#FormFrontQuestion_Title").val(default_title);

				$("#simplemodal-overlay").click(function(){
					modal.close();
				});

				$("#FormFrontQuestion_NeedAnswerDate").datepicker({
				    dateFormat: "yy-mm-dd",
				    minDate: new Date()
				});
				
				$("#FormFrontQuestion_OpenCalendar").click(function() {
					$("#FormFrontQuestion_NeedAnswerDate").datepicker("show");
				});

				$("#FormFrontQuestion_QuestionFromBook_Yes").click(function(){
					$("#FormFrontQuestion_HiddenPart").show();
				});
				
				$("#FormFrontQuestion_QuestionFromBook_No").click(function(){
					$("#FormFrontQuestion_HiddenPart").hide();
				});

				$("#FormFrontQuestion_Subject").change(function(e) {
					$("#FormFrontQuestion_Topic_Container").load(Path_Host + "main/ask_question_topics/" + $(e.target).val());
				});

				$("#FormFrontQuestion_AddAttachment").click(function(e) {
					$("#FormFrontQuestion_Attachment_Container").toggle();
					if ($(e.target).val() == "+") $(e.target).val("-");
					else if ($(e.target).val() == "-") $(e.target).val("+");
				});

				var Errors = false;

				FrontPage_Init_Uploads();

				$("#FormFrontQuestion_Submit").click(function(){
					$("#FormFrontQuestion_Details").val($("#FormFrontQuestion_Text").val());
						$("#FormFrontQuestion_PriceWilling").val($("#FormFrontQuestion_PriceWilling").val().replace(",","."));
						return valid.validate();
					}); 
			}
		});
		});
    */
	});
}

function ViewQuestion_Init() {

	$("#Button_AnswerQuestion").click(function() {
		$("#FormAskStudent_Container").hide();
		$("#FormReportStudent_Container").hide();
		$("#FormAnswerQuestion_Container").toggle();
	});

	$("#Button_AnswerQuestionRedirectToRegister").click(function() {
		window.location = Path_Host + "user/register_form_tutor";
	});

	$("#Button_AskStudent").click(function() {
		$("#FormAnswerQuestion_Container").hide();
		$("#FormReportStudent_Container").hide();
		$("#FormAskStudent_Container").toggle();
	});

	$("#Button_ReportStudent").click(function() {
		$("#FormAnswerQuestion_Container").hide();
		$("#FormAskStudent_Container").hide();
		$("#FormReportStudent_Container").toggle();
	});

	
	$(".Button_SetRedirect").click(function(e) {
		var url = $(e.target).attr("url");
		$.post(Path_Host + "main/setRedirect", { event: "SignIn", redirectTo: ''+url }, function() {
			window.location = Path_Host + "user/login";
		});
		return false;
	});
	
	
	$(".FormAnswerQuestion_AnswerType").click(function(e) {
		var c = $(e.target).val();
		if (c == 1) $("#FormAnswerQuestion_PriceContainer").hide();
		if (c == 2) $("#FormAnswerQuestion_PriceContainer").show();
	});
	
	$("#FormPostAnswer_AddAttachment").click(function(e) {
		$("#FormPostAnswer_Attachment_Container").toggle();
		if ($(e.target).val() == "+") $(e.target).val("-");
		else if ($(e.target).val() == "-") $(e.target).val("+");
	});
	$("#FormPostAnswer_Attachment1").change(function(){
		filename = $("#FormPostAnswer_Attachment1").val();
		$("#FormPostAnswer_AttachmentText1").val(filename);
	});
	$("#FormPostAnswer_Attachment2").change(function(){
		filename = $("#FormPostAnswer_Attachment2").val();
		$("#FormPostAnswer_AttachmentText2").val(filename);
	});
	$("#FormPostAnswer_Attachment3").change(function(){
		filename = $("#FormPostAnswer_Attachment3").val();
		$("#FormPostAnswer_AttachmentText3").val(filename);
	});
}



function FrontPage_Init_Uploads() {
				var valid_extensions = new Array("doc","ppt","jpg","jpeg","png","gif","pdf");
				
				var attachment1 = $("#FormFrontQuestion_Attachment1").clone();
				var attachment2 = $("#FormFrontQuestion_Attachment2").clone();
				var attachment3 = $("#FormFrontQuestion_Attachment3").clone();
				
				$("#FormFrontQuestion_Attachment1").change(function(){
					filename = $("#FormFrontQuestion_Attachment1").val();
					extension = filename.match(/\.(\w+)$/)[1];
					if (!in_array(extension.toLowerCase(),valid_extensions) && filename != "") {
						$("#FormErrors").html("Illegal file type.");
						$("#FormFrontQuestion_Attachment1").replaceWith($(attachment1).clone());
						FrontPage_Init_Uploads();
						return false;
					} 
					$("#FormFrontQuestion_AttachmentText1").val(filename);
				});

				$("#FormFrontQuestion_Attachment2").change(function(){
					filename = $("#FormFrontQuestion_Attachment2").val();
					extension = filename.match(/\.(\w+)$/)[1];
					if (!in_array(extension.toLowerCase(),valid_extensions) && filename != "") {
						$("#FormErrors").html("Illegal file type.");
						$("#FormFrontQuestion_Attachment2").replaceWith($(attachment2).clone());
						FrontPage_Init_Uploads();
						return false;
					} 
					$("#FormFrontQuestion_AttachmentText2").val(filename);
				});
				$("#FormFrontQuestion_Attachment3").change(function(){
					filename = $("#FormFrontQuestion_Attachment3").val();
					extension = filename.match(/\.(\w+)$/)[1];
					if (!in_array(extension.toLowerCase(),valid_extensions) && filename != "") {
						$("#FormErrors").html("Illegal file type.");
						$("#FormFrontQuestion_Attachment3").replaceWith($(attachment3).clone());
						FrontPage_Init_Uploads();
						return false;
					} 
					$("#FormFrontQuestion_AttachmentText3").val(filename);
				});
}

function FormAskQuestion_Topics() {
	$("#FormAskQuestion_Subject").change(function(e) {
		$("#FormAskQuestion_Topic_Container").load(Path_Host + "main/ask_question_topics/" + $(e.target).val());
		
	});
}

function FormAskQuestion_Attachments() {
	$("#FormAskQuestion_AddAttachment").click(function(e) {
		$("#FormAskQuestion_Attachment_Container").toggle();
		if ($(e.target).val() == "+") $(e.target).val("-");
		else if ($(e.target).val() == "-") $(e.target).val("+");
	});
}

function showRecaptcha(element) { 
    Recaptcha.create("{{6Lc44cUSAAAAAOOOmu-avNn6EjIAZVyAxSMcwGxL}}" , element, { 
    theme: "red" 
    }); 
} 

function FormAskQuestion_ValidateRegistration() {

 var post_data = 'Email='+$('#FormRegistrationStudent_Email').val()+'&Username='+$('#FormRegistrationStudent_Username').val();
 post_data = post_data + '&password='+$('#FormRegistrationStudent_Password').val()+'&ConfirmPassword='+$('#FormRegistrationStudent_ConfirmPassword').val();
 post_data = post_data + '&AcceptTOS='+$('#FormRegistrationStudent_AcceptTOS').val()+'&recaptcha_challenge_field='+$('#recaptcha_challenge_field').val()+'&recaptcha_response_field='+$('#recaptcha_response_field').val();
 post_data = post_data + '&Name='+$('#FormRegistrationStudent_Name').val()+'&registermode=ajax';
 
    $.ajax({
        url: Path_Host + 'user/validate_register_form_student',
        type: "POST",
        data: post_data,
        dataType : "json",                     
        success: function (ret_data, textStatus) {
            if (!ret_data['res'])
            {
                $('#FormRegistration_FormErrors').html(ret_data['FormErrors']);

                $("#myrecaptcha").load(Path_Host + "user/include_recaptcha", function() {
                	// Special handling required for Google Recaptcha.
                	window.setTimeout(showRecaptcha, 500, 'myrecaptcha'); 
                });
                
            }
            else{
                $('#FormRegistration_FormErrors').html('');
                
                $('#FormQuestionStudent_Email').val($('#FormRegistrationStudent_Email').val());
                $('#FormQuestionStudent_Username').val($('#FormRegistrationStudent_Username').val());
                $('#FormQuestionStudent_Password').val($('#FormRegistrationStudent_Password').val());
                $('#FormQuestionStudent_Name').val($('#FormRegistrationStudent_Name').val());

                $('#FormQuestionStudent_Level').val($('#FormRegistrationStudent_Level').val());
                $('#FormQuestionStudent_DateOfBirth').val($('#FormRegistrationStudent_DateOfBirth').val());
                $('#FormQuestionStudent_Country').val($('#FormRegistrationStudent_Country').val());
                $('#FormQuestionStudent_State').val($('#FormRegistrationStudent_State').val());
                $('#FormQuestionStudent_School').val($('#FormRegistrationStudent_School').val());
                
                $('#FormAskQuestion').submit();
            }
        }
        });    
}

function FormAskQuestion_Init() {
    FormAskQuestion_Topics();
    FormAskQuestion_Attachments();
	$("#FormAskQuestion_NeedAnswerDate").datepicker({
		dateFormat: "yy-mm-dd",
		minDate: new Date()
	});
	$("#FormAskQuestion_OpenCalendar").click(function() {
		$("#FormAskQuestion_NeedAnswerDate").datepicker("show");
	});

	$("#FormAskQuestion_QuestionFromBook_Yes").click(function(){
		$("#FormAskQuestion_HiddenPart").show();
	});
	$("#FormAskQuestion_QuestionFromBook_No").click(function(){
		$("#FormAskQuestion_HiddenPart").hide();
	});

    //$("#AskQuestionSignIn").click( function(e) {
    //    $("#AskQuestionSignIn_Container").load(Path_Host + "user/login/inline", function() {
    //        FormLogin_Init();
    //
    //    var modal = $("#AskQuestionSignIn_Container").modal({ onShow: function() {}});

    if (location.pathname.indexOf('ask_question') >=0  ) //only for 'Login' page
    {
				$("#btnLogin").click(function(){
            var uname = $('#FormLogin_Username').val();
            var pwd = $('#FormLogin_Password').val();
            var remember = $('#FormLogin_RememberMe').val();
            
            $.ajax({
                url: Path_Host + 'user/login/ajax/' + uname + '/' + pwd + '/' + remember,
                dataType : "json",                     
                success: function (data, textStatus) {
                    if (!data['res'])
                        $('#FormLogin_FormErrors').html(data['FormErrors']);
                    else{
                        $('#FormLogin_FormErrors').html('');
                        $('#FormAskQuestion_Submit').css("display", 'block');

                        $('#FormAskQuestion_Register').css("display", 'none');
                        $('#FormAskQuestion_Register1').css("display", 'none');
                        $('#FormAskQuestion_Register2').css("display", 'none');

                        $('#a_logout').css("display", 'inline');
                        $('#a_login').css("display", 'none');
                        
                        //modal.close();
                    }
                }
                });
        });
    }
        
        //});
    //});
    

}

function FormRegistrationStudent_Init() {
    //alert('123');
    $("#FormRegistrationStudent_DateOfBirth").datepicker({
						    changeYear: true,
						    changeMonth: true,
						    dateFormat: "yy-mm-dd",
						    yearRange: "1900:2020"
					      });
    
    FormRegistrationStudent_LoadStates();
    
    $("#FormRegistrationStudent_Country").change( function(e) {
    	FormRegistrationStudent_LoadStates($(e.target).val());
    });
}

function FormRegistrationTutor_Init() {
	$("#FormRegistrationTutor_QualificationHelp").click(function(){
		message = "<p align='center'><br/>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eleifend eros non tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse elementum. Ut tempus rutrum ante. Phasellus pulvinar.<br /><br/><br/><input type='button' value='OK' class='simplemodal-close' /></p>";
		var modal = $.modal(message, {
			containerCss: {
				height: 200,
				width: 200
			},
			onShow: function() {
				$("#simplemodal-overlay").click(function(){
					modal.close();
				});
			}
		});
	});

}

function FormRegistrationStudent_LoadStates(Country) {
    //alert('1eee');
    if (!Country) Country = $("#FormRegistrationStudent_Country").val();
    DefaultState = $("#FormRegistrationStudent_State_Container").attr("default");
    $("#FormRegistrationStudent_State_Container").load(Path_Host + "user/register_form_states/" + Country + "/" + DefaultState, function() {
	FormRegistrationStudent_LoadSchools();
	$("#FormRegistrationStudent_State").change( function(e) {
	    FormRegistrationStudent_LoadSchools($(e.target).val());
	});
    });
}

function FormRegistrationStudent_LoadSchools(State) {
    if (!State) State = $("#FormRegistrationStudent_State").val();
    DefaultSchool = $("#FormRegistrationStudent_School_Container").attr("default");
    $("#FormRegistrationStudent_School_Container").load(Path_Host + "user/register_form_schools/" + State + "/" + DefaultSchool);
}

function FormToggleRegistration_Init(element, url) {
    $("#FormToggleRegistration_"+element).click( function(e) {
    	$("#MainContent").load(Path_Host + "user/register_"+url, function() {
    	window.setTimeout(showRecaptcha, 500, 'myrecaptcha'); 
	    FormRegistrationStudent_Init();
	    FormRegistrationTutor_Init();
	});
    });
}



function UploadButton_Init() {
	$("#FormEditTutor_Picture").change(function(){
		filename = $("#FormEditTutor_Picture").val();
		$("#FormEditTutor_PictureText").val(filename);
	});
	$("#FormEditStudent_Picture").change(function(){
		filename = $("#FormEditStudent_Picture").val();
		$("#FormEditStudent_PictureText").val(filename);
	});
	$("#FormAskQuestion_Attachment1").change(function(){
		filename = $("#FormAskQuestion_Attachment1").val();
		$("#FormAskQuestion_AttachmentText1").val(filename);
	});
	$("#FormAskQuestion_Attachment2").change(function(){
		filename = $("#FormAskQuestion_Attachment2").val();
		$("#FormAskQuestion_AttachmentText2").val(filename);
	});
	$("#FormAskQuestion_Attachment3").change(function(){
		filename = $("#FormAskQuestion_Attachment3").val();
		$("#FormAskQuestion_AttachmentText3").val(filename);
	});
	$("#FormProfileQualification_Verification").change(function(){
		filename = $("#FormProfileQualification_Verification").val();
		$("#FormProfileQualification_VerificationText").val(filename);
	});
}

function FormProfileTutor_Init() {
	$("#FormProfileExpertise_Subject").change(function() {
		$("#FormProfileExpertise_Topic_Container").load(Path_Host + "user/profile_expertise_edit_topics/" + $("#FormProfileExpertise_Subject").val() + "/" + $("FormProfileExpertise_Id").val(), function() { FormProfileTutor_Init(); });
	});
}

function FormProfileStudent_Init() {
	
    $("#FormProfileStudent_DateOfBirth").datepicker({
						    changeYear: true,
						    changeMonth: true,
						    dateFormat: "yy-mm-dd",
						    yearRange: "1900:2020"
					      });
    
    FormProfileStudent_LoadStates();
    
    $("#FormProfileStudent_Country").change( function(e) {
    	FormProfileStudent_LoadStates($(e.target).val());
    });
}

function FormProfileStudent_LoadStates(Country) {
    if (!Country) Country = $("#FormProfileStudent_Country").val();
    DefaultState = $("#FormProfileStudent_State_Container").attr("default");
    $("#FormProfileStudent_State_Container").load(Path_Host + "user/profile_edit_form_states/" + Country + "/" + DefaultState, function() {
	FormProfileStudent_LoadSchools();
	$("#FormProfileStudent_State").change( function(e) {
	    FormProfileStudent_LoadSchools($(e.target).val());
	});
    });
}

function FormProfileStudent_LoadSchools(State) {
    if (!State) State = $("#FormProfileStudent_State").val();
    DefaultSchool = $("#FormProfileStudent_School_Container").attr("default");
    $("#FormProfileStudent_School_Container").load(Path_Host + "user/profile_edit_form_schools/" + State + "/" + DefaultSchool);
}


function setConfirmations() {
    $(".ConfirmNeeded").click( function() {
    	if (confirm("Are you sure?")) return true;
	return false;
    });
}

function FormProfileExpertise_Init() {
	var active = "/images/ico_expertise_active.png";
	var inactive = "/images/ico_expertise.png";

	var C = $("#FormProfileExpertise_Number_Images");
	var num = $("#FormProfileExpertise_Number");

	C.children("img").mousemove(function(e){
		var o = $(e.target);
		C.children("img").each(function(){
			if (Number($(this).attr("cou")) <= Number($(o).attr("cou"))) {
				this.src = active;
			} else {
				this.src = inactive;
			}
		});
	});

	C.children("img").click(function(e){
		var o = $(e.target);
		num.val($(o).attr("cou"));
	});

	C.mouseout(function(){
		C.children("img").each(function(){
			if ($(this).attr("cou") <= Number(num.val())) {
				this.src = active;
			} else {
				this.src = inactive;
			}
		});
	});
}

function SetRating_Init() {
	var active = "/images/star_feedback.png";
	var inactive = "/images/starempty_feedback.png";

	var C = $("#SetRating_Images");
	var num = $("#SetRating_Rating");

	C.children("img").mousemove(function(e){
		var o = $(e.target);
		C.children("img").each(function(){
			if (Number($(this).attr("cou")) <= Number($(o).attr("cou"))) {
				this.src = active;
			} else {
				this.src = inactive;
			}
		});
	});

	C.children("img").click(function(e){
		var o = $(e.target);
		num.val($(o).attr("cou"));
	});

	C.mouseout(function(){
		C.children("img").each(function(){
			if ($(this).attr("cou") <= Number(num.val())) {
				this.src = active;
			} else {
				this.src = inactive;
			}
		});
	});
}

function in_array(needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
 
    var found = false, key, strict = !!argStrict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}
function show_buy_table(tablename)
{
	//alert(tablename);
  $('#buy_question_tbl'+tablename).slideDown("slow");
	$('#buy_question_btn'+tablename).hide();	
}

function hide_buy_table()
{
  $('#buy_question_btn').style.display='block'; 	
	$('#buy_question_tbl').style.display='none'; 	
}

function FormAskQuestionRegister1Show()
{
 $('#FormAskQuestion_Register1').css('display', 'block');
 $('#FormAskQuestion_Register2').css('display', 'none');
}

function FormAskQuestionRegister2Show()
{
 $('#FormAskQuestion_Register2').css('display', 'block');
 $('#FormAskQuestion_Register1').css('display', 'none');
}
