var group;
var base_url = 'http://54.218.78.31:50/dev/index.php/';
$(document).ready(function(){

	function getUrlVars()
	{
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
	    {
	        hash = hashes[i].split('=');
	        vars.push(hash[0]);
	        vars[hash[0]] = hash[1];
	    }
	    return vars;
	}

	if( getUrlVars()["q"] == 'addlwd' )
	{
		$('#lightbox').modal('show');
	}

	if( getUrlVars()["q"] == 'addcostcenter' )
	{
		$('#lightbox').modal('show');
	}

	if( getUrlVars()["q"] == 'addcontract' )
	{
		$('#lightbox').modal('show');
	}
	if( getUrlVars()["q"] == 'addoffices' )
	{
		$('#lightbox').modal('show');
	}


	/* get signal value by selecting checkbox in lwd screen */
	$('.signal_kill').change(function(){
		//alert( $(this).val() );
		
		if( $(this).data('type') == 'android' )
		{
			//alert();
			$.ajax({
				url: 'http://54.218.78.31:50/dev/index.php/lwd/change_signal_kill/',
				type: 'post',
				data: { lwd_id: $(this).data('lwd_id'), signal_kill: $(this).val() },
				success: function(result)
				{
					console.log(result);
					if( result == 'done' )
					{
						$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/TickGif.gif">');
						$('.modal_text').html('<p>Signal Update</p>');
						$('#lightboxPopup').modal({
                             backdrop: 'static',
                             keyboard: false
                        });
						setTimeout( function() {
							window.location.href="";
						}, 3000);
					}
				}
			});

		}
		if( $(this).data('type') == 'ios' )
		{

			//add_ios($(this).data('lwd_id'),$(this).val(), $(this).data('device_token') );
			

			$.ajax({
				url: 'https://www.redalertws.com/iosconfig/push/iosnotification.php',
				type: 'post',
				data: { lwd_id: $(this).data('lwd_id'), signal_kill: $(this).val(), device_token: $(this).data('device_token') },
				success: function(result)
				{
					console.log(result);
					if( result == 'done' )
					{
						add_ios($(this).data('lwd_id'),$(this).val() );
					}
				}
			});
		}
	});
	$.validator.addMethod(
		    "dateFormat",
		    function(value, element) {
		        // put your own logic here, this is just a (crappy) example
		        var regEx = /^\d{2}-\d{2}-\d{4}$/;
  				return value.match(regEx) != null;
		    },
		    "Please enter a date in the format dd-mm-yyyy."
		);

	$('#setting_screen input[name="falldetectenabled"]').click(function()
	{
		if( $('#falldetectenabled').is(':checked') )
		{
			$('#setting_screen .falldetectsensitivity').removeAttr('disabled');
		}
		else
		{
			$('#setting_screen .falldetectsensitivity').attr('disabled','disabled');
		}
	});


$('#costcenter_dropdown').change(function(){
	$.ajax({
		  url: '/dev/index.php/office/get_contract_area/'+$(this).val() ,
          dataType: "json",	
          beforeSend: function(){
			        $('#constractArea').html('<option>Loading</option>');
			    },  
		  success: function(result){
		  		if( result.length > 0 || result != null || result != ' ' )
		  		{
		  			$('#submit_form').removeAttr('disabled');
		  			$("#constractArea option").remove();
				    $("#constractArea").removeAttr('disabled');
					$.each(result, function(i, item) {
						 $('#constractArea').append(new Option(item.description,item.lindex));
					});
		  		}
		  		if(result.msg == 'fail')
		  		{
		  			$('#submit_form').attr('disabled', 'disabled');
		  			$("#constractArea").css('display', 'inline-block');
		  			$('#constractArea').html('<option>No Contract Area Avaliable</option>');
		  		}
          }
  	});
});

$('.edit_office_model').click(function(){
	$.ajax({
		  url: '/dev/index.php/office/get_office_edit/'+$(this).data('id') ,
          dataType: "json",  
		  success: function(result){
		  	console.log(result);
		  		$('#officeID').val(result.lindex);
	  			$('#edit_costcentre').val( result.costcentre_name );
	  			$('#edit_contractarea').val( result.contractarea_name );
	  			$('#edit_description').val( result.description );
	  			$('#edit_admin_name').val( result.admin_name );
	  			$('#edit_email').val( result.email );
	  			$('#number').val( result.contact_no );
	  			$('#edit_password').val( result.password );
	  			$('#edit_cpassword').val( result.password );
				$('#edit_popup').modal({
                             backdrop: 'static',
                             keyboard: false
                });
	  			
          }
  	});


	
});


/* edit escalation details */
$('#escalation_tab').validate({

	rules:
	{
		name1: 'required',
		name2: 'required',
		name3: 'required',
		phone1:
		{
			required: true,
			number: true
		},
		phone2:
		{
			required: true,
			number: true
		},
		phone3:
		{
			required: true,
			number: true
		}
	},
	submitHandler: function(form)
	{
		$.ajax({
			url: base_url+'lwd/edit_escalation',
			type: 'post',
			data: $('#escalation_tab').serialize(),
			success: function(response)
			{
				console.log(response);
				if( response == 'done' )
				{
					alert(' Escalation Detail Update ');
					window.location.href = '';
				}
				if( response == 'fail' )
				{
					alert( 'Update Fail Check Input' );
				}
			}
		});
	}
});


$('#setting_screen').validate({
		rules:
		{
			redalertnumber:{ 
				required: true,
				number: true
				},
			amberalertnumber: { 
				required: true,
				number: true
				},
			ipaddress: 'required',
			port: 'required',
			redalertsmsnumber: { 
				required: true,
				number: true
				},
			silentdial: { 
				required: true,
				number: true
				},
			positionupdateinterval: { 
				required: true,
				number: true
				},
			falldetectenabled: 'required',
			limitamber: { 
				required: true,
				number: true
				},
			falldetectedsensitivity: {
				required: true
			},
			redalertnumber: { 
				required: true,
				number: true
				}
		},
		 submitHandler: function(form) {
		 	$.ajax({
		 		url: 'lwd/add_setting',
		 		type: 'post',
		 		data: $('#setting_screen').serialize(),
		 		success:function(response)
		 		{
		 			console.log(response);
		 			if(response == "done")
		 			{

		 				$('.error_msg').html('<p style="color: green"><b>Settings Update</b></p>');
		 				setTimeout( function()
		 				{
		 					$('#settingpopup').modal('toggle');
		 					$('#setting_screen')[0].reset();
		 					$('.error_msg').html(' ');
		 				}, 500 )
		 			}
		 		}
		 	})
		 }

	});



	$("#add_lwd").validate({
		rules:
		{
			email: 
			{
				required: true,
				email: true
			},
			password: "required",
			gender:
			{
				required: true
			},
			dob:
			{
				required: true
			},
			fname: 'required',
			login_name: 'required',
			number:
			{
				required: true,
				number: true,
				minlength: 12,
				maxlength: 13
			},
			imei: 'required',
			address: 'required'
		},
		messages: 
		{
			email:
			{
				required: "Email is required",
				email: "Invalid Email"
			},
			gender:
			{
				required: "Please Select Gender"
			},
			number:
			{
				minlength: 'Please insert country code',
				maxlength: 'Please insert country code'
			}
		},
	  submitHandler: function(form) {
	    	$.ajax({
	    		type: 'post',
	    		url: 'lwd/add_lwd',
	    		data: $('#add_lwd').serialize(),
	    		success: function(result)
	    		{
	    			if(result == "done")
	    			{
	    				$('.ajax_msg').html('<span style="color: green; font-weight: bold">Insert Success</span>');
	    				setTimeout(function(){ 
	    					$('.ajax_msg').text(' ');
	    					$("#add_lwd")[0].reset();
	    					$('#lightbox').modal('hide');
	    					window.location.href='';
	    				}, 1500);
	    			}
	    			else
	    			{
	    				$('.ajax_msg').html('<span style="color: red; font-weight: bold">Insert Fail</span>');
	    				setTimeout(function(){ $('.ajax_msg').text(' '); }, 1500);
	    			}
	    		}
	    	})
	  }
 	});


/*----------adding more divs-----------*/


	var clicks = 0;
 	$('.addMoreDiv').on('click', function()
 	{
		group = $('.fullNameField');
 		clicks++;
 		var html_div;
 		var html = $(this).data('form');
 		if( html == "costcenter" )
		{
			html_div = '<div class="row lighboxInner" id="div_'+clicks+'"><div class="col-lg-12"><div class="form-group label-floating"><label class="control-label">Cost Service Name</label><input type="text" class="form-control fullNameField" name="cc_name[]" required=""></div><a href="javascript:void(0);" class="deleteDiv" onclick="return deleteDiv('+clicks+')"><img src="/img/deleteIcon.svg"></a><a href="javascript:void(0);" class="addMoreDivNew"><img src="/img/addIcon.svg"></a></div></div>';
		}
		$('.add_more_fields').append(html_div);
		$('.errorcount').attr("id",clicks);
 	});

 	$('.add_more_fields').on( 'click', '.addMoreDivNew', function(){
 		$('.addMoreDiv').trigger('click');
 	});


 	$('#add_costcenter').submit(function(event){
 		event.preventDefault();
		var hostname = window.location.hostname;
 		$.ajax({
 			url: '/dev/index.php/costcenter/add_cost_center',
 			type: 'post',
 			data: $('#add_costcenter').serialize(),
 			success: function(result)
 			{
 				if(result == "done")
 				{
 					$('.ajax_msg').html('<p style="color: green;">Cost Center Added </p>');
 					setTimeout(function(){ window.location.href='' ; }, 1000);
 				}
 				else if(result == "update")
 				{
 					$('.ajax_msg').html('<p style="color: green;">Cost Center Updated </p>');
 					setTimeout(function(){ window.location.href='' ; }, 1000);
 				}
 				else
 				{
 					$('.ajax_msg').html('<p style="color: green;">'+result+'</p>');	
 					setTimeout(function(){ window.location.href='' ; }, 1000);
 				}
 			}
 		});
 	});


/*----- adding contract area ----*/

$("#add_contractarea").submit(function(e){
		e.preventDefault();
		
		if( $('#contractarea_id').val().length > 1)
		{
			$.ajax({
				url: '/dev/index.php/contractarea/edit_contractArea',
				type: 'post',
				data: $('#add_contractarea').serialize(),
				success: function(result)
				{
					console.log(result);
					if(result == "update")
	 				{
	 					$('.ajax_msg').html('<p style="color: green;">Contract Area Added </p>');
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
	 				else
	 				{
	 					$('.ajax_msg').html('<p style="color: green;">'+result+'</p>');	
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
				}
			});
		}
		else
		{
			
			//alert( $('#add_contractarea').serialize() ); return false;
				if( $('#costcenter').val() != '0' && $('#contract_area').val().length > 0)
				{
					$.ajax({
						url: '/dev/index.php/contractarea/add_contractAreaOffice',
						type: 'post',
						data: $('#add_contractarea').serialize(),
						success: function(result)
						{
							console.log(result);
							if(result == "done")
			 				{
			 					$('.ajax_msg').html('<p style="color: green;">Contract Area Added </p>');
			 					setTimeout(function(){ window.location.href='' ; }, 1000);
			 				}
			 				else
			 				{
			 					$('.ajax_msg').html('<p style="color: green;">'+result+'</p>');	
			 					setTimeout(function(){ window.location.href='' ; }, 1000);
			 				}
						}
					});
				}
				else
				{
					alert('All Field are Required');
				}
		}

		
	});


/*--- add offices ---*/

$("#add_office").validate({
		rules:
		{
			costcenter: 'required',
			office_name: 'required',
			contract_area: 'required',
			admin_name: 'required',
			email_address: 'required',
			contact_number: {
				required: true,
				number: true
			},
			password:
			{
				required: true
			},
			cpassword:
			{
				required: true,
				equalTo: '#password'
			}
		},
		submitHandler: function(form)
		{
			$.ajax({
				url: '/dev/index.php/office/add_Office',
				type: 'post',
				data: $('#add_office').serialize(),
				success: function(result)
				{
					console.log(result);
					if(result == "done")
	 				{
	 					$('.ajax_msg').html('<p style="color: green;">Office Added </p>');
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
	 				else if(result == "update")
	 				{
	 					$('.ajax_msg').html('<p style="color: green;">Office Updated </p>');
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
	 				else
	 				{
	 					$('.ajax_msg').html('<p style="color: red;">'+result+'</p>');	
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
				}
			});
		}
	});


$("#edit_offce").validate({
		rules:
		{
			office_name: 'required',
			admin_name: 'required',
			email_address: 'required',
			contact_number: {
				required: true,
				number: true
			},
			password:
			{
				required: true
			},
			cpassword:
			{
				required: true,
				equalTo: '#edit_password'
			}
		},
		submitHandler: function(form)
		{
			$.ajax({
				url: '/dev/index.php/office/edit_offce',
				type: 'post',
				data: $('#edit_offce').serialize(),
				success: function(result)
				{
					console.log(result);
					if(result == "done")
	 				{
	 					$('.ajax_msg').html('<p style="color: green;">Office Updated </p>');
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
	 				else if(result == "update")
	 				{
	 					$('.ajax_msg').html('<p style="color: green;">Office Updated </p>');
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
	 				else
	 				{
	 					$('.ajax_msg').html('<p style="color: red;">'+result+'</p>');	
	 					setTimeout(function(){ window.location.href='' ; }, 1000);
	 				}
				}
			});
		}
	});



$("#adding_lwd").validate({
		rules:
		{
			fname: 'required',
			login_name: 'required',
			gender: 'required',
			address: 'required',
			device_type: 'required',
			imei: {
				required: true,
				number: true
			},
			email: {
				required: true,
				email: true
			},
			phone: {
				required: true,
				number: true
			},
			password:
			{
				required: true
			}
		},
		submitHandler: function(form)
		{
			$.ajax({
				url: 'add_lwd',
				type: 'post',
				data: $('#adding_lwd').serialize(),
				success: function(response)
				{
					console.log(response);
					if(response == 'done')
					{
						$('#error_msg_lwd').html(' ');
						$('#error_msg_lwd').html('<p style="color: green">Lwd Added</p>');
						setTimeout(function(){
							$('#adding_lwd')[0].reset();
						}, 500);
					}
					if( response == 'fail' )
					{

						$('#error_msg_lwd').html(' ');
						$('#error_msg_lwd').html('<p style="color: red">Error Can not add</p>');
						setTimeout(function(){
							$('#adding_lwd')[0].reset();
						}, 500);
					}
				}
			})			
		}
	});



/*---- change status of cost center ----*/
$('.status').change(function()
{
	/*alert( $(this).data('cost_id') );
	alert( $(this).val() );*/
	$.ajax(
	{
		url: 'costcenter/change_status',
		type: 'post',
		data: { id: $(this).data('cost_id'), status: $(this).val() },
		success: function(result)
		{
			console.log(result);
			if( result == 'done' )
			{
					$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/TickGif.gif">');
					$('.modal_text').html('<p>Status Update </p>');
					$('#lightboxPopup').modal({
                         backdrop: 'static',
                         keyboard: false
                    });
					
					setTimeout( function() {
						window.location.href="";
					}, 3000);
			}
			else
			{
				$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/Cancel.png">');
				$('.modal_text').html('<p>Status Update Fail</p>');
				$('#lightboxPopup').modal({
                         backdrop: 'static',
                         keyboard: false
                    });
					
				
			}
		}
	});
});


/*---- change status of contract area ----*/
$('.contractarea_status').change(function()
{
	$.ajax(
	{
		url: 'contractarea/change_status',
		type: 'post',
		data: { id: $(this).data('cost_id'), status: $(this).val() },
		success: function(result)
		{
			console.log(result);
			if( result == "done" )
			{
				$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/TickGif.gif">');
				$('.modal_text').html('<p>Status Update </p>');
				$('#lightboxPopup').modal({
                         backdrop: 'static',
                         keyboard: false
                    });
					
				setTimeout( function() {
					window.location.href="";
				}, 3000)
			}
			else
			{
				$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/Cancel.png">');
				$('.modal_text').html('<p>Status Update Fail</p>');
				$('#lightboxPopup').modal({
                         backdrop: 'static',
                         keyboard: false
                    });
					
			}
		}
	});
});


/*---- change the status of office ----*/
$('.office_status').change(function()
{
	$.ajax(
	{
		url: 'office/change_status',
		type: 'post',
		data: { id: $(this).data('cost_id'), status: $(this).val() },
		success: function(result)
		{
			console.log(result);
			if( result == "done" )
			{
				$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/TickGif.gif">');
				$('.modal_text').html('<p>Status Update </p>');
				$('#lightboxPopup').modal({
                         backdrop: 'static',
                         keyboard: false
                    });
					
				setTimeout( function() {
					window.location.href="";
				}, 3000)
			}
			else
			{
				$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/Cancel.png">');
				$('.modal_text').html('<p>Status Update Fail</p>');
				$('#lightboxPopup').modal({
                         backdrop: 'static',
                         keyboard: false
                    });
					
			}
		}
	});
});


// autocomplete for searchbar on LWD
$('.searchbar_LWD').autocomplete({
	//source: 'lwd/search_lwd',
	minlength: 3,
	source: function( request, response ) {
	    var terms = split( request.term );
	    if (terms.length < 2) {
	      $.getJSON("degrees.php", { term : extractLast( request.term )},response);
	    }else{
	       $.getJSON("skills.php", { term : extractLast( request.term )},response);
	    }
	}
});

$('.cancel').click(function(e){
	e.preventDefault();
	var r = confirm("Are you sure you want to cancel this action");
    if (r == true) {
        $('.deleteDiv').trigger('click');
		$('.closepopup').trigger('click');
		$('.error').remove();
    } else {
        
    }
	
});


}); /*document ready function*/

/*--------------------- Check for Login Name--------------------------*/
function login_name_check()
{
	//alert();
	$.ajax({
		type: 'get',
		url: 'lwd/login_name',
		data: { login_name: $('#login_name').val() },
		success: function(result)
		{
			if( result == "already" )
			{
				$('.login_name_error').text("Login Name already used");
				$('#submit_button').attr('disabled', 'true');
			}
			else
			{
				$('.login_name_error').text(" ");
				$('#submit_button').removeAttr('disabled');
			}
		}
	});
}


function email_address_check()
{
	$.ajax({
		type: 'get',
		url: 'email_address',
		data: { email_address: $('#email_address').val() },
		success: function(result)
		{
			if( result == "already" )
			{
				$('.email_error').text("Email already used");
				$('#submit_button').attr('disabled', 'true');
			}
			else
			{
				$('.email_error').text(" ");
				$('#submit_button').removeAttr('disabled');
			}
		}
	});
}

function redirect()
{
	window.location.href="";
}

/*---- check for contract area email -----*/
function email_check()
{
	$.ajax({
		type: 'get',
		url: 'contractarea/check_email',
		data: { email_address: $('#email_address').val() },
		success: function(result)
		{
			/*if( result == "already" )
			{
				$('.login_name_error').text("Login Name already used");
			}
			else
			{
				$('.login_name_error').text(" ");	
			}*/
			console.log(result);
		}
	});
}

function add_ios(id,kill, device_token)
{
	//alert(); return false;

			$.ajax({
				url: 'http://54.218.78.31:50/dev/index.php/lwd/change_signal_kill/',
				type: 'post',
				data: { lwd_id: id, signal_kill: kill },
				success: function(result)
				{
					console.log(result);
					if( result == 'done' )
					{

						$('.img_src').html('<img src="http://54.218.78.31:50/dev/img/TickGif.gif">');
						$('.modal_text').html('<p>Signal Update</p>');
						$('#lightboxPopup').modal({
                         backdrop: 'static',
                         keyboard: false
                        });
					
						setTimeout( function() {
							window.location.href="";
						}, 3000);
					}
				}
			})
				
	
}


/*---- deleting more cost center ----*/
function deleteDiv(num)
{
	group = $('.fullNameField');
	$('#div_'+num).html(' ');
    var count = $('.errorcount').attr("id");
    count = count - 1;
    $('.errorcount').attr("id",count);	
}


function add_costcenter_modal()
{
	$('#cc_name').val(' ');
	$('#costcenterID').val(' ');
	$('#lightbox').modal({
       backdrop: 'static',
       keyboard: false
    });
}

/*----- ajax for editing costcenter -------*/
function editing_costcenter(id,name)
{
	$('#cc_name').val(name);
	$('#costcenterID').val(id);
	$('.label-floating').addClass('is-focused');
	$('#lightbox').modal({
       backdrop: 'static',
       keyboard: false
    });
}


function add_contract_area()
{
	$('#pop_heading').text('Add Contract Area');
	$('#contract_area').val(' ');
	$('#contractarea_id').val(' ');
	$('#add_costcenter').css('display', 'block');
	$('#edit_costcenter').html(' ');
	$('#lightbox').modal({
       backdrop: 'static',
       keyboard: false
    });
	
}

function edit_contract_area(id, name, costcenter)
{
	$('#pop_heading').text('Edit Contract Area');
	$('#add_costcenter').css('display', 'none');
	$('#edit_costcenter').html('<select disabled ><option>'+costcenter+'</option></select>');
	$('#contract_area').val(name);
	$('#contractarea_id').val(id);
	$('.label-floating').addClass('is-focused');
	$('#lightbox').modal({
       backdrop: 'static',
       keyboard: false
    });
}