/*------------ Code below will register the user through AJAX Request -----------------------------------------*/
var rTag = $('#front_register .front_reg_submit').parent('div');
$(rTag).children('input').remove();
$(rTag).append('<input type="button" name="submit" value="Agree &amp; Continue" class="submit" />');

$('.age').click(function(){
	$('#age').attr('checked','checked');						 
},function(){
	$('#age').attr('checked',false);		
});

$('#submit_quiz').click(function(){
var mid=$('#m_id').val();
if(mid=="")
{
$(document).ready(function(){
							$(".inline").fancybox({
								'hideOnContentClick': false,
								'autoScale'		: false,
								'autoDimensions'	: false,
								'width': 600,
								'height' : 450,
								'hideOnOverlayClick' : false
							}).trigger('click'); 
						});
}
else
{
$('.loader').show();
$('.loader').html('<img src="images/ajax-loader.gif" style="float:right;" alt="Loading. . ." />');
var ans=$('input[name=options]:checked').val();
var quiz_id = $('#quiz_id').val();


		$.ajax({
		   		type: 'post',
				url: 'components/process_quiz.php',
		   		data : 'ans=' + ans + '&quiz_id=' + quiz_id,
				success:function(results){
					if(results == "correct"){
						$('#fancybox-outer').css('height','350px');
						$('#fancybox-inner').css('height','350px');
						$('.msgbox').html('<div class="success">Congrats, you just earned 1 point</div>');
					}else if(results == "duplicate"){
					 jQuery("input[name='options']").each(function(i) {
					  jQuery(this).attr('disabled', 'disabled');
					});
					jQuery("input[name='submit']").attr('disabled', 'disabled');
						$('#fancybox-outer').css('height','350px');
						$('#fancybox-inner').css('height','350px');
						$('.msgbox').html('<div class="errors">You have already answered this quiz!</div>');
					}
					else if(results == "wrong"){
						$('#fancybox-outer').css('height','350px');
						$('#fancybox-inner').css('height','350px');
						$('.msgbox').html('<div class="errors">Sorry but this was the wrong answer</div>');
					}
					else if(results == "dont_know"){
						$('#fancybox-outer').css('height','350px');
						$('#fancybox-inner').css('height','350px');
						$('.msgbox').html('<div class="errors">Sorry but you have just lost 1 point</div>');
					}
				}
		   })
}		   
});

$('#front_register .submit').click(function(){
	$('.register div.errors').remove();
	$('.loader').show();
	$('.loader').html('<img src="images/ajax-loader.gif" style="float:right;" alt="Loading. . ." />');

	var m_username = $.trim($('#m_username').val());
	var m_email = $.trim($('#m_email').val());
	var m_password = $('#m_password').val();
	var q_id = $('.q_id').val();
	var encoded_id = $('#encoded_id').val();
	
	if($('#age').attr('checked') == false){
		$('.register').prepend('<div class="errors"><p>You must confirm you\'re at least above 13 years old</p></div>');
		$('.register .loader').remove();
		return false;
	}
	var urlpath,curr_url;
	if(window.location.host=="http://dev.webshoppinghelper.com") 
	 urlpath="http://dev.webshoppinghelper.com/include/ajax_registration.php";
	else if(window.location.host=="localhost") 
	 urlpath="http://localhost/wsh/pgsql/include/ajax_registration.php";
	else
	 urlpath="http://www.webshoppinghelper.com/include/ajax_registration.php";	
	
	$.ajax({
		   type: 'post',
		   url : urlpath,
		   data : 'username='+ m_username +'&email='+ m_email +'&password='+ m_password + '&q_id=' + q_id,
			
			success: function(results){
				$("#fancy-outer").css({'height': '600px'});
				$('.register div.errors').remove();
				$('.register .loader').remove();	
				if(results == 'success'){
					$('div.errors').remove();
					document.location = 'http://' + document.domain + '/avatar.php';
				}
				else if(results == 'question_success'){
					$('div.errors').remove();
					document.location = 'question_page.php?q='+encoded_id;
				}else{
					$('.register').prepend(results);
				}
			}
	});
});

$('#front_register .cancel').click(function(){
	$.fancybox.close();														
})

$('#choose_cat_form .cancel').click(function(){
	$.fancybox.close();	
});
/*------------ Register after question has been submitted, END -----------------------------------------*/

/*------------ Code below will log the user through AJAX Request -----------------------------------------*/


$('#login_form .f_submit').click(function(){
	$('.msgbox').hide();
	$('.loader').html('<img src="images/ajax-loader.gif" style="float:right;" alt="Loading. . ." />');
	
	var m_email = $.trim($('#login_name').val());			
	var m_password = $('#login_pass').val();
	var q_id = $('.q_id').val();
	var encoded_id = $('.encoded_id').val();
	var category = $('.category').val();
	var ans = $('.ans').val();
	var urlpath,curr_url;
	if(window.location.host=="dev.webshoppinghelper.com") 
	{
	 urlpath="http://dev.webshoppinghelper.com/include/ajax_login.php";
	 curr_url = 'http://dev.webshoppinghelper.com/';
	}
	else if(window.location.host=="localhost") 
	{
	 urlpath="http://localhost/wsh/pgsql/include/ajax_login.php";
	 curr_url = 'http://localhost/wsh/pgsql/';
	}
	else
	{
     urlpath="http://www.webshoppinghelper.com/include/ajax_login.php";	
	 curr_url = 'http://www.webshoppinghelper.com/';
	}
	$.ajax({
		   		type: 'post',
				url: urlpath,
		   		data : 'm_email=' + m_email + '&m_password=' + m_password + '&q_id=' + q_id + '&ans=' + ans + '&category=' + category,
				success:function(results){
				$('.loader').hide();
				results=results.trim();
				if(results == 'logged'){
						$('.msgbox').show();
						$('.msgbox').html('<div class="success">Login success! You\'re being redirected. . .</div>');
						setTimeout(function(){
							document.location = curr_url;
						},2000);
					}else if(results == 'question_success'){
						$('.msgbox').hide();
						//document.top.location = 'question_page.php?q='+encoded_id;
						document.location.href = 'posted_question.php?q='+encoded_id+"&curr=1";
						
					}else if(results == 'category_page'){
						$('.msgbox').hide();
					document.location.href = 'category.php?category='+category+"&section=category";
						
					}else{
						$('.msgbox').show();
						//$('#fancybox-outer').css('height','350px');
						//$('#fancybox-inner').css('height','350px');
						if(results!="")
						$('.msgbox').html('<div class="errors">'+ results +'</div>');
					}
				}
		   })
	return false;
});

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/*------------ Code below will log the user through AJAX Request END-----------------------------------------*/
/*forgot password by vinay*/
$('#submit_forgot_form .forgot_submit').click(function(){
		
        var m_email = $.trim($('#forgot_email').val());			
		var curr_url = document.location;
		$.ajax({
		   		type: 'post',
				url: 'components/ajax_forgotpasswrd.php',
		   		data : 'm_email=' + m_email,
				
				success:function(results){
					if(results == 'ok'){
						$('.msgbox').html('');
						$('.msgbox').show();
						$('#fancybox-outer').css('height','350px');
						$('#fancybox-inner').css('height','350px');
						$('#submit_forgot_form').css('display','none');
						$('#forgot').css('display','none');
						
						$('.msgbox').html('<div class="success">A mail has been sent to your inbox</div>');
						
						setTimeout(function(){
							parent.window.location = 'register.php?action=login';
						},2000);
						
					}else{
						$('#fancybox-outer').css('height','350px');
						$('#fancybox-inner').css('height','350px');
						$('.msgbox').html('<div class="errors">'+ results +'</div>');
					}
				}
		   })										   
});
/*end of forgot password by vinay*/
/*------------- Simple JQuery Function to toggle below register and login link in Modal Window ---------*/
$('#forgot').toggle(function()
{
	$('#login_form').hide(1000);
	$('.forgot_password').show(1000,function(){	$.fancybox.resize();});
	$('#ajax_login h2').hide().text('Forgot your password').fadeIn('500');
	$('.msgbox').hide();
	return false;
},
function()
{
	$('#login_form').show(1000,function(){$.fancybox.resize()});
	$('.forgot_password').hide(1000);
	$('#ajax_login h2').hide().text('Login to BeesQ').fadeIn('500');
	return false;		
});

	$("#m_email").validate({
		expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
		message: "Please provide a valid email address."
	});
/*-------------/ Simple JQuery Function to toggle below register and login link in Modal Window END---------*/

/*------------- JQuery Function to allow the user to change category after the system has suggested one -----*/

$("input[name='cat']").change(function(){
	var cId = $("input[name='cat']:checked").val();
	
	$('select option[value=' + cId + ']').attr('selected','selected');
});

$('select[name="c_id"]').change(function(){
	var oId = $('select option:selected').val();
	
	if($('input:radio[value=' + oId + ']').length > 0){
		$('input:radio[value=' + oId + ']').attr('checked',true);
	}else{
		$("input[name='cat']").attr('checked',false);
	}
	
	
});

$('#cat_submit').click(function(){

	var c_id = $('select option:selected').val();

	var q_id = $('.question_id').val();
	var encoded_id = $('#encode_q_id').val();
	var checkedRadio = $("input[name='cat']:checked").val();
	
	$.ajax({
		   		type: 'post',
				url: 'include/category_update.php',
				data: 'question_id=' + q_id +'&category_id=' + c_id,
				
				success: function(results){
					$('.preview span p').remove();
					$('.preview span').prepend(results);
							
					setTimeout(function(){

						parent.window.location = 'question_page.php?q='+ encoded_id;
					},3000);
				}
		   });
});

$('.cancel').click(function(){
	parent.$.fancybox.close();							
})
/*------------- JQuery Function to allow the user to change category after the system has suggested one, END -----*/

/*------------- JQuery Ajax Pagination code below ---------------------*/
$(document).ready(function(){	
	
	function showLoad(){
		$('#loading').fadeIn('900');
		$('#loading').html('<img src="images/ajax-loader.gif" alt="Loading..." />');		
	}
	
	function hideLoad(){
		$('#loading').fadeOut('fast');
	}

	$('#current').val(1);
	//$("#paginate a").hide();
	var numOfPages = $("#paginate a").length;
	
	var current = $('#current').val();
	
	if(current < numOfPages){
		var nextPage = parseInt(current) + 1;
	}else{
		var nextPage = numOfPages;
	}
	
	if(numOfPages == 1){
		$('#next').hide();
		$('#prev').hide();
	}
	
	var jsnav = '<div id="prev">Previous</div>';
	jsnav += '<span class="total">Page '+ current +' of '+ numOfPages+'</span>';
	jsnav += '<div id="next">Next</div>';
	$('#jsnav').html(jsnav);
	
	showLoad();
	$(".list_questions").load("list_questions.php?current_page=1&order=desc",hideLoad());
	
	$('#next').click(function(){
		showLoad();
		var current = $('#current').val();
		
		if(current < numOfPages){
			var nextPage = parseInt(current) + 1;
		}else{
			var nextPage = numOfPages;
		}
		
		$('#current').val(nextPage);
		
		if(nextPage <= numOfPages){
			$('.total').html('Page '+ nextPage +' of '+ numOfPages)
			$(".list_questions").fadeTo('fast',0).load("list_questions.php?current_page="+nextPage,function(){hideLoad(); $(this).fadeTo('fast',1)});								  
			return false;
		}
	});

	$('#prev').click(function(){
		showLoad();
		var current = $('#current').val();
		
		if(current > 1){
			var previousPage = parseInt(current) - 1;
		}else{
			var previousPage = 1;
		}

		$('#current').val(previousPage);
		
		if(previousPage >= 1){
			$('.total').html('Page '+ previousPage +' of '+ numOfPages)
			$(".list_questions").load("list_questions.php?current_page="+previousPage,hideLoad());							  
		}
		return false;
	});	
	
	$('#desc').click(function(){
		showLoad();
		$(".list_questions").load("list_questions.php?current_page=1&order=desc",hideLoad());
		return false;
	});	
	
	$('#asc').click(function(){
		showLoad();
		$(".list_questions").load("list_questions.php?current_page=1&order=asc",hideLoad());
		return false;
	});	

	$('#q_view').click(function(){
		showLoad();
		$(".list_questions").load("list_questions.php?current_page=1&order=desc&orderby=q_view",hideLoad());
		return false;
	});	
	
	$('#date').click(function(){
		showLoad();
		$(".list_questions").load("list_questions.php?current_page=1&order=desc&orderby=date",hideLoad());
		return false;
	});	
});
/*------------- JQuery Ajax Pagination code below / END---------------------*/
/*---------------- AJAX Ediding member details ---------------------*/
$('a.edit-about, a.edit-interest').css('display','none');

	
	$('.member_text').click(function(){
		
		var originalTag = $(this);
		var originalTxt = $(this).text();
		
		if($(this).text() == 'No information provided. Click here to add.'){
			originalTxt = '';
		}

		$(this).hide(200).before('<div style="clear:both;" id="theform"><textarea id="member_text" cols="50" rows="5">'+ originalTxt +'</textarea><br /><input type="button" class="edit" value="Edit" /><input type="button" class="profile_cancel" value="Cancel" /></div>');
		
		$('#theform .profile_cancel').click(function(){
												 
			$(this).parent().hide(500,function(){$('#theform .profile_cancel').parent().remove()});
			$(originalTag).text(originalTxt).fadeIn(1000);
			
			if($('#member_text').val() == '')
				$(this).parent().next().text('No information provided. Click here to add.');
		});
		
		$('.edit').click(function(){
			$('.success').hide();
			var field = $(this).parent().prev().text();
			var newValue = $('#member_text').val();
					
			if(newValue == ''){
				newValue = 'No information provided. Click here to add.';	
			}

			$.ajax({
				   	 type: 'post',
					 url: 'components/update_profile.php',
					 data: field +'='+ newValue +'&section='+field,
					 
					 success: function(result){
				   		$('.edit').parent().hide(500,function(){$('.edit').parent().remove()});
						$(originalTag).text(newValue).fadeIn(1000);
						if(field == 'info')
							$('.user_stats').prepend('<div class="success">The about section was updated succesfully.</div>');
						else if(field = 'm_interest')
							$('.user_stats').prepend('<div class="success">The Interests section was updated succesfully.</div>');
					 }
		 	})
		})
	})


$('.current_user_info a.edit').css('display','block');	

$('.current_user_info a.edit_personal').click(function(){
	$('.hidden_form_update').show('slow');		
	
	$('.profile_cancel').click(function(){
		$('.hidden_form_update').hide('slow');						
	})
	return false;
});

$('.hidden_form_update .edit_info').click(function(){
		$('.hidden_form_update img.load').remove();
		$('#a_error').remove();
		$('.hidden_form_update').prepend('<img src="images/ajax-bar.gif" class="load" alt="loading. . ." />');
		
		var m_name = $('#m_name').val();
		var m_gender = $('select#m_gender option:selected').val();
		var m_dob = $('#m_dob').val();
		var m_marital = $('select#m_marital option:selected').val();
		var m_location = $('select#m_location option:selected').val();
		var m_religious = $('#m_religious').val();
		var m_telephone = $('#m_telephone').val();
		
		$.ajax({
			   type: 'post',
			   url : 'include/update_profile.php',
			   data: 'name='+ m_name + '&telephone=' + m_telephone + '&gender=' + m_gender + '&dob=' + m_dob + '&marital='+ m_marital + '&location='+ m_location + '&religious='+ m_religious +'&section=personal',
			   
			   success: function(data){ 
					if(data == 'updated'){
						$('.hidden_form_update img.load').remove();
						$('.hidden_form_update').hide(500);	
						// Set the user's details to the new one
						$('.profile_sep span.name').text(m_name);
						$('.profile_sep1 span.sex').text(m_gender);
						$('.profile_sep1 span.birthday').text(m_dob);
						$('.profile_sep1 span.location').text(m_location);						
						
						if(m_marital == 0)
							$('.profile_sep span.marital').text('Single');
						else if(m_marital == 1)
							$('.profile_sep span.marital').text('In a relationship');
						else if(m_marital == 2)
							$('.profile_sep span.marital').text('Married');
						else if(m_marital == 3)	
							$('.profile_sep span.marital').text('It\'s complicated');
						else if(m_marital == 4)	
							$('.profile_sep span.marital').text('In an open relationship');
						else if(m_marital == 4)
							$('.profile_sep span.marital').text('Widowed');
						
						if(m_gender == 0)
							$('.profile_sep1 span.sex').text('Male');
						else if(m_gender == 1)
							$('.profile_sep1 span.sex').text('Female');

						$('.profile_sep span.religion').text(m_religious);
						
						$('.user_stats div.success').remove();
						$('.user_stats').prepend('<div class="success">The personal section was updated succesfully.</div>');
					}else{
						$('.hidden_form_update img.load').remove();
						$('.hidden_form_update').prepend('<div id="a_error">'+data+'</div>');
					}
			   }			   
		})
})
/*----------------- END AJAX member details -----------------------*/
