
//auto complete function 


$(document).ready(function(){
    $(function() {
  function split( val ) {
                return val.split( /,\s*/ );
        }
                function extractLast( term ) {
                 return split( term ).pop();
        }

        $( "#assign_to" )
            // don't navigate away from the field on tab when selecting an item
              .bind( "keydown", function( event ) {
                if ( event.keyCode === $.ui.keyCode.TAB &&
                        $( this ).data( "autocomplete" ).menu.active ) {
                    event.preventDefault();
                }
            })
			//
		
            .autocomplete({
			
                source: function( request, response ) {
			
                    $.getJSON( "autoload_name.php",{  //Url of controller
                        term: extractLast( request.term )
                    },response );
                },
                search: function() {
                    // custom minLength
                    var term = extractLast( this.value ); 
                    if ( term.length < 1 ) {
                        return false;
                    }
                },
                focus: function() {
                    // prevent value inserted on focus
                    return false;
                },
                select: function( event, ui ) {
                    var terms = split( this.value ); 
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push( ui.item.value );
                    // add placeholder to get the comma-and-space at the end
                    terms.push( "" );
                    this.value = terms.join( "" );
                    return false;
                }
            });
          
 });
});





//auto complete function 


$('.resi_dat').live('click',function(){ 
		 $(this).datepicker({dateFormat:"dd-mm-yy"}).focus();	//alert();
	});
	function clone_dv()
	{
	
/*	 var container = document.getElementById('main_div');
    var clone = document.getElementById('stages').cloneNode(true);
	
    clone.setAttribute('id','div_'+document.getElementById('main_div').getElementsByTagName('div').length);

    container.appendChild (clone);*/
	$('#stages:last').clone()
                          .find("input:text").val("").end()
                          .appendTo('#stages:last');
	
	}
	$('#proj_id').click(function(){
    	$('#savclick').attr('disabled',false);
});
	
	function save_proj()
	{
	var p_stage=$('#proj_stage').val();	
	var p_id=$('#proj_id').val();	
	var p_name=$('#proj_name').val();
	if(p_stage=='' || p_id=='' || p_name=='')
	{
	alert("Please Enter All Fields");
	}
	else
	{
		//$('#savclick').attr('disabled',true);
	dataString = $('#ad_proj').serialize(); 

	
$.post("project_add.php?action=grt_insert",dataString,function(data){
		var timing = data.timing;
	
		$('.box_one:last').after( '<div class="box_one">'+
				
								'<div class="project_id_heading_3">'+timing.proj_id+'</div>'+
								'<div class="project_id_heading_3">'+timing.proj_name+'</div>'+
	'<div class="project_id_heading_3">'+'<li class="dropdown user user-menu">'+'stages'+' <a href="#" class="dropdown-toggle" data-toggle="dropdown">'+'<i class="caret">'+'</i>'+'</a>'+'<ul class="dropdown-menu">'+'<li class="user-footer">'+'</li>'+' </ul>'+'</li>'+'</div>'+'</div>');
	
			$('#lat_list').append( '<div class="box_two">'+
				
								'<div class="recent_added_projects_partition_one">'+timing.proj_id+'</div>'+
								'<div class="recent_added_projects_partition_one_projectname">'+timing.proj_name+'</div>'+'</div>');
	
		},'json');
		
		
		
	$('#proj_stage').val('');	
	$('#proj_id').val('');	
	$('#proj_name').val('');	
}	
		
	}
	
	
	$('#wek_set').on('change', function() {
  //alert( this.value ); // or $(this).val()
});

///master set

		$('#resi_dats').on('change', function() {
		var dat=this.value;

var dateString = this.value;
var date = moment(dateString, "DD-MM-YYYY").format("MMMM, DD, YY"); // date string
var actualDate = new Date(date);// convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+6); // create new increased date


var newDateString =  newDate.getDate() + '-' + (newDate.getMonth()+1) + '-' + newDate.getFullYear();

$('#wek_end').val(newDateString);

$('#wek_to').val(newDateString);
$('#wek_from').val(dat);

});


///user set


$('#wek_usr').live('change', function() {
	var toval=$('#resi_dats').val();
	weekNo = $(this).val();

	var actualWeek = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getWeek(); 
	//console.log(actualWeek);
	var choosedDay = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getDay();
	//console.log(choosedDay);
	//var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(weekNo)-1), choosedDay);
	
var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(weekNo)), choosedDay);
	
	
//	console.log(newWeek);
	
	     for (var p = 0; p < newWeek.length; p++) {
	var datto=newWeek[0];
	var datfrom=newWeek[1];
		 var newDateString_from =  datfrom.getDate() + '-' + (datfrom.getMonth()+1) + '-' + datfrom.getFullYear();
		  var newDateStringTo_from =  datto.getDate() + '-' + (datto.getMonth()+1) + '-' + datto.getFullYear();
        $('#wek_to').val(newDateString_from);
     $('#wek_from').val(newDateStringTo_from); 
    }
 
 if(document.getElementById("r_cnts"))
 {
	 go_to_cal();
 }
 
});




///activity done

$('#wek_usrs_ft').live('change', function(e) {
	e.preventDefault();
	
	
	var toval=$('#resi_dats').val();
	weekNo = $(this).val();

	var actualWeek = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getWeek(); 
	var choosedDay = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getDay();
	//console.log(choosedDay);
	var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(weekNo)), choosedDay);
	


	
	for (var p = 0; p < newWeek.length; p++) {
		
	var datto=newWeek[0];
	var datfrom=newWeek[1];
		 var newDateString_from =  datfrom.getDate() + '-' + (datfrom.getMonth()+1) + '-' + datfrom.getFullYear();
		  var newDateStringTo_from =  datto.getDate() + '-' + (datto.getMonth()+1) + '-' + datto.getFullYear();
        $('#wek_to').val(newDateString_from);
     $('#wek_from').val(newDateStringTo_from); 
	 
	 $('#daily').datepicker('destroy');
	 var min_dat=$('#wek_from').val();
var max_dat=$('#wek_to').val();





$('#daily').datepicker('destroy');

$('#daily').datepicker({ 
	dateFormat:"dd-mm-yy" ,
	'minDate':moment(min_dat, "DD-MM-YYYY").format('YYYY-MM-DD'),
	'maxDate':moment(max_dat, "DD-MM-YYYY").format('YYYY-MM-DD')
});




/*$('#daily').datepicker('option', 'minValue',min_dat);
$('#daily').datepicker('option', 'maxValue', max_dat);
*/
    }
goto_div_val(weekNo);

//date picker block

go_to_cal(newDateString_from,newDateStringTo_from);

});


// 
function change_week(wekno)
{
	var toval=$('#resi_dats').val();
	
	weekNo = wekno;

	var actualWeek = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getWeek(); 
	var choosedDay = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getDay();
	//console.log(choosedDay);
	
	currentWeekNo = wekno;
	
	//currentWeekNo = parseInt(weekNo) - parseInt(actualWeek)+1;
	
	//currentWeekNo = parseInt(weekNo) - parseInt(actualWeek);
	//var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(currentWeekNo)-1), choosedDay);
	var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(currentWeekNo)), choosedDay);
	$('#wek_usrs_ft').val(currentWeekNo);
	
//	console.log(newWeek);
	
	for (var p = 0; p < newWeek.length; p++) {
	var datto=newWeek[0];
	var datfrom=newWeek[1];
		 var newDateString_from =  datfrom.getDate() + '-' + (datfrom.getMonth()+1) + '-' + datfrom.getFullYear();
		  var newDateStringTo_from =  datto.getDate() + '-' + (datto.getMonth()+1) + '-' + datto.getFullYear();
     $('#wek_to').val(newDateString_from);
     $('#wek_from').val(newDateStringTo_from); 
    }
goto_div_val(currentWeekNo);

go_to_cal(newDateString_from,newDateStringTo_from);
}
/**
 * Get the ISO week date week number
 */
 
 
 Date.prototype.getWeekNo = function() {
  var date = new Date(this.getTime());
   date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000
                        - 3 + (week1.getDay() + 6) % 7) / 7);
}
 
Date.prototype.getWeek = function () {
	// Create a copy of this date object
	var target  = new Date(this.valueOf());

	// ISO week date weeks start on monday
	// so correct the day number
	var dayNr   = (this.getDay() + 6) % 7;

	// ISO 8601 states that week 1 is the week
	// with the first thursday of that year.
	// Set the target date to the thursday in the target week
	target.setDate(target.getDate() - dayNr + 3);

	// Store the millisecond value of the target date
	var firstThursday = target.valueOf();

	// Set the target to the first thursday of the year
	// First set the target to january first
	target.setMonth(0, 1);
	// Not a thursday? Correct the date to the next thursday
	if (target.getDay() != 4) {
		target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
	}

	// The weeknumber is the number of weeks between the 
	// first thursday of the year and the thursday in the target week
	return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
}

function getDays(year,week,day) {

    var j10 = new Date(year, 0, 10, 12, 0, 0),
        j4 = new Date(year, 0, 4, 12, 0, 0),
        mon = j4.getTime() - j10.getDay() * 86400000;
        result = [];
		
		result.push(new Date(mon + ((week - 1) * 7 + (day-1)) * 86400000));
		result.push(new Date(mon + ((week - 1) * 7 + (day+5)) * 86400000));
  //  for (var i = -1; i < 6; i++) {
       // result.push(new Date(mon + ((week - 1) * 7 + 1) * 86400000));
  //  }

   return result;
}

function getDays_master(year,week,day) {

    var j10 = new Date(year, 0, 10, 12, 0, 0),
        j4 = new Date(year, 0, 4, 12, 0, 0),
        mon = j4.getTime() - j10.getDay() * 86400000;
        result = [];
		
		result.push(new Date(mon + ((week - 1) * 7 + (day-1)) * 86400000));
		result.push(new Date(mon + ((week - 1) * 7 + (day+5)) * 86400000));
	for (var p = 0; p < result.length; p++) {
	var datto=result[0];
	var datfrom=result[1];
		 var newDateString_from =  datfrom.getDate() + '-' + (datfrom.getMonth()+1) + '-' + datfrom.getFullYear();
		  var newDateStringTo_from =  datto.getDate() + '-' + (datto.getMonth()+1) + '-' + datto.getFullYear();
     $('#resi_dats').val(newDateStringTo_from);
     $('#wek_end').val(newDateString_from); 
    }
	
	var datFrm=$('#resi_dats').val();//alert(3);
	var datTo=$('#wek_end').val(); 
	     var dataString = 'frm='+datFrm+'&tos='+datTo;
     $.ajax({
           type: "POST",
           url: "loadactmasterdate.php",
           data: dataString,
           cache: false,
           success: function(result){
           		$(".flash").hide();
                // $("#m_divs").html(result);
           }
      });
	
	
}



	$('#proj_ids').on('change', function() {
  // or $(this).val()
  $('#proj_name').val(this.value);
  get_stages(this.value);
});
	$('#proj_name').on('change', function() {
 // or $(this).val()
  $('#proj_ids').val(this.value);
  get_stages(this.value);
});



///////code for add activity current date week

function change_week_activity_plan(wekno)
{
	var toval=$('#resi_dats').val();
	
	weekNo = wekno;

	var actualWeek = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getWeek(); 
	var choosedDay = new Date( moment(toval, "DD-MM-YYYY").format('YYYY-MM-DD') ).getDay();
	//console.log(choosedDay);
	
	currentWeekNo =wekno;
	
	//currentWeekNo = parseInt(weekNo) - parseInt(actualWeek)+1;
	//currentWeekNo = parseInt(weekNo) - parseInt(actualWeek);
	//var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(currentWeekNo)-1), choosedDay);
	//var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(currentWeekNo)), choosedDay);
	
	
	var newWeek = getDays( moment(toval, "DD-MM-YYYY").format('YYYY'), actualWeek + (parseInt(currentWeekNo)), choosedDay);
	
	$('#wek_usr').val(currentWeekNo);
	
	
	
	for (var p = 0; p < newWeek.length; p++) {
	var datto=newWeek[0];//alert(datto);
	var datfrom=newWeek[1];
	
	var newDateString_from =  datfrom.getDate() + '-' + (datfrom.getMonth()+1) + '-' + datfrom.getFullYear();
	var newDateStringTo_from =  datto.getDate() + '-' + (datto.getMonth()+1) + '-' + datto.getFullYear();
    
	 $('#wek_to').val(newDateString_from);
     $('#wek_from').val(newDateStringTo_from); 
	 
    }
	
	
	
	
		if(userid!=1)
	{
	
	set_week_val(currentWeekNo);
	}
	//set_week_val(currentWeekNo);

}




function set_week_val(currentWeekNo)
{
	      var dataString = 'WeekNo='+currentWeekNo;
     $.ajax({
           type: "POST",
           url: "loadact_week_plan.php",
           data: dataString,
           cache: false,
           success: function(result){
           		$(".flash").hide();
                $("#wek_act_plan").html(result);
           }
      });
}
///////code for add activity current date week

function get_stages(p_id){
      
     var dataString = 'pj_id='+ p_id;
     $.ajax({
           type: "POST",
           url: "loadstages.php",
           data: dataString,
           cache: false,
           success: function(result){
           $(".flash").hide();
                 $("#chng_stg").html(result);
           }
      });
}


///autoload

/* $("#assign_to").blur(function (){
	$(this.value=='')
					{
						  $('#hid').val('');
						
					}
});*/
	