/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


$( window ).load(function() {
    /*
      * List Announcements 
      */
     
     $('.jAnnouncements').click(function(){
        
    	 var community_id = $("#community_id").val();
         if(community_id >0){
            
         }
         else{
             community_id=$(this).attr('cid');
         }
         //alert(community_id);
         $.blockUI({ message: '' }); 
    	 $.ajax({
    		 type    : "POST",
    		 url     : mainUrl+"user/listannouncements",
    		 data    : 'communityId='+community_id,
    		 cache   : false,
    		 success : function(data){
                         $(".jgroupfeeddisplay_div").hide();
                         $(".jpost_comment_div").hide();
                         $('#jDivDisplayBusiness').show();
    			 $('#jDivDisplayBusiness').html(data);
                         $('#announcement_date').datepicker({
         minDate:0
     });
      $('#tab-Feed').hide();
    			 
    		 }
    	 }); 
     });
     


if(location.hash=='#announcement'){
    
       $('.jAnnouncements').trigger('click');
      
    }

$(document).ajaxStop($.unblockUI); 
    $(".content").hide(); 
    $("#tab-Feed").show();  
    var track_click = 1; //track user click on "load more" button, righ now it is 0 click
    

    /*
     * Tab functionailty
     */
    
    $("a.jtab").click(function () { 
        // switch all tabs off  
        $(".active").removeClass("active");  
          
        // switch this tab on  
        //$(this).addClass("active");
        $(this).parent().addClass("active");
          
        // slide all elements with the class 'content' up  
        $(".content").slideUp();  
          
        // Now figure out what the 'title' attribute value is and find the element with that id.  Then slide that down.  
        var content_show = $(this).attr("title");  
        $("#"+content_show).slideDown();  
       // location.reload();
        
    });
    $(".general_tab").click(function(){
        location.reload();
    })
    
    /*
     * Profile edit
     */
   
    $('.jedit').live('click',function(){
        $('#jDivDisplayEdit').show();
        $('#jDivDisplayAbout').hide();
    });  
    
    $("#msgDisplay").fadeIn('slow').delay(5000).fadeOut('slow');
    
   
    
    /*
     * Profile update
     */
   $('#jUpdate').click(function(){
        var user_firstname      = $("#user_firstname").val();
        var user_lastname       = $("#user_lastname").val();
        var user_email          = $("#user_email").val();
        var user_date_of_birth  = $("#user_date_of_birth").val();
        var user_address        = $("#user_address").val();
        var user_city           = $("#user_city").val();
        var user_state          = $("#user_state").val();
        var user_country        = $("#user_country").val();
        var user_phone          = $("#user_phone").val();
        var user_zipcode        = $("#user_zipcode").val();
        var user_id             = $("#user_id").val();
        var user_alias          = $("#user_alias").val();
        var dataString          = 'user_firstname='+ user_firstname +'&user_lastname='+user_lastname+'&user_email='+user_email+'&user_date_of_birth='+user_date_of_birth+'&user_address='+user_address+'&user_city='+user_city+'&user_state='+user_state+'&user_country='+user_country+'&user_phone='+user_phone+'&user_zipcode='+user_zipcode+'&user_id='+user_id;
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            dataType: 'json',
            url     : mainUrl+"timeline/"+user_alias+"/ajaxTrue",
            data    : dataString,
            cache   : false,
            success : function(data){
                if(data.cls == 'success_div'){
                   $('#jDivDisplayEdit').hide();
                   $.ajax({
                        type    : "POST",
                        url     : mainUrl+"myprofile",
                        data    : 'uid='+user_id+'&alias='+user_alias,
                        cache   : false,
                        success : function(data){
                            $('#jMyProfile').html(data);
                        }
                    }); 
                }
                $('#msgDisplay').html(data.msg);
                $('#msgDisplay').addClass(data.cls);
                
            }
        });
        
     })
     
     /*
      * About profile
      */
     
     $('.jShowProfile').click(function(){
         $.blockUI({ message: '' }); 
        $('#jDivDisplayEdit').hide();
        $("#tab-Friends").hide();
        $("#jFeedSearch").hide();
        var uid=$(this).attr('uid');
        var alias   =$(this).attr('alias');
        $.ajax({
            type    : "POST",
            url     : mainUrl+"myprofile",
            data    : 'uid='+uid+"&alias="+alias,
            cache   : false,
            success : function(data){
                $(".jfeedtimelinedisplay_div").hide();
                $(".jfeeddisplay_div").hide();
                $('#jMyProfile').html(data);
               
            }
        }); 
     });
     
     
     /*
      * List friends
      */
     
     $('.jShowMembers').click(function(){
         $.blockUI({ message: '' }); 
        var alias=$("#community_alias").val();
      
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/listmembers",
            data    : 'communityAlias='+alias,
            cache   : false,
            success : function(data){
//                $(".jgroupfeeddisplay_div").hide();
//                $(".jpost_comment_div").hide();
//                $(".jfeedtimelinedisplay_div").hide();
//                $('#jDivDisplayBusiness').show();
                $('#jDivDisplayBusiness').html('');
                $('#jDivDisplayBusiness').html(data);
//                $('#tab-Friends').html(data);
//                $('#tab-Feed').hide();
                
            }
        }); 
     });
     
     
     /*
      * List Messages
      */
     
     $('.jShowMessages').click(function(){
    	 var alias=$("#community_alias").val();
    	 $.blockUI({ message: '' }); 
    	 $.ajax({
    		 type    : "POST",
    		 url     : mainUrl+"user/listmessages",
    		 data    : 'communityAlias='+alias,
    		 cache   : false,
    		 success : function(data){
    			 $('.find_friends_list_outer').hide();
    			 $('#tab-Messages').html(data);
    			 
    		 }
    	 }); 
     });
     
     /*
      * List Invitations for inbox
      */
     
     $('.jShowInvitationsinbox').click(function(){
    	 var alias=$("#community_alias").val();
         $.blockUI({ message: '' }); 
    	 $.ajax({
    		 type    : "POST",
    		 url     : mainUrl+"user/listinvitationsinbox",
    		 data    : 'communityAlias='+alias,
    		 cache   : false,
    		 success : function(data){
    			$('.find_friends_list_outer').html(data);
    			 //$('#tab-Feed').html(data);
    			 
    		 }
    	 }); 
     });
     
     /*
      * List Invitations 
      */
     
     $('.jShowInvitations').click(function(){
    	 var alias=$("#community_alias").val();
         $.blockUI({ message: '' }); 
    	 $.ajax({
    		 type    : "POST",
    		 url     : mainUrl+"user/listgroupinvitation",
    		 data    : 'communityAlias='+alias,
    		 cache   : false,
    		 success : function(data){
                     $('#jDivDisplayBusiness').show();
    			 $('#jDivDisplayBusiness').html(data);
                         $('#tab-Feed').hide();
    			 
    		 }
    	 }); 
     });
     
     
    $("#searchfriend").live("keyup", function() { 
        var val = $(this).val();
    
    if(val.length > 1){
  
   $.ajax({
            type    : "POST",
            url     : mainUrl+"user/groupmembersearch/1/"+ALIAS+"/"+val,
          
            cache   : false,
            success : function(data){
                $('#community_member_holder').html(data);
                
            }
        }); 

    }else{
        
         $.ajax({
            type    : "POST",
            url     : mainUrl+"user/groupmembersearch/1/"+ALIAS+"/"+val+"/",
          
            cache   : false,
            success : function(data){
                $('#community_member_holder').html(data);
                
            }
        }); 
        
    }
});
  

    /*
     * States display on country change
     */
    
    var stateHtml       = $("#user_state").html(); 
    var countryVal      = $("#user_country").val();
    var userId          = $("#user_id").val();
    if(countryVal != 'US' && countryVal != 'IN' && $("#user_country").val() != 'CA' ){ 
       
        $("#user_state").parent().html("<div class='abtlabel'><label>State  </label></div><input type='text' name='user_state' id='user_state' />&nbsp");
        $.get(mainUrl+'cmshelper/ajaxGetUserState/'+userId, function(result) {
            $('#user_state').val(result);
        });
    }else{ 
            $.get(mainUrl+'cmshelper/ajaxGetStatesByCountryUser/'+$("#user_country").val()+'/'+userId+'/edit', function(result) {
                $("#user_state").parent().html("<div class='abtlabel'><label>State  </label></div><select name='user_state' id='user_state'>"+result+"</select>&nbsp");
            });
        }

    $("#user_country").live("change", function() {

        if($("#user_country").val() != 'US' && $("#user_country").val() != 'IN' && $("#user_country").val() != 'CA' ){
            $("#user_state").parent().html("<div class='abtlabel'><label>State  </label></div><input type='text' name='user_state' id='user_state' />&nbsp");
            $.get(mainUrl+'cmshelper/ajaxGetUserState/'+userId, function(result) {
                $('#user_state').val(result);
            });
        }
        else{  
            $.get(mainUrl+'cmshelper/ajaxGetStatesByCountryUser/'+$("#user_country").val(), function(result) {
                $("#user_state").parent().html("<div class='abtlabel'><label>State  </label></div><select name='user_state' id='user_state'>"+result+"</select>&nbsp ");
            });
        }
    });
	
//---------------------------Initiate Introduction----------------------------------------------	
   //Display Initiate Introduction type
     $('.jInitiateIntroduction').click(function(){
         $.blockUI({ message: '' }); 
        var communityId    =   $(this).attr('cid');
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/initiate_introduction",
            data    : 'communityId='+communityId,
            cache   : false,
            success : function(data){
                $('#tab-InitiateIntroduction').html(data);
            }
        }); 
    });
     
     //Display Goodwill Introduction Details view
    $('.jIntroType').live('click',function(){
        $('#jloader').show();
        var introductionType    =   $(this).val();
        $("input:radio[name=goodwill_intro_type]").attr("checked", false);
        $('#divDisplayGoodFriendIntro').show(); 
        $('#divDisplayIntroductionMemberDetails').hide();
        track_click = 1;
        $('#jloader').hide();
    });
     
//    //Display members based on goodwill type view
//    $('.jGoodWillIntroType').live('click',function(){
//       $.blockUI({ message: '<h4><img src="'+mainUrl+'project/themes/default/images/loadinfo.gif"/>loading...</h4> ' }); 
//        track_click = 1;
//        $('#divDisplayIntroductionMemberDetails').show();
//        var goodwillMemberType    = $(this).val();
//        var communityId			= $('#communityId').val();
//        var alias=$("#community_alias").val();
//        $.ajax({
//            type    : "POST",
//            url     : mainUrl+"user/introduction_recipents_list",
//            data    : 'memberType='+goodwillMemberType+'&communityId='+communityId+'&alias='+alias,
//            cache   : false,
//            success : function(data){
//                $('#divDisplayIntroductionMemberDetails').html(data);
//    			 
//            }
//        }); 
//    });

//Populate hidden field with selected members id
    $checks = $(":checkbox");
    $checks.live('click', function() {
        /* var string = $checks.filter(":checked").map(function(i,v){
            return this.value;
        }).get().join(","); */
        var fields = '';
        $(":checkbox").each(function () {
            if (this.checked) {
                fields += $(this).val() + ',';
            }
        });
        $('#hidSelectedMembers').val(fields);
        console.log(fields);
    });


//Load more friends
    $('#load_more_friends_button').live('click', function() {
        $(this).hide();
        track_click++;
        var totpages = $(this).attr('tot');
        var alias = $(this).attr('alias');
        var search = $('#searchintrofriends').val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_friends",
            data	 : 'page='+track_click+'&alias='+alias+'&totpages='+totpages+'&search='+search,
            cache   : false,
            success : function(data){
                $('#frndslisting_blk_content').append(data);
				 
            }
        });
    });

    //Search friends
    $("#searchintrofriends").live("keyup", function() {
        var totpages = $('#hidTotalPages').val();
        var alias = $('#hidUserAlias').val();
        var search = $(this).val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_friends",
            data    : 'page=1&alias='+alias+'&totpages='+totpages+'&search='+search,
            cache   : false,
            success : function(data){
                $('#frndslisting_blk_content').html(data);
                
            }
        }); 
    });
	
//Load more  bizcom members
    $('#load_more_bizcom_members_button').live('click', function() {
        $(this).hide();
        track_click++;
        var totpages = $(this).attr('tot');
        var alias = $(this).attr('alias');
        var search = $('#searchmembers').val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_bizcom_members",
            data    : 'page='+track_click+'&alias='+alias+'&totpages='+totpages+'&search='+search,
            cache   : false,
            success : function(data){
               $('#frndslisting_blk_content').append(data);
				 
            }
        });
    });

    //Search bizcom members
    $("#searchmembers").live("keyup", function() {
        var totpages = $('#hidTotalPages').val();
        var alias = $('#hidCommunityAlias').val();
        var search = $(this).val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_bizcom_members",
            data    : 'page=1&alias='+alias+'&totpages='+totpages+'&search='+search,
            cache   : false,
            success : function(data){
                $('#frndslisting_blk_content').html(data);
                
            }
        }); 
    });
    
    //Load more non bizcom members
    $('#load_more_non_bizcom_members_button').live('click', function() {
        $(this).hide();
        track_click++;
        var totpages = $(this).attr('tot');
        var alias = $(this).attr('alias');
        var search = $('#searchNonBizcomMembers').val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_non_bizcom_members",
            data    : 'page='+track_click+'&alias='+alias+'&totpages='+totpages+'&search='+search,
            cache   : false,
            success : function(data){
                $('#frndslisting_blk_content').append(data);
				 
            }
        });
    });

    //Search non biz com members
    $("#searchNonBizcomMembers").live("keyup", function() {
        var totpages = $('#hidTotalPages').val();
        var alias = $('#hidCommunityAlias').val();
        var search = $(this).val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_non_bizcom_members",
            data    : 'page=1&alias='+alias+'&totpages='+totpages+'&search='+search,
            cache   : false,
            success : function(data){
                $('#frndslisting_blk_content').html(data);
                
            }
        }); 
    });
   
   //Load more bizcom
    $("#load_more_bizcom_button").live("click", function() {
        $(this).hide();
        track_click++;
        var search = $('#searchbizcom').val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_bizcom",
            data    : 'page='+track_click+'&search='+search,
            cache   : false,
            success : function(data){
                $('#frndslisting_blk_content').append(data);
            }
        });
   });
   //Search Bizcom
   $("#searchbizcom").live("keyup", function() {
        var search = $(this).val();
        $.blockUI({ message: '' }); 
        $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_more_introduction_bizcom",
            data    : 'page=1&search='+search,
            cache   : false,
            success : function(data){
                $('#frndslisting_blk_content').html(data);
                
            }
        }); 
    });
    
    //Mail Preview
  $("#jDisplayMailPreview").live("click", function() {
  $.blockUI({ message: '<h4><img src="'+mainUrl+'project/themes/default/images/loadinfo.gif"/>loading...</h4>' }); 
       var introType        = $("input[name=rad_intro_type]:checked").val();
       var memberType       = $("input[name=goodwill_intro_type]:checked").val();
       var selectedMember   = $.trim($('#hidSelectedMembers').val());
       var mailIds          = $.trim($('#txtMailIds').val());
       var communityAlias          = $.trim($('#community_alias').val());
       
       if(memberType !='5'){
          if(selectedMember =='') {
              alert("Please choose members whom you wish to send the intorduction to");
              return false;
          }
       }
        else{
           if(mailIds =='') {
               alert("Please enter the mail ids");
               return false;
           }
        }
       
       $.ajax({
            type    : "POST",
            url     : mainUrl+"user/load_mail_template",
            data    : 'memberType='+memberType+'&introType='+introType+'&selectedMember='+selectedMember+'&mailIds='+mailIds+'&communityAlias='+communityAlias,
            cache   : false,
            success : function(data){
                $('#tab-InitiateIntroduction').html(data);
                CKEDITOR.replace('txtMailPreview');
                //CKEDITOR.replace('txtPersonalMessage');
            }
        });
   });
   
   //Function to update ckeditor content
   function saveEditorTrigger(){
        for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement();
   }
   
     //Send Mail
  $("#jSendIntroMail").live("click", function() {
   $.blockUI({ message: '<h4><img src="'+mainUrl+'project/themes/default/images/loadinfo.gif"/>Sending mail...</h4>' }); 
      saveEditorTrigger();
      var data=$('#frmMail').serialize();
      $.ajax({
            type    : "POST",
            url     : mainUrl+"user/send_intro_mail",
            //data    : 'memberType='+memberType+'&introType='+introType+'&selectedMember='+selectedMember+'&mailIds='+mailIds+'&communityAlias='+communityAlias+'&mailSubject='+mailSubject+'&mailBody='+mailBody+'&mailSubheading='+mailSubheading+'&mailSpecifiedContact='+mailSpecifiedContact+'&mailUnspecifiedContact='+mailUnspecifiedContact,
            data    :data,
            cache   : false,
            success : function(){
                $('#tab-InitiateIntroduction').html('<div id="msgDisplay1" class="success_div">Introduction mail sent successfully</div>');
                
            }
        });
   });
   
//   $('#jadd_announcement').live('click',function(){
//       alert("hello");
//       $.ajax({
//            type    : "POST",
//            url     : mainUrl+"user/add1",
//            //data    : 'memberType='+memberType+'&introType='+introType+'&selectedMember='+selectedMember+'&mailIds='+mailIds+'&communityAlias='+communityAlias+'&mailSubject='+mailSubject+'&mailBody='+mailBody+'&mailSubheading='+mailSubheading+'&mailSpecifiedContact='+mailSpecifiedContact+'&mailUnspecifiedContact='+mailUnspecifiedContact,
//            cache   : false,
//            success : function(){
//                //$('#tab-InitiateIntroduction').html('<div id="msgDisplay1" class="success_div">Introduction mail sent successfully</div>');
//                
//            }
//        });
//   })
   
    if(location.hash=='#InitiateIntroduction'){
       $('.jInitiateIntroduction').trigger('click');
    }
    
    $('#jadd_announcement').live('click',function(){
        var count = $("#announcement_count").val();
        
        $(".no_announcement").hide();
        var file_data = $("#announcement_file").prop("files")[0];   // Getting the properties of file from file field
	var form_data = new FormData();                  // Creating object of FormData class
	form_data.append("file", file_data);
        $("#announcement_file").val('');
    $(".announcerrmsg").html("");
    var flag    = 0; 
    var mode    = $("#announcement_id").val();
    var date    = $("#hiddate").val();
    var title   = $("#announcement_title").val();
    var desc    = $("#announcement_desc").val();
   // console.log(desc);exit;
    //desc = desc.replace(/'/g, "");

    var status  = $("input:radio[name=announcement_status]:checked").val();
    var commid  = $('#hidcommunity_id').val();
    
    if(title.trim()=="")
        {
            $("#errtitle").html("Please provide title!");
            $(".announcerrmsg").show();
            flag = 1;
        }
        if(desc.trim()=="")
        {
            $("#errdesc").html("Please provide description!");
            $(".announcerrmsg").show();
            flag = 1;
        }
   
    if(flag==1)
        return false;
    else
        {
            $("#annsection").hide();
            $("#loadingannc").show();
         form_data.append("communityId",commid) ;
         form_data.append("title",title) ;
         form_data.append("desc",desc) ;
         form_data.append("status",status) ;
         form_data.append("mode",mode) ;
            $.ajax({
    		 type    : "POST",
    		 url     : mainUrl+"user/addannouncements",
                 cache   : false,
                 contentType: false,
                 processData: false,
    		 data    : form_data,
                // data    : 'communityId='+commid+'&title='+title+'&desc='+desc+'&status='+status+'&mode='+mode,
    		
    		 success : function(data){ 
                    
                     var data = data.split("@");
                      //console.log(data[0]);
                                 $("#annsection").show();
                                    $("#loadingannc").hide();
                              if(mode=="")
                                  {
                                     count = Number(count)+1;
                                      
                                      str = "<div class='col-sm-8 col-md-8 col-lg-8'><div class='mediapost announcementblk' id='announcementdiv_"+data[1]+"'><div class='media-body'> <h4 class='media-heading'><span id=id='announctitle_"+data[1]+"'>"+title+"</span> <span class='commentsdate listannounce_date'><div id='announcdate_"+data[1]+"'>"+date+"</div></span></h4><p>"+desc+"</p></div>";
                         if(data[0] != ''){ 
                            // alert("here");
                         str += "<div class='profile-bnr'><img src="+data[3]+data[0]+" class='img-responsive'></div>";
                     }

//         <div class='business_profilelist_detailsarea  annsection_cont_outer_2' id='announcementdiv_"+data[0]+"'><div class='business_profile_desc_colmiddle'><h3><span id='announctitle_"+data[0]+"'>"+title+"</span></h3><div class='business_profile_desc_colside_list'><div id='starring'><div id='announcdate_"+data[0]+"'>Date : "+date+"</div><a class='delete_link_business' style='cursor:pointer;' onclick='return deleteConfirm("+data[0]+");'>Delete</a><a class='edit_link_business' style='cursor:pointer;' onclick='return editAnnonc("+data[0]+");'>Edit</a></div></div><p style='position:relative;height:54px;overflow: hidden;' id='announcements_"+data[0]+"' class='announcements'>"+desc+"</p>";
           
//            if(desc.length > 200)
//                {
//            str += "<a class='readmore' id='readmore_"+data[0]+"' style='cursor: pointer;'>Read More </a>";
//            }
//       
//           str += "</div><div class='clear'></div></div>";
           str += "<div class='listannouncements_img_bottom'><a class='delete_link_business' style='cursor:pointer;' onclick='return deleteConfirm("+data[1]+");'>Delete</a> <a class='edit_link_business' style='cursor:pointer;' onclick='return editAnnonc("+data[1]+");'>Edit</a></div></div><div class='clearfix'></div></div>";
           
          // $("#annsection > div:nth-child(3)").after(str);
           $("#jannouncementsDisplay").prepend(str);
           $("#anouncement_add_sec").hide();
           $("#announcement_count").val(count);
           $("#annsuccmsg").html("Announcement added successfully!");
                                  }
                                  else
                                      {
                                        var str1;  
                                          $("#announctitle_"+mode).html(title);
                                          $("#announcdate_"+mode).html(date);
                                          $("#announcdesc_"+mode).html(desc);
                                        // alert($("#img_"+mode).attr('src'));
                                          $("#announcementdiv_"+data[1]+" .profile-bnr").empty();
                                             // alert("here");
                                                 $("#img_"+mode).remove();
                                          //}
                                          //else{
                                             //  alert("here");
                                            // console.log(data);exit;
                                        if(data[0] != " "){
                                           
                                          str1 = "<div class='profile-bnr'><img src="+data[3]+data[0]+" class='img-responsive'></div>";
                                        }
                                          $("#announcementdiv_"+data[1]+" .media-body").append(str1);
                                         // }
                      
                                          $("#anouncement_add_sec").hide();
                                          $("#annsuccmsg").html("Announcement edited successfully!");
                                          
                                      }
                        $(".business_profilelist_detailsarea").show();
                        $("#announcement_setting").html("Announcements ("+data[2]+")");
                        
                                    //$( "#announcement_setting" ).trigger( "click" );
                            
                            
    		 }
    	 });    
        
        //return true;
        }
    
});
});


function searchvalue(val)
{
  if(val.length >= 1)
      {
          alert(val);
      }
  
}

