
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

Ajax.Responders.register({
 	        onCreate: function() {
 	                if($('processing_image') && Ajax.activeRequestCount > 0)
 	                    $('processing_image').show();
 	                    
 	                    // Hide All flashes
 	                    $('flash-notice').hide();
 	                    $('flash-error').hide(); 
 	        },
 	        onComplete: function() {
 	                if($('processing_image') && Ajax.activeRequestCount == 0){
 	                        $('processing_image').hide();
 	                        //Effect.Fade('notification',{duration: 0.30, queue: 'end'});
 	                       
 	                  }
 	                  
 	                  // ****************** SORTABLE ******************
 	                  //sortable
 	                  forEach(document.getElementsByTagName('table'), function(table) {
                          if (table.className.search(/\bsortable\b/) != -1) {
                            sorttable.makeSortable(table);
                          }
                          
                          //Report
                          if (table.className.search(/\breport\b/) != -1) {
			                 ts_makeSortable(table);
		                  }    	
            
                      });
                      
                      
 	                  //**************** END SORTABLE ****************
 	        }
 	        
 	       
 	        
 	});

/* ATTACHING FILES TO THE TICKET */
function AddUploadTextField(){
  i=1
  i++;
  v =  "uploaded_data_" + i;
  new Insertion.Bottom('files', "<input type='file' name='document["+ v +"]' size = 30/>");  
}

function AddAttachments(){
  Element.show('attachments');
  Element.show('add_another_doc');
}

function NewTicket(){
  Element.hide('list-tickets');
  Element.show('new-ticket');
}

function CancelNewTicket(){
  Element.show('list-tickets');
  Element.hide('new-ticket');
}    

function ReOpenTicket(id){
  if(confirm("Are you sure you want to re open this ticket?")){
    new Ajax.Updater('', '/tickets/re_open_ticket/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}
/*  END   */

/* JAVA SCRIPT FOR STAND */
function UpdateOwnersPresent(){
   
  if($('stand_status').value == 'unoccupied'){
    $('stand_owner_present').checked = false;
    $('stand_owner_present').disabled = true;
    }
  else{  
    $('stand_owner_present').disabled = false;
  }
}

/* profile filter links */
function FilterSearchProfileLinks(){
  column  = $('users_type').value;
  new Ajax.Request('/profile/load_filtered_links/?column='+ column +'&user_type='+ user_type + '&delete_action='+ delete_action, {asynchronous:true, evalScripts:true});
}

/* Stand filter links */
function FilterSearchStandLinks(){
  column  = $('stand_column').value;
  new Ajax.Request('/stands/load_filtered_links/?column='+ column, {asynchronous:true, evalScripts:true});
}


function ValidateCellPhone(){
  number_length = $('person_cellphone').value.length
  value = $('person_cellphone').value
  
  if (isNaN(value)) {
    alert("cellphone must be digitss");
    $F('person_cellphone').focus();
    return false 
  }else if(number_length != 9 && number_length != ""){
    alert("Please enter your full cellphone number without the first zero e.g 082 1234 567 must be 821234567")
    $F('person_cellphone').focus();
    return false; 
  }
  else
    return true;
}

function ValidateTelPhone(){
  number_length = $('person_telephone').value.length
  value = $('person_telephone').value
  
  if (isNaN(value)) {
    alert("Telephone must be digits");
    $('person_telephone').focus();
  }else if(number_length != 9 && number_length != ""){
    alert("Please enter your full Telephone number without the first zero e.g 082 1234 567 must be 821234567")
    return $('person_telephone').focus(); 
  }else
    return true;
}

function ValidateFaxNo(){
  number_length = $('person_fax').value.length
  value = $('person_fax').value
  
  if (isNaN(value)) {
    alert("fax must be digits");
    $('person_fax').focus() == true;
  }else if(number_length != 9 && number_length != ""){
    alert("Please enter your full fax number without the first zero e.g 082 1234 567 must be 821234567")
    $('person_cellphone').focus() 
  }
  else
    return true;
}

/* Remove equipemnt type */

function RemoveEquipmentType(id){
  if(confirm("Are you sure you want to remove this equipment type?")){
    new Ajax.Request('/equipment_type/remove/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}
function RemoveVendorCategory(id){
  if(confirm("Are you sure you want to remove this category?")){
    new Ajax.Request('/services/remove_category/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}

function RemoveSetviceProviderService(id){
  if(confirm("Are you sure you want to remove this service?")){
    new Ajax.Request('/service_provider_services/remove/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}


function UploadProfileImage(){
  Element.show('form_upload_image');
  Element.hide('upload-image');
}

function CancelUploadProfileImage(){
  Element.hide('form_upload_image');
  Element.show('upload-image');
}

function ApproveServiceProvider(){
  Element.hide('person_details');
  Element.show('approve_service_provider');
}

function CancelApproveServiceProvider(){
  Element.show('person_details');
  Element.hide('approve_service_provider');
}

function SuspendServiceProvider(id){
  if(confirm("Are you sure you want to suspend this service provider?")){
    new Ajax.Request('/business/suspend_service_provider/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}

function BlacklistServiceProvider(id){
  if(confirm("Are you sure you want to Blacklist this service provider?")){
    new Ajax.Request('/business/blacklist_service_provider/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}


function ApproveVendor(){
  Element.hide('person_details');
  Element.show('approve_vendor');
}

function CancelApproveVendor(){
  Element.show('person_details');
  Element.hide('approve_vendor');
}

function SuspendVendor(id){
  if(confirm("Are you sure you want to suspend this vendor?")){
    new Ajax.Request('/business/suspend_vendor/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}

function BlacklistVendor(id){
  if(confirm("Are you sure you want to blacklist this vendor?")){
    new Ajax.Request('/business/blacklist_vendor/?id='+ id, {asynchronous:true, evalScripts:true});
  }
}


/*   EQUIPMENT LOCATIONS */

function hideequipment_location(id){
  Element.hide('remove-'+id);
  Element.hide('edit-'+id);
  Element.hide('details-'+id);
}

function DetailsEquipmentLocation(id){
  hideequipment_location(id)
  Element.show('details-'+id);
 }

function RemoveEquipmentLocation(id){
  hideequipment_location(id)
  Element.show('remove-'+id);
 }
 
function EditEquipmentLocation(id){
  hideequipment_location(id);
  Element.show('edit-'+id);
}

function ViewAllEquipmentLocations(){
  new Ajax.Request('equipment_locations/?estate_id='+ id, {asynchronous:true, evalScripts:true});           
}

/*  REMOVE STAND FROM THE OWNER */
function RemoveStandFromOwner(stand_id, id){
  if(confirm("Are you sure you want to remove this stand from this owner?")){
    new Ajax.Request('/profile/remove_stand/?stand_id='+ stand_id + "&id="+ id, {asynchronous:true, evalScripts:true});
  }
}


function ListAllTickets(){
  new Ajax.Request('/admin_tickets/list_all', {asynchronous:true, evalScripts:true});
}

function RemoveTicket(id){
  if(confirm("Are you sure you want to delete this ticket")){
    new Ajax.Request('/admin_tickets/remove_ticket/?id='+ id, {asynchronous:true, evalScripts:true});               
  }  
}

function EditTicket(id){
  new Ajax.Request('/admin_tickets/edit/?id='+ id, {asynchronous:true, evalScripts:true});                         
} 

/* SCRIPT FOR HELPDESK(services/department) */
function hidedepartment(id){
  Element.hide('view-'+id);
  Element.hide('remove-'+id);
  Element.hide('edit-'+id);
  Element.hide('details-'+id);
}
    
function DetailsDepartment(id){
  hidedepartment(id)
  Element.show('details-'+id);
}
    
function ViewDepartment(id){
  hidedepartment(id)
  Element.show('view-'+id);
}
    
function RemoveDepartment(id){
  hidedepartment(id)
  Element.show('remove-'+id);
}
     
function EditDepartment(id){
  hidedepartment(id);
  Element.show('edit-'+id);
}
    
function ViewAllDepartments(){
  new Ajax.Request('departments/?estate_id='+ id, {asynchronous:true, evalScripts:true});           
}

/*  SERVICE PROVIDER/VENDOR SCRIPT */
function DeleteSP(id){
  if(confirm("Are you sure you want to delete this SP")){
    new Ajax.Request('service_providers/?estate_id='+ id, {asynchronous:true, evalScripts:true});                   
  }
}

function ApproveSP(id){
  if(confirm("Are you sure you want to approve this SP")){
    new Ajax.Request('approve_service_provider/?id='+ id, {asynchronous:true, evalScripts:true});                   
  }
}
    
function ViewAllDepartments(){
  new Ajax.Request('service_providers/?estate_id='+ id, {asynchronous:true, evalScripts:true});           
}

function RemoveFAQ(id){
  if(confirm("Are you sure you want to delete this FAQ?")){
    new Ajax.Request('remove/?id='+ id, {asynchronous:true, evalScripts:true});     
  }
}


function LoadServiceProvider(){
 spc = $('service_provider_services_id').value
 new Ajax.Request('/business/load_service_providers/?service_provider_category_id='+ spc, {asynchronous:true, evalScripts:true});

}

function ConfirmTermsAndCoditions(linkid){
  if($('terms_and_coditions').checked){
    opener.location.href=linkid
  }
  window.close();  
}

function CheckAllColumns(mode, checked){
   if(checked == 'false'){
     Element.show('check_all');
     Element.hide('uncheck_all');
     checked = true
   }  
   else{  
     Element.show('uncheck_all');
     Element.hide('check_all');
     checked = false
   }  
   
   var aa = document.getElementById(mode);
	 if (checked == false)
          {
           checked = true
          }
        else
          {
          checked = false
          }
	for(var i =0; i < aa.elements.length; i++){
	  
	  // Only the checkboxes must be toggle.
	  aa.elements[i].checked = checked;
	}
}

// REPORTS //

// Ordering of columns to be shown on reports.
function OrderUserColumns(mode, old){
  var selected_columns =[]; 
  var aa = document.getElementById(mode);
  var count = 0;
  var count_selected = 0;
  

  // Get all selected columns.
  for(var i =0; i < aa.elements.length; i++){
    if(aa.elements[i].name == "column[]" && aa.elements[i].checked == true){
      selected_columns[count] = aa.elements[i]
      count +=1;
    }
  }
  
  // make sure there s atlest one selected column
  if(count == 0){
    alert("Please select at least one column");
    return;
  }

  Element.show('generate-report-button');
  Element.update('order-columns',"");
  $('order_column').disabled = true;

  
  if(old == '1'){
    for(var s=0; s < count; s++){
      c = s + 0 
      html = "<select name='order_columns[" + c +"]' class='dropdownSelect'>"
	    html += "<option name='column[]' value='" + selected_columns[c].value + "'>"+ (selected_columns[c].value) +"</option>"
      html += "</select>&nbsp;&nbsp;&nbsp;&nbsp;"
    
      // show the dropdown in our form.
      Element.insert('order-columns',html);
    }
  }else{
    for(var s=0; s < count; s++){
      c = s + 1 
      html = "<select name='order_columns[" + c +"]' class='dropdownSelect'>"
	  for(var i =0; i < selected_columns.length; i++){
	    html += "<option name='column[]' value='" + selected_columns[i].value + "'>"+ (selected_columns[i].value) +"</option>"
	  }
      html += "</select>&nbsp;&nbsp;&nbsp;&nbsp;"
    
      // show the dropdown in our form.
      Element.insert('order-columns',html);
    }
  }
}

function ColumnShowMe()
{
 Element.hide('report-table');
 Element.hide('generate-report-button');
 $('order_column').disabled = false ;
}


// ******* VENDOR APPLICATION FORM ******** //
  function CheckDuplicateIdNumber(){
  id_number = $('user_id_number').value
  new Ajax.Request("/services/service_provider_check_id_number/?id_number="+ id_number, {asynchronous:true, evalScripts:true});
}

function IdExist(){
  alert('Email has already been taken, please use another email')
  return false;
}

// Hide Business form and show User form.
function HideVendorShowUser(){
  var select_service = true;
  var select_estate = true;
  
  
  if($('business_company_registration_number').value == ""){
    alert("Please Enter Company Registration Number");
    return;
  }
  else if($('business_company_name').value == ""){
    alert("Please Enter Company Name");
    return;
  }
  else if($('business_telephone').value == ""){
    alert("Please Enter Telephone");
    return;
  }
  else if($('business_email').value == ""){
    alert("Please Enter Email");
    return;
  }  
  // Make sure one service is selected.
  aa = document.getElementById('create_vendor');
  
  for(var i =0; i < aa.elements.length; i++){
	if(aa.elements[i].name == "services[]" && aa.elements[i].checked == true){
      select_service = false;  
	}  
  }
  
  // Please select oat least one service.
  if(select_service == true){
    alert("Please select at least one category for the products you want to sell");
    return;
  }
    

  // Make sure one estate is selected.
  for(var i =0; i < aa.elements.length; i++){
	if(aa.elements[i].name == "available_estates[]" && aa.elements[i].value != ""){
	  select_estate = false;
	}  
  }
  
   // Please select oat least one eState.
  if(select_estate == true){
    alert("Please select at least one eState");
    return;
  }
  
  // All fields r filled with correct data... process to next step on vendor app. 
  Element.hide('business_form'); Element.show('person_form');
  return  
  
  
}

function validate_user_form(form){
  
  // VALIDATES THE USERS FORM IN IT IS EXISTING...
    // validate initials
    if (form.user_initial.value == ""){
      alert("Initials can't be blank")
      form.user_initial.focus = true
      return false;
    }
  
    if(form.user_firstname.value == ""){
      alert("Firstname can't be blank")
      form.user_firstname.focus = true
      return false;
    }
  
    if (form.user_lastname.value == ""){
      alert("Lastname can't be blank")
      form.user_firstname.focus = true
      return false;
    }
  
    if (form.user_id_number.value == ""){
      alert("ID number can't be blank")
      form.user_id_number.focus = true
      return false;
    }
    
    if (isNaN(form.user_id_number.value)){
      alert("ID number must be a number")
      form.user_id_number.focus = true
      return false;
    }
  
    //CheckDuplicateIdNumber();
    if (form.user_telephone.value == ""){
      alert("Telphone can't be blank")
      form.user_telephone.focus = true
      return false;
    }
    
  //CheckDuplicateIdNumber();
    if (isNaN(form.user_telephone.value)){
      alert("Telphone must be a number")
      form.user_telephone.focus = true
      return false;
    }
    
    if (form.user_cellphone.value == ""){
      alert("Cellphone can't be blank")
      form.user_cellphone.focus = true
      return false;
    }
    
    if (isNaN(form.user_cellphone.value)){
      alert("Cellphone must be a number")
      form.user_cellphone.focus = true
      return false;
    }
  
    if(form.user_email.value == ""){
      alert("Email can't be blank")
      form.user_email.focus = true
      return false;
    }
  
    if(validateEmail(form.user_email.value) == false){
      alert("Email format is invalid")
      form.user_email.focus = true
      return false;
    }
}

function validateEmail( strValue) {
    var objRegExp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,6}$/i;
    
    //check for valid email
    return objRegExp.test(strValue);
  }

// ***** END VENDOR APPLICATION FORM ****** //

function ShowTextField(c){
  stand = $('stand_id').value
  if(c.checked == true && stand != '')
    alert("To use this option make sure you Stand is NOT selected")
  else if(c.checked == true)
    Element.show('enter-stand') 
  else
    Element.hide('enter-stand')
}
/*    ******* SERVICE PROVIDER APPLICATION INSIDE ESTATEPORTAL *********/
// Validate the selection of services
function ValidateServices(id, ma_id, checkbox){
  check = checkbox.checked
  aa = document.getElementById('create_service_provider')
  if(ma_id == id && check == true){
    for(var i =0; i < aa.elements.length; i++){
	  // Only the checkboxes must be toggle.
	  if(aa.elements[i].name == "services[]" && aa.elements[i].value != id){
	    aa.elements[i].checked = false;
	  }  
    }
  }else{
    for(var i =0; i < aa.elements.length; i++){
	  // Only the checkboxes must be toggle.
	  if(aa.elements[i].name == "services[]" && aa.elements[i].value == ma_id){
	    aa.elements[i].checked = false;
	  }  
    }
  }
  
  checkbox.checked = check
}

// Hide Business form and show User form.
function ShowUserForm(user){
  if($('business_company_registration_number').value == ""){
    alert("Please Enter Company Registration Number");
    return;
  }
  else if($('business_company_name').value == ""){
    alert("Please Enter Company Name");
    return;
  }
  else if($('business_telephone').value == ""){
    alert("Please Enter Telephone");
    return;
  }
  else if($('business_email').value == ""){
    alert("Please Enter Email");
    return;
  }  
  // Make sure one service is selected.
  aa = document.getElementById('create_service_provider')
  
  for(var i =0; i < aa.elements.length; i++){
	if(aa.elements[i].name == "services[]" && aa.elements[i].checked == true){
	  if(!user || (user == true && $('user_option_new').checked)){
        Element.hide('business_form'); Element.show('person_form');
      }else{
        new Ajax.Request("/business/load_users/", {asynchronous:true, evalScripts:true});	    
	  }
	  return  
    }
  }
  // Please select oat least one service.
  alert("Please select at least one service");
  return;
  
}

function LoadStandForRepoCategory(group){
  // Get the group that has been selected.
  gp = group.value
  //Hide Stands
  Element.hide('stands')
  Element.hide('users')

  if(gp == 3){
    new Ajax.Request("/document_repository/load_stands", {asynchronous:true, evalScripts:true});
  }else if(gp == 4){
    new Ajax.Request("/document_repository/load_users", {asynchronous:true, evalScripts:true});
  }
}

function RepoDocumentRemoveDocument(id){
  if(confirm("Are you sure you want delete this document?")){
    new Ajax.Request("/document_repository/delete/?id="+ id, {asynchronous:true, evalScripts:true});
  }
}

function ValidateAccessPortal(){
  if($('user_access_portal').checked){ 
    if(!validateEmail($('user_email').value)){
      alert("Please enter email before activating this function")
      $('user_access_portal').checked = false
    }
  }else{
    $('user_access_account').checked = false
  }
}

function ValidateEmail(){
  if($('user_receive_resident_email').checked){ 
    if(!validateEmail($('user_email').value)){
      alert("Please enter email before activating this function")
      $('user_receive_resident_email').checked = false
    }
  }
}

function ValidateCellphoneForSMS(){
  if($('user_receive_resident_sms').checked){ 
    if($('user_cellphone').value == ""){
      alert("Please enter cellphone before activating this function")
      $('user_receive_resident_sms').checked = false
    }
  }
}

function ValidateAccessResidentAccount(){
  if($('user_access_account').checked && !$('user_access_portal').checked){
    $('user_access_account').checked = false
    alert("You need to have access to login to eStateportal to have this functionality")
  }
}
/*    ******* END SERVICE PROVIDER APPLICATION INSIDE ESTATEPORTAL *********/

function SaveReportUser(){
  save_as = $F('save_as')
  
  if(save_as == ""){
    alert("Please enter Report Title");
    return
  }
  new Ajax.Request("/reports/save_report_user/?save_as=" + save_as, {asynchronous:true, evalScripts:true});
}

function SaveReportStand(){
  save_as = $F('save_as')
  
  if(save_as == ""){
    alert("Please enter Report Title");
    return
  }
  new Ajax.Request("/reports/save_report_stand/?save_as=" + save_as, {asynchronous:true, evalScripts:true});
}

function SaveReportHelpdesk(){
  save_as = $F('save_as')
  
  if(save_as == ""){
    alert("Please enter Report Title");
    return
  }
  new Ajax.Request("/reports/save_report_helpdesk/?save_as=" + save_as, {asynchronous:true, evalScripts:true});
}

function NoActiveServices(){
  alert("You dont have active service(s), You can activate services by going to 'My Services'")
}

function RemoveService(id){
  if(confirm("Are you sure you want remove this service?")){
    new Ajax.Request("/services/remove_service/?id=" + id, {asynchronous:true, evalScripts:true});
  }
}

function StandNoExt(){
  alert("Error: Stand selected has no extension(s)!")
}

function SelectAllStands(){
  alert("This will list all the extensions for this estate.")
}

function EnableProceedBtn(checkbox){
  if(checkbox.checked){
    $('procees').disabled = false
  }else{
  $('procees').disabled = true
  }
}

function GenerateDebitOrder(t){
  if(confirm('This will activate services and generate a DEBIT ORDER in a pdf format, Are you sure you want to continue?')){
    Element.show('success-message');
    Element.remove('terms-and-conditions');
    Element.remove('flash-warning');
    Element.hide('procees');
   // $('procees').remove(); 
    t.form.submit();
  }
}

function CheckServiceName(c){
    if($('network_administrator').checked == true){
      alert("If you want to remove the selected service, Please uncheck it first");
      return
      c.value = "Network Administrator"
    }else if($('managing_agent').checked == true){
      alert("If you want to remove the selected service, Please uncheck it first");
      return
      c.value = "Mananging Agent"
    }
}

function CheckServiceManagingAgent(c){
    $('network_administrator').checked = false
    $('service_usaged_based').checked = false
    
    if($('managing_agent').checked == true)
      $('service_name').value = "Managing Agent";
    else
      $('service_name').value = "";    
}    

function CheckServiceNetworkAdministrator(c){
    $('managing_agent').checked = false
    $('service_usaged_based').checked = false
    
    if($('network_administrator').checked == true)
      $('service_name').value = "Network Administrator";
    else
      $('service_name').value = "";
      
}

function ValidatePrice(txt){
  if (isNaN(txt)) {
    alert("Price must be numbers");
    $('business_service_price').value = 0;
  }  
}


function ValidateDuplicateEmails(c){
  if(c.checked){
     if($('user_email').value == ''){
       alert("Please enter valid email.")
       return 
     }
     if(confirm('This will allow Duplicates for this email, Are you sure you want to continue?')){
       c.checked = true
     }else
     c.checked = false
  } 
}

function CheckGBTitle(c){
  if(c.checked){
    Element.show('gb_title');
  }
  else
  {
    Element.hide('gb_title');
    $('user_gb_title').value = "";
  }
}
function searchProperty(mo){
  new Ajax.Updater('/forsale/search/?id = search_form',{asynchronous:true, evalScripts:true});
}

function CheckUserTopic()
{
  alert ("You cannot delete or edit this topic, only the person who created it can Delete or Edit it.")
}