/**********************************************
Useful Functions
***********************************************/
var path = "/";

function validate_email(contactemail){
	var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	if (!filter.test(contactemail)){
		return false;
	}else
		return true;
}

$(document).ready(function(){
	
/**************************************************************************************************************************************
		Testimonial Cycler: Loads all the testimonials from the DB, then cycles through them.

		Name:		Testimonial Cycler
		File Name:	-
		Version: 	1.0
		Date:		26/04/2010
		Developer	Jason Hungerford
		
		Copyright rembasoft 2010

**************************************************************************************************************************************/

	function loadTestimonial(){
		$.post(path+"ajax/randomTestimonial.php", {'prev': $('[testimonial=current]').val()}, function(xml){
				$('[testimonial=main]').text($(xml).find('testimonial').text());
				$('[testimonial=customer]').text($(xml).find('customer').text());
				$('[testimonial=current]').val($(xml).find('current').text())
				$('[testimonial=testimonial]').fadeIn(1000).delay(8000).fadeOut(1000, loadTestimonial);	
		});
	}
	
    loadTestimonial();

/**************************************************************************************************************************************
		Image Loader: Preloads an images with the tag il=true and the image has _thumb as the source.
		
		V1.2 update: Added functionality to add also process css background images.
		
		Name:		Image Loader
		File Name:	ImageLoader_v1.2.js
		Version: 	1.2
		Date:		28/03/2010
		Developer	Jason Hungerford
		
		Copyright rembasoft 2010

**************************************************************************************************************************************/
	$('[il|=true]').bind("imageLoad", function(){
		$(this).attr('src')!=null? $(this).attr('src', ($(this).attr('src').replace("_thumb", ""))):$(this).css('background-image', $(this).css('background-image').replace("_thumb", ""));		
	});
	
	$(window).load(function() { 
	//	alert($('[il|=true]').length);				
		$('[il|=true]').trigger("imageLoad");
	});
	
	
	/*************************************
			Faq Box Functionality
	*************************************/

	$('#faqbox').find('dl').find('dd').hide().end().find('dt').click(function(e) {
		e.preventDefault();
		//alert($(this).attr('id'));
		var id = $(this).attr('id');
		if($(this).next().css('display') == 'none' && $('#faqviewed'+id).val() != "true"){
			$.post(path+"ajax/addViewFAQ.php", { 'id': $(this).attr('id'), 'key': $('#key').val() }, function(xml){
			   // format and output result
				$('#faqviewed'+id).val("true");
				
			});
		}
		$(this).next().slideToggle('fast');
	});
	
	$('#faqbox a').click(function(e) {
		if($(this).attr('id') == 'faqbox_yes' || $(this).attr('id') == 'faqbox_no'){
			e.preventDefault();
			var id = $(this).attr('href'); 			
			if($('#faqvoted'+id).val() != "true"){
				$.post(path+"ajax/addResultFAQ.php", { 'result': $(this).attr('id').replace("faqbox_", ""), 'id': $(this).attr('href')}, function(xml){
					// format and output result					
					$('#faqvoted'+id).val("true");
				});
			}
			
			$(this).parent().parent().slideToggle('fast');
		}
	});
	
	
	/*************************************
			Popup Examples and images
	*************************************/
	//SETTING UP OUR POPUP
	//0 means disabled; 1 means enabled;
	var popupWindowStatus = 0;

	$("#loading").hide();
	
	$("#loading").ajaxStart(function(e){							 
	   PositionWindowCenter("loading");
	   $(this).show('fast');
	 });
	$("#loading").ajaxStop(function(){
	   $(this).hide();
	 });
	
	//centering popup
	function PositionCenter(name){
		//request data for centering
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = $("#"+name).height();
		var popupWidth = $("#"+name).width();
		//centering
		$("#"+name).css({
			"position": "absolute",
			"top": windowHeight/2-popupHeight/2,
			"left": windowWidth/2-popupWidth/2
		});
		//only need force for IE6	
	}
	
	function centerPopupWindow(name){
		//request data for centering
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = $("#"+name).height();
		var popupWidth = $("#"+name).width();
		//centering
		$("#"+name).css({
			"position": "absolute",
			"top": windowHeight/2-popupHeight/2,
			"left": windowWidth/2-popupWidth/2
		});
		//only need force for IE6
		
		$("#backgroundPopup").css({
			"height": windowHeight
		});
	}
	
	function PopupCenter(name, w,h) {
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
		$("#"+name).css({
			"top": top,
			"left": left
		});
	} 

	
	function centerWindowOnEvent(e, name){
		//request data for centering
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = $("#"+name).height();
		var popupWidth = $("#"+name).width();
		//centering
		$("#"+name).css({
			"position": "absolute",
			"top": (popupHeight/2) + (e.pageX/2),
			"left": (windowWidth/2)-(popupWidth)
		});
		//only need force for IE6
		
		$("#backgroundPopup").css({
			"height": windowHeight
		});
	}

	function loadBackgroundWindow(){
		
		if(popupWindowStatus==0){
			
			$("#backgroundPopup").css({
				"opacity": "0.7"
			});
			
			$("#backgroundPopup").fadeIn("fast");	
			
		}
	}
	
	function loadPopupWindow(name){
		//loads popup only if it is disabled
		if(popupWindowStatus==0){
			$("#"+name).fadeIn(500);
			popupWindowStatus2 = 1;
			
			popupWindowStatus = 1;
		}
	}
	
	function disableBackgroundWindow(name){
			//disables popup only if it is enabled
			$("#backgroundPopup").fadeOut( "fast", function(){});		
	}
	
	//disabling popup with jQuery magic!
	function disablePopupWindow(name){
		//disables popup only if it is enabled
		if(popupWindowStatus==1){
			$("#"+name).hide(function(){
				$("#backgroundPopup").fadeOut( "fast", function(){
				
				popupWindowStatus = 0;
				});
			});
		}
	}
	
	
	
	//$('#CloseRestoration2').click(closehandler);
	
	function WindowClosehandler(e) {
	  	e.preventDefault();
		disablePopupWindow(e.currentTarget.title, 'close');
	}
	
	$("#backgroundPopup").click(function(e){
		disablePopupWindow('Example', 'close');
	});
	
	$("#opExample1").click(function(e){
		e.preventDefault();
		loadBackgroundWindow();
		//centering with css
		centerWindowOnEvent(e, 'Example1');
		//load popup
		loadPopupWindow('Example1');
	});	
	
	$("#opExample2").click(function(e){
		e.preventDefault();
		loadBackgroundWindow();
		//centering with css
		centerWindowOnEvent(e, 'Example2');
		//load popup
		loadPopupWindow('Example2');
	});	
	
	$("#Example2").click(function(e){
		e.preventDefault();
		disablePopupWindow('Example2', 'close');
	});
	
	$("#Example1").click(function(e){
		e.preventDefault();
		disablePopupWindow('Example1', 'close');
	});	
	
	
	/**************************************************************************************************************************************
		FEEDBACK: Provide feedback on all your pages. Login/Register and submit feedback on all your pages.
		
		Name:		Web Feedback
		File Name:	Feedback_v1.0.js
		Version: 	1.1
		Date:		08/04/2010
		Developer	Jason Hungerford
		
		Update v1.1:
			- Added # of pages of # 
			- Fixed page name size issue
			- Added functionality to "anonomys" checkbox
		
		Copyright rembasoft 2010

**************************************************************************************************************************************/
	$(window).load(function(){		
		if($.browser.mozilla){
			reset_feedback_values();
		}		
	});
	
	function show_hide_feedback(){		 
		if($('#Feedback').css('display')=='none'){		
			loadBackgroundWindow();
			PopupCenter("Feedback", 528, 600);
		   $('#Feedback').show('slow', function(){ updateFeedbackCount(); calculate_overall(); calculate_rating()});		   
		}else{
			$('#Feedback').hide('fast', function(){reset_feedback();});
			//$('#btnFeedback').html('Show Feedback Form >>');
			disableBackgroundWindow();
			reset_feedback();
		}		
	}
	
	function submit_feedback(e){
		e.preventDefault();
		
		calculate_overall();
		
		if($('#Anonymous').attr('checked') == true)
			$('#userid').val('0');
			
		//Get Browser
		
		if($.browser.msie)
			$('#browser').val('msie');
		else if($.browser.mozilla)
			$('#browser').val('mozilla');
		else if($.browser.opera)
			$('#browser').val('opera/chrome');
		else if($.browser.safari)
			$('#browser').val('safari');
		$('#version').val($.browser.version);
		
		
		
		$.post(path+"ajax/submitFeedback.php", $("#frmFeedback").serialize(), function(xml){			
			if($(xml).text() == 1){
				$('#Feedback_Thankyou').html('<h2 style="text-align:center;">Thank you for your feedback</h2>');			
				$('#Feedback_Questions').fadeOut('fast', function(){
					$('#Feedback_Thankyou').fadeIn(500, function(){						
						$('#Feedback_Thankyou').animate({opacity:0.9}, 700, function(){ show_hide_feedback(); reset_feedback_values();});
					});		
				});
			}else	
				alert("error with save");				
		});		
		
	}
		
	function updateFeedbackCount(){	
			
		$.post(path+"ajax/getFeedbackCount.php", function(xml){			
			if($(xml).find('status').text() == 1){				
				$('#feedbackcount').val($(xml).find('feedback').text());
				$('#pagecount').val($(xml).find('pagecount').text());
				//alert($('.headernote').html().replace('[feedbackcount]', $(xml).find('pagecount').text()));
				$('.headernote').html($('.headernote').html().replace('[feedbackcount]', $(xml).find('feedback').text()));	
				$('.headernote').html($('.headernote').html().replace('[pagecount]', $(xml).find('pagecount').text()));	
			}
		});
	}
	
	function reset_feedback(){
		$('#Feedback_Thankyou').css('display', 'none');	
		$('#Feedback_Thankyou').css('opacity', '1');	
		$('#Feedback_Login').css('display', 'none');
		$('#Feedback_Register').css('display', 'none');
		$('#Feedback_Questions').css('display', 'block');
	}	
	
	function reset_feedback_values(){
		for(var i=0; i<4; i++){
			$('#op'+i+'sel').val('0');	
			$('.op'+i+'rating').css('background-image', $('.op'+i+'rating').css('background-image').replace("op1.png", "op1bg.png"));
		}
		$('#oprating').val('0');
		calculate_overall();
	}
	
	function feedback_login(e){
		e.preventDefault();
			// send request			
		$.post(path+"ajax/login.php", $("#frmFeedbackLogin").serialize(), function(xml){
			if($("status", xml).text() == "1"){	
				
				$(".headernote").html("Thank you offering to provide feedback. You have provided feedback on [feedbackcount] of [pagecount] pages.");
				updateFeedbackCount();
				$(".footnoteright").html('Logged in as '+$(xml).find('firstname').text()+' '+$(xml).find('surname').text()+' <a href="#" id="FeedbackLogout2" name="FeedbackLogout2">Log out</a>');
				$('#userid').val($(xml).find('custno').text());
				$('#FeedbackLogout2').click(feedback_logout);
				switchToQuestion();
			}else
				alert("failed to login");
		});
		
	}
	
	function feedback_logout(e){
		e.preventDefault();
			// send request
		$.post(path+"ajax/logout.php", function(xml){
			if($("status", xml).text() == "1"){	
				$(".headernote").html("Thank you offering to provide feedback. <a href=\"#\" id=\"FeedbackRegister\">Don't forget to register for all the latest news about Remba</a></p>");
				$(".footnoteright").html('<a href="#" id="FeedbackLogin2" name="FeedbackLogin2">Login</a> | <a href="#" id="FeedbackRegister2" name="FeedbackRegister2">Register</a>');	
				$('#userid').val("0");
				$('#FeedbackLogin2').click(function(e){ e.preventDefault(); switchToLogin();});
				$('#FeedbackRegister2').click(function(e){ e.preventDefault(); switchToRegister();});
				
				switchToQuestion();
			}else
				alert("failed to logout");
		});		
	}
	
	function feedback_register(){
			// send request	
		if(feedback_validate()){
			
			$.post(path+"ajax/checkuser.php", $("#frmFeedbackRegister").serialize(), function(xml){				
				if($("status", xml).text() == "0"){					
					$('#email').css('background-color', '#d5f793');
					$('.errornote').html('* This email address already exists. Please login or use an alternative email.');					
				}else{
					$.post(path+"ajax/register.php", $("#frmFeedbackRegister").serialize(),  function(xml){
						if($("status", xml).text() == "1"){	
							$(".headernote").html("Thank you offering to provide feedback. You have provided feedback on "+$(xml).find('feedbackcount').text()+" of "+$(xml).find('pagecount').text()+" pages.");
							$(".footnoteright").html('Logged in as '+$(xml).find('firstname').text()+' '+$(xml).find('surname').text()+' <a href="#" id="FeedbackLogout2" name="FeedbackLogout2">Log out</a>');
							
							$('#userid').val($(xml).find('custno').text());
							$('#FeedbackLogout2').click(feedback_logout);
							$('#Feedback_Thankyou').html('<h2 style="text-align:center;">Registering...<img class="loading" src="/feedback/images/loading.gif" alt="Loading" height="16" width="16" /></h2>');			
							$('#Feedback_Register').fadeOut('fast', function(){
								$('#Feedback_Thankyou').fadeIn(500, function(){						
									$('#Feedback_Thankyou').animate({opacity:0.9}, 700, function(){ 
										$('#Feedback_Thankyou').html('<h2 style="text-align:center;">Thank you for registering</h2>');																	 								$('#Feedback_Thankyou').animate({opacity:1.0}, 800, function(){ 
											switchToQuestion(); 											
										});
									});
								});		
							});
						}else
							alert("failed to register");
					});						
				}
			});			
		}
	}
	
	function feedback_validate(){
		var ok = true;
		$('.errornote').html('');
		$('[required=true]').each(function(i){
			if($(this).val() == ''){
				$(this).css('background-color', '#d5f793');
				if(ok)
					$('.errornote').html('*Please ensure all feilds are completed');
				ok=false
			}else
				$(this).css('background-color', '#fff');
		});
		
		if(!ok)
			return false;
		
		var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		if (!filter.test($('#email').val())){
			if(ok)
				$('.errornote').html('* Please enter a vaild email address.');
			$('#email').css('background-color', '#d5f793');
			$('#email').focus();
			return false;
		}
		
		//Check Passwords are the same
		if($('#passwd').val() != $('#confirmpassword').val()){
			if(ok)
				$('.errornote').html('* Passwords did not match');
			
			$('#passwd').css('background-color', '#d5f793');
			$('#confirmpassword').css('background-color', '#d5f793');
			return false;
		}
		if($('#acceptTandC').attr('checked') == false){
			if(ok)
				$('.errornote').html('* Please accept the terms and conditions to continue.');
			return false;
		}	
		
		return true;
	}
	
	function switchToQuestion(){ 
		$('#Feedback_Login').css('display', 'none');	
		$('#Feedback_Register').css('display', 'none');
		$('#Feedback_Thankyou').css('display', 'none');	
		$('#Feedback_Questions').css('display', 'block');
	}
	
	function switchToLogin(){
		$('#Feedback_Questions').css('display', 'none');
		$('#Feedback_Register').css('display', 'none');
		$('#Feedback_Login').css('display', 'block');
	}
	
	function switchToRegister(){
		$('#Feedback_Questions').css('display', 'none');	
		$('#Feedback_Login').css('display', 'none');
		$('#Feedback_Register').css('display', 'block');
	}
	
	function calculate_rating(){
		var avg = $('#avgrating').val();
		avg = (avg/5)*100;
		$('#feedback_rating').animate({width: avg+"px"}, 1000);	
							
	}
	
	$('#btnFeedback').click(function(e){ e.preventDefault(); show_hide_feedback();});
	
	$('#btnFeedbackClose').click(function(e){e.preventDefault(); show_hide_feedback();});
	$('#btnFeedbackCancel').click(function(e){ e.preventDefault(); show_hide_feedback();});	
	
	$('#btnRegisterSubmit').click(function(e){e.preventDefault(); feedback_register();});
	$('#btnRegisterCancel').click(function(e){ e.preventDefault(); switchToQuestion();});	
	
	
	$('#CloseFeedbackX').click(function(e){ e.preventDefault(); show_hide_feedback();});	
	
	$('#btnFeedbackSubmit').click(submit_feedback);
	
	$('#FeedbackLogin1').click(function(e){ e.preventDefault(); switchToLogin();});
	$('#FeedbackRegister1').click(function(e){ e.preventDefault(); switchToRegister();});
	$('#FeedbackRegister2').click(function(e){ e.preventDefault(); switchToRegister();});
	
	$('#FeedbackLogout1').click(feedback_logout);
	
	
	$('#btnFeedbackLogin').click(feedback_login);
	
	$('.op0rating').click(rate_question);
	$('.op1rating').click(rate_question);
	$('.op2rating').click(rate_question);
	$('.op3rating').click(rate_question);
	
	function rate_question(e){
		//alert($(this).css('background-image'));
		$(this).css('background-image', $(this).css('background-image').replace("bg", ""));
		var count = $(this).attr('id');
		var question = $(this).attr('class');
		var question = question.replace("rating", "sel");
		$('#'+question).val(count);
		$(this).siblings().each(function(i){
			if(i<count){
				$(this).css('background-image', $(this).css('background-image').replace("bg", ""));
			}
			if(i>=count){
				if($(this).css('background-image').search(/bg.png/i)<0)
					$(this).css('background-image', $(this).css('background-image').replace(".png", "bg.png"));				
			}
			
		});
		calculate_overall();
	}
	
	function calculate_overall(){
		var count = 0;
		var sum = 0 ;
		for(var i=0; i<4; i++){
			if($('#op'+i+'sel').val() > 0){
				sum+= parseInt($('#op'+i+'sel').val());
				count++;
			}
		}
		if(sum>0){
			avg = (sum/count);
			avgPercentage = (avg/5)*100;
		}else{
			avg = 0;
			avgPercentage = 0;
		}
		$('#oprating').val(avg);
		$('#customer_rating').animate({width: avgPercentage+"px"}, 600);	
	}

});
