(function($){

	$.fn.clearForm = function() {
		return this.each(function() {
			var obj = $(this);
			var defaultValue = obj.val();
			obj.click(function() {
				if( $(this).val() == defaultValue ) {
					$(this).val("");
					$(this).addClass("entered");
				}  
			});
		});
	};
	
	$.fn.startWaiting = function() {  
 
		 return this.each(function() {  
			var obj = $(this);
			obj.fadeTo('fast', 0.5);
		 });  
	};

	$.fn.stopWaiting = function() {  
 
		return this.each(function() {  
			var obj = $(this);
			obj.fadeTo('fast', 1);
		});  
	};
	
	$.fn.loadingPulse = function() {  
 
		return this.each(function() {  
			var obj = $(this);
			obj.fadeIn('fast');
			var continuePulse = true;
			var fadeInAndOut = function() {
				obj.fadeTo('slow', .5, function() {
					if (continuePulse) {
						obj.fadeTo('slow', 1, fadeInAndOut);
					} else {
						obj.fadeOut('fast');
					}
				});
			};
			fadeInAndOut();
			obj.bind('stopLoadingPulse', function() {
				continuePulse = false;
			});
		});  
	};
	
	$.fn.stopLoadingPulse = function() {  
 
		return this.each(function() {  
			var obj = $(this);
			obj.trigger('stopLoadingPulse');
		});
	};
	
	$.enableGrid = function() {
		// This should only be called once, even if there are
		// multiple grids.
		$(document).bind("updateGridDisplay", function(e, data) {
			data.options = true;
			jQuery.bbq.pushState(data);
		});
	};
	
	$.fn.makeGrid = function(endPoint, infiniteEndPoint, appendTo) {
		return this.each(function() {
			var obj = $(this);
		   $(window).bind('hashchange', function(e) {
				if ($.param.fragment().match(/options=true/)) { 
					data = $.bbq.getState(true);
					obj.updateGridDisplay(data, endPoint, infiniteEndPoint, appendTo);
				}
			});   
			$(document).ready(function($) {
				if (($.param.fragment().length > 0) && $.param.fragment().match(/options=true/)) {
					data = $.bbq.getState(true);
					if (data.infinite && (parseInt(data.page) > 1)) {
						data.page = 1;
					}
					obj.updateGridDisplay(data, endPoint);
				}
			});
		});
	};
	
	$.fn.updateGridDisplay = function(options, endPoint, infiniteEndPoint, appendTo) {  		
		return this.each(function() {
			var obj = $(this);
			data["show_filters"] = filters_down; 
			if (options.infinite && (parseInt(options.page) > 1)) {
				obj.find(appendTo).trigger('willAppendMoreData');
				$.get(infiniteEndPoint, options, function(data){
					obj.find(appendTo).append(data);   
					obj.find(appendTo).trigger('moreDataAppended');
				});
			} else {
				obj.find(appendTo).startWaiting();
				$.ajax({url: endPoint, data: options,
   	 			 	success: function(data){
						animate -= 1;
						if(animate < 1){
							obj.html(data);
						   	obj.find(appendTo).stopWaiting(); 
							if(parseInt(options.page) > 1){
								window.scrollTo(0, obj.offset().top);
							}  
						}
					},
					failure: function(){animate -= 1;if(animate < 1){obj.find(appendTo).stopWaiting();}}     
				});
			}
		});
	};

	
	$.fn.loadCategorySplash = function(options, callback) {
		return this.each(function() {
			var obj = $(this);
			$.get(options.base_url + options.category_id, options, function(data) {
				obj.html(data);
				callback();
			});
		});
	};
	
	$.fn.castVote = function(options) {
		if (!options) {
			return;
		}
		return this.each(function() {
			var obj = $(this);
			obj.startWaiting();
			options.ideation_title = obj.parent().parent().find(".ideation-title").html();
			obj.trigger('castVote', options);
		});
	};
	
	$.fn.reverseVote = function(options) {
		return this.each(function() {
			var obj = $(this);
			obj.startWaiting();
			obj.trigger('reverseVote', options);
		});
	};
	
	$.fn.listenForCastVote = function(options) {
		return this.each(function() {
			var obj = $(this);
			$(document).bind("voteCast." + options.vote.voteable_id, function(e, data) {
				obj.stopWaiting();
				if (options.unvote_button_text) {
					obj.find(".text").html(options.unvote_button_text);
				} else {
					obj.find(".text").html("Take Your Vote Back");
				}
				obj.removeClass("bright");
				obj.addClass("soft");
				obj.attr("onclick", "");
				obj.unbind("click");
				obj.bind("click", function(e) { e.preventDefault(); obj.reverseVote(data); });
			});
		});
	};
	
	$.fn.listenForReversedVote = function(options) {
		return this.each(function() {
			var obj = $(this);
			$(document).bind("voteReversed." + options.vote.voteable_id, function(e, data) {
				obj.stopWaiting();
				if (options.vote_button_text) {
					obj.find(".text").html(options.vote_button_text);
				} else {
					obj.find(".text").html("Vote For This");
				}
				obj.removeClass("soft");
				obj.addClass("bright");
				obj.attr("onclick", "");
				obj.unbind("click");
				obj.bind("click", function(e, data) { e.preventDefault(); obj.castVote(options); });
			});
		});
	};
	
	$.fn.modSelector = function() {
		return this.each(function() {
			var obj = $(this);
			obj.focus();
			obj.select();
			return false;
		});
	};
	
	$.checkLogin = function(callback) {
		if (!$._qIsLoggedIn) {
			$(document).trigger('promptLogin', { success: callback });
		} else {
			callback();
		}
	} 
	
	$.fn.checkLoginSubmit = function(options){
		$(this).live('click', function(e){ 
			e.preventDefault(); 
			var obj = $(this);                 
		   	$.checkLogin(function(){ 
				obj.parents("form:first").ajaxForm(options);
				obj.parents("form:first").submit();
			}); 
		});
	}
	
	$.voteUp = function(options) {
		$.checkLogin(function() {
			$.ajax({
				type: "POST",
				url: "/votes",
				data: {vote: options.vote},
				success: options.success,
				error: options.error,
				timeout: options.timeout,
				dataType: "json"
			});
		});
	}
	
	$.voteDown = function(options) {
		$.checkLogin(function() {
			$.ajax({
				type: "DELETE",
				url: "/votes/" + options.vote.id,
				data: {vote: options.vote},
				success: options.success,
				error: options.error,
				timeout: options.timeout,
				dataType: "json"
			});
		});
	}
	
	$.createBookmark = function(options) {
		$.checkLogin(function() {
			$.ajax({
				type: "POST",
				url: "/bookmarks",
				data: options.bookmark,
				success: options.success,
				error: options.error,
				dataType: "json"
			});
		});
	}
	
	$.removeBookmark = function(options) {
		$.checkLogin(function() {
			$.ajax({
				type: "DELETE",
				url: "/bookmarks/" + options.bookmark.id,
				data: options.bookmark,
				success: options.success,
				error: options.error,
				dataType: "json"
			});
		});
	}
	
	$.voting = function(e,link,handler){
		var link = jQuery(link);
		var voted = link.attr('data-voted');
		var id = link.attr('data-id');
		var options = {};
		options.timeout = 10000;
		if(typeof(id) != 'undefined' ){
			$('.voter').die('click',handler);
			if (voted == 'true') {
				var vote_id = link.attr('data-vote-id');
				options.vote = {id:vote_id,voteable_id:id,voteable_type:'Ideation'};
				options.success = function(data){
					if(data == null){
						alert("We're sorry but an error has occurred. Please try again later.");
					}else{
						link.attr('data-voted','false');
						link.removeAttr('data-vote-id');
						link.toggleClass('vote unvote');
					}
					$('.voter').live('click',handler);
					jQuery(link).stopWaiting();
				}
				options.error = function(data,type){
					alert("We're sorry but an error has occurred. Please try again later.");
					$('.voter').live('click',handler);
					jQuery(link).stopWaiting();
				}
				jQuery.voteDown(options);
			} else {
				var type = link.attr('data-type');
				options.vote = {voteable_id:id, voteable_type:type, value:1}
				options.success = function(data){
					if(data == null){
						alert("We're sorry but an error has occurred. Please try again later.");
					}else{
						link.attr('data-voted','true');
						link.attr('data-vote-id',data.vote.id);
						link.toggleClass('vote unvote');
					}
					$('.voter').live('click',handler);
					jQuery(link).stopWaiting();
				}
				options.error = function(data,type){
          var rmessage = data.responseText;
          if ((typeof rmessage == "string") && rmessage.match(/You cannot cast more/)) {
            rmessage = JSON.parse(rmessage);
            var theError = rmessage.first();
            var errorMessage = theError[1];
            alert(errorMessage);
          } else {
					  alert("We're sorry but an error has occurred. Please try again later.");
          }
					$('.voter').live('click',handler);
					jQuery(link).stopWaiting();
				}
				jQuery.voteUp(options);
			}
		}
	}
	
	$.saving = function(e,link,handler){
		var link = jQuery(link);
		var id = link.attr('data-id');
    	var link_text = jQuery(link).find('span').first();
		var saved = link.attr('data-saved');
		var options = {}
		if(typeof(id) != 'undefined' ){
			$('.saver').die('click',handler);
			if (saved == 'true') {
				var id = link.attr('data-bookmark-id');
				options.bookmark = {id:id};
				options.success = function(data){
					link.attr('data-saved','false');
					link.removeAttr('data-bookmark-id');
					link.toggleClass('save unsave');
	        		link_text.html('Save');
					$('.saver').live('click',handler);
					jQuery(link).stopWaiting();
				}
				options.error = function(data){
					alert("We're sorry but an error has occurred. Please try again later.");
					$('.saver').live('click',handler);
					jQuery(link).stopWaiting();
				}
				jQuery.removeBookmark(options);
			} else {
				options.bookmark = {ideation_id:id};
				options.success = function(data){
					link.attr('data-saved','true');
					link.attr('data-bookmark-id',data.id);
					link.toggleClass('save unsave');
			        link_text.html('Unsave');
					$('.saver').live('click',handler);
					jQuery(link).stopWaiting();
				}
				options.error = function(data){
					alert("We're sorry but an error has occurred. Please try again later.");
					$('.saver').live('click',handler);
					jQuery(link).stopWaiting();
				}
				jQuery.createBookmark(options);
			}
		}
	}
	
	$.sendToSocial = function(e,link){
		e.preventDefault();
		window.open(link.href,"_blank","height=300,width=500");
	}

  $.ajaxifyLogin = function() {

    var loginFailed = function() {
		  jQuery("#loginForm").stopWaiting();
		  jQuery("#error").replaceWith("<p class='login-error' id='error'>Login Failed</p>");
	  }

		$("#loginForm").ajaxForm({
      dataType: 'json', 
      beforeSubmit: function(){ jQuery("#loginForm").startWaiting();},
      success: function () { jQuery(document).trigger('loginSuccessful'); }, 
      error: loginFailed
    });
  } 


  $.setFilters = function(param, className, selectedClass) {
    var url = $.url();
    var filters = url.param(param);
    if (filters != undefined) {
      if (!(filters instanceof Array)) {
        filters = [filters]
      }
      $('.' + className).each(function() {
        $(this).removeClass(selectedClass);
      });
      var length = filters.length;
      for (var i = 0; i < length; i++) {
        $('.' + className).each(function() {
          if ($(this).attr('data-value') == filters[i]) {
            $(this).addClass(selectedClass);
          }
        });
      }
    }
  }

  $.ideationFilterSet = function() {
    $.setFilters('filters[]', 'filter', 'selected');
    $.setFilters('category[]', 'cat-filter', 'selected');

  }

  $.ideationFilter = function() {
    $.ideationFilterSet();
    $(document).bind('filtersUpdated', function() {
  
      window.location.href = $.ideationQueryString();
    });
  }

  $.ideationQueryString = function() {
    var cats = [];
    $('.cat-filter.selected').each(function(index) {
      var cat = $(this).attr('data-value');
      if (cat != "all") {
        cats.push(cat);
      }
    });
    var filters = [];
    $('.filter.selected').each(function(index) {
      var filter = $(this).attr('data-value');
      if (filter != "all") {
        filters.push(filter);
      }
    });
    var sort = $('.sort.selected').first().attr('data-value');
    qstring = "?";
    if (sort && (sort.length > 0)) {
      filters.push(sort)
    }
    if (filters && (filters.length > 0)) {
      var length = filters.length;
      for(var i = 0; i < length; i++) {
        qstring += ("&filters[]=" + filters[i]);
      }
    }
    if (cats && (cats.length > 0)) {
      var length = cats.length;
      for(var i = 0; i < length; i++) {
        qstring += ("&category[]=" + cats[i]);
      }
    }
    qstring = qstring.replace(/\?\&/, "?");
    return qstring;
  }

  $.getIdeationQueryForPage = function(page) {
    var url = $.url();
    var query = url.attr('query');
    if (query.match(/page=\d+/)) {
      query = query.replace(/page=\d+/, ("page=" + page));
    } else {
      if (query.length > 0) {
        query += ("&page=" + page);
      } else {
        query += ("page=" + page);
      }
    }
    return query;
  }

  $.getIdeationQueryForNextPage = function(page) {
    var url = $.url();
    var page_param = url.param('page');
    var query = "";
    if (page_param) {
      page_param++;
      query = $.getIdeationQueryForPage(page_param);
    } else {
      query = $.getIdeationQueryForPage(2);
    }
    return query;
  }

  $.fn.ideationSearch = function() {
		return this.each(function() {
      var obj = $(this);
      var url = $.url();
      var query = url.param("q");
      obj.attr('value', query);

      obj.keyup(function(event){
        if(event.keyCode == 13){
          var query = obj.attr('value');
          if (query.length < 1) {
            return false;
          }
          var qstring = "?q=";
          qstring += query;
          var filters = [];
          $('.filter.selected').each(function(index) {
            var filter = $(this).attr('data-value');
            if ($.inArray(filter, ["most_recent", "most_popular", "finalists"]) >= 0) {
              filters.push(filter);
            }
          });
          if (filters && (filters.length > 0)) {
            var length = filters.length;
            for(var i = 0; i < length; i++) {
              qstring += ("&filters[]=" + filters[i]);
          }
          }
          window.location.href = qstring;
        }
      });
    });
  }

	$.setupIdeaDraftListener = function() {
	  _listener = {
		idea_draft_id : null,
		project_id : null,
		form_id : null,
		
		load_recent : function(project_id) {
			this.project_id = project_id;
			
			listener = this;
			jQuery.ajax({
				type: "GET",
				url: "/idea_drafts/recent/" + listener.project_id,
				context: listener,
				success: listener.after_idea_draft_load
			});
		},
		
		attach_to_form : function(form_id) {
			this.form_id = form_id;
			
			listener = this;
			jQuery(listener.form_id).focusout(function() {
				if (listener.idea_draft_id == null) {
					action = "create";
				} else {
					action = "update";
				}
				
				// save this idea draft every time any part of this form loses focus
				jQuery.ajax({
					type: "POST",
					url: "/idea_drafts/" + action,
					context: listener,
					data: jQuery(listener.form_id).serialize(),
					success: listener.after_idea_draft_create_update
				});
			});
		},
			
		attach_to_clear_button : function(clear_button_id) {
			listener = this;
			
			jQuery(clear_button_id).click(function() {
				listener.idea_draft_id = null;
				
				// remove draft id from form because starting over
				jQuery("#idea_draft_id").remove();

				// clear out all draft fields
				jQuery("#idea_title").val('');
				jQuery("#idea_problem").val('');
				jQuery("#idea_solution").val('');
				jQuery("#features input").each(function() { jQuery(this).val(''); });
				jQuery("#similar_products input").each(function() { jQuery(this).val(''); });
				jQuery("#categories a").removeClass("bright").addClass("light-soft");
				if (jQuery("#idea_category_id").length != 0) { jQuery("#idea_category_id").remove(); }
				jQuery("#clear_idea_wrapper").fadeOut("slow");

				return false;
			});
		},
		
		after_idea_draft_load : function(idea_draft) {
			if (idea_draft !== null) {
				// perform the same actions you would if were creating a brand new draft
				this.after_idea_draft_create_update(idea_draft);
			
				// automatically fill in fields if have previous idea draft
				jQuery("#idea_title").val(idea_draft.title);
				jQuery("#idea_problem").val(idea_draft.problem);
				jQuery("#idea_solution").val(idea_draft.solution);
				for (i = 0; i < idea_draft.features.length; i++) {
					jQuery("#idea_feature_" + i).val(idea_draft.features[i]);
				}
				for (i = 0; i < idea_draft.similar_products.length; i++) {
					jQuery("#idea_similar_product_" + i).val(idea_draft.similar_products[i]);
				}
				if (jQuery("#" + idea_draft.category).length > 0) {
					jQuery("#" + idea_draft.category).click();
				}
				
				var area = jQuery("#idea_title")[0]
				if(typeof area != 'undefined'){
					var new_length = jQuery(area).val().length;
					jQuery("#char_counter").html(140 - new_length);
					if(new_length > 140){
						jQuery("#char_counter").css('color','#CC0000');
					}else{
						jQuery("#char_counter").css('color','');
					}
				}
				
				
				// show user that we resumed a draft
				jQuery("#clear_idea_wrapper").fadeIn("fast");			
			}
		},
		
		after_idea_draft_create_update : function(idea_draft) {
			if (idea_draft !== null) {
				this.idea_draft_id = idea_draft._id;			
				if (jQuery("#idea_draft_id").length <= 0) {
					jQuery(this.form_id).append("<input id='idea_draft_id' name='idea[id]' type='hidden' value='" + this.idea_draft_id + "'>");
				}
			}
		}
	  }
	  return _listener;
	};

  $.setupSplashPanels = function() {
    var _qSplash = {
      panels : [],
      processedPanels : [],
      changeInProcess : false,
      panelMouseIn : null,
      panelChangeRetry : null,
      panelFirstShown : false,
      continueAnimation: true,

      processSplashPanel : function() {
        var panel = this.panels.pop();
        if (panel) {
          var div_id = "#" + panel.splash_id;
          var qSplash = this;
          jQuery(div_id).ready(function($) {
            jQuery(div_id).loadCategorySplash({base_url: panel.template_url, category_id: panel.category_id}, function() {
              if (!qSplash.panelFirstShown) {
                  qSplash.panelChangeInProcess = true;
                  jQuery(div_id).fadeIn("fast");
                  qSplash.panelFirstShown = true;
                  jQuery(div_id).addClass("selected");
                  jQuery(document).trigger("splashPanelCategorySelected", {link_id: panel.link_id, splash_id: panel.splash_id});
                  qSplash.panelChangeInProcess = false;
              }
    
              jQuery("#" + panel.link_id).hover(function(){
                  qSplash.continueAnimation = false;
                  jQuery(document).trigger('showProductSplashPanel', { splash_id: panel.splash_id, link_id: panel.link_id });
                }, function() {
                    qSplash.panelMouseIn = null;
              });

              setTimeout(function() {
                qSplash.processSplashPanel();
              }, 100);
            }); // end loadCategorySplash
          }); // end ready
          qSplash.processedPanels.unshift(panel);
        } else {
          jQuery(document).trigger('splashPanelsDoneLoading');
        }
      }, // end processSplashPanel
      
      pushPanel : function(panel) {
        this.panels.push(panel);
      }, // end pushPanel
      
      setupBindings : function() {
        var qSplash = this;
        jQuery(document).bind("splashArrayHasElements", function() {
            jQuery(document).unbind("splashArrayHasElements");
          qSplash.processSplashPanel();
        }); // end splashArrayHasElements

        jQuery(document).bind('showProductSplashPanel', function(event, options) {
             var $ = jQuery;
             if (jQuery("#splash-panel-list").children(".selected").attr("id") == options.splash_id) {
                return;
             }
             qSplash.panelMouseIn = options.splash_id;
             setTimeout(function() {
            if (qSplash.panelMouseIn != options.splash_id) {
                    return null;
                 }
                 if (!qSplash.panelChangeInProcess) {
                    qSplash.panelChangeInProcess = true;
                    var currently_selected = $("#splash-panel-list").children(".selected");
                    var will_be_selected = $("#" + options.splash_id);
                    jQuery(document).trigger("splashPanelCategorySelected", {link_id: options.link_id});
                    currently_selected.fadeOut("fast", function() {
                        currently_selected.removeClass("selected");
                        will_be_selected.fadeIn("fast", function() {
                            will_be_selected.addClass("selected");
                            qSplash.panelChangeInProcess = false;
                });
              });
                 } else {
                    /** This is if someone hovers over a new category
                    while a change is in process, and they are still
                    hovering when the change is done. */
                    qSplash.panelChangeRetry = options.splash_id;
                    setTimeout(function() {
                if (qSplash.panelChangeRetry == options.splash_id) {
                  $(document).trigger('showProductSplashPanel', options);
                }
                    }, 500, 1);
            }
          }, 200, 1);
        }); // end showProductSplashPanel

        jQuery(document).bind('splashPanelCategorySelected', function(event, options) {
            jQuery("#splash-panel-links").children(".selected").removeClass("selected");
            jQuery("#" + options.link_id).addClass("selected");
        }); // end splashPanelCategorySelected

        jQuery(document).bind('splashPanelsDoneLoading', function(event) {
          jQuery("#splash-panel-links").fadeIn("fast");
          setTimeout(function() {
            if (qSplash.processedPanels.length > 1) {
              var panelIndex = 0;
              var nextPanel = qSplash.processedPanels[panelIndex];
              var animateToNext = function() {
                if (qSplash.continueAnimation) {
                  jQuery(document).trigger('showProductSplashPanel', nextPanel);
                  panelIndex++;
                  if ((panelIndex + 1) > qSplash.processedPanels.length) {
                    panelIndex = 0;
                  }
                  nextPanel = qSplash.processedPanels[panelIndex];
                  setTimeout(animateToNext, 4000);
                }
              }
              animateToNext();
            }
          }, 4000);
        }); // end splashPanelsDoneLoading
      } // end setupBindings
      
    } // end _qSplash
    
    return _qSplash;
  } 

 $.editSurvey = function() {
	   jQuery(".place-block").live("click", function(e){ 
			if(jQuery(this).hasClass("choice-block")){
				jQuery(this).parent("li").children(".survey-form-container").show();
			}else if(jQuery(this).hasClass("question-block")){
				jQuery(this).parent("div").children(".survey-form-container").show();
			}  
	   });
	              
	
	
    jQuery(".survey-form").ajaxForm({ 
										resetForm:true,
										clearForm:true,
										dataType:"js",      
										success: function(data){ 
										   	jQuery("#edit-survey-questions").append(data);
										}
	   });
	
	 jQuery(".new-choice").ajaxForm({
									resetForm:true,
									clearForm:true,
									dataType:"json",      
									success: function(data){  
									   		jQuery("#question-" + data.question_id + "-choices").append(data.mark_up).children("li:last");
									}
			
 	 }); 
	
	  jQuery(".question-form").live("submit", function(){
					jQuery(this).ajaxSubmit({ 
										type:"put",
		 								dataType:"json",
										success: function(data){ 
											jQuery("#question-text-" + data.question_id).html(data.text);
											jQuery("#question-container-" + data.question_id + " input").stopWaiting();
											jQuery("#question-container-" + data.question_id).hide();
										}
	  			   });
					return false;
	  });
	
	
		jQuery(".choice-form").live("submit", function(){
		   jQuery(this).ajaxSubmit({ 
												dataType:"json",
												success: function(data){      
												     jQuery("#choice-" + data.choice_id).html(data.text);                      
												 	 jQuery("#choice-container-" + data.choice_id + " input").stopWaiting();
													 jQuery("#choice-container-" + data.choice_id).hide();  
												},
												failure: function(data){
													alert("Something went wrong, try again?");
												}
			   });  
			return false;
		});
	
		jQuery(".choice-form input, .question-form input").live("blur", function(e){
			jQuery(this).startWaiting(); 
			jQuery(this).parent("form:first").submit();  
		});
	
	    jQuery(".survey-delete").live("click", function(e){
		   e.preventDefault(); 
		   ob = jQuery(this);
		   if(ob.hasClass("delete-choice")){
			     tar = ob.parent("li");
			}else{
				 tar = ob.parent("div");
			}
		   jQuery.ajax({
						type: "delete", 
			   			url:ob.attr("href"),
						dataType:"json",
						success:function(data){
								 tar.remove();
						},
						failure:function(data){
								alert("Something went wrong... try again");
						}
			});
		});
 }

 $.setupSurvey = function() {  
	window.submittable = true;
	jQuery(".survey-choice").click(function(e){ 
			ob = jQuery(this);
		  	e.preventDefault();
		    jQuery.checkLogin(function(){

				jQuery.ajax({
				   url: ob.attr("href"),
				   dataType: "json",
				   beforeSend: function(){ 
 							    var onstate = ob.hasClass("bright");


								if(ob.hasClass("multiple")){
								    // don't clear previous choices
								}else{     
					            	ob.parents("ul").children("li").children("a.bright").removeClass("bright").addClass("light-soft");
								}      

								if(onstate){ 
									ob.removeClass("bright").addClass("light-soft");  
								}else{       
						   			ob.removeClass("light-soft").addClass("bright"); 
								}



								ob.parents(".userSurveyItem").startWaiting(); 
				   		},
				   success: function(data){ jQuery("#question-" + data.question_id).stopWaiting();  
				                            	if(data.all_answered){
					                                jQuery("#success").show();
												}else{
					                                jQuery("#success").hide();
												}
										 	}, 
				   failure: function(data){                    
								ob.removeClass("bright").addClass("light-soft");
					   			ob.parents("ul").stopWaiting();
					}
				});

			});

			return false;
		}); 

		jQuery(".survey_text_question").ajaxForm({
													dataType: "json",
		 											success:function(data){    
																			jQuery("#question-" + data.question_id).stopWaiting(); 
																			jQuery("#continue-return").stopWaiting();  
																			window.submittable = true; 
																			                            	if(data.all_answered){
																				                                jQuery("#success").show();
																											}else{
																				                                jQuery("#success").hide();
																											}
																		  }
												  });
												
        jQuery("#continue-return").click(function(e){
	    	e.preventDefault();
		    var checkFormStatus = function(callback){
			   if(window.submittable){
					if(typeof callback == "function"){
						callback();
					}
				}else{
					setTimeout(function(){ checkFormStatus(callback);}, 100)
				}
			} 
			
			checkFormStatus(function(){window.location = jQuery("#continue-return").attr("href");});		
		});  
		
		jQuery(".survey_text_field").focus(function(e){
		   window.submittable = false;
		});
		 		
		jQuery(".survey_text_field").blur(function(e){
		   ob = jQuery(this);
		   pf = ob.parents("form:first");
		   pf.parent(".userSurveyItem").startWaiting();
		   jQuery.checkLogin(function(){
			 	pf.submit();
			});
		}); 
		
 } 

var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    jQuery.event.special.focus = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'focus';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid1, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('focus', handler, true);
                } else {
                    _self.attachEvent('onfocusin', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid1);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('focus', handler, true);
                } else {
                    this.detachEvent('onfocusin', handler);
                }
            }
        }
    };

    jQuery.event.special.blur = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'blur';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid2, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('blur', handler, true);
                } else {
                    _self.attachEvent('onfocusout', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid2);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('blur', handler, true);
                } else {
                    this.detachEvent('onfocusout', handler);
                }
            }
        }
    };

	
})(jQuery);

function scroll_to(id){
  jQuery('html,body').animate({scrollTop: jQuery("#"+id).offset().top},'slow');
}

_qNewVideoRecorded = function(name, url) {
  jQuery(document).trigger('newVideoRecorded', {video_name: name, video_url: url});
}  





