//http://www.featureblend.com/license.txt
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}
return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";

var Koda = {};

Koda.ready = function(fn) {
  setTimeout(fn, 0);
}

Koda.formChange = function(inst) {
  Koda.MultiEditor.triggerTextFieldChanged();
  //$('#' + inst.id).change();
}

var SlugValidator = {
  slugUrl: "/registration/slug/validate/",
  validate: function(slug) {
    $.ajax()
  }
};


var Koda = window.Koda || {};

(function() {
        
    var self = Koda.FB = {
      status: null, // 'unknown': not logged in, 'notConnected': not yet accepted, 'connected': accepted
      
      init: function() {
        $(".fb-connect").live("click", self.connect);
        $('.fb-import-photo').live("click", self.jobSeekerProfilePhotoSetup);
      },
      
      connect: function() {
        
        self._check_login_and_call(self._connect_callback, $(this));
        return false;
      },
      
      _connect_callback: function($connect_link) {
        if( self._is_logged_in() && self._already_accepted_application() ) {
          $(location).attr('href', $connect_link.attr('href').replace('new', 'login'));
        } else {
          $('#TB_window').remove();
          if( $('#TB_overlay').length == 0 ) {
            $('body').append('<div id="TB_overlay" class="TB_overlayBG"></div>')
          }
          $connect_link.clone().popupwindow({fb: { onUnload: self._unload, width: 650, height: 300, center: 1}}).click();
        }
      },
      
      jobSeekerProfilePhotoSetup: function() {
        var $elt = $(this);
        
        $elt.animate({left:0,top:130}, 350, function() { $elt.addClass('expanded'); });
        $elt.parents('div.section').find('.fb-photo').animate({right:0,top:0}, 350);
        
        if ($elt.position().left == 0) {
          $.ajax({
            beforeSend: function(request) {
              $elt.parents('.section').find('img.fb-loader').show();
              $elt.parents('.section').find('img.fb-photo').addClass('transparent');
              $elt.parents('.section').find('span > img').hide();
              $elt.parents('.section').find('a.fb-import-photo.expanded').hide();
            },
            url: $elt.attr('link'),
            type:'post',
            onSuccess: function(){
                        $elt.animate({left:130,top:0}, 350);
                        $elt.parents('div.section').find('.fb-photo').animate({right:-128,top:-128}, 350);
                        $elt.removeClass('expanded');
                       }
          });
        }
      },
      
      _check_login_and_call: function(callback, $element) {
        FB.getLoginStatus( function(response) {
                             self.status = response.status;
                             callback($element);
                           }, true);
      },
      
      _is_logged_in: function() {
        return (self.status != 'unknown');
      },
      
      _already_accepted_application: function() {
        return (self.status == 'connected')
      },
      
      _unload: function() {
        $('#TB_overlay').remove();
      }
    };
  }
)();

(function($) {
	$.fn.ellipsis = function(enableUpdating){
		var s = document.documentElement.style;
		if (!('textOverflow' in s || 'OTextOverflow' in s)) {
			return this.each(function(){
				var el = $(this);
				if(el.css("overflow") == "hidden"){
					var originalText = el.html();
					var w = el.width();

					var t = $(this.cloneNode(true)).css('position', 'absolute').hide()
					.css('width', 'auto').css('overflow', 'visible');
					el.after(t);

					var text = originalText;
          var twidth;
          var elwidth;
					while(text.length > 0 && (twidth = t.width()) > (elwidth = el.width())){
						text = text.substr(0, text.length - ((twidth - elwidth) / 10));
            t.html(text + "...");
					}
					el.html(t.html());

					t.remove();

					if(enableUpdating == true){
						var oldW = el.width();
						setInterval(function(){
							if(el.width() != oldW){
								oldW = el.width();
								el.html(originalText);
								el.ellipsis();
							}
						}, 200);
					}
				}
			});
		} else return this;
	};
})(jQuery);

Koda.Autocomplete = {
  init: function(element, options) {
    var defaultOptions = {
      max: 10, matchSubset: false, cacheLength: 1, delay: 250, scrollHeight: 250, minChars: 1, width: 'auto', minWidth: element.width(), selectFirst: false,
      highlight: function(value, term) {
        return "<span class='inner'><span class ='inner'>" + value + " <img src='/images/tag-chooser/plus_white.gif' alt='add'/></span></span>";
// TODO: Fix our code to use this regexp somehow...
//        return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,
//            "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
      },
      formatItem: function(value) {
        return "<span title='"+value+"'>" + value + "</span>";
      }
    };
    var mergedOptions = $.extend(defaultOptions, options);
    element.autocomplete(mergedOptions.url, mergedOptions);
  }
}

Koda.Autocomplete.Simple = {
  init: function(element, options) {
    var defaultOptions = {
      max: 10, matchSubset: false, cacheLength: 1, delay: 250, scrollHeight: 250, minChars: 1, width: element.width() + 4, resultsClass: 'ac_filter_results', selectFirst: false,
      highlight: function(value, term) {
        return value;
      },
      formatItem: function(value) {
        return "<span title='"+value+"'>" + value + "</span>";
      }
    };
    var mergedOptions = $.extend(defaultOptions, options);
    element.autocomplete(mergedOptions.url, mergedOptions);
  }
}


Koda.Autocomplete.oneoff = {
  init: function(element, options) {
    var defaultOptions = {
      max: 10, matchSubset: false, cacheLength: 1, delay: 250, scrollHeight: 250, minChars: 1, width: element.width() + 4, resultsClass: 'ac_results miniTagChooserResults', selectFirst: false,
      highlight: function(value, term) {
        return "<span class='inner'><span class ='inner'>" + value + " <img src='/images/tag-chooser/plus_white.gif' alt='add'/></span></span>";
// TODO: Fix our code to use this regexp somehow...
//        return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,
//            "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
      },
      formatItem: function(value) {
        return "<span title='"+value+"'>" + value + "</span>";
      }
    };
    var mergedOptions = $.extend(defaultOptions, options);
    element.autocomplete(mergedOptions.url, mergedOptions);
  }
}

Koda.TagChooser = {
  init: function() {
    var element = $(this);
    element.bind('addTag', Koda.TagChooser.addTag);
    element.find('.tag-chooser-add').click(function() {
      var tagField = element.find('input[type="text"]');
      $(this).parents(".tag-chooser").trigger('addTag', tagField.attr("value"));
      tagField.attr("value", "");
      return false;
    });

    element.find('.tag-chooser-controls input[type="text"]').keypress(function(e) {
      var code = (e.keyCode ? e.keyCode : e.which);
      if (code == 13) {
        var tagField = $(this);
        $(this).parents(".tag-chooser").trigger('addTag', tagField.attr("value"));
        tagField.attr("value", "");
        return false;
      }
    });

    Koda.TagChooser.addDeleteFunction(element.find('ul li.tag'));
  },

  addTag: function(event, tagName) {
    var tagList = $(this).find('ul:not(.featured)')
    var oldTagNames = $.map(tagList.find('.tag input:hidden'), function(elem) {
      return $(elem).val().toLowerCase();
    });

    if (tagName != "" && $.inArray(tagName.toLowerCase(), oldTagNames) == -1) {
      var newTag = jQuery('<li class="tag"><span>' + tagName + '<a href="#" class="remove-tag" onclick="return false;"><img src="/images/tag-chooser/x_green.png" /></a></span></li>');//.attr('tag_name', tagName.toLowerCase());
      newTag.append(jQuery('<input type="hidden" name="' + $(this).attr("field_name") + '"></input>').val(tagName));
      tagList.append(newTag);
      Koda.TagChooser.addDeleteFunction(newTag);

      tagList.show();
      tagList.parent().find("ul.featured").hide();
    }
  },

  addDeleteFunction: function(elements) {
    var deleteLink = elements.find('a.remove-tag');
    deleteLink.click(function(event) {
      $(this).parent("span").parent("li.tag").each(function() {
        var list = $(this).parents("ul:eq(0)");
        $(this).remove();
        if (list.find("li.tag").length == 0) {
          list.hide();
          list.parent().find("ul.featured").show();
        }
      });

    });
  }

//  showFeatured: function(visible) {
//    if(visible) {
//
//    }
//  }
}

Koda.LocationTagChooser = {

  tagChooser          : function() { return $('#locations_tag_chooser') },
  tagChooserTextBox   : function() { return $('#locations_tag_chooser .tag-chooser-controls input[type="text"]') },
  tagChooserAddButton : function() { return $('#locations_tag_chooser .tag-chooser-add') },

  suggestion          : function() { return $('.location_suggest') },
  suggestionTextBox   : function() { return $('.location_suggest .tag-chooser-controls input[type="text"]') },
  suggestionTryButton : function() { return $('.location_suggest .tag-chooser-add') },

  init: function() {

    L.tagChooserAddButton().unbind('click');
    L.tagChooserAddButton().click(function() {
      if (L.tagChooserTextBox().attr("value") != "") {
        L.addTag_or_presentSuggestions();
      }
      return false;
    });

    L.tagChooserTextBox().unbind('keypress');
    L.tagChooserTextBox().keypress(function(e) {
      var code = (e.keyCode ? e.keyCode : e.which);
      if ((code == 13) && (L.tagChooserTextBox().attr("value") == "")) {
        return false;
      } else if (code == 13) {
        L.addTag_or_presentSuggestions();
        return false;
      }
    });

    L.suggestionTryButton().unbind('click');
    L.suggestionTryButton().click(function() {
      L.presentSuggestions( L.suggestionTextBox().attr("value") );
      return false;
    });

    L.suggestionTextBox().unbind('keypress');
    L.suggestionTextBox().keypress(function(e) {
      var code = (e.keyCode ? e.keyCode : e.which);
      if ((code == 13)) {
        return false;
      }
    });

  },

  toggleChooser: function() {
    L.tagChooser().toggle();
    L.tagChooser().parent().parent().find('.checkbox-container').toggle();
    L.suggestion().toggle();
  },

  addTag_or_presentSuggestions: function() {
    var tagValue = L.tagChooserTextBox().attr("value");

    $.ajax({
            dataType: "text",
            url: "/locations",
				    data: ({ q: tagValue, test_location_exists: true}),
				    success: function(msg)
              {
                L.tagChooserTextBox().attr("value", "").keydown();

                response = msg.split(/\n/);
                if( response.shift() == "1" ) // location exists
                {
                  L.tagChooser().trigger('addTag', response.pop() );
                }
                else // location suggestions
                {
                  L.presentSuggestions( tagValue );
                  L.toggleChooser();
                }
				      }
			    });
  },

  presentSuggestions: function(tagValue) {

    L.suggestion().find('ul li').replaceWith("");
    L.suggestionTextBox().attr("disabled","disabled");
    L.suggestionTryButton().parents("span.inner:first").addClass('spinner');

    tagSuggestions = $.ajax({ dataType: "text",
                              url: "/locations",
                              async: false,
				                      data: ({ q: tagValue, suggestions: true })
			                      }).responseText.split("\n");

    tagsText = '';
    for( tag in tagSuggestions )
    {
      tagName = tagSuggestions[tag];
      if( tagName != '' ) {
        tagsText += '<li><a class="location_suggestion" href="#" onclick="return false;">'+tagName+'</a></li>';
      }
    }

    L.suggestion().find('ul').append(tagsText);
    L.suggestionTextBox().attr("value",tagValue).removeAttr("disabled");
    L.suggestionTryButton().parents("span.inner:first").removeClass('spinner');

    L.suggestion().find('ul li').click(function() {
      L.tagChooser().trigger('addTag', $(this).text() );
      L.toggleChooser();
      L.suggestionTextBox().attr("value",tagValue);
    });
  }

}

L = Koda.LocationTagChooser




Koda.MiniTagChooser = {
  init: function() {

    var element = $(this);
    var tagField = element.find('input[type="text"]');
    var fieldOffset = tagField.offset();

    Koda.MiniTagChooser.tagContainer = element.find('.chosenTags').css({
        position: "absolute",
        top: fieldOffset.top + tagField.height() + 2,
        left: fieldOffset.left - 3,
        width: tagField.width() + 4 }).appendTo(document.body);

    Koda.MiniTagChooser.addDeleteFunction( Koda.MiniTagChooser.tagContainer.find('ul li.tag'));
    Koda.MiniTagChooser.container = element

    Koda.MiniTagChooser.tagContainer.find('.expandTab').click(function() {
        $('.chosenTags > ul').toggle();
    });


   //tagField.focus(function() {
  //  Koda.MiniTagChooser.tagContainer.find('ul').show();
   //});


   //tagField.blur(function(event) {
   //     Koda.MiniTagChooser.tagContainer.find('ul').hide();
   //});

    element.bind('addTag', Koda.MiniTagChooser.addTag);
    element.find('.mini-tag-chooser-add').click(function() {
      $(this).parents(".miniTagChooser").trigger('addTag', tagField.attr("value"));
      tagField.attr("value", "");
      return false;
    });

    tagField.keypress(function(e) {
      var code = (e.keyCode ? e.keyCode : e.which);
      if (code == 13) {
        var tagField = $(this);
        $(this).parents(".miniTagChooser").trigger('addTag', tagField.attr("value"));
        tagField.attr("value", "");
        return false;
      }
    });
  },


  addTag: function(event, tagName) {
      var miniTagChooserContainer = Koda.MiniTagChooser.container

      var pillContainer = Koda.MiniTagChooser.tagContainer
      var pillList = pillContainer.find('ul')
      var pillSize = pillContainer.find('ul > li').size() + 1

      var oldTagNames = $.map(miniTagChooserContainer.find('input:hidden'), function(elem) {
        return $(elem).val().toLowerCase();
      });

    if (tagName != "" && $.inArray(tagName.toLowerCase(), oldTagNames) == -1) {
      var pill = jQuery('<li class="tag"><span class="inner"><span class="inner">' + tagName + '<a href="#" class="remove-tag" onclick="return false;"><img src="/images/tag-chooser/x_green.png" /></a></span></span></li>');//.attr('tag_name', tagName.toLowerCase());
      miniTagChooserContainer.append(jQuery('<input type="hidden" name="' + $(this).attr("field_name") + '"></input>').val(tagName));
      pillList.append(pill);
      pillContainer.find('div.expandTab > span').text( pillSize );
      Koda.MiniTagChooser.addDeleteFunction(pill);
    }
  },

  addDeleteFunction: function(elements) {
    var deleteLink = elements.find('a.remove-tag');
    var tag_name = elements.find('span.inner > span.inner').text()
    deleteLink.click(function(event) {

      $(this).parent("span").parent("span").parent("li.tag").parent('ul').parent('div.chosenTags').each(function(){
        $(this).find('div.expandTab > span').text($(this).find('ul > li').size() - 1);
      });  

      $(this).parent("span").parent("span").parent("li.tag").each(function() {
        $(this).remove();
      });

      Koda.MiniTagChooser.container.find( 'input:hidden[value=' + tag_name + ']').remove();
    });
  }
}

$("div.tag-chooser").livequery(Koda.TagChooser.init);
$("div.miniTagChooser").livequery(Koda.MiniTagChooser.init);
$("div#locations_tag_chooser").livequery(Koda.LocationTagChooser.init); // overwrites previous initialization

Koda.EducationSelector = {
  init: function() {
    $('#university_education_degree_name,#education_degree_name').change(function() {
      Koda.EducationSelector.showRelevantSpecificDegree();
    });
    $('select.education-selector').change(function(event) {
      Koda.EducationSelector.showCorrespondingDiv();
    });
    Koda.EducationSelector.showCorrespondingDiv();
  },

  showCorrespondingDiv: function() {
    var toShow = null;
    $('.possible-educations').children().hide();
    $('.possible-educations input').attr("disabled", "disabled");
    $('.possible-educations select').attr("disabled", "disabled");
    switch($('select.education-selector').val()) {
      case 'HighSchoolEducation': toShow = $('.possible-educations > .high-school'); break;
      case 'AbroadEducation': toShow = $('.possible-educations > .abroad'); break;
      case 'UniversityEducation': toShow = $('.possible-educations > .university');
    }
    toShow.show();
    toShow.find('input').attr("disabled", false);    
    toShow.find('span.field-wrapper:not(.hidden) select').attr("disabled", false);
  },

  showRelevantSpecificDegree: function() {
    $('span.specific-degrees span.select').parents("span.field-wrapper").addClass("hidden");
    $('span.specific-degrees select').attr("disabled", true);
    if($('#university_education_degree_name,#education_degree_name').val() && $('#university_education_degree_name,#education_degree_name').val().length > 0) {
      $('#' + $('#university_education_degree_name,#education_degree_name').val()).attr('disabled', false).parents("span.select:eq(0)").
          parents("span.field-wrapper").removeClass("hidden");
    }
  }


};

$('select.education-selector').livequery(Koda.EducationSelector.init);

Koda.DefaultValue =  {
  init: function() {
    if (this.type != 'text' && this.type != 'password' && this.type != 'textarea')
      return;

    var fld_current = $(this);

    if (fld_current.val() == '' || fld_current.val() == fld_current.attr('hint')) {
      fld_current.val(fld_current.attr('hint')).addClass('hint');
    }

    fld_current.focus(function() {
      if (fld_current.val() == fld_current.attr('hint') || fld_current.val() == '') {
        fld_current.removeClass('hint').val('');
      }
    });

    fld_current.blur(function() {
      if (fld_current.val() == fld_current.attr('hint') || fld_current.val() == '') {
        fld_current.val(fld_current.attr('hint')).addClass('hint');
      }
    });
  },

  clearAll: function(form) {
    if(!form || !form.nodeName || form.nodeName.toLowerCase() != "form") { return; }
    $(form).find("input, textarea").each(function() {
      var fld_current = $(this);
      if (fld_current.val() == fld_current.attr('hint')) {
        fld_current.removeClass('hint').val('');
      }
    })
  }
};

$('input[hint], textarea[hint]').livequery(Koda.DefaultValue.init);

Koda.FileUpload = {
  init: function() {
    $('.uploaded_file_selection').change(function(event) {
      Koda.FileUpload.displayFileUploadName();
      Koda.FileUpload.enableSaveAssociation();
    });
    Koda.FileUpload.disableSaveAssociation();

  },

  displayFileUploadName: function() {
    $(".upload_filename").html($('.uploaded_file_selection').val());
  },
  disableSaveAssociation: function() {
    $("#save_association").addClass('disabled');
  },
  enableSaveAssociation: function() {
    $("#save_association").removeClass('disabled');
  }
};

$('.uploaded_file_selection').livequery(Koda.FileUpload.init);

//Koda.MultiEditor.finishAndContinue(function() { window.location = '/people/bob/registration/step2'; });
Koda.MultiEditor = {
  init: function() {
    var element = $(this);
    element.click(function() {
      var link = $(this);
      link.attr('disabled', true);
      Koda.MultiEditor.finishAndContinue(function() {
        showSpinner();
        $.ajax({
          url: link.attr('href'),
          type: 'get',
          dataType: 'html',
          success: function(data, textStatus) {
            link.parent('li.navigation').before(data);
            link.attr('disabled', false);
          },
          complete: function() {
            hideSpinner();
          }
        });
      });
      return false;
    });
  },

  isCurrentlyEditing: function() {
    return $('.multi-editor-form').length > 0 && Koda.MultiEditor.textFieldChanged;
  },

  finishAndContinue: function(success_callback) {
    if (Koda.MultiEditor.isCurrentlyEditing()) {
      Koda.MultiEditor.successCallback = success_callback;
      $('div.multi-editor-form button[type=submit]').click().attr("disabled", true);
    } else {
      Koda.TinymceTextarea.removeAll();
      success_callback();
    }
  },

  runSuccessCallback: function() {
    if (Koda.MultiEditor.successCallback) {
      var callback = Koda.MultiEditor.successCallback;
      Koda.MultiEditor.clearSuccessCallback();
      callback();
    }
  },

  clearSuccessCallback: function() {
    Koda.MultiEditor.successCallback = undefined;

  },

  editInProgress: function() {
    return "return false"; //$('#save_association').length == 0
  },

  bindChangeOnTextFields: function(parent) {
    Koda.MultiEditor.textFieldChanged = false;
//    $(parent).find("input:text, input:password, textarea").change(Koda.MultiEditor.triggerTextFieldChanged);
    $(parent).find("input:text, input:password, textarea, select, input:checkbox, input:file").each(function() {
      $(this).delayedObserver(0, Koda.MultiEditor.triggerTextFieldChanged);
    });
  },

  triggerTextFieldChanged: function() {
    Koda.MultiEditor.textFieldChanged = true;
    $("button.new-multi-editor").attr('disabled', false);
  }

};

$('button.new-multi-editor').livequery(Koda.MultiEditor.init);

$("div.multi-editor-form").livequery(function() {
  $(".multi-editor").find("button.edit, button.delete").attr('disabled', true);
  $("button.new-multi-editor").attr('disabled', true);
  Koda.MultiEditor.bindChangeOnTextFields(this);
}, function() {
  $(".multi-editor").find("button.edit, button.delete").removeAttr('disabled');
});

Koda.PrimaryPhoto = {}
Koda.PrimaryPhoto.setPrimaryPhotoForm = function(form) {
  $('.multi-editor-details input:radio').attr('checked', false);
  $(form).find('input:radio').attr('checked', true);
}


$("input.ac_input:text").livequery(function() {
  $(this).keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
      return false;
    }
  });
});

function showSpinner() {
  var selector = $('.lightbox > .header');
  selector.addClass("loading");
}

function hideSpinner() {
  var selector = $('.lightbox > .header');
  selector.removeClass("loading");
}

function hashLength(hash) {
  var length = 0;
  for (var key in hash) {
    length++;
  }
  return length;
}

$("#TB_window form").livequery(function() {
  $(this).find("input:text:enabled:eq(0)").focus();
});

$("select:disabled").livequery(function() {
  $(this).parents("span.select:eq(0)").addClass("disabled");
}, function() {
  $(this).parents("span.select:eq(0)").removeClass("disabled");
});


$(function() {
  if (!navigator || !navigator.userAgent || navigator.userAgent.toLowerCase().indexOf('firefox') == -1 && navigator.userAgent.toLowerCase().indexOf('msie') == -1 && navigator.userAgent.toLowerCase().indexOf('safari') == -1) {
    if (document.cookie.indexOf("override_browser=1") == -1) {
      $('.browser-warning').show();
    }
  }
});

$(function() {
  window.domLoaded = true;
  $(".location-dot").show();
})

window.getViewportScrollX = function() {
  var scrollX = 0;
  if (document.documentElement && document.documentElement.scrollLeft) {
    scrollX = document.documentElement.scrollLeft;
  }
  else if (document.body && document.body.scrollLeft) {
    scrollX = document.body.scrollLeft;
  }
  else if (window.pageXOffset) {
      scrollX = window.pageXOffset;
    }
    else if (window.scrollX) {
        scrollX = window.scrollX;
      }
  return scrollX;
};

window.getViewportScrollY = function() {
  var scrollY = 0;
  if (document.documentElement && document.documentElement.scrollTop) {
    scrollY = document.documentElement.scrollTop;
  }
  else if (document.body && document.body.scrollTop) {
    scrollY = document.body.scrollTop;
  }
  else if (window.pageYOffset) {
      scrollY = window.pageYOffset;
    }
    else if (window.scrollY) {
        scrollY = window.scrollY;
      }
  return scrollY;
};

jQuery.preloadImages = function()
{
  for (var i = 0; i < arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$('input:radio[id*=company_hiring_]').livequery(function() {
  $(this).change(function() {
    if ($("#company_hiring_true").attr('checked')) {
      $('#hiring_url').show("fast");
    } else {
      $('#hiring_url').hide("fast");
    }
  });
});

$('.page .compatibility-graph > li').livequery(function() {
  $(this).hover(function() {
    var parent = $(this).parent();
    parent.next('.compatibility-hover').find("li").removeClass("hover");
    parent.next('.compatibility-hover').find('li.' + $(this).attr('class')).addClass("hover");
    var hover = parent.next('.compatibility-hover').clone().show();
    var top = parent.offset().top + parent.height();
    hover.css("top", top);
    var left = $(this).offset().left + $(this).width() / 2 - 12;
    hover.css("left", left);
    $('body').append(hover);
  }, function() {
    $('body > .compatibility-hover').remove();
  });
});

$("div.help-text-tl a").livequery(function() {
  $(this).bigTarget({
    'clickZone': "div.help-text-tl:eq(0)"
  });
});

$('#TB_overlay').livequery(function() {
 //* $('html').css('overflow', 'hidden'); *//
  $('html').addClass('no_scroll');
}, function() {
  //*$('html').css('overflow', 'auto');*//
  $('html').removeClass('no_scroll');
});

function cleanupTinyMce(inst) {
  var newlength = inst.getBody().innerHTML.length;
  if (Math.abs(newlength - inst.oldBodyLength) > 100) {
    inst.execCommand('mceCleanup');
  }
  inst.oldBodyLength = inst.getBody().innerHTML.length;
}

function setupCleanupTinyMce(inst) {
  inst.oldBodyLength = inst.getBody().innerHTML.length;
  inst.timeoutId = setInterval(function() {
    cleanupTinyMce(inst);
  }, 1000);
  setTimeout(function() { inst.focus(); }, 0);
  setTimeout(function() {$(inst.getContainer()).parents('form').find('input:first').focus();}, 0);  
}

function removeCleanupTinyMce(inst) {
  clearInterval(inst.timeoutId);
}

//$("div.checkbox-container").livequery(function() {
//  $(this).children("input").checkBox(false);
//});


$('body.mozilla div.preview > ul > li').livequery(function() {
  $(this).ellipsis(false);
});
  
$('body.mozilla h1.opportunities').livequery(function() {
  $(this).ellipsis(false);
});

$('body.mozilla h1.job').livequery(function() {
  $(this).ellipsis(false);
});

function processNewDismissed(body, the_type) {
  var parent = $('.article > .main ul.previews.' + the_type);
  var newLi = $('<li class="row" style="display: block">' + body + '</li>');
  newLi.hide();
  parent.append(newLi);
  newLi.fadeIn('normal');
}

$.ui.checkBox.defaults = {replaceInput: true,addLabel: true};
$('div.checkbox-container input').livequery(function() {
  $(this).checkBox(); 
});


$('a.error-info').livequery( function() {
  var that = this;
  $elem = $(this);
  
  if( $elem.css('visibility') == 'visible' && $elem.css('display') != 'none' && $('.apply_focus_to_this_error').length == 0 ) {
    $elem.addClass('apply_focus_to_this_error')
    setTimeout(function() { $elem = $(that);
                            $elem.removeClass('apply_focus_to_this_error');
                            $focused_elem = $elem.parents('.field-wrapper').find('input:visible, textarea:visible, select:visible').first()
                            $focused_elem.focus().blur()
                            
                            // does not seem to work for Webkit browsers (Chrome, Safari) for focused input textfields
                          }, 0)
  }
});

$("a.error-info.with-error:visible").livequery(function() {
  $(this).bt({
    custom_overides: 'koda-error',
    positions: ['right'],
    width: '15em',
    contentSelector: "$(this).next('span').html()",
    cssStyles: {color: '#FFFFFF', padding: '4px 8px'},
    fill: '#bb421a',
    spikeLength: 10,
    spikeGirth: 12,
    cornerRadius: 0,
    strokeWidth: 1,
    strokeStyle: '#bb421a'
  });
});

$("a.notice-info").livequery(function() {
  $(this).bt({
    positions: ['right'],
    width: '15em',
    contentSelector: "$(this).next('span').html()",
    cssStyles: {color: '#FFFFFF', padding: '4px 8px'},
    fill: '#353535',
    spikeLength: 10,
    spikeGirth: 12,
    cornerRadius: 0,
    strokeWidth: 1,
    strokeStyle: '#353535'
  });
});

$("a.koda-info").livequery(function() {
  $(this).bt({
    positions: ['top', 'left', 'bottom'],
    width: '14em',
    contentSelector: "$(this).next('span').html()",
    cssStyles: {color: '#FFFFFF', padding: '4px 8px'},
    fill: '#353535',
    spikeLength: 10,
    spikeGirth: 12,
    cornerRadius: 0,
    strokeWidth: 1,
    strokeStyle: '#353535',
    lightbox : 'no'
  });
});

Koda.ready(function() {
  $('select').trigger('change');
});

Koda.CompanySizeSlider = {
  init: function(options) {
    var element = $(this);
    var hiddenCompanySize = $('#company_company_size');

    if (hiddenCompanySize.val() == null || hiddenCompanySize.val() == '') {
      hiddenCompanySize.val('0');
    }

    var displayCompanySize = $('#company_size_value');
    displayCompanySize.html(Koda.CompanySizeSlider.Steps[hiddenCompanySize.val()]);

    element.slider({value : hiddenCompanySize.val(), min: 0, max: 7,
      slide: function(e, ui) {
        Koda.CompanySizeSlider.update(ui.value);
      }});
  },

  update :function(value) {
    $('#company_company_size').val(value);
    $('#company_size_value').html(Koda.CompanySizeSlider.Steps[value]);
  }
};

Koda.CompanySizeSlider.Steps = {0: '1-10', 1: '11-50', 2:'51-200', 3:'201-500', 4:'501-1000', 5:'1001-5000', 6:'5001-10,000', 7:'10,000+'};

$('#company_size_slider').livequery(Koda.CompanySizeSlider.init);

Koda.JobPostedAtSlider = {
  init: function(options) {
    var element = $(this);
    var hiddenCompanySize = $('#search_posted_date');

    if (hiddenCompanySize.val() == null || hiddenCompanySize.val() == '') {
      hiddenCompanySize.val('0');
    }

    var displayCompanySize = $('#posted_date_value');
    displayCompanySize.html(Koda.JobPostedAtSlider.Steps[hiddenCompanySize.val()]);

    element.slider({value : hiddenCompanySize.val(), min: 0, max: 7,
      slide: function(e, ui) {
        Koda.JobPostedAtSlider.update(ui.value);
      }});
  },

  update :function(value) {
    $('#search_posted_date').val(value);
    $('#posted_date_value').html(Koda.JobPostedAtSlider.Steps[value]);
  }
};

Koda.JobPostedAtSlider.Steps = {0:'3 days', 1:'7 days', 2:'10 days', 3:'14 days', 4:'30 days', 5:'45 days', 6:'60 days', 7: '60+ days'};

$('#posted_date').livequery(Koda.JobPostedAtSlider.init);

Koda.SchoolEnrollmentSlider = {};
Koda.SchoolUndergradEnrollmentSlider = {
  init: function(options) {
    var element = $(this);
    var hiddenSize = $('#school_undergrad_enrollment');
    if (hiddenSize.val() == null || hiddenSize.val() == '') {
      hiddenSize.val('2');
    }

    var displaySize = $('#undergrad_enrollment_value');
    displaySize.html(Koda.SchoolEnrollmentSlider.Steps[hiddenSize.val()]);
    element.slider({value : hiddenSize.val(), min: 0, max: 7,
      slide: function(e, ui) {
        Koda.SchoolUndergradEnrollmentSlider.update(ui.value);
      }});
  },

  update: function(value) {
    $('#school_undergrad_enrollment').val(value);
    $('#undergrad_enrollment_value').html(Koda.SchoolEnrollmentSlider.Steps[value]);
  }
};

Koda.SchoolGraduateEnrollmentSlider = {
  init: function(options) {
    var element = $(this);
    var hiddenSize = $('#school_graduate_enrollment');
    if (hiddenSize.val() == null || hiddenSize.val() == '') {
      hiddenSize.val('2');
    }

    var displaySize = $('#graduate_enrollment_value');
    displaySize.html(Koda.SchoolEnrollmentSlider.Steps[hiddenSize.val()]);
    element.slider({value : hiddenSize.val(), min: 0, max: 7,
      slide: function(e, ui) {
        Koda.SchoolGraduateEnrollmentSlider.update(ui.value);
      }});
  },

  update: function(value) {
    $('#school_graduate_enrollment').val(value);
    $('#graduate_enrollment_value').html(Koda.SchoolEnrollmentSlider.Steps[value]);
  }
};

Koda.SchoolEnrollmentSlider.Steps = {0: '1-10', 1: '11-50', 2:'51-200', 3:'201-500', 4:'501-1,000', 5:'1,001-5,000', 6:'5,001-10,000', 7:'10,000+'};
$('#undergrad_enrollment_slider').livequery(Koda.SchoolUndergradEnrollmentSlider.init);
$('#graduate_enrollment_slider').livequery(Koda.SchoolGraduateEnrollmentSlider.init);



Koda.CompanyCompatibilityMinDegreeSlider = {
  init: function() {
    var element = $(this);
    var hiddenMinDegreeSize = $('#company_compatibility_min_degree');
    var displayMinDegreeSize = $('#company_compatibility_min_degree_value');
    displayMinDegreeSize.html(Koda.CompanyCompatibilityMinDegreeSlider.Steps[hiddenMinDegreeSize.val()]);
    element.slider({range : 'max', value : hiddenMinDegreeSize.val(), min: 0, max: 5,
      slide: function(e, ui) {
        Koda.CompanyCompatibilityMinDegreeSlider.update(ui.value);
      }});
  },

  update :function(value) {
    $('#company_compatibility_min_degree').val(value);
    $('#company_compatibility_min_degree_value').html(Koda.CompanyCompatibilityMinDegreeSlider.Steps[value]);
  }
};

Koda.CompanyCompatibilityMinDegreeSlider.Steps = {0: 'High School', 1: 'Some college', 2: 'Associate', 3: 'Bachelor', 4:'Master', 5:'Doctorate'};


$('#company_compatibility_min_degree_slider').livequery(Koda.CompanyCompatibilityMinDegreeSlider.init);

Koda.DoubleSlider = {
  init: function() {
    var element = $(this);
    var steps = JSON.parse(element.attr('steps'));
    var hiddenSizeMin = element.nextAll('.min_value');
    var hiddenSizeMax = element.nextAll('.max_value');
    var options = {range: true, values : [hiddenSizeMin.val(), hiddenSizeMax.val()], min: 0, max: (hashLength(steps) - 1),
      slide: function(e, ui) {
        Koda.DoubleSlider.update(element, steps);
      },
      stop: function(e, ui) {
        var min_value = element.slider('values')[0];
        var max_value = element.slider('values')[1];
        if(max_value == 0) {
          max_value = 1;
          element.slider('option', 'values', [min_value,max_value]);
        }
        if(min_value == hashLength(steps) - 1) {
          min_value = hashLength(steps) - 2;
          element.slider('option', 'values', [min_value,max_value]);
        }
      }};
    element.slider(options);
    Koda.DoubleSlider.updateDisplay(element, steps);
  },

  update: function() {
    var element = $('.double_slider');
    var steps = JSON.parse(element.attr('steps'));

    var min_value = element.slider('values')[0];
    var max_value = element.slider('values')[1];
    var old_min_value = element.nextAll('.min_value').val();
    var old_max_value = element.nextAll('.max_value').val();
    if(min_value == max_value) {
      if(min_value != old_min_value) {
        if(max_value == hashLength(steps) - 1) {
          min_value--;
        } else {
          max_value++;
        }
      } else if (max_value != old_max_value) {
        if(min_value == 0) {
          max_value++;
        } else {
          min_value--;
        }
      }
    }
    element.slider('option', 'values', [min_value,max_value]);
    element.nextAll('.min_value').val(min_value);
    element.nextAll('.max_value').val(max_value);
    Koda.DoubleSlider.updateDisplay(element, steps);
  },

  updateDisplay: function(element, steps) {
    var hiddenSizeMin = element.nextAll('.min_value');
    var hiddenSizeMax = element.nextAll('.max_value');
    element.find('.min_value_slider').html(steps[hiddenSizeMin.val()]);
    element.find('.max_value_slider').html(steps[hiddenSizeMax.val()]);
  }
};

$('.double_slider').livequery(Koda.DoubleSlider.init);


if(window.tinyMCE) {
  Koda.TinymceTextarea =  {
    init: function() {
      var fld_current = $(this);
      tinyMCE.execCommand('mceAddControl', false, fld_current.attr('id'));
    },

    saveAll: function() {
      tinyMCE.triggerSave();
    },

    removeAll: function() {
      $('#TB_window textarea.mceEditor').each(function() {
        tinyMCE.execCommand('mceRemoveControl', false, $(this).attr('id'));
      });
    },

    restoreAll: function() {
      $('textarea.mceEditor').each(function() {
        tinyMCE.execCommand('mceAddControl', false, $(this).attr('id'));
      });
    },

    wrap: function(wrapping_function) {
      Koda.TinymceTextarea.removeAll();
      wrapping_function();
      Koda.TinymceTextarea.restoreAll();
    }
  };

  $(function() {
    $('html').ajaxComplete(function() {
      Koda.TinymceTextarea.restoreAll();
    });
  });
} else {
  Koda.TinymceTextarea =  {
    saveAll: function() {},
    removeAll: function() {},
    restoreAll: function() {},
    wrap: function() {}
  };
}



Koda.SlugValidator = {
  init: function() {
    var inputElement = $('input[validation_url]') || $('#job_seeker_unique_name');
    $('.check_availability').click(function(){Koda.SlugValidator.triggerEvent(inputElement)});
    inputElement.bind('keypress', function(e){
      var code = (e.keyCode ? e.keyCode : e.which);
      if(code == 13) {
        Koda.SlugValidator.triggerEvent(inputElement);
        e.stopPropagation();
        return false;
      }
    });
  },

  triggerEvent: function (inputElement) {
      if (inputElement.val() != inputElement.attr('lastValue')) {
        if (inputElement.hasClass('active-request')) {
          inputElement.attr('lastValueToSend', inputElement.val());
        } else {
          inputElement.css("background", "url(/images/indicator.gif) no-repeat right 50%");
          Koda.SlugValidator.doAjax(inputElement, inputElement.val());
        }
        inputElement.attr('lastValue', inputElement.val());
      }
    },

  showResponse: function(inputElement, responseText, type) {
    inputElement.css("background", "none");
    $('.slug_notice').html(responseText);
    $('.slug_notice').removeClass('error').addClass(type);
  },

  doAjax: function(inputElement, fieldValue) {
    inputElement.addClass('active-request');
    $.ajax({
      url: inputElement.attr('validation_url'),
      data: {unique_name: JSON.stringify(fieldValue)},
      dataType: 'text',
      type: 'get',
      success: function(data, textStatus, XMLHttpRequest) {
        Koda.SlugValidator.showResponse(inputElement, data, '');
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        Koda.SlugValidator.showResponse(inputElement, XMLHttpRequest.responseText, 'error');
      },
      complete: function() {
        inputElement.removeClass('active-request');
        if (inputElement.attr('lastValueToSend')) {
          Koda.SlugValidator.doAjax(inputElement, inputElement.attr('lastValueToSend'));
          inputElement.removeAttr('lastValueToSend');
        }
      }
    });
  }
};

$('.check_availability').livequery(Koda.SlugValidator.init);


Koda.Resize = {
  init: function() {
    $(window).resize(Koda.Resize.resize);
    $('#TB_window .lightbox .main > .inner > .inner').livequery(Koda.Resize.resize);
  },
  resize: function() {
    $('#TB_window .lightbox .main > .inner > .inner').css('max-height', $(window).height() - 150);
  }
}

Koda.Resize.init();

Koda.CompatibilitySelects = {
  init: function(who) {
    if (who == "job_seeker") {
      Koda.CompatibilitySelects.disable_first_two("#job_seeker_compatibility_env_pace")
      Koda.CompatibilitySelects.disable_first_two("#job_seeker_compatibility_env_space")
      Koda.CompatibilitySelects.disable_first_two("#job_seeker_compatibility_env_attire")
      Koda.CompatibilitySelects.disable_first_two("#job_seeker_compatibility_travel_frequency")
      Koda.CompatibilitySelects.disable_first_two("#job_seeker_compatibility_travel_distance")
    }

    if (who == "company") {
      Koda.CompatibilitySelects.disable_first_two("#company_compatibility_env_pace")
      Koda.CompatibilitySelects.disable_first_two("#company_compatibility_env_space")
      Koda.CompatibilitySelects.disable_first_two("#company_compatibility_env_attire")
      Koda.CompatibilitySelects.disable_first_two("#company_compatibility_travel_frequency")
      Koda.CompatibilitySelects.disable_first_two("#company_compatibility_travel_distance")
    }
  },

  disable_first_two: function (select_box_id) {
    $(select_box_id).find("option").each(
        function(intIndex) {
          if (intIndex == 0 || intIndex == 1) {
            this.disabled = true;
          }
        })
  }
}

Koda.PhotoViewer = {

  // photoData is an array of [photo URL, photo width, photo height, photo title] elements

  init: function(_photoData) {
    this.photoData = _photoData;
    this.photo_count = _photoData.length;
    this.selected_photo = 0;
  },
  
  selectPhoto: function(photo) {
    
    photo_class = ".media-photo img"
    top_space = 200 - 0.5 * this.photoData[photo][2];
    left_space = 200 - 0.5 * this.photoData[photo][1];
    
    $(photo_class).attr("src", this.photoData[photo][0]);
    $(photo_class).attr("width", this.photoData[photo][1]);
    $(photo_class).attr("height", this.photoData[photo][2]);
    $(photo_class).attr("style", "top: " + top_space + "px; left: " + left_space + "px;");

    $("#photo_title").html(this.photoData[photo][3]);

    $('#media_viewer ul#thumbnails li .frame').removeClass('active');
    $('#thumb_'+photo).addClass('active');

    if( photo == this.photo_count - 1)
      $(".lightbox .more_photos a.next").addClass('disable');
    else
      $(".lightbox .more_photos a.next").removeClass('disable');

    if( photo == 0)
      $(".lightbox .more_photos a.previous").addClass('disable');
    else
      $(".lightbox .more_photos a.previous").removeClass('disable');

    this.selected_photo = photo;

  },

  selectNextPhoto: function() {
    if( this.selected_photo != this.photo_count - 1) // not last photo
      this.selectPhoto( this.selected_photo + 1);
  },

  selectPreviousPhoto: function() {
    if( this.selected_photo != 0 ) // not first photo
      this.selectPhoto( this.selected_photo - 1);
  }

}

var Koda = window.Koda || {};

(function($) {

    var self = Koda.AccountMerge = {

        init: function() {
          $('.check_link_account_exists').live("click", self.check_link_account_exists);
          $('.submit_link_account_request').live("click", self.submit_link_account_request);
          $('.finish_registration').live("click", self.finish_registration)
          
          self._resize_window();
          
          return self;
        },
        
        check_link_account_exists: function() {
          $button  = $(this);
          $field   = $button.parents('.field');
          $error   = $field.next();
          $action  = $error.next();
          
          account_name = $.trim( $('input', $field).val() );
          
          if( account_name.length == 0 ) {
            $error.text('Please enter an email address');
            self._resize_window();
            return false;
          }
          
          self._toggle_lightbox_loading();
          
          $.ajax({
            type: 'get',
            url: $(this).attr('href') + '?address=' + account_name,
            complete: function() {
              self._toggle_lightbox_loading();
              self._resize_window();
            },
            success: function(response) {
              $error.text('');
              $action.html(response);
            },
            error: function(response) {
              $error.text(response.responseText);
              $action.html('');
            }
          });
          
          return false;
        },
        
        submit_link_account_request: function() {
          self._toggle_lightbox_loading();
          
          $.ajax({
            type: 'get',
            url: $(this).attr('href'),
            complete: function() {
              self._toggle_lightbox_loading();
            },
            success: function(response) {
              $('.link_accounts').addClass('submitted').html('<p>We sent a confirmation email to the address you specified!</p>');
              self._resize_window();
              setTimeout(self.finish_registration, 2000);
            },
            error: function() {
              alert("Attempt to link accounts failed!");
            }
          });
          
          return false;
        },
        
        finish_registration: function() {
          $.ajax({
            type: 'get',
            url: $('.finish_registration').attr('href'),
            success: function(response) {
              redirection_url = $.trim(response)
              window.opener.location = ( redirection_url.length > 0 ) ? redirection_url : window.opener.location;
              window.close();
            }
          });
          return false;
        },
        
        _resize_window: function() {
          // Chrome does not support window.resizeTo
          if( navigator.userAgent.match(/chrome/i) )
          {
            submitted_h    = 190
            default_h      = 320
            error_h        = 340
            confirmation_h = 360
            
            if( $('.link_account_confirmation').length > 0 ) {
              window.resizeTo(650, confirmation_h);
            } else if( $('.error').text().length > 0 ) {
              window.resizeTo(650, error_h);
            } else if( $('.link_accounts.submitted').length > 0 ) {
              window.resizeTo(650, submitted_h);
            } else {
              window.resizeTo(650, default_h);
            }
            
          } else {
            h = 300
            window.resizeTo(650,h);
            
            content_h  = $('.lightbox').height();
            viewport_h = $(window).height();
            new_h = h + (content_h - viewport_h);
            
            window.resizeTo(650,new_h);
          }
        },
        
        _toggle_lightbox_loading: function() {
          $('.lightbox .header').toggleClass('loading');
        }
    };

})(jQuery);
