 var base = "";
 
 $(document).ready(function(){
 
   var api = $("div.scrollable").scrollable({
		 vertical: true,
		 speed: 1500,
		 clickable: false,
		 keyboard: false
	}).circular().autoscroll({
		 autoplay: true,
		 interval: 3000,
		 autopause: false
	});
    
    $("#airlineSearch").autocomplete(base+"/autocomplete/airline", {
		width: 200,
		max: 10,
		minChars: 2, 
		highlight: false,
		scroll: false,
		scrollHeight: 150,
		formatItem: function(data, i, n, value) {
			return value.split(",")[0];
		},
		formatResult: function(data, value) {
			return value.split(",")[0];
		}
	});
	
	$("#airportSearch").autocomplete(base+"/autocomplete/airport", {
		width: 200,
		max: 10,
		minChars: 3, 
		highlight: false,
		scroll: false,
		scrollHeight: 150,
		formatItem: function(data, i, n, value) {
			return value.split(",")[0];
		},
		formatResult: function(data, value) {
			return value.split(",")[0];
		}
	});
	
    
    attachReadingEvents();
    attachAirportEvents();
    attachAirportBizEvents();
    attachBookmarkEvents();
    attachFollowEvents();
    attachSubscribeEvents();
    attachAddUserEvents();
    attachShoutEvents();
    attachAirportCheckinEvents();
    attachShareEvents();
    attachResendEmailEvents();
    attachHiEvents();
    attachFriendsConnect();
    attachFlightSearchEvents();
    attachMsgReplyEvents();
    attachMsgDeleteEvents();
    attachMsgConnectAcceptEvents();
    attachUpdateEmailEvents();
    attachFbShareEvents();
    attachInlineEmailUpdate();
    attachFlightPrivacyEvents();
    attachCreateMCMessageValidation();
    attachMCReplyEvents();
    attachMCVoteEvents();
    attachFlagEvents();
    
  });
  
  function attachFlagEvents() {
  	$(".report-abuse").click(function() {
  		 var URL = $(this).attr('url');
  		 if (URL) {
  		 	$.get(URL, function(response) {
	        	var $dialog = $(response).dialog(setUpDialogOptions(500, 205));
	  	 		$('.popup-cancel').click(function() {
	 	 		    $dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$("#abuse-flagged").remove();
				});
				
				$('#reportAbuseForm').submit(function() {
					$(this).ajaxSubmit({success: getReportUpdate});
					return false;
				});
				
				function getReportUpdate(response) {
					if ($(response).attr('success') == 'true') {
						$('#msg-anchor-flag').after('<p id="msg-sent">Your message is sent.</p>');
						setTimeout(function() {
							$dialog.dialog("close");										   
							$dialog.dialog("destroy");
							$("#abuse-flagged").remove();
						}, 1500);
					} else if ($(response).attr('success') == 'false') {
						var error = $(response).attr('error');
						$('#msg-anchor-flag').after('<p class="text-red">'+error+'</p>');
					}
				}
				$dialog.dialog("open");
				
	    	});
  		 
  		 }
  	});
  }
  
  function attachMCReplyEvents() {
  	$("#replyMC").click(function() {
  		if (ensureLogin()) {
  		
	  		var replyForm = $('#reply-form').find('#reply-mc-form');
	  		var $dialog = $(replyForm).dialog(setUpDialogOptions(490, 325));
	       	$('.popup-cancel').click(function() {
		 		$dialog.dialog("close");										   
				$dialog.dialog("destroy");
				$('#reply-mc-form').remove();
				$('#reply-form').append(replyForm);
			});
			$('#reply-mc-form').bind('dialogclose', function(event, ui) {										   
				$dialog.dialog("destroy");
				$('#reply-mc-form').remove();
				$('#reply-form').append(replyForm);
			});
			
			$('#replyMCForm').submit(function() {
				$(this).ajaxSubmit({success: getReplyMCUpdate});
				return false;
			});
				
			function getReplyMCUpdate(response) {
				if ($(response).attr('success') == 'true') {
					$('#msg-anchor').after('<p id="msg-sent">Your message is sent.</p>');
					setTimeout(function() {
						$dialog.dialog("close");										   
						$dialog.dialog("destroy");
						$('#hi').remove();
						$(replyForm).find('#msg-sent').remove();
						$('#reply-form').append(replyForm);
					}, 1500);
				} else if ($(response).attr('success') == 'false') {
					var error = $(response).attr('error');
					$('#msg-anchor').after('<p class="text-red">'+error+'</p>');
				}
			}
			
	       	$dialog.dialog('open');
	    }
  		
  		
  	});
  }
  
  function attachMCVoteEvents() {
  	$('#voteMC').click(function() {
  		ensureLogin();
  	    var URL = $(this).attr('url');
  	    
  	    var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getMCVoteUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
    	
    	function getMCVoteUpdate(response) {
    		if ($(response).attr('success') == 'true') {
    		   var type = $(response).attr('type');
    		   
    		   var voteLink = $(response).find('#voteMC');
    		   if (voteLink) {
    		       $('#voteMC').replaceWith(voteLink);
    		       attachMCVoteEvents();
    		   }
    		   
    		   var totalVotes = $('#mc-like-total').attr('total');
    		   if (type == 'like') {
    		       totalVotes = (totalVotes * 1) + 1;
    		   } else if (type == 'unlike' && totalVotes > 0) {
    		   	   totalVotes = (totalVotes * 1) - 1;
    		   }
    		   $('#mc-like-total').attr('total', totalVotes);
    		   $('#mc-like-total').text(totalVotes);
    			
			} else if ($(response).attr('success') == 'false') {
				alert("Oops, something went wrong. Try again later.");
    		}
    	}
  	});
  
  }
  
  function attachCreateMCMessageValidation() {
    $('#createMCMsgForm').submit(function() {
    	if ($('[name=data[Message.title]]').val().length == 0) {
    		alert("Please provide title for your message.");
    		return false;
    	}
    	
    	if ($('[name=data[Message.airport]]').val().length == 0) {
    		alert("Please provide airport information.");
    		return false;
    	}
    	
    	if ($('[name=data[Message.desc]]').val().length == 0) {
    		alert("You need to provide message or description.");
    		return false;
    	}
    	
    	if ($('[name=data[Message.type]]').val() == 0) {
    		alert("Choose a type of message.");
    		return false;
    	}
    });
  
  }
  
  function showLoadingDisplay() {
  	$('#body').append('<div id="loading" class="ajax-big-loading"/>');
  }
  
  function hideLoadingDisplay() {
  	$('#loading').remove();
  }
  	
  function attachFlightPrivacyEvents() {
  	$('#fPrivate').click(function() {
  	    showLoadingDisplay();
  		var url = $(this).attr('url');
  		var fid = $(this).attr('fid');
  		if (url && fid) {
	  		if ($(this).attr('checked')) {
	  			url = url+"?fid="+fid+"&p=0";
	  		} else {
	  			url = url+"?fid="+fid+"&p=1";
	  		}
	  		$.get(url, function(response) {
	  		    hideLoadingDisplay();
	  			var $dialog = $(response).dialog(setUpDialogOptions(400, 180));
	  	 		$('.popup-cancel').click(function() {
	 	 		    $dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$("#fprivacy-msg").remove();
				});
				$dialog.dialog("open");
	  		});
	  	}
  	
  	});
  }
  
  function attachInlineEmailUpdate() {
  	$('#inlineUpdateEmailForm').submit(function() {
  	    showLoadingDisplay();
  		$(this).ajaxSubmit({beforeSubmit:ensureEmail, success: getUpdateInlineEmailUpdate});
		return false;
  	});
  	
  	function ensureEmail(formData, jqForm, options) {
  	  var email = formData[2].value;
      if (email.length == 0) {
      	return false;
      }
  	}
  	
  	function getUpdateInlineEmailUpdate(response) {
  	    hideLoadingDisplay();
		if ($(response).attr('success') == 'true') {
			$('#msg-anchor-ie').after('<p id="msg-sent" class="text-bold">Your profile is updated.</p>');
			setTimeout(function() {
				// remove update email info on side bar
				$("#update-email-msg").remove();
			}, 1500);
			
			// update subscribe info
			var subscribeInfo = $(response).find('#subscribe-status');
	  		if (subscribeInfo) {
	  			$('#subscribe-status').replaceWith(subscribeInfo);
	  			attachSubscribeEvents();
	  		}
		} else {
			$('#msg-anchor-ie').after('<p class="text-red">'+$(response).attr('error')+'</p>');
		}
	}
  }
  
  function attachFbShareEvents() {
  	$('#fb-share-api').click(function() {
  		var socialUser = $('#social-user');
	  	if (socialUser) {
	  	 	var type = socialUser.attr('type');
	  	 	if (type == 'facebook') {
	  	 		facebookPubishFlight(socialUser);
	  	 	} 
	  	}
  	});
  }
  
  function attachUpdateEmailEvents() {
    var askEmailUpdate = $('#ask-email-update');
    if (askEmailUpdate) {
    	var updateEmail = askEmailUpdate.find('#update-email-flight');
    	if (updateEmail) {
    		var $dialog = $(updateEmail).dialog(setUpDialogOptions(350, 235));
  	 		$('.popup-cancel').click(function() {
 	 		    $dialog.dialog("close");										   
				$dialog.dialog("destroy");
				$("#ask-email-update").remove();
			});
			
			$('#updateEmailForm').submit(function() {
				$(this).ajaxSubmit({success: getupdateEmailUpdate});
				return false;
			});
			
			function getupdateEmailUpdate(response) {
				if ($(response).attr('success') == 'true') {
					$('#msg-anchor').after('<p id="msg-sent">Your profile is updated.</p>');
					setTimeout(function() {
						$dialog.dialog("close");										   
						$dialog.dialog("destroy");
						$("#ask-email-update").remove();
					}, 1500);
					
					// remove update email info on side bar
					$("#update-email-msg").remove();
					
					// update subscribe info
					var subscribeInfo = $(response).find('#subscribe-status');
			  		if (subscribeInfo) {
			  			
			  			$dialog.dialog("close");										   
						$dialog.dialog("destroy");
						$("#subscribe-input").remove();
						
			  			$('#subscribe-status').replaceWith(subscribeInfo);
			  			attachSubscribeEvents();
			  			
			  		}
				} else {
					$('#msg-anchor').after('<p class="text-red">'+$(response).attr('error')+'</p>');
				}
			}
			$dialog.dialog("open");
    	
    	}
    }
  }
  
  function attachMsgConnectAcceptEvents() {
  	$('a.msg-accept').click(function() {
  		ensureLogin();
  	    var URL = $(this).attr('url');
  	    $.get(URL, function(response) {
        	//Todo: check session time out.
        	var addForm = response;
        	var $dialog = $(response).dialog(setUpDialogOptions(550, 215));
  	 		$('.popup-cancel').click(function() {
 	 		    $dialog.dialog("close");										   
				$dialog.dialog("destroy");
				$("#add-msg").remove();
			});
			
			$('#addUserMessageForm').submit(function() {
				$(this).ajaxSubmit({success: getConnectAcceptUpdate});
				return false;
			});
			
			function getConnectAcceptUpdate(response) {
				if ($(response).attr('success') == 'true') {
					$('#msg-anchor-add').after('<p id="msg-sent">Your message is sent.</p>');
					setTimeout(function() {
						$dialog.dialog("close");										   
						$dialog.dialog("destroy");
						$("#add-msg").remove();
					}, 1500);
				}
			}
			$dialog.dialog("open");
			
    	});
  	});
  }
  
  function attachMsgDeleteEvents() {
  	$('a.msg-delete').click(function() {
  		var URL = $(this).attr('url');
  		var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getMsgDeleteUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
    	
    	function getMsgDeleteUpdate(response) {
    		if ($(response).attr('success') == 'true') {
    			var msgId = $(response).attr('msgid');
    			if (msgId) {
    				$('#msg-'+msgId).remove();
    			}
			} else if ($(response).attr('success') == 'false') {
				alert("Oops, something went wrong. Try deleting later.");
    		}
    	}
  	});
  }
  
  function attachMsgReplyEvents() {
  	$("a.msg-reply").click(function() {
  		var mId = $(this).attr('msgid');
  		var fromPid = $(this).attr('fromPid');
  		var imgUrl = $('#msg-img-'+mId).attr('src');
  		var title = $('#msg-title-'+mId).text();
  		
  		var replyForm = $('#reply-form').find('#hi');
  		$(replyForm).find('#reply-to-img').attr('src', imgUrl);
  		$(replyForm).find('#reply-to-id').attr('value', fromPid);
  		$(replyForm).find('#reply-title-holder').text("Reply: "+title);
  		$(replyForm).find('#message').attr('value',"");
  		var $dialog = $(replyForm).dialog(setUpDialogOptions(580, 200));
       	$('.popup-cancel').click(function() {
	 		$dialog.dialog("close");										   
			$dialog.dialog("destroy");
			$('#hi').remove();
			$('#reply-form').append(replyForm);
		});
		$('#hi').bind('dialogclose', function(event, ui) {										   
			$dialog.dialog("destroy");
			$('#hi').remove();
			$('#reply-form').append(replyForm);
		});
		
		$('#replyToForm').submit(function() {
			$(this).ajaxSubmit({success: getReplyToUpdate});
			return false;
		});
			
		function getReplyToUpdate(response) {
			if ($(response).attr('success') == 'true') {
				$('#msg-anchor').after('<p id="msg-sent">Your message is sent.</p>');
				setTimeout(function() {
					$dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$('#hi').remove();
					$(replyForm).find('#msg-sent').remove();
					$('#reply-form').append(replyForm);
				}, 1500);
			} else if ($(response).attr('success') == 'false') {
				var error = $(response).attr('error');
				$('#msg-anchor').after('<p class="text-red">'+error+'</p>');
			}
		}
		
       	$dialog.dialog('open');
  		
  		
  	});
  }
  
  function attachFlightSearchEvents() {
  	$('#OnThisFlightForm').submit(function() {
  		var airline = $(this).find("#airlineSearch").attr('value');
  		var flightNumber = $(this).find("#flightNumber").attr('value');
  		var dep = $(this).find("#departureDate").attr('value');
  		if (airline.length == 0 || flightNumber.length == 0 || dep.length == 0) {
  			return false;
  		}
  	});
  }
  
  function attachFriendsConnect() {
  	$('a.add-friend').click(function() {
  	    showLoadingDisplay();
  		var URL = $(this).attr('url');
  		var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getFriendsConnectUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
    	
    	function getFriendsConnectUpdate(response) {
    	    hideLoadingDisplay();
    		if ($(response).attr('success') == 'true') {
    			var pid = $(response).attr('pid');
    			if (pid) {
    				$('#fconnect-'+pid).empty();
    				$('#fconnect-'+pid).append($(response).attr('message'));
    			}
			} else if ($(response).attr('success') == 'false') {
				alert($(response).attr('message'));
    		}
    	}
    	
  	});
  }
  
  function attachHiEvents() {
  	$('#say-hi').click(function() {
  		ensureLogin();
  		var hiForm = $('#hi-form').find('#hi');
  		var $dialog = $(hiForm).dialog(setUpDialogOptions(580, 180));
       	$('.popup-cancel').click(function() {
	 		$dialog.dialog("close");										   
			$dialog.dialog("destroy");
			$('#hi').remove();
			$('#hi-form').append(hiForm);
		});
		
		$('#hi').bind('dialogclose', function(event, ui) {										   
			$dialog.dialog("destroy");
			$('#hi').remove();
			$('#hi-form').append(hiForm);
		});
		
		$('#sayHiForm').submit(function() {
			$(this).ajaxSubmit({success: getSayHiUpdate});
			return false;
		});
			
		function getSayHiUpdate(response) {
			if ($(response).attr('success') == 'true') {
				$('#msg-anchor').after('<p>Your message is sent.</p>');
				setTimeout(function() {
					$dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$('#hi').remove();
					$('#hi-form').append(hiForm);
				}, 1500);
			} else if ($(response).attr('success') == 'false') {
				var error = $(response).attr('error');
				$('#msg-anchor').after('<p class="text-red">'+error+'</p>');
			}
		}
		
       	$dialog.dialog('open');
  	
  	});
  
  }
 
  
  function attachResendEmailEvents() {
  	$('#resend-verify').click(function() {
  	    showLoadingDisplay();
  		var URL = $(this).attr('url');
  		$.get(URL, function(response) {	
  		        hideLoadingDisplay();
  				var $dialog = $(response).dialog(setUpDialogOptions(400, 180));
	        	$('.popup-cancel').click(function() {
			 		$dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$("#resend-msg").remove();
				});
	        	$dialog.dialog('open');
        });
  	});
  }
  
  function attachShareEvents() {
  
    $('#share-email').click(function() {
        showLoadingDisplay();
        ensureLogin();
		var URL = $(this).attr('url');
		
    	$.get(URL, getShareEmailUpdate);
    	function getShareEmailUpdate(response) {
    	    hideLoadingDisplay();
    		var shareForm = $(response).find('#share-by-email');
    		if (shareForm) {
	    		var $dialog = $(shareForm).dialog(setUpDialogOptions(560, 325));
	        	$('.popup-cancel').click(function() {
			 		$dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$("#share-by-email").remove();
				});
						
				$('#sendEmailForm').submit(function() {
					$(this).ajaxSubmit({success: getShareEmailUpdate});
					return false;
				});
						
				function getShareEmailUpdate(response) {
				    var rep = $(response).find('#send-status'); 
					if (rep.attr('success') == 'true') {
						var msg = rep.attr('message');
						$('#msg-anchor').after('<p>'+msg+'</p>');
						setTimeout(function() {
							$dialog.dialog("close");										   
							$dialog.dialog("destroy");
							$("#share-by-email").remove();
						}, 1500);
						
					} else if (rep.attr('success') == 'false') {
						var error = rep.attr('error');
						$('#msg-anchor').after('<p class="text-red">'+error+'</p>');
					}
				}
	        	$dialog.dialog('open');
	        }
    	
    	}
    	
        return false;
  		
  	});
 
  
  }
  
  function attachAirportCheckinEvents() {
  	if ($("#nearby-ap").attr('query')) {
		navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
	}
  }
  
  function foundLocation(position) {
  	var lat = position.coords.latitude;
  	var long = position.coords.longitude;
  	if (lat && long) {
  		var div =  '<div class="right-inner-frame inner-frame-formatting"><p><span class="title-style">Check-in @ nearby airports</span></p>';
  		div += '<p class="horizontal-line">&nbsp;</p><div class="spacer"> </div><div id="nb-ap-list" class="right-content">';
  		div += '<p>Loading nearby airport within 1 mile radius ...</p></div></div>';
  		if ($("#nearby-ap").children().length == 0) {
	  		$("#nearby-ap").append(div);
	  		$.get(base+"/profiles/nearestAirport/"+lat+"/"+long+"/2", function(response) {	
	  					$('#nb-ap-list').empty();
	    				$('#nb-ap-list').append(response);
	    				$("a.ap-checkin").click(function() {
	    					ensureLogin();
					  		var URL = $(this).attr('url');
					  		$.get(URL, popupCheckin);
	    				});
    		});
    	}
  	} else {
  	    $("#global").data("locationInfo", "no-location");
  		alert("Oops, can't get your location.");
  	}

  }
  
  function popupCheckin(response) {
  	//Todo: check session time out.
    var $dialog = $(response).dialog(setUpDialogOptions(550, 320));
    $('.popup-cancel').click(function() {
 		$dialog.dialog("close");										   
		$dialog.dialog("destroy");
		$("#checkin-msg").remove();
	});
			
	$('#checkinForm').submit(function() {
		$(this).ajaxSubmit({success: getCheckinUpdate});
		return false;
	});
			
	function getCheckinUpdate(response) {
		if ($(response).attr('success') == 'true') {
			var checkinInfoMsg = $(response).find('#checkin-info-msg');
			if (checkinInfoMsg) {
				$("#checkin-msg").remove();
				$('#checkin-info').empty();
				$('#checkin-info').append(checkinInfoMsg);
			}
			
			$dialog.dialog("close");										   
			$dialog.dialog("destroy");
			
			var socialUser = $(response).find('#social-user');
			if (socialUser) {
				var type = socialUser.attr('type');
		  	 	if (type == 'facebook') {
		  	 		facebookPubishFlight(socialUser);
		  	 	}
			}
		}
	}
    $dialog.dialog('open');
  }
  
  function noLocation() {
  	// do something if user don't share the location.
  }
  
  function attachShoutEvents() {
  	$('#shoutForm').submit(function() {
  		$(this).ajaxSubmit({resetForm:true, beforeSubmit: ensureShout, success: getShoutUpdate});
        return false;
  	});
  
  }
  
  function ensureShout(formData, jqForm, options) {
  	  var shout = formData[2].value;
      if (shout.length == 0) {
      	return false;
      }
      ensureLogin();
  }
  
  function getShoutUpdate(response) {
  	$('#lshout').replaceWith(response);
  }
  
  function attachAddUserEvents() {
  	$('#add-user').click(function() {
  	    ensureLogin();
  	    showLoadingDisplay();
  	    var URL = $(this).attr('url');
  	    $.get(URL, function(response) {
        	//Todo: check session time out.
        	hideLoadingDisplay();
        	var $dialog = $(response).dialog(setUpDialogOptions(550, 200));
  	 		$('.popup-cancel').click(function() {
 	 		    $dialog.dialog("close");										   
				$dialog.dialog("destroy");
				$("#add-msg").remove();
			});
			
			$('#addUserMessageForm').submit(function() {
				$(this).ajaxSubmit({success: getAddUserUpdate});
				return false;
			});
			
			function getAddUserUpdate(response) {
				if ($(response).attr('success') == 'true') {
				
					$('#msg-anchor-add').after('<p id="msg-sent">Your message is sent.</p>');
					setTimeout(function() {
						$dialog.dialog("close");										   
						$dialog.dialog("destroy");
						$("#add-msg").remove();
					}, 1500);
					
					$('#add-user-msg').text('Connect request pending.');
				}
			}
			$dialog.dialog("open");
			
    	});
  	});
  }
  
  function attachSubscribeEvents() {
    $('#edit-subscribe').click(function() {
    	showLoadingDisplay();
    	var URL = $(this).attr('url');
    	$.get(URL, function(response) {	
    			hideLoadingDisplay();
  				var $dialog = $(response).dialog(setUpDialogOptions(650, 430));
	        	$('.popup-cancel').click(function() {
			 		$dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$("#subscribe-input").remove();
				});
				
				
			  	$('#subscribeUpdatesForm').submit(function() {
			    	$(this).ajaxSubmit({beforeSubmit: validateInputForSubscribe, success: getSubscribeUpdate});
			        return false;
			    });
			    
			    function getSubscribeUpdate(response) {
				  	if ($(response).attr('success') == 'true') {
				  		
				  		var subscribeInfo = $(response).find('#subscribe-status');
				  		if (subscribeInfo) {
				  			
				  			$dialog.dialog("close");										   
							$dialog.dialog("destroy");
							$("#subscribe-input").remove();
							
				  			$('#subscribe-status').replaceWith(subscribeInfo);
				  			attachSubscribeEvents();
				  			
				  		}
				  	} else {
				  		$('#s-error').text('Oops, something went wrong. Try again later.');
				  	}
				}
			    
	        	$dialog.dialog('open');
        });
    });
  
  }
  
  function validateInputForSubscribe(formData, jqForm, options) {
    ensureLogin();
    
    
    var emailIntervalSusbscribed = false;
    var smsIntervalSubscribed = false;
    var email = "";
    var phone = "";
    var provider = "";
    for (var i = 0; i < formData.length; i++) {
    	var name = formData[i]['name'];
    	
    	if (name == "data[Flight.3hrsBefore-s]" || name == "data[Flight.2hrsBefore-s]" || name == "data[Flight.departed-s]"
    		|| name == "data[Flight.30minsBefore-s]"|| name == "data[Flight.landed-s]") {
    		if (formData[i]['value'] != 0) {
    			smsIntervalSubscribed = true;
    		}
    	}
    	
    	if (name == "data[Flight.3hrsBefore-e]" || name == "data[Flight.2hrsBefore-e]" || name == "data[Flight.departed-e]"
    		|| name == "data[Flight.30minsBefore-e]"|| name == "data[Flight.landed-e]") {
    		if (formData[i]['value'] != 0) {
    			emailIntervalSusbscribed = true;
    		}
    	}
    	
    	if (name == "data[Flight.email]") {
    		email = formData[i]['value'];
    	}
    	
    	if (name == "data[Flight.mobile]") {
    		phone = formData[i]['value'];
    	} 
    	
    	if (name == "data[Flight.mobileProvider]") {
    		provider = formData[i]['value'];
    	} 
    }
    
    if (emailIntervalSusbscribed || smsIntervalSubscribed) {
    	if (smsIntervalSubscribed) {
    		if (phone.length != 10) {
    			alert("Please provide valid 10 digits mobile phone number (6505558888).");
    			return false;
    		} else if (phone.length == 10 && (provider.length == 0 || provider == "1")) {
    			alert("Please select your mobile service provider.");
    			return false;
    		} 
    	}
    	
    	if (emailIntervalSusbscribed) {
    		if (!isValidEmailAddress(email)) {
		  		alert("Please provide valid email.");
		  		return false;
		  	}
   		}
   		
   		return true;
    } else {
    	return true;
    }
    
    
    return false;
  }
 
  function attachFollowEvents() {
    $('#flight-follow').click(function() {
       showLoadingDisplay()
  		var URL = $(this).attr('url');
    
    	ensureFollowEvents();
    	$.get(URL, getFollowUpdate);
        return false;
    });
  }
  
  function ensureFollowEvents() {
  	var status = getLoginStatus();
    if (status == 'false') {
     	window.location = base+'/account/login/?rf=true&act=follow';
    }
  }
  
  function getFollowUpdate(response) {
    hideLoadingDisplay()
    var followers = $(response).find('#followed');
   
    if (followers && followers.attr('type')) {
    	$('#followed').replaceWith(followers);
    	attachFollowEvents();
    	
    	var total = followers.attr('total');
    	var pid = followers.attr('pid');
    	if (followers.attr('type') == 'unfollow') {
    		$('#f-'+pid).remove();
    		$('#subscribe-status').remove();
    		$('#flight-privacy-setting').remove();
    		if (total == 0 || total.length == 0) {
    			$('#followers-title').after('<div id="follow-inst" class="follow-bg"></div>');
    		}
    	} else if (followers.attr('type') == 'follow') {
    		if (total == 1) {
    			$('#follow-inst').remove();
    		}
    		var profile = $(response).find('#f-'+pid);
    		if (profile) {
    			$('#followers-title').after(profile);
    		}
    		var sub = $(response).find('#subscribe-status'); 
		  	if (sub) {
		  	 	$('#share-flight').after(sub);
		  	 	attachSubscribeEvents();
		  	} 
		  	
		  	var privacy = $(response).find('#flight-privacy-setting'); 
		  	if (privacy) {
		  		if ($('#subscribe-status').attr('id')) {
		  	 		$('#subscribe-status').after(privacy);
		  	 	} else {
		  	 		$('#share-flight').after(privacy);
		  	 	}
		  	 	attachFlightPrivacyEvents();
		  	} 
    	
    	}
    }
      	 
  	
  	 
  	 
  	 var socialUser = $(response).find('#social-user');
  	 if (socialUser) {
  	 	var type = socialUser.attr('type');
  	 	if (type == 'facebook') {
  	 		facebookPubishFlight(socialUser);
  	 	} else if (type = 'twitter') {
  	 		twitterPublishFlight(socialUser);
  	 	}
  	 
  	 }
  	 
  	 /*
  	 var $dialog = $(response).dialog(setUpDialogOptions(600, 340));
  	 $dialog.dialog("open");	
  	 
  	 */
  	 return false;
  	 
  }
  
  function facebookPubishFlight(info) {
    if (info) {
    	var fb = info.find('#facebook');
    	var uid = fb.attr('uid'); 
	  	FB.ensureInit(function() {
			var attachment = {'name':fb.attr('name'),
			                  'href':fb.attr('url'),
			                  'description':fb.attr('description'),
			                  'media':[{'type':'image',
			                             'src': fb.attr('airlineLogo'),
			                             'href':fb.attr('url')}]
			                 };
			                
			var action_links = [{'text':fb.attr('actionName'),'href':fb.attr('actionUrl')}];
			
			  		
		    FB.Connect.streamPublish('', attachment, action_links, uid);
		});
	}
  
  }
  
  function twitterPublishFlight(info) {
  	var twitter = info.find('#twitter');
  	if (twitter) {
  		var uid = twitter.attr('uid');
  		var tform = twitter.find('#twitter-publish');
  		if (tform) {
  			var $dialog = $(tform).dialog(setUpDialogOptions(550, 250));
        	$('.popup-cancel').click(function() {
		 		$dialog.dialog("close");										   
				$dialog.dialog("destroy");
				$("#twitter-publish").remove();
			});
					
			$('#publishTwitterForm').submit(function() {
				$(this).ajaxSubmit({success: getPublishTwitterUpdate});
				return false;
			});
					
			function getPublishTwitterUpdate(response) { 
				if ($(response).attr('success') == 'true') {
					$dialog.dialog("close");										   
					$dialog.dialog("destroy");
					$("#twitter-publish").remove();
				} else if ($(response).attr('success') == 'false') {
					var error = $(response).attr('error');
					
					$('#msg-anchor').after('<p class="text-red">'+error+'</p>');
				}
			}
        	$dialog.dialog('open');
  		}
  	
  	}
  }
  
  function setUpDialogOptions(dialogWidth, dialogHeight){
		var dialogOpts = {
				modal: true,
               	overlay: {
                   opacity: 0.8,
                   background: "black"
               	},	
				autoOpen: false,
				width: dialogWidth,
				height: dialogHeight
		};
		
		return dialogOpts;
	}
  
  
  function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
  }
  
  function validateEmailInput(formData, jqForm, options) {
  	var email = formData[0]['value'];
  	if (isValidEmailAddress(email)) {
  		return true;
  	}
  	return false;
  }
  
  function attachBookmarkEvents() {
  	$('a.bookmark-it').click(function() {
  		var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getBookmarkItUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
    
    $('a.bookmark-remove').click(function() {
  		var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getBookmarkRemoveUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
  }
  
  function getBookmarkRemoveUpdate(response) {
  	if ($(response).attr('status') == 'success') {
  	    var id = $(response).attr('bid');
  		$('#b-'+id).remove();
  	}
  }
  
  function getBookmarkItUpdate(response) {
  	if ($(response).attr('status') == 'success') {
  		$('#bookmark-link').text('In Bookmarks');
  	}
  }
  
  function attachAirportBizEvents() {
  	$('a.vote-biz').click(function() {
        var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getVoteAirportBizUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
    
    $('#AirportBizReviewForm').submit(function() {
    	$(this).ajaxSubmit({resetForm:true, beforeSubmit: ensureReview, success: getWriteBizReviewUpdate});
        return false;
    });
  
    attachVoteBizReviewEvent();
  }
  
  function getVoteAirportBizUpdate(response) {
  	if ($(response).attr('voteid') > 0) {
  	 	var votes = $(response).attr('total');
  	 	var percent = $(response).attr('percent');
  	 	
  	 	if (votes == '1') {
  	 	  $("#first-to-vote").replaceWith("<p class=\"text-size15\">Congrats! you are the first to vote.</p>");
  	 	} else if (votes > 1) {
  	 		$("#vc").text(votes);
  	 		$("#percent-like").text(percent);
  	 	}
  	 	
  	 }
  }
  
  function getWriteBizReviewUpdate(response) {
  	$("#biz-review-title").after(response);
  	attachVoteBizReviewEvent();
  }
  
  function attachVoteBizReviewEvent() {
  	$('a.vote-biz-review').click(function() {
    	var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getVoteReviewUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
  }
  
  function attachAirportEvents() {
    $('a.vote-airport').click(function() {
        var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getVoteAirportUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
    
    $('#AirportReviewForm').submit(function() {
    	$(this).ajaxSubmit({resetForm:true, beforeSubmit: ensureReview, success: getWriteReviewUpdate});
        return false;
    });
  
    attachVoteReviewEvent();
  }
  
  function ensureReview(formData, jqForm, options) {
  	  var review = formData[0].value;
      if (review.length == 0) {
      	return false;
      }
      ensureLogin();
  }
  
  function getWriteReviewUpdate(response) {
  	$("#review-title").after(response);
  	attachVoteReviewEvent();
  }
  
  function attachVoteReviewEvent() {
    $('a.vote-review').click(function() {
    	var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getVoteReviewUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
  }
  
  function getVoteReviewUpdate(response) {
    if ($(response).attr('review') > 0) {
  	 	var id = $(response).attr('review');
  	 	var points = $(response).attr('points');
  	 	
  	 	var pointsLabel = "("+points+" points)";
  	 	if (points == 1) {
  	 		pointsLabel = "(1 point)";
  	 	}
  	 	$("#rp-"+id).text(pointsLabel);
  	 }
  }
  
  function getVoteAirportUpdate(response) {
    if ($(response).attr('voteid') > 0) {
        var code = $(response).attr('code');
  	 	var votes = $(response).attr('total');
  	 	var percent = $(response).attr('percent');
  	 	
  	 	$("#va-"+code).text(votes);
  	 	$("#percent-like").text(percent);
  	 }
  
  }
  
  
  function attachReadingEvents() {
    $('#ReadingGetPageInfo').submit(function() {
        $(this).ajaxSubmit({resetForm:true, beforeSubmit: getPageInfoBefore, success: getPageInfoUpdate});
        return false;
    });
    
    
    $('#ReadingAddCommentForm').submit(function() {
    	$(this).ajaxSubmit({resetForm:true, beforeSubmit: ensureAddComment, success: getAddCommentUpdate});
        return false;
    });
    
    attachVoteArticleEvent();
    attachVoteCommentEvent();
  }
  
  function attachVoteArticleEvent() {
  	$('a.vote-article').click(function() {

    	var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getVoteArticleUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
  }
  
  function attachVoteCommentEvent() {
  	$('a.vote-comment').click(function() {
    	var URL = $(this).attr('url');
    	var options = {
    	      beforeSubmit: ensureLogin,
    		  success: getVoteCommentUpdate,
    		  url:URL,
    		  type: 'post'
    	};
    	
    	$(this).ajaxSubmit(options);
        return false;
    });
  }
  
  function getVoteCommentUpdate(response) {
  	if ($(response).attr('comment') > 0) {
  	 	var id = $(response).attr('comment');
  	 	var points = $(response).attr('points');
  	 	
  	 	var pointsLabel = "("+points+" points)";
  	 	if (points == 1) {
  	 		pointsLabel = "(1 point)";
  	 	}
  	 	$("#cp-"+id).text(pointsLabel);
  	 }
  }
  
  function ensureLogin() {
     var status = getLoginStatus();
     if (status == 'false') {
     	window.location = base+'/account/login/?rf=true';
     	return false;
     }
     return true;
  }
  
  function getVoteArticleUpdate(response) {
  	 if ($(response).attr('article') > 0) {
  	 	var id = $(response).attr('article');
  	 	var votes = $(response).attr('votes');
  	 	var points = $(response).attr('points');
  	 	
  	 	$("#vc-"+id).text(votes);
  	 	$("#vp-"+id).text(points);
  	 }
  }
  
  function ensureAddComment(formData, jqForm, options) {
      var comment = formData[0].value;
      if (comment.length == 0) {
      	return false;
      }
      ensureLogin();
  }
  
  function getAddCommentUpdate(response) {
    $("#comment-title").after(response);
    var count = ($("#ccount").attr("count") * 1) + 1;
    var label = "No comments";
    if (count == 1) {
    	label = "1 comment";
    } else if (count > 1) {
    	label = count+" comments";
    }
    $("#ccount").text(label);
    attachVoteCommentEvent();
  }
  
  function getPageInfoBefore() {
     $("#submit").attr("disabled", "true");
     $("#loader").before('<div id="loading" class="ajax-loader align-left"/>');
  }
  
  function attachEventsForPageInfo() {
    $("#close").mouseover(function() {
    	$("#close-icon").attr('class', 'close-icon-dark');
    });
    
    $("#close").mouseout(function() {
    	$("#close-icon").attr('class', 'close-icon-light');
    });
    
    $("#close").click(function() {
    	$("#pageInfo").remove();
    	$("#getPageInfo").show();
    });
  }
  
  function getPageInfoUpdate(response, success) {
    $("#loading").remove();
    $("#submit").removeAttr("disabled");
    $("#getPageInfo").after(response);
    attachEventsForPageInfo();
    attachThumbnailsSelectorEvents();
    $("#getPageInfo").hide();
  
  }
  
  function attachThumbnailsSelectorEvents() {
    $("#left").click(function() {
      var total = $("#img-pos").attr("total");
      var current = $("#img-pos").attr("current");
      current = current * 1;
      total = total * 1;
      if (current > 1) {
        var next = current - 1;
        $("#thumbnail-"+current).hide();
        $("#thumbnail-"+next).show();
        $("#img-pos").attr("current", next);
        $("#img-pos").text(next+"/"+total);
        
        $("#thumbnailURL").attr("value",  $("#thumbnail-"+next).attr("src"));
      } 
    });
    
    $("#right").click(function() {
      var total = $("#img-pos").attr("total");
      var current = $("#img-pos").attr("current");
      current = current * 1;
      total = total * 1;
      if (current < total) {
        var next = current + 1;
        $("#thumbnail-"+current).hide();
        $("#thumbnail-"+next).show();
        $("#img-pos").attr("current", next);
        $("#img-pos").text(next+"/"+total);
        
        $("#thumbnailURL").attr("value",  $("#thumbnail-"+next).attr("src"));
      }
    });
    
    $("#nothumbnail").click(function() {
        var current = $("#img-pos").attr("current");
        if ($(this).attr('checked')) {
          $("#thumbnail-"+current).hide();
        } else {
          $("#thumbnail-"+current).show();
        }
    });
  }
  
  
  function getLoginStatus() {
    return $('#login-status').attr('status');
  }

