// JavaScript Document
//Functions to call and execute

//Function for Sign-up new Account
function sign_up_account()
{
	new Ajax.Request('ajax/ajax_signup.php',{parameters: {
						fname: $j('#fname').val(), 
						lname: $j('#lname').val(),
						email: $j('#email_signup').val(),
						mobile: $j('#mobile_signup').val(),
						username: $j('#username_signup').val(),
						password: $j('#password_signup').val(),
						org: $j('#organization').val(),
						zip: $j('#zip').val(),
						how: $j('#how').val(),
						func: 'sign_up_new_user'},
						method: 'post', onSuccess:function(transport){
						
			if(200 == transport.status){
				
				if(transport.responseText == "Authenticate"){
					$j('#error_signup').fadeIn(750);
					lasterror = $j("#error_signup");
					$j('#error_signup').html("Successfully submitted... <br>Please check your email for account verification.");
					$j('#error_signup').fadeOut(750);
					document.location.href =  base_url+'/authenticate.php?UserName='+$j('#username_signup').val()+'&mobile='+$j('#mobile_signup').val()+"&email="+$j('#email_signup').val();
					$j('#fname').val() = "";
					$j('#lname').val()  = "";
					$j('#email_signup').val()  = "";
					$j('#mobile_signup').val() = "";
					$j('#username_signup').val() = "";
					$j('#password_signup').val() = "";
					$j('#re_password_signup').val() = "";
					$j('#organization').val() = "";
					$j('#zip').val() = "";
					$j('#how').val() = "";
					
				}else{
					$j('#error_signup').fadeIn(750);
					lasterror = $j("#error_signup");
					$j('#error_signup').html("Problem occured...<br>Please check your inputs before procced and try again.");
				}
				return true;
			}
		}});
}

function check_email_existed(el_email)
{
	new Ajax.Request('ajax/ajax_signup.php', {parameters: {
						email: el_email, 
						func: 'check_email_existed'},
						method: 'post', onSuccess:function(transport){
						
			if(200 == transport.status){
				
				if(transport.responseText == "Authenticate"){
					$j('#error_signup').fadeIn(750);
					$j("#email_signup").addClass("needsfilled");
					lasterror = $j("#error_signup");
					$j('#error_signup').html("Email address already existed.");

				return false;
				}
				return true;
			}
		}});
}

function check_username_existed(el_username)
{
	new Ajax.Request('ajax/ajax_signup.php', {parameters: {
						username: el_username, 
						func: 'check_username_existed'},
						method: 'post', onSuccess:function(transport){
						
			if(200 == transport.status){
				
				if(transport.responseText == "Authenticate"){
					$j('#error_signup').fadeIn(750);
					$j("#username_signup").addClass("needsfilled");
					lasterror = $j("#error_signup");
					$j('#error_signup').html("This username already existed.");
				}
			}
		}});
}

function check_mobile_existed(el_mobile)
{
	new Ajax.Request('ajax/ajax_signup.php', {parameters: {
						mobile: el_mobile, 
						func: 'check_mobile_existed'},
						method: 'post', onSuccess:function(transport){
						
			if(200 == transport.status){
				
				if(transport.responseText == "Authenticate"){
					$j('#error_signup').fadeIn(750);
					$j("#mobile_signup").addClass("needsfilled");
					lasterror = $j("#error_signup");
					$j('#error_signup').html("Mobile number already existed.");
				}
			}
		}});
}

//End of signup Code

// Function call for Login
function authenticate_login(el_username,el_pass)
{		
			new Ajax.Request('ajax/authenticate_login.php', {parameters: {
						username: el_username, 
						password: el_pass,
						func: 'login'},
						method: 'post', onSuccess:function(transport){
						
			if(200 == transport.status){
				if(transport.responseText == "Authenticate"){ 
					
					//$j('#error_login').css('color', '#fff');
					//$j('#error_login').css('background-color', '');
					//$j('#error_login').html('Redirecting....');
					document.location.href = base_url+'/admin/home.php?controller=dashboard';
				}else{
					$j('#error_login').fadeIn(750);
					//$j('#error_login').css('color', 'red');
					$j('#error_login').html(transport.responseText);
				}
			}
		}});

			return false;
}


//Funciton Call for Forgot Password
function authenticate_forgot_password(el_username, el_email)
{
		new Ajax.Request('ajax/authenticate_login.php', {
				
				parameters:{
					username: el_username,
					email: el_email,
					func: 'forgot_password'
				},
				method: 'post',
				onSuccess: function(transport)
				{
					if(200 == transport.status){
						$j('#error').fadeIn(750);
						if(transport.responseText == "Authenticate"){
							$j('#error').css('color', '#006600');
							$j('#error').html('Username and Password has been sent to '+el_email+'. Please check your email.');
						}else{
							$j('#error').css('color', 'red');
							$j('#error').html(transport.responseText);
						}
					}	
				}
						 
		
		});
	
}

//Function to Activate New Account
function activate_new_account()
{
		new Ajax.Request('ajax/ajax_signup.php', {
				
				parameters:{
					username: gup('UserName'),
					email: gup('email'),
					mobile: gup('mobile'),
					accesscode: $j('#act_code').val(),
					func: 'activate_account'
				},
				method: 'post',
				onSuccess: function(transport)
				{
					if(200 == transport.status){
						$j('#error').fadeIn(750);
						if((transport.responseText == "Problem Occured.<br />Please check your inputs and try again.") || 
						   (transport.responseText == "Problem Occured.<br />Invalid Activation Code.") || 
						   (transport.responseText == "This Activation Code was already been activated.")){
								$j('#error').css('color', 'red');
								$j('#error').html(transport.responseText);
						}else{
								authenticate_login(gup('UserName'),transport.responseText);
								$j('#error').css('color', '#006600');
								$j('#error').html('Your Account is activated.<br>You will be redirected to your account in a moment. Thank you.');
						}
					}	
				}
						 
		
		});
}

//Functions Dashboard


//End Dashboard

//Functions Buy Credits

	var subm = false;
function HideButt()
{
	if (subm) return false;
	subm = true;
	return true;
}

/*function validateForm()
{
	if($j('#credit').val() >= 167) {
		//buycredits.submit();
		
		CalculatePrice();
		var newamount = $j('#credit').val() * $j('#amounteach').val();
		//alert(newamount);
		$j('#amount').val(newamount);
		return true;
	}else {
		alert("Minimum purchase is $5.00, please enter 167 credits or greater.");
		return false;
	}
}
//End Buy Credits
*/
//Function Contacts management
function get_groupassoc(el_recip)
{
		$j('#global_loading').show();
		$j.post('ajax/contacts.php',{func: 'get_contactgroups',
							 recipient: el_recip},
							 
				function(transport)
				{
					$j('#contactsassocgroups').html(transport);
				
					$j('.removegroup').click(function(){ 
						var ans = confirm("Are you sure to remove this organization?");
						var recipid = $j(this).attr('recipient');
						if(ans){
							$j.post('ajax/contacts.php',
								{
									func: 'remove_assoc',
									recipient: $j(this).attr('recipient'),
									group: $j(this).attr('group')
								},
								function()
								{
									get_groupassoc(recipid);
								}							
							);
						}
					});
					
					$j('#global_loading').hide();	
					
					
				}
		);
}

//Function in Retriving the Contact for Editing
function get_contact_info(id)
{

}

//Function in Editing Contact
function set_contact_info()
{
	$j('#global_loading').show();
	$j.post('ajax/contacts.php',
			{func:'set_editcontact',
						 fname: $j("#fname").val(),
						 lname: $j("#lname").val(),
						 mobile: $j("#mobile").val(),
						 email: $j("#email").val(),
						 id: $j("#contactID").val(),
						 mob_provider: $j("#provName option:selected").val()
			},		 
			function(transport){
					
						$j('#error_signup').fadeIn(750);						
						if(transport == "GOOD"){
							$j('#global_loading').hide();
							$j('#error_signup').html("Contact successfully updated.");
							
							$j('.ui-button-text').each(function(){
								if($j(this).text() == "Cancel"){
									$j(this).text("Done");	
								}								
							});
							
							get_contacts();
							get_how_many();		
							$j('#global_loading').hide();
						}else{
							$j('#global_loading').hide();
							$j('#error_signup').html("Saving contact information failed.");
						}
			}
			);
}


//Function to validate form in Create Contact
function validate_contact_form(edit)
{
	lasterror = "";
	emptyerror = "Please fill out this field.";
	emailerror = "Please enter a valid e-mail.";
	required = ["fname", "lname","mobile"];
	//email = $j("#email");
	errornotice = $j("#error_signup");
	//Validate required fields
	for (i=0;i<required.length;i++) {
		var input = $j("#"+required[i]);
		if ((input.val() == "") || (input.val() == emptyerror)) {
			input.addClass("needsfilled");
			input.val(emptyerror);
			$j("#error_signup").fadeIn(750);
			lasterror = errornotice; 
		} else {
			input.removeClass("needsfilled");
		}
	}
	
	// Validate the e-mail.
	if($j("#email").val() != "") {
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($j("#email").val())) {
			$j("#error_signup").fadeIn(750);
			$j('#error_signup').html("Please enter a valid e-mail");
			return false;
		}
	}
	
	if ($j("#fname").hasClass("needsfilled") || $j("#lname").hasClass("needsfilled") || $j("#email").hasClass("needsfilled") || $j("#mobile").hasClass("needsfilled")) {
		return false;
	} else {
		if(edit)
		{
			set_contact_info();
		}else{
			set_newcontact();
		}
		
	}
	return false;
}

function send_sms(el)
{
		$j('#global_loading').show();
		
		$j.post('ajax/contacts.php',
				{ func: 'sendsms',
				  recipient:el},
				function(transport)
					{
						$j('#contactsendsms').html(transport);
						$j('#global_loading').hide();	
						limit_sms_message();
					});	
					
}

function limit_sms_message()
{
	$j('#message').click(function(){
		if($j(this).val() == 'Your TXT Here')
		{
			$j(this).val('');
		}
	});
	
	$j('#message').keyup(function(){
		limitChars('message', 130, 'messcounter');
	});
	
	$j('#message').blur(function(){
		if($j(this).val() == '' || $j(this).val()=='Your TXT Here')
		{
			$j(this).val('Your TXT Here');
		}
	});
}

function limitChars(textid, limit, infodiv)
{
	var text = $j('#'+textid).val();
	var textlength = text.length;
	if(textlength > limit)
	{
		$j('#' + infodiv).css('color','red');
		$j('#' + infodiv).html(0); //$j('#' + infodiv).html('You cannot write more than '+limit+' characters!');
		//$j('#smserror').html('Character Count');
		$j('#'+textid).val(text.substr(0,limit));
		return false;
	}
	else
	{
		$j('#' + infodiv).css('color','#006699');
		$j('#' + infodiv).html((limit - textlength));
		//$j('#smserror').html('Character Count');
		return true;
	}
}

function get_contacts()
{
		$j('#global_loading').show();
		$j.post('ajax/contacts.php',
			{
				 func: 'get_contacts'
			},
			function(transport)
			{
				$j('#contacts').html(transport);
				get_how_many();
				
				$j(".groupcontactassoc").click(function(){
					$j('#global_loading').show();
					var dialog = $j('<div id="assocgroups" title="Groups Associations"><div id="contactsassocgroups"></div></div>').appendTo('body');
					
					dialog.dialog({
							autoOpen: false,
							resizable: false,
							oneInstance: false, 
							close: function(ev, ui) { 
									dialog.remove();
									$j(this).dialog('close'); },
							dragable: true,
							width: 450,
							height: 290,
							modal: true,
							buttons:
							{
									"Save": function(){
											save_user_assoc_groups();
									},
									"Cancel": function(){
											$j('#assocgroups').remove();
											$j(this).dialog('close');
									}
							}
					});
					
					$j('.ui-dialog-buttonpane').append("<div id='error_signup' style='float:left; width:250px;'>Please select at least one (1) Group to associate with this user.</div>");
					$j("#ui-dialog-title-assocgroups").html("Group Association(s) :: "+$j(this).attr("title"));		
					dialog.dialog("open");
					$j('#global_loading').hide();
					return false;
				});	
				$j(".smssend").click(function(){
					var dialog = $j('<div id="sendsms" title="Send SMS"><div id="contactsendsms"></div></div>').appendTo('body');
					dialog.dialog({
							autoOpen: false,
							resizable: false,
							oneInstance: false, 
							close: function(ev, ui) { 
									dialog.remove();
									$j(this).dialog('close'); },
							dragable: true,
							width: 450,
							height: 290,
							modal: true,
							buttons:
							{
									"Send SMS": function(){
											if($j('#message').val() != "") {
															$j.post('ajax/sms.php',
																{
																func: "job_sms",
																//"groupid[]": "",
																singlenumber: $j('#singleNumber').val(),
																message: $j('#message').val(),
																f_date_c1: $j('#schedNow').val(),
																credit: 1
																
																},
																function(info)
																{
																	$j('#message').val("");
																	$j('#error_signup').css('color', 'red');
																	$j('#error_signup').fadeIn(750);
																	$j('#error_signup').html(info);
																	
																	
																	$j('.ui-button-text').each(function(){
																	
																		if($j(this).text() == "Cancel"){
																			$j(this).text("Done");
																		}
																	});
																	
																		
																	
																	
																	$j('#global_loading').hide();
																}
															);
														}else{
																$j('#error_signup').css('color', 'red');
																$j('#error_signup').fadeIn(750);
																$j('#error_signup').html(info);
																$j('#global_loading').hide();
														}
									},
									"Cancel": function(){
											$j('#sendsms').remove();
											$j(this).dialog('close');
									}
							}
					});
					$j('.ui-dialog-buttonpane').append("<div id='error_signup' style='float:left; width:250px;'>There were errors on the form, please make sure all fields are fill out correctly.</div>");
					$j("#ui-dialog-title-sendsms").html("Send SMS To "+$j(this).attr("title"));		
					alert($j(this).attr('recipID'));
					//send_sms();
					dialog.dialog("open");
					$j('#global_loading').hide();
					return false;
				});	
				$j("#contactlist").tablesorter({headers:{0:{sorter:false},4:{sorter:false}}}).tablesorterPager({container: $j("#pager")}); 
			}
	);
		
}

function search_contacts()
{
	
	$j.post('ajax/contacts.php',{
			func: 'search_contacts',
			value: $j("#filter-box").val()
			},
			function(transport)
			{
					$j('#contacts').html(transport);
					//$j('#global_loading').hide();
			}
			);
}

function get_how_many()
{
	$j('#global_loading').show();
	
	$j.post('ajax/contacts.php',{func: 'get_no_contacts'},
			function(transport){
				$j('#nocontacts').html(transport);
				$j('#global_loading').hide();
				return true;
			}
			);
}


function set_newcontact()
{
	$j('#global_loading').show();
		
	var data = [];
	$j('.contact_groups').each(function(){
		if($j(this).is(':checked')) {
			data.push($j(this).val());
		}
	});
	$j.post('ajax/contacts.php',
			{	func:'set_newcontact',
				fname: $j("#fname").val(),
				lname: $j("#lname").val(),
				mobile: $j("#mobile").val(),
				email: $j("#email").val(),
				'groups': data//$j("#selGroup").val()
			},
			function(transport){
					
						$j('#error_signup').fadeIn(750);
								if(transport == "BAD_MOBILE"){
									
									$j('#error_signup').html("This mobile number already exists in your account");
									$j('#global_loading').hide();	
								}
								if(transport == "GOOD_GR"){
									
									$j('#error_signup').html("Contact Successfully Added and Assigned to a Group");
									$j("#fname").val();
									$j("#lname").val();
									$j("#mobile").val();
									$j("#email").val();
									
									$j('.ui-button-text').each(function(){
										if($j(this).text() == "Cancel"){
											$j(this).text("Done");	
										}								
									});
									get_contacts();
									get_how_many();	
								}
								if(transport == "BAD_GR"){
									
									$j('#error_signup').html("Contact Successfully Added and Not Assigned to a Group");
									$j('#global_loading').hide();	
								}
								if(transport == "BAD_RECIP"){
									
									$j('#error_signup').html("Contact Not Added.. Please Check your inputs and Try again.");
									$j('#global_loading').hide();	
								}
								if(transport == "GOOD_RECIP"){
									
									$j('#error_signup').html("Contact Successfully Added.");
									$j("#fname").val();
									$j("#lname").val();
									$j("#mobile").val();
									$j("#email").val();
									
									$j('.ui-button-text').each(function(){
										if($j(this).text() == "Cancel"){
											$j(this).text("Done");	
										}								
									});
									get_contacts();
									get_how_many();		
								}
			}
			);
}
//End of Contacts management

//Manage Groups Functions
function create_group(el_groups,el_desc)
{	
		$j('#global_loading').show();
		$j.post('ajax/groups.php',{groups:el_groups, desc: el_desc, func:'create_group'},
				function(transport)
				{
						$j('#groupslist').prepend(transport);
						$j('#groupname').val("");
						$j('#groupdesc').val("");
						$j('#global_loading').hide();
						
						
						//OrgUserlist
						$j('.orguser').click(function(){
		$j('#global_loading').show();
		var dialog = $j('<div style="width:100%;" id="addremoveorguser" title="Group Management"><div id="orguserlist"></div></div>').appendTo('body');	
		dialog.dialog({
			autoOpen: false,
			oneInstance: false, 
			resizable: false,
			dragable: true,
			width: 720,
			height: 500,
			minHeight: 400,
			modal: true,
			close: function(ev, ui) { 
				dialog.remove();
				$j(this).dialog('close'); },
			buttons:
			{
					"Save": function(){
							saveorgsettings();
					},
					"Cancel": function(){
							dialog.remove();
							$j(this).dialog('close');
					}
			}
		});
		$j('.ui-dialog-buttonpane').append("<div id='error_signup' style='float:left; width:400px;'>There were errors on the form, please make sure all fields are fill out correctly.</div>");
		$j('#ui-dialog-title-addremoveorguser').html("Group Management :: "+$j(this).text());		
		//get_orguser();
		dialog.dialog('open');

		$j.post('ajax/groups.php',
			{group:$j(this).attr('org_id'),
				func:'get_usersgroup'}, 
			function(transport){
													
					$j('#orguserlist').html(transport);
					$j("#editable").editInPlace({
					saving_animation_color: "#ECF2F8",
					callback: function(idOfEditor, enteredText, orinalHTMLContent, settingsParams, animationCallbacks) {
						animationCallbacks.didStartSaving();
						setTimeout(animationCallbacks.didEndSaving, 2000);
						saveorgdesc(enteredText);
						return enteredText;
					}
				});

				$j(".child").click ( function() {	
					$j("#chkMainInGroup").removeAttr ( "checked" );
				});

				$j(".childnotinggroup").click ( function() {	
					$j("#chkMainNotInGroup").removeAttr ( "checked" );
				});

				$j("#chkMainInGroup").click ( function() {

				if ( $j(this).is ( ":checked" ) )
				{
				  //$j(".child").attr ( "disabled" , true );
				  // $j(".child").removeAttr ( "checked" );
				  $j(".child").attr ( "checked" , true );
				}
				else
				{
				  //$j(".child").removeAttr ( "disabled" );
				  $j(".child").removeAttr ( "checked" );
				}
				});

				$j("#chkMainNotInGroup").click ( function() {

				if ( $j(this).is ( ":checked" ) )
				{
				  //$j(".childnotinggroup").attr ( "disabled" , true );
				  //$j(".childnotinggroup").removeAttr ( "checked" );
				  $j(".childnotinggroup").attr ( "checked" , true );
				}
				else
				{
				  //$j(".childnotinggroup").removeAttr ( "disabled" );
				  $j(".childnotinggroup").removeAttr ( "checked" );
				}
				});
						$j('#global_loading').hide();
							   
			 });
			 

		
		return false;
	});
						//EndOrgUserlist
				}
		);
}


function saveorgdesc(el_orgdesc)
{
	$j.post('ajax/groups.php',{org:$j('#groupid').val(), desc:el_orgdesc, func:'update_orgdesc'},
		function(transport){
				
				if(transport == "Done")
				{
						$j('.'+$j('#groupid').val()).html(el_orgdesc);
						return 'true';
				}else{
						return 'false';
				}
		}
	);
}

function saveorgsettings()
{
	$j('#global_loading').show();
	var usersmember = [];
	
	$j('.multiselect :selected').each(function(i,selected)
	{
		usersmember[i] = $j(selected).val();
	});
	$j.post('ajax/groups.php',{org: $j('#groupid').val(),'user[]': usersmember,func: 'assign_group'},
		
		function(transport){
				if(transport == "DONE"){
					$j('#error_signup').fadeIn(750);
					$j("#error_signup").html('Adding/Removing Contacts on this group completed.');
					$j('#global_loading').hide();
					window.location.href = 'groups.php?controller=groups';
				}
		}
	
		
	);
		
	get_numgroups($j('#groupid').val());
}

//Contact Groups Associate Save
function save_user_assoc_groups()
{
	$j('#global_loading').show();
	var data = [];
	$j('.recip_groups').each(function(){
		if($j(this).is(":checked"))
			data.push($j(this).val());
	});
	
	$j.post('ajax/contacts.php',
		{
			'groups' : data,
			recipient : $j('#recipID').val(),
			func : 'assign_assoc'
		},
		function(transport){
			if(transport == "DONE"){
				$j('#error_signup').fadeIn(750);
				$j("#error_signup").html('Adding/Removing Groups on this Contact completed.');
				$j('.ui-button-text').each(function(){
					if($j(this).text() == "Cancel"){
						$j(this).text("Done");	
					}								
				});
			}else{
				$j('#error_signup').fadeIn(750);
				$j("#error_signup").html(transport);
			}
			$j('#global_loading').hide();
		}
	);
}


function get_numgroups(el_group)
{
	$j('#global_loading').show();
	
	$j.post('ajax/groups.php',
			{group:el_group, func: 'group_no'},
			function(transport)
			{
				$j('#'+el_group).html(transport);
						$j('#global_loading').hide();
			}
	
	);
}

//End of Manage Groups

//Support Functions
function get_username()
{
		$j('#global_loading').show();	

		$j.post('ajax/support.php',
				{
					func: 'support_username'
				},
				function(transport)
				{
					$j('#txtUserID').val(transport);
					$j('#global_loading').hide();
				}
			);
		
}

function get_email()
{
		$j('#global_loading').show();	
		$j.post('ajax/support.php',
				{
					func: 'support_email'
				},
				function(transport)
				{
					$j('#txtEmail').val(transport);
					$j('#global_loading').hide();
				}
			);
}

function send_support()
{
	$j('#global_loading').show();	
		
	$j.post('ajax/support.php',
			{
			name: $j('#txtName').val(),
			email: $j('#txtEmail').val(),
			mess: $j('#txtMess').val(),
			jabber_user: $j('#txtUserID').val(),
			func: 'send_support'	
			},
			function(transport)
			{
				$j('#error').fadeIn(750);
				$j('#error').html(transport);
				$j('#txtName').val("");
				$j('#txtEmail').val("");
				$j('#txtMess').val("");
				$j('#txtUserID').val("");
				get_username();
	  		 get_email();
				$j('#global_loading').hide();
			}
		);
}
//End of Support Functions
//-------------------- UTILS
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

