var view_width = 547 //the width of each form view
var view_spacing = 20 //the space between views - helps FF2
var view_count = 20; //total number of steps in the process
var progress_button_width = 34;
var progress_button_padding_right = 4;
var progress_bar_move = 8;
var progress_bar_current_pos = 0;
var image_path = '/sites/all/themes/cap/images/membership_application/';
var ajax_path = '/sites/all/themes/cap/membership_application/';
var uid = queryString('uid');
var applicant_id = uid.substring(0, 36);
var	isAdminMode = uid.substring(36, 37) === "0" ? true : false;
var current_index = 0; 
var completed_steps = 0;
var files_object = null;
var application_is_editable = true;
var tabindex = 0;
var upload_file_path = "/sites/all/themes/cap/membership_application/doajaxfileupload.php"; 
var date_pattern = /^\d{4}-\d{2}-\d{2}$/;
$('document').ready(function(){	
	
	init_progress_meter(completed_steps);
	
	init_form();
	
	set_view(completed_steps);

	set_state(completed_steps);
	
	setInputMasks();
	
	setDatePicker();
	
	setUploadNotifications();
	
	//files_object is writen at the server and declared on form_view.php
	if(applicant_id){//user has logged in (not a new application)
		MA.populate_file_status(files_object);	
		setPrintButton();
	}
	
	setFileDeleteEvent();	
});

function init_progress_meter(step_completed){	
	for(var i = 1; i < (view_count + 1); i++){
		var img = new Image();
		img.rel =  i;
		img.style.paddingRight = progress_button_padding_right + 'px';
		img.title = MA.viewOptions[i-1].title;
		img.alt = 'Navigate to ' + MA.viewOptions[(i - 1)].title;
		str_image_num = ('' + i).length == 1 ? '0' + i : '' + i;		
		if(i <= step_completed){			
			img.src = image_path + str_image_num + '_complete.jpg';
			$(img).attr('completed', 'true');
			img.style.cursor = 'pointer';
			embed_progress_meter(img);
		}
		else{;
			img.src = image_path + str_image_num + '_incomplete.jpg';
			embed_progress_meter(img);
		}
	}
	
	$('#ma_move_left').css('cursor', 'pointer').click(function(){
		move_progress_bar(false);			
	});
	
	$('#ma_move_right').css('cursor', 'pointer').click(function(){
		move_progress_bar(true);			
	});
}

function init_form(){
	var left = 0;
	//preload buttons
	var imgSaving = new Image();
	imgSaving.src = image_path + 'btn_saving.gif';
	var imgDone = new Image();
	imgDone.src = image_path + 'btn_complete.gif';
	
	//set help button and message
	if(location.pathname.indexOf('quick_links/online_membership_application') != -1){
		$('div.heading h1')
		.css('position', 'relative')
		.append('<span id="btnHelp" style="position:absolute; right:0; cursor:pointer; text-decoration:underline;">Help</span>')
		.append('<div id="help" style="width:180px; height:100px; padding:0 20px; position:absolute; right:0; top:22px; z-index:2; display:none; background-color:white; border:solid 1px #DFD9BD; font-family:Arial, Sans-Serif;"><p>For assistance, please call 800-356-5672 and ask for Membership Development Online Application Help.</p></div>')
		.find('#btnHelp')
		.hover(function(evt){
			evt.stopPropagation();
			$(this).next().fadeIn();	
		}, function(){
			$(this).next().fadeOut();
		});
	}
	
	$('#ma_container > div').each(function(i){ 
	    var $this = $(this);
	    $this.css({'left': left, 'position': 'absolute', 'width':view_width, display:'block'});//set the position of form views
	    //handle key press events
	    $(':input', $this).keydown(function(event){
			if(event.keyCode == 13){
            	event.preventDefault();
            	$('.ma_save img', $this).trigger('click');
        	}
			if($(this).hasClass('last_index')){
				if(event.keyCode == 9){
					event.preventDefault();
				}
			}	
		}).attr('tabindex', '0');
		
	    //add back/save navigation bar to each view and setup save event if the form is editable
	    if(application_is_editable){
		    if(i < (view_count - 1)){//don't show the save button on the last page
			    $('#ma_bottom_nav_clone_source .bottom_navigation_bar').clone(true).appendTo($this).find('.ma_save img').click(function(){
			        var $form = $('form', $this);
			        if($form.length > 0){
						if(MA.viewOptions[i].validation($form)){
				            var $btn = $(this);
							$btn.attr('src', image_path + 'btn_saving.gif').css('cursor', 'inherit');
							$.ajax(
								{
									type: 'POST'
									,url: ajax_path + 'handle_view.php'
									,dataType: 'text'
									,timeout: 30000
									,data: $form.serialize()
									,error: function(xhr, textStatus, exceptionObj){
										//server may be unavailable or no connection
										if(xhr.readyState == 4 && textStatus === 'error'){
											var conn = false;
											testConnection(function(){
												conn = true;	
											});
											
											//if our test fails after 2 seconds the
											//problem may be the user's Internet connection
											var timer = setTimeout(function(){
												if( ! conn){//no Internet connection?
													logXHR('status:Internet connection down');
													alert(
														'An error occured!\r\n'
														+ 'Your Internet connection may be down.\r\n'
														+ 'Please try agin or come back later to complete your application');
														resetSaveButton($btn);	
												}
												else{//server may not be responding 
													logXHR('status:server not responding');
													alert(
														'An error occured!\r\n'
														+ 'Our server is temporarily unavailable.\r\n'
														+ 'Please try agin or come back later to complete your application');
														resetSaveButton($btn);		
												}	
											}, 2000);
										}
										else if(textStatus === 'error' || exceptionObj){
											logXHR('status:error');
											alert(
											'An error occured!\r\n'
												+ 'Please try agin or come back later to complete your application');
												resetSaveButton($btn);
										}
										else if(textStatus === 'timeout'){
											logXHR('status:timeout');
											alert(
											'An error occured!\r\n'
												+ 'The server has timed out.\r\n'
												+ 'Please try agin or come back later to complete your application');
												resetSaveButton($btn);
										}
										
										/*debug*/
										//var xhrStatus = xhr.readyState == 4 ? xhr.status : xhr.readyState;
										//console.log('response status: ' + xhrStatus + ' | status: ' + textStatus + ' | error thrown: ' + exceptionObj);
									}
									,success: function(data, textStatus){
										completed_steps += 1;
										//only run this if we are on the ID creation view (step one) and this is a new application
						                if(i == 0 && ! applicant_id){
						                	//if the user already exists in the system then show them an appropriate message and end the routine
											if(data.toLowerCase() === 'exists'){
												$('#duplicateUserError', $form).removeClass('hide');
												$btn.attr('src', image_path + 'btn_complete.gif').fadeIn('normal');
												return;
											}
											applicant_id = data;
											set_applicant_id();	
											setPrintButton();
											/*debug*/
											//if(console){
											//	console.log(data);
											//}	
										}
										
										if(i === 18){
											pageTracker._trackPageview('/membership_applicaiton/finish');
										}

						                $btn.fadeOut('normal', function(){
											$btn.attr('src', image_path + 'btn_complete.gif').fadeIn('normal', function(){
												setTimeout(function(){
													set_view(i + 1);
													set_state(i +1);
												}, 1000);
												setTimeout(function(){//reset the save button for update requirement
													$btn.attr('src', image_path + 'btn_save_move_next.jpg').css('cursor', 'pointer');	
												}, 3000);
											});
										});	
									}
								}
							);
			            }
			        } 
			        else{ //view does not have any form fields so just go to next
			            set_view(i + 1);
			            set_state(i + 1);
			        }
				}).css('cursor', 'pointer')//end click event handler
				.end()
				.find('.ma_back img').css({cursor:'pointer'}).click(function(){ //back button click event
					set_view(i - 1);
					set_state(i - 1);
				});
			}
			if(i == 0){
				if(isAdminMode){
					$('.bottom_navigation_bar', $this).hide();	
				}
				else{
					$($this).find('.ma_back img').css('display', 'none');
				}
			}
			else if(i == 18){
				if(isAdminMode){
					$('.bottom_navigation_bar', $this).hide();
				}
				else{
					$($this).find('.ma_save img').attr('src', image_path + 'btn_approval.png').click(function(){//switch to the "I Approve" button
						setTimeout(function(){
							$('.bottom_navigation_bar').hide(); //hide save and back buttons upon applicant approval - application is now not editable
						},1500);
					});
				}
			}
		}//end save event handling
	    
		left += (view_width + view_spacing);		   
	}); //end .each
	
	
	if(applicant_id){
		//required for applicant login
		set_applicant_id();	
	}
	else{
		//populate specialty lists - this is handled on form_view.php for edit mode
		MA.setSpecialtySelectList('SPECIALTYINFORMATION_Specialty', '', false);
		MA.setSpecialtySelectList('SPECIALTYINFORMATION_SubSpecialty', '', true);
	}
	
	$('#SPECIALTYINFORMATION_Specialty').change(function(){
		MA.setAddendum($(this).val(), '#specialty_addendum');	
	});
	
	$('#SPECIALTYINFORMATION_SubSpecialty').change(function(){
		MA.setAddendum($(this).val(), '#subspecialty_addendum');	
	});
}

function setPrintButton(){
	$('a.bttnPrintView').click(function(evt){
		evt.preventDefault();
		var win = window.open(ajax_path + 'print_view.php?uid=' + applicant_id, 'win', 'width=680, scrollbars, menubar, resizable'); win.focus();
	});	
}

function resetSaveButton($btn){
	$btn.attr('src', image_path + 'btn_save_move_next.jpg').css('cursor', 'pointer');		
}

function logXHR(error){
	var req = 'http://sensisagency.com/CAP_XHR_Log/Default.aspx?applicantID=' + applicant_id + '&error=' + error + '&jasoncallback=?';
	$.getJSON(req);	
}

function embed_progress_meter(img){
	$('#ma_progress_bar').append(img);
}

function set_applicant_id(){
	$(':input[name=Applicant_ID]').val(applicant_id);
}

function move_progress_bar(move_left){
	var full_button_width = (progress_button_width + progress_button_padding_right);
	if(move_left && progress_bar_current_pos > -(full_button_width  * 6)){
		progress_bar_current_pos = progress_bar_current_pos - (progress_bar_move * full_button_width);		
	}
	else if( ! move_left && progress_bar_current_pos < 0){
		progress_bar_current_pos = progress_bar_current_pos + (progress_bar_move * full_button_width);
	}
	$('#ma_progress_bar').animate({left:progress_bar_current_pos + 'px'}, 1000);
}

//does this belong in set_state()?
function set_view(index, func){
    $('#ma_container').animate({left: ((index * -view_width) - (index * view_spacing))}, 'slow', function(){
		if(arguments.length > 1){func();}
		$('html, body').animate({scrollTop:0}, 'slow');
		//set focus to first input field
		
		$(this).children('div').eq(index).find(':input.first_index').each(function(){
			//console.log($(this).attr("name"))
			this.focus();
		})
	/*	
		var $view_element = $(this).children('div').eq(index);
		var view_height = $view_element.height();
		view_height += 200;
		var mask_height = view_height > 500? view_height : 500;
		$('#ma_mask').height(mask_height);
		$('#principal_inner').animate({height: (mask_height + 200) + 'px'});
	*/
	})
}

function set_state(index){
	current_index = index;
	
	set_title_bar(index);
	
	set_progress_bar(index);
	
	bind_progress_bar();
}

function set_title_bar(index){
	$('#ma_view_title h3').empty().append(MA.viewOptions[index].title);
	$('#ma_view_pager').empty().append('Step ' + (index + 1) + ' of ' + view_count);
}

function bind_progress_bar(){
	$('#ma_progress_bar img[completed]').each(function( i ){
			$(this).unbind().bind('click', function(){
			current_index = i;
			set_title_bar( i );
			set_progress_bar( i );
			set_view( i );
			return false;
		});
	});
}

function set_progress_bar(index){
	$('#ma_progress_bar img[completed]').each(function( i ){
		var src = $(this).attr('src');
		src = src.replace('_active.jpg', '_complete.jpg');
		$(this).attr('src', src).css('cursor', 'pointer');
	})
	
	//index is 0-based but our images are 1-based
	var active_img_path = image_path + prepend_single_digit('' + (index + 1)) + '_active.jpg';
	$('#ma_progress_bar img').eq(index).attr('src', active_img_path).attr('completed', 'true').css('cursor', 'inherit');

	//don't move on 13
	if((index + 1) > 13){
		move_progress_bar(true);
	} 
	else if((index +1) < 13){
		move_progress_bar(false);
	}
}

function testConnection(callback){
	var rand = Math.floor(Math.random()*1000);
	var img = new Image();
	img.src = 'http://sensisagency.com/CAP_XHR_Log/1x1.gif?rand=' + rand;
	img.onload = function(){
		callback();
	}
}


function prepend_single_digit(digit){
	return digit.length == 1 ? '0' + digit : digit;
}

function queryString(param, url){
    if(arguments.length == 1){
        url = window.location.href;
    }
    var qs = url.substr((url.indexOf('?') + 1));
    qs = qs.split('#')[0];//account for named anchors
    var params = qs.split('&');
    for(var i = 0; i < params.length; i++){
        var pair = params[i].split('=');
        if(pair[0] == param){
            return pair[1];
        }
    }
    return '';
}

function setInputMasks(){
	$('.num').setMask(
		{
			mask:'9999',
			type:'reverse',
			onInvalid:function(){alert('Please enter numbers only!');}
		}
	);
}

function setDatePicker(){
	$.datepicker.setDefaults({dateFormat:'yy-mm-dd'});
	$(':input.date_picker').each(function(){
		var $this = $(this);
		var currentYear = new Date().getFullYear();
		var opts = eval("(" + $this.attr('yearRange') + ")");
		var strYearRange = "{ yearRange: '" + (currentYear - opts.past) + ":" + (currentYear + opts.future) + "' }";
		var yearRange = eval("(" + strYearRange + ")");
		$this.datepicker(yearRange);
		//$this.datepicker({ yearRange: '1933:2008' });
	});
}

function setUploadNotifications(){
	//Upload instructions cloning and display
	$('#ma_container a.uploadInstructions').each(function(index){
		var $this = $(this);
		var $instructions = $('ol#uploadInstructionsCloneSource').clone().attr('id', 'uploadInstructions_' + index).hide();
		$this.after($instructions);
		//$this.parent('label').prev('div').before($instructions);
		$this.toggle(function(){
			$instructions.fadeIn('normal');
			$this.text('hide instructions');
		}, function(){
			$instructions.fadeOut('normal');
			$this.text('show instructions');
		});				
	});
	
	//Upload notification source cloning
	var html = $('#uploadNotificationCloneSource').html();
	$('#ma_container div.uploadNotification').each(function(){
		$(this).html(html);
	})
}

function setFileDeleteEvent(){
	$('.file_status').click(function(e){
		var $target = $(e.target);
		var $this = $(this);
		var fileId = $target.attr('fileId');
		if(fileId){
			if(confirm('Are you sure?')){
				$.ajax({
					url:'/sites/all/themes/cap/membership_application/delete_file.php'
					, type: 'POST'
					, data: 'fileId=' + fileId
					, success: function(data, textStatus, xhr){
						//remove deleted file line-item and replace it with a default message if there are no other line-items present
						$target.parent('li').remove();
						if($('li', $this).length === 0){
							$this.append('<li class="file_absent">A file has not been uploaded!</li>');
						}
						$this.prev().prev().addClass('success').fadeIn().children().hide().end().find('h3.deleteConfirmation').show();
					}
				});
			}
		}
			
	});
}

function ajaxFileUpload(input_element_id, file_subject, uploadNoticeId){
	if( ! $('#' + input_element_id).val()){
		alert('Please select a file to upload');
		return false;
	}
	if(uploadNoticeId){
		var $notice = $('#' + uploadNoticeId);
		$('.progress', $notice).show();
		$('.confirmation', $notice).hide();
		$('.deleteConfirmation', $notice).hide();
		$notice.removeClass('success');
		$notice.fadeIn('fast');
	}
	$('#' + input_element_id + '+ button + img.loading')
	.show()
	.ajaxStart(function(){
		
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload(
		{
			url: upload_file_path,
			secureuri:false,
			fileElementId:input_element_id,
			applicant_id: applicant_id,
			file_subject: file_subject,
			dataType: 'json',
			success: function (data, status){
				if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						alert(data.error);
					}else
					{
						var file_object = new Object();
						file_object[file_subject] = [{"file_id": data.file_id, "file_name": data.file_name, "file_size": data.file_size}];
						MA.populate_file_status(file_object);
						
						if(uploadNoticeId){
							$('.progress', $notice).hide();
							$('.confirmation', $notice).show();
							$('.deleteConfirmation', $notice).hide();
							$notice.addClass('success');
						}
						else{
							alert(data.msg);
						}
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	);	
	return false;
}

