/*  -------------------   globals ---------------------- */
var descArrObj = new Object(); 
var kDESCRIPTION_LENGTH = 750;
var kAPATH = 'assets/business_booster_content/';

var clientObj = null;

var serial_attempts = 0;

var currentSection;
var currentSubsection;
/*  -------------------   globals end ---------------------- */



$(document).ready(function() {
	 
	$(".tipsBannerLink").click(function() {
		$("#tips_dropdown").slideDown(700);
		var destination = $(this).offset().top;
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-10}, 500 );
	});
	
	$("#closeDropdown").click(function() {
		$("#tips_dropdown").slideUp(700);
	});
	
	$("#growBanner").click(function() {
		$.colorbox({
			'href':"grow_your_business.php"
		});
	});
		
	$(".mobile_warning .close_warning").click(function(e) {
		e.preventDefault();
		$('.mobile_warning_cntr').hide();
		setCookie('mobile_warning', true, 30);
		
	});


	function setCookie(c_name,value,exdays)
	{
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		document.cookie=c_name + "=" + c_value;
	}


	 
	 
	 $('#loginBtn').click(function(e){
		// alert("login");	 
	 });
	
	function loginFunction(e, el) {
		e.preventDefault();
		
		var fromCBox = false;
		
		if(el.attr('id') == 'sub_signin') {
			fromCBox = true;
		}
		
		// alert("Signing In");
		var username;
		if(fromCBox) {
			username = $('#sub_username');
		}
		else {
			username = $("#username");
		}
         email = username.val().toLowerCase();
 		 username.val(email);

		 var valid = validateEmail(username.attr('value'));
		 
		 // validate email
		 if(valid) {
			// alert("valid");
			var postData = el.serialize();
			
			var callback = function(jsonObj) {
				if(jsonObj.status == 'success') {
					loggedIn(jsonObj);
					$('#username').val('');
					$('#password').val('');


					// if we are on discussion board page reload the iframe.

					$('#boardframe').attr({src: $('#boardframe').attr('src')});


					
				} else {
						// inform error
					display('Login Error', jsonObj.errorMessage, 'Login Error');
					
				}	
			}
			
			var callback2  = function(jsonObj) {
				if(jsonObj.status == 'success') {
					loggedIn(jsonObj);
					$('#username').val('');
					$('#password').val('');


					// if we are on discussion board page reload the iframe.

					$('#boardframe').attr({src: $('#boardframe').attr('src')});
					$.colorbox.remove();


					
				} else {
						// inform error
					$("#sub_error").text(jsonObj.errorMessage);
					
				}	
			}
			
			if(!fromCBox) {
				$.post("signin.php", postData, callback, "json" );
			}
			else {
				$.post("signin.php", postData, callback2, "json" );
			}
			 
		 } else {
			if(!fromCBox) {
				display('Login Error', 'Invalid Email Address', 'Login Error');
			}
			else {
				$("#sub_error").text("Invalid Email Address");
			}
		 }
		 
		 return false;
	}
	
	$('#signin, #sub_signin').submit(function(e){
		 loginFunction(e, $(this));
	});
	
	$('#sub_signin_submit').click(function(e){
		$("#sub_error").text('');
		 loginFunction(e, $("#sub_signin"));
	});
	
	/*
	 $('#signin, #sub_signin').submit(function(e){
		 e.preventDefault();
				
		// alert("Signing In");
         email = $('#username').val().toLowerCase();
 		 $('#username').val(email);

		 var valid = validateEmail($('#username').attr('value'));
		 
		 // validate email
		 if(valid) {
			// alert("valid");
			var postData = $(this).serialize();
			
			var callback = function(jsonObj) {
				if(jsonObj.status == 'success') {
					loggedIn(jsonObj);
					$('#username').val('');
					$('#password').val('');


					// if we are on discussion board page reload the iframe.

					$('#boardframe').attr({src: $('#boardframe').attr('src')});


					
				} else {
						// inform error
					 display('Login Error', jsonObj.errorMessage, 'Login Error');
				}
				
			}
			
			$.post("signin.php", postData, callback, "json" );
			 
		 } else {
		   display('Login Error', 'Invalid Email Address', 'Login Error');
		 }
		 
		 return false;
	 });
	*/

	$('#forumLink').click(function(e){
		//alert("clicked");
		if(clientObj == null) {
			display("Membership Required.", "You must be a Ricoh Business Booster member and logged into your account to access and participate in the discussion forum. If you are not a member, click here to register.", "Membership Required.");

		} else {
			window.location.href = "discussion.php";
		}
		
		return false;
	});
	
	
	$("a[rel='veiwDocMobile']").click(function(e) {
		e.preventDefault();
		
		$(this).attr("id").replace("view_", "");
		
		if(clientObj != null && clientObj.loggedIn == true) {
			window.location.href = $(this).attr('href'); 
		}
		else {
			$('#' + $(this).attr("id")).colorbox.remove();
        	$('#' + $(this).attr("id")).colorbox.init();
        	$('#' + $(this).attr("id")).colorbox({"href":"#no_perm", "width":"640", "height":"500", "inline":true, "opacity":0.5, "transition":'elastic', "title":"Membership Required"});

		}
	});
	 
	$("a[rel='viewDoc']").click(function(e){
	
		e.preventDefault();
		//alert($(this).attr("id"));
		var id = $(this).attr("id").replace("view_", "");
		var title = $("#title_" + id).text();
		
		var doc_loc = kAPATH + $(this).attr('href');

		//alert(clientObj.loggedIn);
		
        if(clientObj != null && clientObj.loggedIn == true) {
	      
	      	if(mobile_device) {
	      		window.open(doc_loc);
	      	}
	      	else {
		      	$('#' + $(this).attr("id")).colorbox.remove();
		        $('#' + $(this).attr("id")).colorbox.init();
		      	if (doc_loc.substr(doc_loc.lastIndexOf(".") + 1) == "flv") {
		      		
		      		$('#' + $(this).attr("id")).colorbox({"rel" : "nofollow",  "width":"800", "height":"600", "iframe":true, "opacity":0.85, "transition":'elastic', "title":title, "href":"video.php?&fp=" + $(this).attr('href').replace(".flv", "")});
		      		
		      	} else {
		      		
		        	$('#' + $(this).attr("id")).colorbox({"rel" : "nofollow",  "width":"800", "height":"600", "iframe":true, "opacity":0.85, "transition":'elastic', "title":title, "href":doc_loc});
		      	}
		      	
		      	logAction(clientObj.login_id, currentSection, currentSubsection, id);
		      	
	      	} 
      } else {
        $('#' + $(this).attr("id")).colorbox.remove();
        $('#' + $(this).attr("id")).colorbox.init();
        $('#' + $(this).attr("id")).colorbox({"href":"#no_perm", "width":"640", "height":"500", "inline":true, "opacity":0.5, "transition":'elastic', "title":"Membership Required"});
      }
			
	});
		
	$("a[rel='dlDoc']").click(function(e){
  			e.preventDefault();

  			var doc_loc = kAPATH + $(this).attr('href');
  			var id = $(this).parent().attr("id");

        if(clientObj != null && clientObj.loggedIn == true) {
          $(this).colorbox.remove();
          $(this).colorbox.init();
          $('#dl_link').attr('href', doc_loc);
          $('#dl_link').trigger('click');
          logAction(clientObj.login_id, currentSection, currentSubsection, id);
        } else {
          $(this).colorbox.remove();
          $(this).colorbox.init();
          $(this).colorbox({"href":"#no_perm", "width":"640", "height":"500", "inline":true, "opacity":0.5, "transition":'elastic', "title":"Membership Required"});
        }

  	 });
  		
  		
  	 $('#dl_link').bind('click', function() {
  		if(mobile_device) {
          	window.open(this.href);
        }
        else {
        	window.location.href = this.href;
        }
        return false;
     });
	
	 
	 $('#model_id').change(function(){
		window.location.href = "resources.php?subsection=3&model_id=" + $('#model_id option:selected').attr('value') + "&page=1&sort=";
	 });
	 
	 $('#vmid').change(function(){
			window.location.href = "resources.php?subsection=7&vmid=" + $('#vmid option:selected').attr('value') + "&page=1&sort=";
	 });
	 
	 
	 
	 
	 $(".adjust").click(function() {

		 var desc_id = 'desc_' + + $(this).attr('id').replace("sc_", "");

		 if($(this).text() == "[+] Show Content"){
			 $('#' + desc_id).text(descArrObj[desc_id]);
			 $(this).text("[-] Hide Content");
		 } else {
			 $('#' + desc_id).text(descArrObj[desc_id].substr(0, kDESCRIPTION_LENGTH) + " ... ");
		 	$(this).text("[+] Show Content");
		 }
		 
	 	});
	 
	 
	 $('#registerFormBtn').click(function(e){
		 e.preventDefault();
		 
		 $('.validationError').remove();  // remove if we had a failed submit attempt
		 $('.errorHighlight').remove();
		 
		 var serial = $('#product_serial').val().toUpperCase();
 		 $('#product_serial').val(serial);
 		 
 		 conf_serial = $('#confirm_serial').val().toUpperCase();
 		 $('#confirm_serial').val(conf_serial);

         email = $('#email').val().toLowerCase();
 		 $('#email').val(email);

         conf_email = $('#confirm_email').val().toLowerCase();
 		 $('#confirm_email').val(conf_email);
		 
		 if(!validate()) {
			 return;
		 }

		 //alert("2");
		 
		 // check serial
		 
		 ++serial_attempts;
		 var valid_sn = false;

		var callback = function(jsonObj) {
			
				if(jsonObj.status == true) {
					valid_sn = true;
					serial_attempts = 0;
	       			$.colorbox({"href":"#terms_conditions", "width":"640", "height":"460", "inline":true, "opacity":0.5, "transition":'elastic', "title":"Terms And Conditions"});
					
				} else {
					if(serial_attempts == 3) {
		   				serial_attempts = 0;
		    			
						$('#reg_inst').html('<h1>Invalid serial number.</h1>We\'re sorry, but we cannot verify your product serial number.<br/> If you have entered a valid serial number please contact us at <a id="alink" href="mailto:info@ricohbusinessbooster.com">info@ricohbusinessbooster.com</a>');
		    			$('#register').hide();
						return;
					}
				 	
						$.colorbox.remove();
						$.colorbox.init();
						$.colorbox({"width":"33%", "inline":true, "opacity":0.5, "href":"#invalidSerialCBDialog"});
				}
			};

		 var postData = 's=' + serial;
		 
		  $.post("sobjx.php", postData, callback, "json" );


	});
	 
	 
	 
	 
	 $('#changePassFormBtn').click(function(e){
		 e.preventDefault();
		 
		 $('.validationError').remove();  // remove if we had a failed submit attempt
		 $('.errorHighlight').remove();
		 
		 var postData = $('#change_pass_form').serialize();
		 
		 if(!chgPwdValidate()) {
			 return;
		 }
		 

		var callback = function(jsonObj) {
			
				if(jsonObj.status == 'success') {
	       			$.colorbox({"href":"#passwordChanged", "width":"640", "height":"320", "inline":true, "opacity":0.5, "transition":'elastic', "title":"Change Password"});
					
				} else {
						$.colorbox.remove();
						$.colorbox.init();
						$.colorbox({"width":"33%", "inline":true, "opacity":0.5, "href":"#chgPwdError"});
				}
			};

		 
		  $.post("change_pass_proc.php", postData, callback, "json" );
			
			//callback({"status":false});


	});
	
	 
	 
	 $('#acceptTerms').click(function(e) {
	 $('#registerFormBtn').colorbox.remove();
	   
	    var postData = $('#register').serialize();

 			 var callback = function(jsonObj) {
 				  if(jsonObj.status == 'success') {
   					$('#register').remove();

   					$('#reg_inst').html('<H1>Registration Successful!</h1>Your registration is complete and you may now login to the site. A confirmation email will be sent to you shortly for your records.')

   				} else {
   					alert('Error processing request');
   				}

 			  };

 		    $.post("register_user.php", postData, callback, "json" );
	 });
	 
	 
	 $('#decline').click(function(e) {
	    
	    $('#registerFormBtn').colorbox.close();
	    
	   });
	 
	 $("#logoutBtn").click(function() {
		 postData = '';

		 var callback = function(jsonObj) {
				if(jsonObj.status == 'success') {
					logOut();

					// if we are on discussion board page reload the iframe.

					$('#boardframe').attr({src: $('#boardframe').attr('src')});
					
				} else {
					alert('Error on logout.');
					logOut();
				}
				
			};
		 
		  $.post("logout.php", postData, callback, "json" );
		 
	 	});
	 	
	 	
	 	$('.exSiteLink').click(function(e){
	 	  e.preventDefault();
	 	  
	 	  window.open($(this).attr('href'), $(this).attr('id')+'Window', 'width=800,height=600,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
	 	  
	 	});
	 	
	 	$('.colorbox_close').click(function(){
	 	    $(this).colorbox.close();
	 	})
	 	
	 	
	 	$('#optimalLink').click(function(){
	 	  $(this).colorbox({"href":"#browse_req", "width":"640", "height":"480", "inline":true, "opacity":0.5, "transition":'elastic', "title":"Browsing Requirements"});
	 	});
	 	
	 
	 hideDescContentInit(descArrObj);
	 
 });  /// document ready


function hideDescContentInit(anObj) {

	 $('.rs-description').each(function(index){

		 var textSwitch = $("#sc_" + $(this).attr('id').replace("desc_", "")); // i cant think of a better name!!!
		 
		 anObj[$(this).attr('id')] = $(this).text();
		 
		 if ( $(this).text().length >= kDESCRIPTION_LENGTH) {
			 $(this).text($(this).text().substr(0, kDESCRIPTION_LENGTH) + " ... ");
			 textSwitch.show();
		 } else {
			 textSwitch.hide();
		 }
		 
	 });
	 
	 
	 
	 $('#contactusBtn').click(function(e){
		 e.preventDefault();
		 
		 $('.validationError').remove();  // remove if we had a failed submit attempt
		 $('.errorHighlight').remove();
		 
		 if(!contactValidate()) {
			 return;
		 }
		 
		 
		 var postData = $('#contactusForm').serialize(); 
			
			var callback = function(jsonObj) {
				if(jsonObj.status == 'success') {
					$('#contactusForm').remove();
					
					$('#reg_inst').html('<h1>Your message has been sent!</h1>We appreciate your feedback.');
					
				} else {
					display('Contact Us Error', 'Error processing request.', 'Contact Us Error');
				}
				
			};

		 
		$.post("contact_proc.php", postData, callback, "json" );
		 
	 });
	 
 }
 
function regInit() {
	
}


function validate() {
	
	var validated = true;
	
	$('#regContainer div label input').each(function(){
		 
		 if($(this).attr('value') == '') {
			$(this).parent().append('<span class="validationError, errorHighlight">*</span>');
			 validated = false;
		 }
		 
	 });
		
		
		if(!validated) {
		   $('#reg_inst').append('<div class="validationError" style="padding-top:10px;">Please fill in the required (*) fields</div>');
		   display('Registration Error', 'Please fill in all the required fields.', 'Registration Error');
		   return false;
		 }
	
	
	if(!validateEmail($('#email').attr('value'))) {
    display('Registration Error', 'Invalid email address.', 'Registration Error');
		validated = false;
	}
	
	if (($('#email').attr('value') != '' && $('#confirm_email').attr('value') != '') && ($('#email').attr('value') != $('#confirm_email').attr('value') )) {
		display('Registration Error', 'Email and confirmation email must match.', 'Registration Error');
		validated = false;
	}
	
	//alert ($('#password').attr('value') + ' ' + $('#confirm_password').attr('value'));
	if (($('#password').attr('value') != '' && $('#confirm_password').attr('value') != '') && ($('#password').attr('value') != $('#confirm_password').attr('value') )) {
		display('Registration Error', 'Password and confirmation password must match.', 'Registration Error');
		validated = false;
	}
	
	if (($('#product_serial').attr('value') != '' && $('#confirm_serial').attr('value') != '') && ($('#product_serial').attr('value') != $('#confirm_serial').attr('value') )) {
		display('Registration Error', 'Product serial numbers must match.', 'Registration Error');
		validated = false;
	}
	
	return validated;
	
}


function contactValidate() {
	
	var validated = true;
	
	$('#regContainer div label input').each(function(){
		 
		 if($(this).attr('value') == '') {
			$(this).parent().append('<span class="validationError, errorHighlight">*</span>');
			 validated = false;
		 }
		 
	 });
	
	if(!validateEmail($('#email').attr('value'))) {
		display('Contact Us Error', 'Invalid email address.', 'Contact Us Error');
		validated = false;
	}
	
	if(!validated) {
		$('#reg_inst').append('<div class="validationError" style="padding-top:10px;">Please fill in the required (*) fields</div>');
	}
	
	return validated;
	
}


function chgPwdValidate() {
	
	var validated = true;
	
	$('.genBlock label input').each(function(){
		 
		 if($(this).attr('value') == '') {
			$(this).parent().append('<span class="validationError, errorHighlight">*</span>');
			 validated = false;
		 }
		 
	 });
	
	if(!validated) {
		$('#reg_inst').append('<div class="validationError" style="padding-top:10px;">Please fill in the required (*) fields</div>');
		return false;
	}
	
	if (($('#new_pass').attr('value') != '' && $('#new_pass_confirm').attr('value') != '') && ($('#new_pass').attr('value') != $('#new_pass_confirm').attr('value') )) {
		display('Change Password Error', 'Password and confirmation password must match.', 'Change Password Error');
		validated = false;
	}
	
	return validated;
	
}


function validateEmail(emailAddress) {
	// email validate
	var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
	
	if(!filter.test(emailAddress)) {
	
		return false;
	}
	
	return true;
}

function loginInit(infoObj) {

	if(infoObj != null) {
		clientObj = infoObj;
		$('#userInfo').text('Hi, ' + infoObj.username);
		$('#userInfo').show();
		$('#changePass').show();
		$('#logoutContainer').show();
		$('#container').hide();
		$('#registerBtn').hide();
		
	} else {

		if(window.location.href.search(/discussion.php/i) >= 0) {
			window.location.href = "community.php";
		}
		
		clientObj = null;
		$('#userInfo').hide();
		$('#changePass').hide();
		$('#logoutContainer').hide();
		$('#container').show();
		//ie garbage
		$(".signin").removeClass("menu-open");
		$("#signin_menu").hide();
		
		
		$('#registerBtn').show();
		
	}
	
}


function loggedIn(infoObj) {
  clientObj = infoObj;
	$('#userInfo').text('Hi, ' + infoObj.username);
	$('#userInfo').show();
	$('#changePass').hide();
	$('#logoutContainer').show();
	$('#container').hide();
	$('#registerBtn').hide();
}

function logOut() {
  	clientObj = null;
	// leave forum page if necessary
	if(window.location.href.search(/discussion.php/i) >= 0) {
		window.location.href = "community.php";
	}
	
  	$('#container').show();
	$('#userInfo').hide();
	$('#changePass').hide();
	$('#logoutContainer').hide();
	
	//ie garbage all the ILLOGICAL SHIT BELOW IS TO MAKE IE WORK!!!
	$(".signin").removeClass("menu-open");
	$("signin_menu").hide();
	$("fieldset#signin_menu").toggle();
	$('#registerBtn').show();
	$("fieldset#signin_menu").toggle();

	

}


function loginInitGSA(){
  /*
  $.getJSON('http://www.ricohbusinessbooster.com/getsession.php', function(data) {
		//var rbbData = data.rbbData;
		loginInit(data);
		if(data != null) {
		  alert(data.uli);
		}
	});
	
	*/
}


function display(errorHeading, errorMsg, errorType) {
  $('#dialog_heading').text(errorHeading);
  $('#dialog_msg').text(errorMsg);
  $.colorbox({"href":"#dialog", "width":"480", "inline":true, "opacity":0.5, "transition":'elastic', "title":errorType});
}

function logAction(userid, section, tablename, docid) {
  
  var postData = "userid=" + clientObj.login_id  + "&section=" + currentSection + "&t_id=" + currentSubsection + "&docid=" + docid;
  //alert(postData);
  var logDocCallback = function(jsonObj) {
		  if(jsonObj.status == 'success') {
			} else {
				//alert('Error processing request');
			}

	  };

    $.post("log_doc_view.php", postData, logDocCallback, "json" );
}

function setSectionAndSub(section, sub) {
  currentSection = section;
  currentSubsection = sub;
}

 
 

