$(function() { 

	if (document.getElementsByName('gen-ajax-upload')) {
	
		gen_ajax_upload_count = 0;
		$('.gen-ajax-upload').each(function() {
		
			var _this = $(this);
			
			var exts = [];
			if (document.getElementById($(this).attr('id')+'_ext')) {
			
				exts = $('#'+$(this).attr('id')+'_ext').val().split('-');
			
			}
			
			var uploader = new qq.FileUploader({
				
				allowedExtensions: exts ,
				element : $(this)[0] ,
				action  : 'ajax/ajax_gen_upload/' ,
				debug   : false ,
				params  : { id: $(this).attr('id') } ,
				showMessage: function(message) { alert(message); } ,
				onComplete: function(id, fileName, responseJSON){ 
					switch(responseJSON['success']) {
						case true : alert(fileName+' uploaded successfully.'); break;
						case false : alert(fileName+' could not be uploaded. Please try again.'); break;
					};	
					gen_ajax_upload_count--;
				} ,
				onSubmit: function(id, fileName){					
					gen_ajax_upload_count++;		
				},
				onCancel: function(id, fileName){
					gen_ajax_upload_count--;
				} ,
				sizeLimit: _this.parents('form').find('#MAX_FILE_SIZE').val() // max size 
				
			});
		
		});
	
	}

	if (document.getElementsByName('hideme'))
		$('.hideme').hide();

	if (document.getElementById('custom_issue_date')) {
	
		$('#custom_issue_date').change(function() {
		
			$.post(
				'ajax/ajax_expire_date/' ,
				{ issue_date: $(this).val() } ,
				function(data) {
					
					$('#custom_expire_date').val(data);
					
				} ,
				'html'
			);
		
		});
	
	}
	
	if (document.getElementById('client_certificate_datetime_uploaded')) {
	
		$('#client_certificate_datetime_uploaded').change(function() {
		
			$.post(
				'ajax/ajax_expire_date/' ,
				{ issue_date: $(this).val() } ,
				function(data) {
					
					$('#client_certificate_datetime_expires').val(data);
					
				} ,
				'html'
			);
		
		});
	
	}
	
	if (document.getElementsByName('terms-file-uploader')) {
	
		terms_upload_count = 0;
		$('.terms-file-uploader').each(function() {
					
			var c_id = $(this).attr('id').split('-')[1];
			
			var uploader = new qq.FileUploader({
			
				element : $(this)[0] ,
				action  : 'ajax/terms/' ,
				debug   : false ,
				params  : { c_id: c_id } ,
				showMessage: function(message) { alert(message); } ,
				onComplete: function(id, fileName, responseJSON){ 
					switch(responseJSON['success']) {
						case true : alert(fileName+' uploaded successfully.'); break;
						case false : alert(fileName+' could not be uploaded. Please try again.'); break;
					};	
					var filename = responseJSON['filename'];
					$('#filename').val(filename);
					
					terms_upload_count--;
				} ,
				onSubmit: function(id, fileName){					
					terms_upload_count++;		
				},
				onCancel: function(id, fileName){
					terms_upload_count--;
				} ,
				sizeLimit: 10485760*50// max size 
			});
		
		});
		
		$('#form_submit').click(function() {
		
			if (terms_upload_count > 0) {
			
				alert('Files are still being uploaded. Please wait for the upload to complete and then click on '+$(this).val()+' again');
				return false;
				
			}
			
			return true;
		
		});
	
	}

	if (document.getElementsByName('listbox')) {
	
		$('.rules-field-ajax').change(function() {
		
			var field = $(this).val();			
			var id = $(this).attr('id');
			var table = $(this).parent().children('div.hidden').find('input').val();
			
			if (typeof table === 'undefined') {
				
				table = $(this).parent().prev('div.hidden').find('input').val();
			
			}
			
			var _this = $(this);
						
			$.post(
				'rules/ajax_field/' , 
				{ table: table , field: field } ,
				function(data) {		
					
					_this.parent().children('.rules-field-value').html(data);
					
				} ,
				'html'
			);			
		
		});

		$('.listbox').find('.add').each(function() { 

			$(this).click(function() {  
			
				$(this).attr('selected','selected');
				return !$(this).parents('.listbox').find('.select1 option:selected').remove().appendTo($(this).parents('.listbox').find('.select2')); 
			
			}); 
			
			$(this).show();
			
		});
		$('.listbox').find('.remove').each(function() { 

			$(this).click(function() {  
			
				$(this).attr('selected','');
				return !$(this).parents('.listbox').find('.select2 option:selected').remove().appendTo($(this).parents('.listbox').find('.select1')); 
			
			}); 
			
			$(this).show();
			
		});
		
		if (document.getElementById('user_groups_in')) {
		
			$('.add, .remove').click(function() {
			
				var vm = false;
				var om = false;
				var admin_details = false;
				var eme_client = false;
				var project_partner = false;
			
				$('.select2 option').each(function() {
				
					if ($(this).html() == 'Verification Manager') {
					
						vm = true;
					
					}
					
					if ($(this).html() == 'Operations Manager') {
					
						om = true;
					
					}
					
					if ($(this).html() != 'EME Client' && $(this).html() != 'EME Project Partner') {
					
						admin_details = true;
					
					}
					
					if ($(this).html() == 'EME Client') {
					
						eme_client = true;
					
					}
					
					if ($(this).html() == 'EME Project Partner') {
					
						project_partner = true;
					
					}
				
				});
				
				if (vm) {
					$('.vm-sig-upload-fs').show();
				}
				else {					
					$('.vm-sig-upload-fs').hide();
				}
				if (om) {
					$('.om-emails-fs').show();
				}
				else {
					$('.om-emails-fs').hide();
				}
				if (admin_details) {
					$('.admin-details').show();
				}
				else {
					$('.admin-details').hide();
				}
				if (eme_client) {
					$('.eme-details').show();
				}
				else {
					$('.eme-details').hide();
				}
				if (project_partner) {
					$('.partner-details').show();
				}
				else {
					$('.partner-details').hide();
				}
								
			});
		
		}
		
		$('.listbox').parents('form').submit(function() {
			$('.select2 *').attr('selected','');

			$('.listbox').each(function() {
			
				var newval = '';
				
				$(this).find('.select2 option').each(function() {
				
					newval += newval.length == 0 ? '' : '-' ;
				
					newval += $(this).attr('value');
				
				});
				
				$(this).find('#'+$(this).find('.select2').attr('id')+'_values').val(newval);
				
				//$('<input type="hidden" id="'+$(this).find('.select2').attr('id')+'_values" name="'+$(this).find('.select2').attr('id')+'_values" value="'+newval+'" />').appendTo($(this));
			
			});		
			
		}); 
		
	}

	if (document.getElementsByName('toggle-next')) {
		$('.toggle-next').each(function() {
			$(this).next().slideToggle(0);			
		});
		$('.toggle-next').click(function() {
			$(this).next().slideToggle(100);
			return false;
		});
	}
	if (document.getElementById('client')) {
		if (document.getElementById('fieldset_client_client_employees_id')) {
			$('#fieldset_client_client_employees_id').hide();
			
		}		
	}
	if (document.getElementsByName('datetimepicker')) {
		$('.datetimepicker').datetimepicker({ dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm:ss' });
	}
	if (document.getElementsByName('datepicker')) {
		$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
	}
	if (document.getElementById('client_client_sector_id')) {		
		ajax_sub_sector();
		$('#client_client_sector_id').change(ajax_sub_sector);
	}	
	if (document.getElementById('client_history_client_sector_id')) {
		client_history_ajax_sub_sector();
		$('#client_history_client_sector_id').change(client_history_ajax_sub_sector);
	}
	
	if (document.getElementsByName('toggle-next')) {		
		$('.toggle-next').attr('title','Click to show more details');
	}
	if (document.getElementsByName('banner-wrapper')) {
		$('.banner-wrapper').image_cycler({timeout : 5000, fadetime : 2000});
	}
	
	if (document.getElementById('cal-day-start')) {
	
		var new_position = $('#cal-day-start').offset();
		window.scrollTo(new_position.left,new_position.top);
	
	}

	if (document.getElementsByName('certscor-file-uploader')) {
		certscor_upload_count = 0;
		$('.certscor-file-uploader').each(function() {
		
			var file = $(this).attr('id').split('-')[0];
			var c_id = $(this).attr('id').split('-')[1];	

			var uploader = new qq.FileUploader({
			
				element : $(this)[0] ,
				action  : 'ajax/certscor/' ,
				debug   : false ,
				params  : { file: file, c_id: c_id } ,
				showMessage: function(message) { alert(message); } ,
				onComplete: function(id, fileName, responseJSON){ 
					switch(responseJSON['success']) {
						case true : alert(fileName+' uploaded successfully.'); break;
						case false : alert(fileName+' could not be uploaded. Please try again.'); break;
					};	
					
					var model_id = responseJSON['written_id'];
					$('#'+file+'-id').val(model_id);
					
					certscor_upload_count--;
				} ,
				onSubmit: function(id, fileName){					
					certscor_upload_count++;		
				},
				onCancel: function(id, fileName){
					certscor_upload_count--;
				} ,
				sizeLimit: 10485760*50// max size 
			});
		
		});
		
		$('#form_submit').click(function() {
		
			if (certscor_upload_count > 0) {
			
				alert('Files are still being uploaded. Please wait for the upload to complete and then click on '+$(this).val()+' again');
				return false;
				
			}
			
			return true;
		
		});
		
	}
	
	ajax_upload_count = 0;
	ajax_complete_jump = false;
	if (document.getElementsByName('file-uploader')) {		
		$('.file-uploader').each(function() {
			var code = $(this).attr('id');
			code = code.split('-');			
			var uploader = new qq.FileUploader({
				// pass the dom node (ex. $(selector)[0] for jQuery users)
				element: $(this)[0],
				// path to server-side upload script
				action: 'ajax/upload/' ,
				debug: true ,
				params: { code: code[2], folder: code[1], cid: code[0] } ,
				showMessage: function(message){ alert(message); } ,
				onComplete: function(id, fileName, responseJSON){ 
					switch(responseJSON['success']) {
						case true : alert(fileName+' uploaded successfully.'); break;
						case false : alert(fileName+' could not be uploaded. Please try again.'); break;
					};					
					ajax_upload_count--;					
					if ((ajax_upload_count == 0) && (ajax_complete_jump)) {
						var vars = false;
						if ((document.getElementById('value_adding_turnover')) && (document.getElementById('value_adding_netprof'))) {
							vars['turnover'] = $('#value_adding_turnover').val();
							vars['netprof'] = $('#value_adding_netprof').val();
							var wages = $('#value_adding_wages').val();
							vars['netprof'] = parseFloat(vars['netprof']) + parseFloat(wages);
						}
						ajax_save(vars);
					}
				} ,
				onSubmit: function(id, fileName){					
					ajax_upload_count++;		
				},
				onCancel: function(id, fileName){
					ajax_upload_count--;
				} ,
				sizeLimit: 10485760*50// max size   				
			});
		});
	}
	
	if (document.getElementsByName('correspondence-upload')) {
	
		correspondence_upload = 0;
		$('.correspondence-upload').each(function() {
		
			var folder = $(this).attr('id');

			var uploader = new qq.FileUploader({				
				element: $(this)[0],				
				action: 'ajax/correspondence_attachment/' ,
				debug: true ,
				params: { folder: folder } ,
				showMessage: function(message){ alert(message); } ,
				onComplete: function(id, fileName, responseJSON){ 					
					correspondence_upload--;
					switch(responseJSON['success']) {
						case true : alert(fileName+' uploaded successfully.'); break;
						case false : alert(fileName+' could not be uploaded. Please try again.'); break;
					};					
				} ,
				onSubmit: function(id, fileName){					
					correspondence_upload++;		
				},
				onCancel: function(id, fileName){
					correspondence_upload--;
				} ,
				sizeLimit: 10485760*50// max size   				
			});
		
		});
		
		$('#form_submit').click(function() {
		
			if (correspondence_upload > 0) {
			
				alert('Files are still being uploaded. Please wait for the upload to complete and then click on '+$(this).val()+' again');
				return false;
				
			}
			
			return true;
		
		});
	
	}
	
	if (document.getElementsByName('quick-upload')) {	
		$('.quick-upload').each(function() { 
			var folder = $(this).attr('id');
	
			var uploader = new qq.FileUploader({
				// pass the dom node (ex. $(selector)[0] for jQuery users)
				element: $(this)[0],
				// path to server-side upload script
				action: 'ajax/file_upload/' ,
				debug: true ,
				params: { folder: folder } ,
				showMessage: function(message){ alert(message); } ,
				onComplete: function(id, fileName, responseJSON){ 					
					switch(responseJSON['success']) {
						case true : alert(fileName+' uploaded successfully.'); break;
						case false : alert(fileName+' could not be uploaded. Please try again.'); break;
					};					
				} ,
				onSubmit: function(id, fileName){					
					ajax_upload_count++;		
				},
				onCancel: function(id, fileName){
					ajax_upload_count--;
				} ,
				sizeLimit: 10485760*50// max size   				
			});
		});
	}
	
	if (document.getElementById('ajax-submit-button')) {
		$('#ajax-submit-button').show();
		$('#ajax-submit-button').click(function() {
			if (0 < ajax_upload_count) {
				ajax_complete_jump = true;
				$(this).after('<div><div style="text-align:center; padding:0.5em; margin:2em 0 0 1em; width:93%;" class="error fl">There are currently files uploading. Once they are complete your page will refresh.</div><div style="text-align:center; " ><img style="margin-top:1em;" src="images/loading.gif" alt="loading" /></div></div>');
				return false;
			}
			else {				
				var vs = new Array();
				var turnover = $('#value_adding_turnover').val();
				var netprofit = $('#value_adding_netprof').val();
				var wages = $('#value_adding_wages').val();
				//netprofit = parseFloat(netprofit) + parseFloat(wages);
				
				if ((turnover != '') && (netprofit != '') && (wages != '')) {
					vs['turnover'] = turnover;
					vs['netprof'] = netprofit;
					vs['salaries'] = wages;
					vs['cid'] = $('#cid').val();
					ajax_save(vs);
				}				
				window.location.reload();
			}
		});
	}
	
	if(getElementsByClassName('newtab')){
		$('.newtab').click(function(){
			window.open($(this).attr('href'));
			return false;
		});
	}
	
	if (document.getElementById('add_for')) {
		$('#add_for').click(function(){
			var for_email = $('#correspondence_email_to_email').val(); 
			if(for_email.length>5){ 
				for_email = for_email+';'+$('#client_email_select option:selected').val();
			}
			else{
				for_email = for_email+$('#client_email_select option:selected').val();
			}
			$('#correspondence_email_to_email').val(for_email);
		});
		
		$('#add_cc').click(function(){
			var for_email = $('#correspondence_email_to_cc').val(); 
			if(for_email.length>5){ 
				for_email = for_email+';'+$('#client_email_select option:selected').val();
			}
			else{
				for_email = for_email+$('#client_email_select option:selected').val();
			}
			$('#correspondence_email_to_cc').val(for_email);
		});		
		
		$('#add_bcc').click(function(){
			var for_email = $('#correspondence_email_to_bcc').val(); 
			if(for_email.length>5){ 
				for_email = for_email+';'+$('#client_email_select option:selected').val();
			}
			else{
				for_email = for_email+$('#client_email_select option:selected').val();
			}
			$('#correspondence_email_to_bcc').val(for_email);
		});			
	}
	
});

function ajax_save(vs) {		
	$.post(
		'ajax/value_adding_supplier/' , 
		{ turnover: vs['turnover'], netprof: vs['netprof'], salaries: vs['salaries'], cid: vs['cid'] } ,
		function(data) {		
			if (data['error'])
				alert(data['error']);				
			//window.location.reload();						
		} ,
		'json'
	);	
}

function ajax_sub_sector() {
	var sector = $("#client_client_sector_id option:selected").val();
	var sub_sector = $("#client_client_sub_sector_id option:selected").val();   /* , sub_sector_id: sub_sector*/
	$.post(
		'ajax/client_sector/', 
		{sector_id: sector, sub_sector_id: sub_sector}, 
		function(data) {			
			$('#client_client_sub_sector_id').html(data);
			if (sector != 1)
				$('#fieldset_client_client_sub_sector_id').hide();
			else
				$('#fieldset_client_client_sub_sector_id').show();
		},
		'html'
	);
}

function client_history_ajax_sub_sector() {
	var sector = $("#client_history_client_sector_id option:selected").val();
	var sub_sector = $("#client_history_client_sub_sector_id option:selected").val();   /* , sub_sector_id: sub_sector*/
	$.post(
		'ajax/client_sector_from_history/', 
		{sector_id: sector, sub_sector_id: sub_sector}, 
		function(data) {			
			$('#client_history_client_sub_sector_id').html(data);
			if (sector != 1)
				$('#fieldset_client_history_client_sub_sector_id').hide();
			else
				$('#fieldset_client_history_client_sub_sector_id').show();
		},
		'html'
	);
}

function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function popUseragent(_this) {
	
	var useragent = _this.html();		
	
	$.post(
		'ajax/useragent/' ,
		{ useragent: useragent } ,
		function(data) {
			_this.html(data);
		} ,
		'html'
	);
		
}
