var IndeedQuiz = {
	expire_time: 0,
	submited_value: '',
	do_decode: '',
	quiz_id: 0,
	question_id: 0,
	submit_quiz_button: '',
	next_bttn: '',
	course_id: 0,

	start: function(){
	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : {
	                   action: "ulp_start_quiz",
	                   qid: this.quiz_id,
										 course_id: this.course_id,
	               },
	        success: function (r) {
	        	window.location.href = r;
	        }
	   	});
	},
	shift: function(d){
		//console.log(this.course_id);
		//return false;
	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : {
	                   action: "ulp_quiz_shift_question",
	                   question_id: this.question_id,
	                   qid: this.quiz_id,
	                   direction: d,
										 course_id: this.course_id,
	        },
	        success: function (r) {
							//console.log(r);return false;
				  		window.location.href = r;
	        }
	   	});
	},
	saveAnswer: function(do_submit){
		var s = "[name=" + this.question_id + "]";
		var t = jQuery(s).attr('type');
		var do_decode = 0;
		if (typeof t=='undefined'){
				is_sorting = jQuery("[name='" + this.question_id + "[]']").attr('data-field_type');
				if (is_sorting=='sorting'){
						t = 'sorting';
				} else if (is_sorting=='fill_in'){
						t = 'fill_in';
				} else if (is_sorting=='matching'){
						t = 'matching';
				} else if (is_sorting=='textarea'){
						t = 'textarea';
				} else {
						//Essay
						is_sorting = jQuery("[name='" + this.question_id + "']").attr('data-field_type');
						if (is_sorting=='textarea'){
							t = 'textarea';
						}else{
							t = 'checkbox';
						}
				}
		}

		var ajaxData = {
							 action: "ulp_save_question_answer",
							 question_id: this.question_id,
							 qid: this.quiz_id,
							 course_id: this.course_id,
		};
		switch (t){
			case 'radio':
				var v = jQuery(s+":checked").val();
				break;
			case 'text':
			case 'number':
			case 'hidden':
			case 'textarea':
				var v = jQuery(s).val();
				break;
			case 'sorting':
					var c = new Array();
					jQuery("[name='" + this.question_id + "[]']").each(function(){
							c.push(jQuery(this).val());
					});
					v = JSON.stringify(c);
					do_decode = 1;
				break;
			case 'checkbox':
				var c = new Array();
				jQuery("[name='" + this.question_id + "[]']").each(function(){
					if (jQuery(this).is(":checked")){
						c.push(jQuery(this).val());
					}
				});
				v = JSON.stringify(c);
				do_decode = 1;
				break;
			case 'fill_in':
				var c = new Array();
				jQuery("[name='" + this.question_id + "[]']").each(function(){
						c.push(jQuery(this).val());
				});
				v = JSON.stringify(c);
				do_decode = 1;
				break;
			case 'matching':
				var c = new Array();
				jQuery("[name='" + this.question_id + "[]']").each(function(){
						c.push(jQuery(this).val());
				});
				v = JSON.stringify(c);
				var questions = new Array();
				jQuery(".js-ulp-micro-question").each(function(){
						questions.push(jQuery(this).html());
				});
				ajaxData.the_questions = questions;
				//console.log(ajaxData.the_questions)
				do_decode = 1;
				break;
		}

		ajaxData.the_value = v;
		ajaxData.decode = do_decode;

	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : ajaxData,
	        success: function (r) {
	        	/// some extra jobs
	        	if (do_submit==true){
		        	IndeedQuiz.submit();
	        	}
	        }
	   	});
	},
	makeDisabled: function(){
			var t = jQuery("[name=" + this.question_id + "]").attr('disabled', 'disabled');
	},
	returnCorrectOrWrong: function(){
		var c = this.correct_answer_msg;
		var w = this.wrong_answer_msg;
		jQuery.ajax({
				type : "post",
				url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
				data : {
									 action: "ulp_question_return_correct_or_wrong",
									 question_id: this.question_id,
									 qid: this.quiz_id,
									 course_id: this.course_id,
							 },
				success: function (r) {
						if (r==1){
								jQuery('.ulp-question-responses').append(c);
						} else {
								jQuery('.ulp-question-responses').append(w);
						}
						if (IndeedQuiz.is_last()==1){
								//IndeedQuiz.insert_submit();
						} else {
								IndeedQuiz.insert_next();
						}
				}
		});
	},
	submit: function(){
	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : {
	                   action: "ulp_submit_quiz",
	                   qid: this.quiz_id,
										 course_id: this.course_id,
	        },
	        success: function (r) {
	        	window.location.href = r;
	        }
	   	});
	},
	is_last: function(){
			return this.is_last_question;
	},
	insert_submit: function(){
			jQuery('.ulp-question-buttons-wrapper').append(this.submit_quiz_button);
	},
	insert_next: function(){
			jQuery('.ulp-question-buttons-wrapper').append(this.next_bttn);
	},
};

var IndeedCourse = {
	enroll: function(CourseId){
	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : {
	                   action: "ulp_do_enroll_course",
	                   course_id: CourseId,
	        },
	        success: function (r){
						jQuery('#enroll_course_'+CourseId).remove();
						jQuery('#ulp_enroll_box_course_'+CourseId).append(r);
						setTimeout(function(){
								location.reload();
						}, 2000);
	        }
	   	});
	},
	finish: function(){
		var CourseId = jQuery('#ulp_finish_course_bttn').attr('data-course_id');
	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : {
	                   action: "ulp_finish_course",
	                   course_id: CourseId,
	        },
	        success: function (r) {
							//window.location.href = r;
							location.reload();
	        }
	   	});
	},

	retake: function(CourseId){
	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : {
	                   action: "ulp_do_retake_course",
	                   course_id: CourseId,
	        },
	        success: function (r){
						jQuery('#ulp_retake_box_message_'+CourseId).append(r);
						setTimeout(function(){
								location.reload();
						}, 6000);
	        }
	   	});
	},


}
var IndeedLesson = {
	doComplete: function(){
		var LessonId = jQuery('#ulp_lesson_complete_bttn').attr('data-lesson_id');
		jQuery.ajax({
			type: 'post',
			url: decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
			data: {
	                   action: "ulp_complete_lesson",
	                   lesson_id: LessonId,
			},
			success: function(r){
				if (r==1){
					location.reload(); /// refresh
				}
			}
		});
	}
};
var IndeedQuestion = {
	showHint: function(){
		var d = jQuery('#ulp_the_hint').attr('class');
		if (d=='ulp-hint-hide'){
			jQuery('#ulp_the_hint').attr('class', 'ulp-hint-show');
		} else {
			jQuery('#ulp_the_hint').attr('class', 'ulp-hint-hide');
		}
	}
};
var UltimateLearningPro = {
	current_page: null,
	init: function(){
		var ulp_general_messages = JSON.parse(ulp_messages);
		//============= QUIZES
		/// START QUIZ
		jQuery('#ulp_start_quiz_bttn').click(function(){
			IndeedQuiz.start();
		});
		/// RETAKE QUIZ
		jQuery('#ulp_retake_quiz_bttn').click(function(){
			IndeedQuiz.start();
		});
		/// NEXT QUESTION
		jQuery(document).on('click', '#ulp_quiz_next_question', function(){
				IndeedQuiz.saveAnswer(false);
				IndeedQuiz.shift('forward');
		});
		/// PREV QUESTION
		jQuery(document).on('click', '#ulp_quiz_prev_question', function(){
				IndeedQuiz.saveAnswer(false);
				IndeedQuiz.shift('back');
		});
		/// SUBMIT QUIZ
		jQuery(document).on('click', '#ulp_submit_quiz_bttn', function(){
				IndeedQuiz.saveAnswer(true);
		});
		jQuery('#ulp_quiz_submit_via_ajax').click(function(){
				IndeedQuiz.saveAnswer(false);
				IndeedQuiz.makeDisabled();
				jQuery('#ulp_quiz_submit_via_ajax').remove();
				jQuery('#ulp_hint_link').remove();
				setTimeout(function(){
					IndeedQuiz.returnCorrectOrWrong();
				}, 1000);
				//IndeedQuiz.returnCorrectOrWrong();
		});
		/// show hint
		jQuery('#ulp_hint_link').click(function(){
			IndeedQuestion.showHint();
		});
		jQuery('#ulp_become_instructor').click(function(){
			jQuery.ajax({
				type: 'post',
				url: decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
				data: {
		    		action: "ulp_become_instructor_ajax",
				},
				success: function(r){
					jQuery('#ulp_become_instructor').remove();
					jQuery('.ulp-become-instructor-wrapp').append(window.become_instructor_message);
					//if (r==1){
						location.reload(); /// refresh
					//}
				}
			});
		});
		//=============== COURSES
		/// FINISH COURSE
		jQuery('#ulp_finish_course_bttn').click(function(){
			IndeedCourse.finish();
		});
		jQuery('.ulp-enroll-course-the-button').click(function(){
			var course_id = jQuery(this).attr('data-cid');
			IndeedCourse.enroll(course_id);
		});

		jQuery('#ulp_retake_course_bttn').click(function(){
			var course_id = jQuery(this).attr('data-course_id');
			IndeedCourse.retake(course_id);
		});
		//============ LESSONS
		jQuery('#ulp_lesson_complete_bttn').click(function(){
			IndeedLesson.doComplete();
		});
		/// course rating
		jQuery('.ulp-star-item .fa-ulp').on('hover', function(e){
				var parent = jQuery(this).parent().parent().attr('class');
				ulpUnsetStars(parent);
				var num = jQuery(this).parent().attr('data-star_num');
				ulpSetStar(parent, num);
		});
		jQuery('.ulp-star-item .fa-ulp').on('mouseout', function(e){
				var parent = jQuery(this).parent().parent().attr('class');
				ulpUnsetStars(parent);
				if (jQuery('.js-ulp-course-rating').val()){
						ulpSetStar(parent, jQuery('.js-ulp-course-rating').val() );
				}
		});
		jQuery('.ulp-star-item .fa-ulp').on('click', function(e){
				var parent = jQuery(this).parent().parent().attr('class');
				var num = jQuery(this).parent().attr('data-star_num');
				ulpSetStar(parent, num);
				jQuery('.js-ulp-course-rating').val(num);
				return false;
		});
		/// notes
		jQuery('#note_course_id').on('click', ulpNoteOpenPopup);
		/// buy course
		jQuery('.js-ulp-pay-course-bttn').on('click', function(){
				var courseId = jQuery(this).attr('data-course_id');
				var paymentType = jQuery(this).attr('data-payment_type');
				jQuery.ajax({
						type: 'post',
						url: decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
						data: {
								action: 'ulp_buy_course_via_standard_bttn',
								course_id: courseId,
								payment_type: paymentType,
						},
						success: function(response){
								if (response==0 || response=='0'){
										//alert("An error have occued, please try again later!");
										swal({
													title: ulp_general_messages.error,
													text: ulp_general_messages.general_error,
													type: "error",
													showCancelButton: false,
													confirmButtonClass: "ulp-btn-danger",
													confirmButtonText: "Ok",
													closeOnConfirm: true
										});
								}	else {
										window.location.href = response;
								}
						}
				});
		});
		jQuery('#ulp_checkout').on('submit', function(){
				var got_type = jQuery('[name=payment_type]:checked').val();
				if (typeof got_type=='undefined'){
						//alert('Please select a payment type!');
						swal({
								  title: ulp_general_messages.error,
								  text: ulp_general_messages.payment_type_error,
								  type: "error",
								  showCancelButton: false,
								  confirmButtonClass: "ulp-btn-danger",
								  confirmButtonText: "Ok",
								  closeOnConfirm: true
						});
						return false;
				}
				return true;
		});
	}, ///end of init
};
function ulpSetStar(parent, num){
	for (i=1; i<=num; i++){
			jQuery('.' + parent + ' .i_'+i+ ' .fa-ulp').removeClass('fa-star-o-ulp').addClass('fa-star-ulp');
	}
}
function ulpUnsetStars(parent){
	for (i=1; i<6; i++){
			jQuery('.' + parent + ' .i_'+i+ ' .fa-ulp').removeClass('fa-star-ulp').addClass('fa-star-o-ulp');
	}
}
/// execute script
jQuery(function(){
	UltimateLearningPro.init();
});
///////////// NOTES
function ulpNoteOpenPopup(){
		jQuery.ajax({
				type : "post",
				url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
				data : {
									 action: "ulp_get_note_popup"
				},
				success: function (r) {
						jQuery('body').append(r);
				}
		});
}
function ulpOpenInvoice(i){
		jQuery.ajax({
				type : "post",
				url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
				data : {
									 action: "ulp_get_invoice_popup",
									 order_id: i
				},
				success: function (r) {
						jQuery('body').append(r);
				}
		});
}
function ulpClosePopup(){
		jQuery('#ulp_popup').fadeOut(500, function(){
				jQuery(this).remove();
		});
}
function ulpNoteSave(){
	jQuery.ajax({
			type : "post",
			url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
			data : {
								 action: "ulp_save_note",
								 course_id: jQuery('#note_course_id').attr('data-course_id'),
								 title: jQuery('#note_title').val(),
								 content: jQuery('#note_content').val(),
			},
			success: function (r) {
					ulpClosePopup();
			}
	});
}
function ulpLoveCourse(course, elem){
		var the_action = jQuery('#' + elem).attr('data-action');
		if (the_action=='add'){
				var t = 'ulp_add_to_watch_list';
		} else {
			  var t = 'ulp_remove_from_watch_list';
		}
		//console.log(the_action);
		jQuery.ajax({
				type : "post",
				url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
				data : {
									 action: t,
									 course_id: course,
				},
				success: function (r) {
						if (the_action=='add'){
								jQuery('#'+elem).attr('class', '');
								jQuery('#'+elem).attr('class', 'ulp-watch-list-button ulp-watch-list-active');
								jQuery('#wishlist-icon').attr('class', '');
								jQuery('#wishlist-icon').attr('class', 'fa-ulp fa-watch_list-ulp');
								jQuery('#'+elem).attr('data-action', 'remove');
						} else {
							jQuery('#'+elem).attr('class', '');
							jQuery('#'+elem).attr('class', 'ulp-watch-list-button ulp-watch-list-noactive');
							jQuery('#wishlist-icon').attr('class', '');
							jQuery('#wishlist-icon').attr('class', 'fa-ulp fa-watch_list_not_assign-ulp');
							jQuery('#'+elem).attr('data-action', 'add');
						}
				}
		});
}
function ulpRemoveFromWatchList(e){
		jQuery.ajax({
				type : "post",
				url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
				data : {
									 action: 'ulp_remove_from_watch_list',
									 course_id: jQuery(e.target).attr('data-course_id'),
				},
				success: function(){
						course_id = jQuery(e.target).attr('data-course_id');
						jQuery('.ulp-remove-'+course_id).remove();
				}
		});
}
function ulpRemoveNote(e){
		jQuery.ajax({
				type : "post",
				url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
				data : {
									 action: 'ulp_delete_note',
									 id: jQuery(e.target).attr('data-id'),
				},
				success: function(r){
						jQuery(e.target).parent().remove();
				}
		});
}
jQuery(document).ready(function(){
		jQuery('.js-remove-watch-list').on('click', ulpRemoveFromWatchList, this.element);
		jQuery('.js-ulp-remove-note').on('click', ulpRemoveNote, this.element);
		jQuery('#ulp_checkout_payment_select input').on('click', ulpPaymentSelect, this.element);
});
function ulpOpenCertificate(certificateId){
	jQuery.ajax({
			type : "post",
			url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
			data : {
								 action: "ulp_get_certificate_popup",
								 user_certificate_id: certificateId
			},
			success: function (r) {
					jQuery('body').append(r);
			}
	});
}
function ulpPaymentSelect(e){
		jQuery('#js_ulp_checkout_loading_gif').css('visibility', 'visible');
		if (jQuery(e.target).val()=='stripe'){
				jQuery.ajax({
						type : "post",
						url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
						data : {
											 action: 'ulp_get_stripe_payment_form',
						},
						success: function(r){
								if ( jQuery('#ulp_stripe_payment_form_fields').length==0 ){
										jQuery(e.target).parent().append(r);
										jQuery('#ulp_stripe_payment_form_fields').slideDown(500, function (){
												jQuery('#js_ulp_checkout_loading_gif').css('visibility', 'hidden');
										});
								} else {
										jQuery('#js_ulp_checkout_loading_gif').css('visibility', 'hidden');
								}
						}
				});
		} else {
				if ( jQuery('#ulp_stripe_payment_form_fields').length ){
						jQuery('#ulp_stripe_payment_form_fields').slideUp(500, function(){
								jQuery('#ulp_stripe_payment_form_fields').remove();
								jQuery('#js_ulp_checkout_loading_gif').css('visibility', 'hidden');
						});
				} else {
						jQuery('#js_ulp_checkout_loading_gif').css('visibility', 'hidden');
				}
		}
}
function ulpDeleteFileViaAjax(id, u_id, parent, name, hidden_id){
	var r = confirm("Are you sure you want to delete?");
	if (r) {
			var s = jQuery(parent).attr('data-h');
	   	jQuery.ajax({
	        type : "post",
	        url : decodeURI(window.ulp_site_url)+'/wp-admin/admin-ajax.php',
	        data : {
	                   action: "ulp_delete_attachment_ajax_action",
	                   attachemnt_id: id,
	                   user_id: u_id,
	                   field_name: name,
										 h: s
	        },
	        success: function (data) {
	        	jQuery(hidden_id).val('');
	        	jQuery(parent + ' .ajax-file-upload-filename').remove();
	        	jQuery(parent + ' .ulp-delete-attachment-bttn').remove();
	        	if (jQuery(parent + ' .ulp-member-photo').length){
	        		jQuery(parent + ' .ulp-member-photo').remove();
	        		if (name=='ulp_avatar'){
	        			jQuery(parent).prepend("<div class='ulp-no-avatar ulp-member-photo'></div>");
	        			jQuery(parent + " .ulp-file-upload").css("display", 'block');
	        		}
	        	}
	        	if (jQuery(parent + " .ulp-file-name-uploaded").length){
	        		jQuery(parent + " .ulp-file-name-uploaded").remove();
	        	}
	        	if (jQuery(parent + ' .ajax-file-upload-progress').length){
	        		jQuery(parent + ' .ajax-file-upload-progress').remove();
	        	}
	        	if (jQuery(parent + ' .ulp-icon-file-type').length){
	        		jQuery(parent + ' .ulp-icon-file-type').remove();
	        	}
	        }
	   });
	}
}

function ulpCheckAndH(s, t){
	if (jQuery(s).is(':checked')){
		jQuery(t).val(1);
	} else {
		jQuery(t).val(0);
	}
}

function ulpShowSelectorIf(target, check, value_to_compare){
		if (check==value_to_compare){
				jQuery(target).css('display', 'block');
				return;
		}
		jQuery(target).css('display', 'none');
}

function ulpDoModuleToggle(i){
	var ulp_general_messages = JSON.parse(ulp_messages);
		var display = jQuery('#ulp_module_content_inside_'+i).css('display');
		if (display=='none'){
				jQuery('#ulp_module_content_inside_'+i).slideDown( 500 );
				var str = '<i class="fa-ulp fa-toggle_up-ulp" title="' + ulp_general_messages.toggle_section + '" ></i>';
		} else {
				jQuery('#ulp_module_content_inside_'+i).slideUp( 500 );
				var str = '<i class="fa-ulp fa-toggle_down-ulp" title="' + ulp_general_messages.toggle_section + '" ></i>';
		}
		jQuery('#ulp_toggle_modukle_' + i ).html(str);
}

function ulpAddZero(i)
{
		if (i < 10) {
				i = "0" + i;
		}
		return i;
}

function openMediaUp(target, img_target){
    //If the uploader object has already been created, reopen the dialog
  var custom_uploader;
  if (custom_uploader) {
      custom_uploader.open();
      return;
  }
  //Extend the wp.media object
  custom_uploader = wp.media.frames.file_frame = wp.media({
      title: 'Choose Image',
      button: {
          text: 'Choose Image'
      },
      multiple: false
  });
  //When a file is selected, grab the URL and set it as the text field's value
  custom_uploader.on('select', function() {
      attachment = custom_uploader.state().get('selection').first().toJSON();
      jQuery(target).val(attachment.url);
      if (img_target!=''){
      	jQuery(img_target).attr('src', attachment.url);
      	jQuery(img_target).css('display', 'block');
      }
  });
  //Open the uploader dialog
  custom_uploader.open();
}

// start developer work

// end developer work
