/*
 *  $server_url = 'http://www.jobdisco.com';
        $app_dir = '/build_a_resume/';


        //== /build_a_resume/img/
        $img_url = $server_url.$app_dir.'img/';

        //== $_SERVER['DOCUMENT_ROOT'].'/build_a_resume/
        $server_app_root = $_SERVER['DOCUMENT_ROOT'].$app_dir;

        <div id="preview_resume_share" class="menu_bar_button">
            <div class="menu_bar_button_left"></div>
            <div class="menu_bar_button_middle">Share</div>
            <div class="menu_bar_button_right"></div>
        </div>
 *
 */
/*
 *
 *  Ajax Autocomplete for Prototype, version 1.0.4
 *  (c) 2010 Tomas Kirda
 *
 *  Ajax Autocomplete for Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the web site: http://www.devbridge.com/projects/autocomplete/
 *
 */

//function loadjscssfile(filename, filetype){
// if (filetype=="js"){ //if filename is a external JavaScript file
//  var fileref=document.createElement('script')
//  fileref.setAttribute("type","text/javascript")
//  fileref.setAttribute("src", filename)
//  fileref.setAttribute("id", "ki_loader")
// }
// else if (filetype=="css"){ //if filename is an external CSS file
//  var fileref=document.createElement("link")
//  fileref.setAttribute("rel", "stylesheet")
//  fileref.setAttribute("type", "text/css")
//  fileref.setAttribute("href", filename)
// }
// if (typeof fileref!="undefined")
//  document.getElementsByTagName("head")[0].appendChild(fileref)
//}

var Autocomplete = function(el, options){
  if ($(el) == undefined){
      return false;
  }
  this.el = $(el);
  this.id = this.el.identify();
  this.el.setAttribute('autocomplete','off');
  this.suggestions = [];
  this.data = [];
  this.badQueries = [];
  this.selectedIndex = -1;
  this.currentValue = this.el.value;
  this.intervalId = 0;
  this.cachedResponse = [];
  this.instanceId = null;
  this.onChangeInterval = null;
  this.ignoreValueChange = false;
  this.serviceUrl = options.serviceUrl;
  this.options = {
    autoSubmit:false,
    minChars:1,
    maxHeight:300,
    deferRequestBy:0,
    width:0,
    container:null
  };
  if(options){Object.extend(this.options, options);}
  if(Autocomplete.isDomLoaded){
    this.initialize();
  }else{
    Event.observe(document, 'dom:loaded', this.initialize.bind(this), false);
  }
};

Autocomplete.instances = [];
Autocomplete.isDomLoaded = false;

Autocomplete.getInstance = function(id){
  var instances = Autocomplete.instances;
  var i = instances.length;
  while(i--){if(instances[i].id === id){return instances[i];}}
};

Autocomplete.highlight = function(value, re){
  return value.replace(re, function(match){return '<strong>' + match + '<\/strong>'});
};

Autocomplete.prototype = {

  killerFn: null,

  initialize: function() {
    var me = this;
    this.killerFn = function(e) {
      if (!$(Event.element(e)).up('.autocomplete')) {
        me.killSuggestions();
        me.disableKillerFn();
      }
    } .bindAsEventListener(this);

    if (!this.options.width) {this.options.width = this.el.getWidth();}

    var div = new Element('div', {style: 'position:absolute;'});
    div.update('<div class="autocomplete-w1"><div class="autocomplete-w2"><div class="autocomplete" id="Autocomplete_' + this.id + '" style="display:none; width:' + this.options.width + 'px;"></div></div></div>');

    this.options.container = $(this.options.container);
    if (this.options.container) {
      this.options.container.appendChild(div);
      this.fixPosition = function() { };
    } else {
      document.body.appendChild(div);
    }

    this.mainContainerId = div.identify();
    this.container = $('Autocomplete_' + this.id);
    this.fixPosition();

    Event.observe(this.el, window.opera ? 'keypress':'keydown', this.onKeyPress.bind(this));
    Event.observe(this.el, 'keyup', this.onKeyUp.bind(this));
    Event.observe(this.el, 'blur', this.enableKillerFn.bind(this));
    Event.observe(this.el, 'focus', this.fixPosition.bind(this));
    this.container.setStyle({maxHeight: this.options.maxHeight + 'px'});
    this.instanceId = Autocomplete.instances.push(this) - 1;
  },

  fixPosition: function() {
    var offset = this.el.cumulativeOffset();
    $(this.mainContainerId).setStyle({top: (offset.top + this.el.getHeight()) + 'px', left: offset.left + 'px'});
  },

  enableKillerFn: function() {
    Event.observe(document.body, 'click', this.killerFn);
  },

  disableKillerFn: function() {
    Event.stopObserving(document.body, 'click', this.killerFn);
  },

  killSuggestions: function() {
    this.stopKillSuggestions();
    this.intervalId = window.setInterval(function() {this.hide();this.stopKillSuggestions();} .bind(this), 300);
  },

  stopKillSuggestions: function() {
    window.clearInterval(this.intervalId);
  },

  onKeyPress: function(e) {
    if (!this.enabled) {return;}
    // return will exit the function
    // and event will not fire
    switch (e.keyCode) {
      case Event.KEY_ESC:
        this.el.value = this.currentValue;
        this.hide();
        break;
      case Event.KEY_TAB:
      case Event.KEY_RETURN:
        if (this.selectedIndex === -1) {
          this.hide();
          return;
        }
        this.select(this.selectedIndex);
        if (e.keyCode === Event.KEY_TAB) {return;}
        break;
      case Event.KEY_UP:
        this.moveUp();
        break;
      case Event.KEY_DOWN:
        this.moveDown();
        break;
      default:
        return;
    }
    Event.stop(e);
  },

  onKeyUp: function(e) {
    switch (e.keyCode) {
      case Event.KEY_UP:
      case Event.KEY_DOWN:
        return;
    }
    clearInterval(this.onChangeInterval);
    if (this.currentValue !== this.el.value) {
      if (this.options.deferRequestBy > 0) {
        // Defer lookup in case when value changes very quickly:
        this.onChangeInterval = setInterval((function() {
          this.onValueChange();
        }).bind(this), this.options.deferRequestBy);
      } else {
        this.onValueChange();
      }
    }
  },

  onValueChange: function() {
    clearInterval(this.onChangeInterval);
    this.currentValue = this.el.value;
    this.selectedIndex = -1;
    if (this.ignoreValueChange) {
      this.ignoreValueChange = false;
      return;
    }
    if (this.currentValue === '' || this.currentValue.length < this.options.minChars) {
      this.hide();
    } else {
      this.getSuggestions();
    }
  },

  getSuggestions: function() {
    var cr = this.cachedResponse[this.currentValue];
    if (cr && Object.isArray(cr.suggestions)) {
      this.suggestions = cr.suggestions;
      this.data = cr.data;
      this.suggest();
    } else if (!this.isBadQuery(this.currentValue)) {
      new Ajax.Request(this.serviceUrl, {
        parameters: {query: this.currentValue},
        onComplete: this.processResponse.bind(this),
        method: 'get'
      });
    }
  },

  isBadQuery: function(q) {
    var i = this.badQueries.length;
    while (i--) {
      if (q.indexOf(this.badQueries[i]) === 0) {return true;}
    }
    return false;
  },

  hide: function() {
    this.enabled = false;
    this.selectedIndex = -1;
    this.container.hide();
  },

  suggest: function() {
    if (this.suggestions.length === 0) {
      this.hide();
      return;
    }
    var content = [];
    var re = new RegExp('\\b' + this.currentValue.match(/\w+/g).join('|\\b'), 'gi');
    this.suggestions.each(function(value, i) {
          content.push((this.selectedIndex === i ? '<div class="selected"' : '<div'), ' title="', value, '" onclick="Autocomplete.instances[', this.instanceId, '].select(', i, ');" onmouseover="Autocomplete.instances[', this.instanceId, '].activate(', i, ');">', Autocomplete.highlight(value, re), '</div>');
    } .bind(this));
    var i = this.suggestions.length;


    //Here we insert the add non-supported school option
    //content.push('<div onmouseover="Autocomplete.instances['+this.instanceId+'].activate('+i+');" onclick="alert(\'Enter name of school\');" title="Click here if school isn\'t listed">Click here if school isn\'t listed</div>');



    this.enabled = true;
    this.container.update(content.join('')).show();
  },

  processResponse: function(xhr) {
    var response;
    try {
      response = xhr.responseText.evalJSON();
      if (!Object.isArray(response.data)) {response.data = [];}
    } catch (err) {return;}
    this.cachedResponse[response.query] = response;
    if (response.suggestions.length === 0) {this.badQueries.push(response.query);}
    if (response.query === this.currentValue) {
      this.suggestions = response.suggestions;
      this.data = response.data;
      this.suggest();
    }
  },

  activate: function(index) {
    var divs = this.container.childNodes;
    var activeItem;
    // Clear previous selection:
    if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
      divs[this.selectedIndex].className = '';
    }
    this.selectedIndex = index;
    if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
      activeItem = divs[this.selectedIndex]
      activeItem.className = 'selected';
    }
    return activeItem;
  },

  deactivate: function(div, index) {
    div.className = '';
    if (this.selectedIndex === index) {this.selectedIndex = -1;}
  },

  select: function(i) {
    var selectedValue = this.suggestions[i];
    if (selectedValue) {
      this.el.value = selectedValue;
      if (this.options.autoSubmit && this.el.form) {
        this.el.form.submit();
      }
      this.ignoreValueChange = true;
      this.hide();
      this.onSelect(i);
    }
  },

  moveUp: function() {
    if (this.selectedIndex === -1) {return;}
    if (this.selectedIndex === 0) {
      this.container.childNodes[0].className = '';
      this.selectedIndex = -1;
      this.el.value = this.currentValue;
      return;
    }
    this.adjustScroll(this.selectedIndex - 1);
  },

  moveDown: function() {
    if (this.selectedIndex === (this.suggestions.length - 1)) {return;}
    this.adjustScroll(this.selectedIndex + 1);
  },

  adjustScroll: function(i) {
    var container = this.container;
    var activeItem = this.activate(i);
    var offsetTop = activeItem.offsetTop;
    var upperBound = container.scrollTop;
    var lowerBound = upperBound + this.options.maxHeight - 25;
    if (offsetTop < upperBound) {
      container.scrollTop = offsetTop;
    } else if (offsetTop > lowerBound) {
      container.scrollTop = offsetTop - this.options.maxHeight + 25;
    }
    this.el.value = this.suggestions[i];
  },

  onSelect: function(i) {
    (this.options.onSelect || Prototype.emptyFunction)(this.suggestions[i], this.data[i]);
  }

};

Event.observe(document, 'dom:loaded', function(){Autocomplete.isDomLoaded = true;}, false);







/*autosize textbox*/

if (window.Widget == undefined) window.Widget = {};

Widget.Textarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    this.options = $H({ }).update(options);

// Disable scroll bars and Safari resizing.
this.textarea.setStyle({overflowY: 'hidden', resize: 'none', visibility: 'visible'});

// See notes above.
this.original_height = parseInt(this.textarea.getStyle('height'));

// Used to store the scroll offset of the shadow textarea so that we only
// need to do a resize if there's a change to this value.
this.previous_scroll_top = 0;

// Clone the textarea and copy any styles that will affect the amount of
// space consumed by text.
this._shadow = this.textarea.cloneNode(false).setStyle({
lineHeight: this.textarea.getStyle('lineHeight'),
fontSize: this.textarea.getStyle('fontSize'),
fontFamily: this.textarea.getStyle('fontFamily'),
letterSpacing: this.textarea.getStyle('letterSpacing'),
width: this.textarea.getStyle('width'),
height: this.textarea.getStyle('height'),
position: 'absolute',
visibility: 'visible',
top: '-10000px',
left: '-10000px'
}).writeAttribute({id: null, name: null, disabled: true});
//alert(this.textarea.getStyle('width'));
    this.textarea.insert({after: this._shadow});

// Could also fire on keydown, but I don't have a strong enough reason to
// do so at present. We'd be doubling the number of calls to refresh().
    this.textarea.observe('keyup', this.refresh.bind(this));
this.textarea.observe('change', this.refresh.bind(this));
this.refresh();
  },

  refresh: function()
  {
// Update the shadow textarea and scroll to the bottom.
    this._shadow.update($F(this.textarea).replace(/</g, '&lt;').replace(/&/g, '&amp;')).scrollTop = 10000;
    // Do nothing if the scroll offset hasn't changed.
    if(this._shadow.scrollTop == this.previous_scroll_top) {return;}

    this.textarea.setStyle({
    height: (this._shadow.scrollTop + this.original_height) + 'px'
    });

    this.previous_scroll_top = this._shadow.scrollTop;
  }
});




function in_array(arr, value){
    for (var i = 0; i < arr.length; i++){
        if (arr[i] == value){
            return i;
        }
    }
    return false;
}

function get_college_cnt(){
    return $('rb_college_cnt').value;
}

function set_college_cnt(value){
    $('rb_college_cnt').value = value;
}

function get_degree_cnt(college_id){
    return parseInt($('rb_college_'+college_id+'_degree_cnt').value);
}

function set_degree_cnt(college_id, value){
    $('rb_college_'+college_id+'_degree_cnt').value = value;
}

function get_major_cnt(college_id, degree_id){
    //alert('rb_college_'+college_id+'_d'+degree_id+'_major_cnt');
    return parseInt($('rb_college_'+college_id+'_d'+degree_id+'_major_cnt').value);
}

function set_major_cnt(college_id, degree_id, value){
    $('rb_college_'+college_id+'_d'+degree_id+'_major_cnt').value = value;
}

function get_minor_cnt(college_id, degree_id){
    //alert('rb_college_'+college_id+'_d'+degree_id+'_major_cnt');
    return parseInt($('rb_college_'+college_id+'_d'+degree_id+'_minor_cnt').value);
}

function set_minor_cnt(college_id, degree_id, value){
    $('rb_college_'+college_id+'_d'+degree_id+'_minor_cnt').value = value;
}

function get_high_school_cnt(){
    return parseInt($('rb_hs_cnt').value);
}

function set_high_school_cnt(value){
    $('rb_hs_cnt').value = value;
}

function get_test_cnt(){
    return parseInt($('rb_st_cnt').value);
}

function set_test_cnt(value){
    $('rb_st_cnt').value = value;
}

function get_organization_cnt(){
    return parseInt($('rb_organization_cnt').value);
}

function set_organization_cnt(value){
    $('rb_organization_cnt').value = value;
}



function observeForm(input_wrapper_id, submit_form_id, url){
    return null;
    var a = new Array();var i = 0;
    $$("#"+input_wrapper_id+" input").each(
        function(input){
            a[i] = new inputAjaxObject(input, $(submit_form_id), url);
            a[i].observe();
            i++;
        }
    );
    $$("#"+input_wrapper_id+" textarea").each(
        function(input){
            a[i] = new inputAjaxObject(input, $(submit_form_id), url);
            a[i].observe();
            i++;
        }
    );
    

}

function inputObject(input_obj, default_text, type, changed){

    var self = this;

    

    this.input_obj = input_obj;
    this.default_text = default_text;
    this.type = type;
    if (changed !== undefined){
        this.changed = changed;
    } else {
        this.changed = false;
    }

    this.focus_color = 'black';
    this.blur_color = '#555555';
    this.highlight_color = '#fffbba';

    this.clear_hl_focus_fx = function(){
        if (!self.changed){
            self.clear_default_text();
            self.set_highlight();
        }
        self.input_obj.style.color = self.focus_color;
        
    }

    this.clear_hl_blur_fx = function(){
        if (self.input_obj.value != ''){
            //if the type isset and input passes, set true
            if (self.type != null){
                if (self.check_input(self.type, self.input_obj.value)){
                    self.changed = true;
                } else {
                    self.input_obj.value = '';
                    self.changed = false;
                }
            } else {
                self.changed = true;
            }
            
        } else {
            self.changed = false;
        }


        if (!self.changed){
            self.clear_default_text();
            self.set_highlight('#ff9898');

        }
        self.input_obj.style.color = self.blur_color;
        //alert('blur_fx');
    }




    this.observe = function(){
        if (self.input_obj.value == ''){
            self.input_obj.value = self.default_text;
        }

        

        self.input_obj.style.color = self.blur_color;
        self.focus_bind = self.clear_hl_focus_fx.bindAsEventListener();
        self.blur_bind = self.clear_hl_blur_fx.bindAsEventListener();

        Event.stopObserving(self.input_obj, 'focus', self.focus_bind);
        Event.stopObserving(self.input_obj, 'blur', self.blur_bind);
        Event.observe(self.input_obj, 'focus', self.focus_bind);
        Event.observe(self.input_obj, 'blur', self.blur_bind);
        self.set_highlight();
        //make sure that content isnt null!
//        if(self.input_obj.readAttribute('title') != null){
//            new Tip(self.input_obj, self.input_obj.readAttribute('title'), {
//              title: 'Resume Tip',
//              stem: false,
//              hook: { tip: 'topRight', target: 'topLeft'},
//              offset: { x: -10, y: 0 },
//              hideOthers: true,
//              hideOn: { element: 'closeButton', event: 'click' },
//              showOn: 'focus'
//            });
//        }
        
        //self.input_obj.writeAttribute('title', false);
        //new Tooltip(self.input_obj, {backgroundColor: '#fffdc4', borderColor: '#f4f42a', maxWidth: 350, opacity: .90});
    }

    this.clear_default_text = function(){
        var obj = self.input_obj;
        var defaultText = self.default_text;

        if (obj.value==defaultText){
            obj.value='';
        } else if (obj.value==''){
            obj.value=defaultText;
        }
    }

    this.set_highlight =  function(color){
        var obj = self.input_obj;
        var defaultText = self.default_text;

        if (!self.changed && obj.value == defaultText){
            if (color !== undefined){
                obj.style.backgroundColor = color;
            } else {
                obj.style.backgroundColor = self.highlight_color;
            }

        } else {
            obj.style.backgroundColor = '';
        }
    }

    this.check_input = function(type, value){
        switch(type){
            case 'email_input':
                var emailPattern = /^((\w+\+*\-*)+\.?)+@((\w+\+*\-*)+\.?)*[\w-]+\.[a-z]{2,6}$/i;
                return emailPattern.test(value);
                break;
            case 'phone_input':
                var phoneRE = /^\(\d{3}\) \d{3}-\d{4}$/;
                var phoneRE2 = /^\d{3}-\d{3}-\d{4}$/;
                if (value.match(phoneRE) || value.match(phoneRE2)){
                    return true;
                } else {
                    return false;
                }
                break;
            case 'date':
                /*
                 * if end year is greater than start year, return true
                 * else if end year == start year && end month > start month, return true
                 * else return false
                 *
                 */

                break;

            case 'city_state':
                var cityStatePattern = /^[a-z]+, [a-z]+/;
                return cityStatePattern.test(value);
                break;
        }
        return true;
    }

}

function inputAjaxObject(input_obj, form_obj, url){


    var self = this;

    input_obj.stopObserving('change', self.ajax);

    this.input_obj = input_obj;
    this.form_obj = form_obj;
    this.url = url;


    this.observe = function(){
        Event.stopObserving(self.input_obj, 'change', self.ajax);
        Event.observe(self.input_obj, 'change', self.ajax);
    }

    this.ajax = function() {
        new Ajax.Request(self.url, {
            method: 'post',
            parameters: self.form_obj.serialize(true)
        });
    }

}



function educationObject(){
    /*
     * Manages colleges, high schools, and test scores objects
     *
     * this should keep track of global counters and any education objects
     *
     */


}

function collegeObject(college_id, college_data_exists, is_college_set){

    var self = this;

    this.degree_id = 0;
    
    this.college_id = college_id;
    this.college_object_id = 'college_object_'+self.college_id;
    //this is where we insert the college node
    this.education_form = $('form_education');
    this.education_hidden_form = $('college_hidden_info');
    this.add_college_button_id = 'add_college_network_'+self.college_id;
    this.college_search_input_id = 'college_'+self.college_id+'_network_search';
    this.college_selection_id = 'college_'+self.college_id+'_id_selection';
    this.college_selection_wrapper_id = 'rb_college_'+self.college_id+'_id_wrapper';
    this.edit_degree_button_id = 'college_major_display_wrapper'+self.college_id+'_'+self.degree_id;


    this.typeahead_url = ''+window.ra_app_dir+'core/db/actions/typeahead_college.php';
    this.typeahead_degree_url = ''+window.ra_app_dir+'core/db/actions/typeahead_degree.php';
    
    if (is_college_set !== undefined){
        this.is_college_set = is_college_set;
    } else {
        this.is_college_set = false;
    }
    
    if (college_data_exists !== undefined){
        this.college_data_exists = college_data_exists;
    } else {
        this.college_data_exists = false;
    }



    this.college_node_html = '<div class="college_object_wrapper" id="college_object_'+self.college_id+'" style="display: none;">\n\
                                    <div class="selection_wrapper">\n\
                                        <div class="college_selection_wrapper" id="rb_college_'+self.college_id+'_id_wrapper">\n\
                                            <div class="add_object_button" id="add_college_network_'+self.college_id+'">\n\
                                                <div class="add_button_left"></div><div class="add_button_middle" style="font-size: 14px">Add a college</div><div class="add_button_right"></div>\n\
                                            </div>\n\
                                            <input type="text" id="college_'+self.college_id+'_network_search" name="college_'+self.college_id+'_network_search" class="college_network_search_input" style="display: none;"/>\n\
                                        </div>\n\
                                    </div>\n\
                                </div>';

    
    this.edit_degree = function(){
        var degree_id = 0;
        var edit_degree_button_id = self.edit_degree_button_id;
        var edit_degree_wrapper = 'college_major_edit_wrapper'+self.college_id+'_'+degree_id;
        var finish_button = 'college_major_edit_finish'+self.college_id+'_'+degree_id;
        var degree_input_id = 'rb_college_'+self.college_id+'_d'+degree_id+'_degree_type';

        new Autocomplete(degree_input_id, {
            serviceUrl:self.typeahead_degree_url,
            minChars:2,
            maxHeight:400,
            width:300,
            deferRequestBy:100,
            onSelect: function(value, data){
//                alert(data[0]);
                $(degree_input_id).value = data[0];
            }
        });


        

        var hide_edit = function(){
            var degree_title = self.calc_new_degree_string();
            var default_degree_title = '(Enter degree type here) Example: B.S. or B.A.';
            $(edit_degree_button_id).innerHTML = degree_title;
//            alert(degree_title.substr(0, default_degree_title.length));
//            alert(default_degree_title);
            if (degree_title.substr(0, default_degree_title.length) == default_degree_title){
                $(edit_degree_button_id).style.backgroundColor = '#FFFBBA';
            } else {
                $(edit_degree_button_id).style.backgroundColor = '';
            }

            Effect.BlindUp(edit_degree_wrapper);
            $(edit_degree_button_id).show();
        }

        var show_edit = function(){
            Effect.BlindDown(edit_degree_wrapper);
            $(finish_button).observe('click', hide_edit);
            $(edit_degree_button_id).hide();
        }

//        var auto_hide = function(event){
//            var elem = event.element;
//            if (elem.readAttribute('id') == edit_degree_wrapper){
//                hide_edit();
//            }
//        }

        $(edit_degree_button_id).observe('click', show_edit);

//        $(edit_degree_wrapper).observe('click', );

    }

    this.calc_new_degree_string = function(){
        var degree_id = 0;
        var degree = $('rb_college_'+self.college_id+'_d'+degree_id+'_degree_type');
        var majors = $$('#college_major_wrapper'+self.college_id+'_'+degree_id+' .college_major_input');
        var minors = $$('#college_minor_wrapper'+self.college_id+'_'+degree_id+' .college_minor_input');
        var major_str = '';
        var minor_str = '';

        var major_list_suffix = '';
        var minor_list_suffix = '';

        if (degree.value.toLowerCase() == 'Attended'.toLowerCase()){
            return degree.value;
        }


        var temp_majors = [];
        majors.each(function(textarea){
            if (textarea.readAttribute('name') != null){
                temp_majors.push(textarea);
            }
        });
        majors = temp_majors;

        var temp_minors = [];
        minors.each(function(textarea){
            if (textarea.readAttribute('name') != null){
                temp_minors.push(textarea);
            }
        });
        minors = temp_minors;

        var i;
        for(i=0; i<majors.length; i++){
            if (majors[i].value != '(Click here to add a major)'){
                if (i == majors.length-2){
                    if (majors.length < 3){
                        major_list_suffix = ' and ';
                    } else {
                        major_list_suffix = ', and ';
                    }
                } else {
                    major_list_suffix = ', ';
                }
                major_str += majors[i].value+major_list_suffix;
            }

        }
        for(i=0; i<minors.length; i++){
            if (minors[i].value != '(Click here to add a minor)'){
                if (i == minors.length-2){
                    if (minors.length < 3){
                        minor_list_suffix = ' and ';
                    } else {
                        minor_list_suffix = ', and ';
                    }
                } else {
                    minor_list_suffix = ', ';
                }
                minor_str += minors[i].value+minor_list_suffix;
            }
        }

        major_str = major_str.substr(0, (major_str.length - major_list_suffix.length));
        minor_str = minor_str.substr(0, (minor_str.length - minor_list_suffix.length));


        if (minor_str != ''){
            minor_str = ', minoring in '+minor_str;
        }
        

        if (major_str == ''){
            var final_str = degree.value;
        } else {
            var final_str = degree.value+' in '+major_str+minor_str;
        }



        return final_str;

    }

    this.add_major_node = function(){
        var degree_id = 0;
        var major_cnt = get_major_cnt(self.college_id, degree_id);


        var add_major_button_id = 'majors_header'+self.college_id+'_'+degree_id;
        var major_wrapper_id = 'college_major_wrapper'+self.college_id+'_'+degree_id;
        var add_major_func = function (){
            var degree_id = 0;
            var major_cnt = get_major_cnt(self.college_id, degree_id);
            
            $(major_wrapper_id).insert('<li id="rb_college_'+self.college_id+'_d'+degree_id+'_major_'+major_cnt+'_li" style="display:none;"><input type="text" style="color: rgb(85, 85, 85);" title="" value="(Enter Major Here)" name="rb_college_'+self.college_id+'_d'+degree_id+'_major_'+major_cnt+'" id="rb_college_'+self.college_id+'_d'+degree_id+'_major_'+major_cnt+'" class="college_major_input"/></li>');
            Effect.BlindDown('rb_college_'+self.college_id+'_d'+degree_id+'_major_'+major_cnt+'_li');
            set_major_cnt(self.college_id, degree_id, major_cnt+1);
            observeForm(major_wrapper_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php');
        }
        $(add_major_button_id).observe('click', add_major_func);


    }

    this.add_minor_node = function(){
        var degree_id = 0;
        var minor_cnt = get_minor_cnt(self.college_id, degree_id);


        var add_minor_button_id = 'minors_header'+self.college_id+'_'+degree_id;
        var minor_wrapper_id = 'college_minor_wrapper'+self.college_id+'_'+degree_id;
        var add_minor_func = function (){
            var degree_id = 0;
            var minor_cnt = get_minor_cnt(self.college_id, degree_id);

            $(minor_wrapper_id).insert('<li id="rb_college_'+self.college_id+'_d'+degree_id+'_minor_'+minor_cnt+'_li" style="display:none;"><input type="text" style="color: rgb(85, 85, 85);" title="" value="(Enter minor Here)" name="rb_college_'+self.college_id+'_d'+degree_id+'_minor_'+minor_cnt+'" id="rb_college_'+self.college_id+'_d'+degree_id+'_minor_'+minor_cnt+'" class="college_minor_input"/></li>');
            Effect.BlindDown('rb_college_'+self.college_id+'_d'+degree_id+'_minor_'+minor_cnt+'_li');
            set_minor_cnt(self.college_id, degree_id, minor_cnt+1);
            observeForm(minor_wrapper_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php');
        }
       // $(add_minor_button_id).observe('click', add_minor_func);


    }

    this.add_college_button = function(){
        if (!self.is_college_set){
            $('colleges_section_wrapper').insert(self.college_node_html);
            $(self.add_college_button_id).observe('click', self.college_enable_search);
        } else {
            //$(self.college_selection_id).observe('click', self.college_enable_search);
        }
       

        new Autocomplete(self.college_search_input_id, {
            serviceUrl:self.typeahead_url,
            minChars:3,
            maxHeight:400,
            width:400,
            deferRequestBy:100,
            onSelect: function(value, data){
//                alert(value);
//                alert(data['id']);
                if (data['id'] == 'add_new_school'){
                    var submit_url = ''+window.ra_app_dir+'core/db/actions/add_new_college.php';
                    var form_data = {'college_name' : data['name']};
                    new Ajax.Request(submit_url,
                          {
                            method:'post',
                            parameters: form_data,
                            onComplete: function(transport){
                                var new_data = transport.responseJSON;
//                                alert(new_data['name']);
//                                alert(new_data['id']);
                                self.select_search(new_data['name'], new_data);
                            }
                          });
                } else {
//                    alert(data['name']);
//                    alert(data['name_full']);
                    self.select_search(value, data);
                }
            }
        });

        if (!self.is_college_set){
            $(self.college_object_id).appear();
            set_college_cnt(parseInt(self.college_id)+1);
        }


    }

    this.add_college_form = function(college_name){
        var degree_id = 0;
        var id = self.college_id;
        var html;
        new Ajax.Request(''+window.ra_app_dir+'core/lib/html/get_college_html.php',
          {
            method:'get',
            parameters: {'college_id':id},
            onComplete: function(transport){
              html = transport.responseText;
              $(self.college_object_id).insert(html);
                var a = new collegeObject(id+1, false, false);
                a.add_college_button();

                self.initCollegeEvents();

                
                
                $('rb_college_'+self.college_id+'_dname').value = college_name;
                //new bulletPoint('college_accomplishments_wrapper', 'rb_college_'+self.college_id+'_d'+degree_id+'_ha_cnt', 0, 'rb_college_'+self.college_id+'_d'+degree_id+'_ha_', true, 'college_accomplishment_input').init_bullet_point();
                //new bulletPoint('college_extracurriculars_wrapper', 'rb_college_'+self.college_id+'_d'+degree_id+'_extracurricular_cnt', 0, 'rb_college_'+self.college_id+'_d'+degree_id+'_extracurricular_', true, 'college_extracurricular_input').init_bullet_point();
                //observe the entire form and add ajax watches
                observeForm('college_form_element_'+id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php');
                //initObservers();
                new observerLoader().loadFromWrapper(self.college_object_id);
                setTimeout(function(){
                    Effect.BlindDown('college_form_element_'+id);
                }, 300);
            },
            onFailure: function(){}
          });
          
          //alert(html);

        
    }

    this.college_enable_search = function(){
        if (!self.is_college_set){
            $(self.add_college_button_id).style.display = 'none';
        } else {
            $(self.college_selection_id).style.display = 'none';
        }
        
        $(self.college_search_input_id).style.display = 'block';
        $(self.college_search_input_id).value = 'Start typing the name of your college...';

        var default_text = function(){
            $(self.college_search_input_id).value = '';
            $(self.college_search_input_id).stopObserving('keydown', default_text);
        }
        
        var reset_add_button = function(){
            $(self.add_college_button_id).style.display = 'block';
            $(self.college_search_input_id).style.display = 'none';
            $(self.college_search_input_id).stopObserving('blur', reset_add_button);
        }

        $(self.college_search_input_id).observe('keydown', default_text);
        $(self.college_search_input_id).observe('blur', reset_add_button);

        $(self.college_search_input_id).focus();
        new Effect.Highlight($(self.college_search_input_id), {startcolor: '#A0E345', restorecolor: '#fff'});

    }

    this.select_search = function(value, data){
        $(self.add_college_button_id).stopObserving();
        $(self.add_college_button_id).remove();
        $(self.college_search_input_id).stopObserving();
        $(self.college_search_input_id).remove();

        var id = self.college_id;
        if (!self.college_data_exists){
            self.insert_college_hidden_inputs(self.education_hidden_form, id, data['id']);
        } else {
            $('rb_college_'+id+'_id').value = data['id'];
        }

        var college_name = '';
        if (data['name_full'] != null && data['name_full'] != ''){
            college_name = data['name_full'];
        } else {
            college_name = data['name'];
        }

        if (!self.is_college_set){
//            $(self.college_selection_wrapper_id).insert('<div class="school_selection_link" id="'+self.college_selection_id+'"><b>College: </b>'+college_name+'</div>');
            self.add_college_form(college_name);
            
        } else {
            $(self.college_selection_id).innerHTML = '<b>College: </b>'+college_name+'</div>';
            $(self.college_selection_id).style.display = 'block';
        }
        //$(self.college_selection_id).observe('click', self.college_enable_search);

        //add college form, and create another college_object
        
        self.college_data_exists = true;
        self.is_college_set = true;
    }

    this.insert_college_hidden_inputs = function(parent_obj, id, value){
        //need to set all counts
        parent_obj.insert('<input id="rb_college_'+id+'_id" name="rb_college_'+id+'_id" value="'+value+'" type="hidden"/>');
        parent_obj.insert('<input id="rb_college_'+id+'_degree_cnt" name="rb_college_'+id+'_degree_cnt" value="1"/>');
        parent_obj.insert('<input id="rb_college_'+id+'_d0_major_cnt" name="rb_college_'+id+'_d0_major_cnt" value="1"/>');
        parent_obj.insert('<input id="rb_college_'+id+'_d0_minor_cnt" name="rb_college_'+id+'_d0_minor_cnt" value="1"/>');
        parent_obj.insert('<input id="rb_college_'+id+'_d0_ha_cnt" name="rb_college_'+id+'_d0_ha_cnt" value="1"/>');
        parent_obj.insert('<input id="rb_college_'+id+'_d0_extracurricular_cnt" name="rb_college_'+id+'_d0_extracurricular_cnt" value="1"/>');
        parent_obj.insert('<input id="rb_college_'+id+'_class_cnt" name="rb_college_'+id+'_class_cnt" value="0"/>');
    }

    this.initCollegeEvents = function (){
        new deleteObject(self.college_object_id).init();

        var degree_id = 0;
        //alert('college events init: id = '+self.college_id);
        //self.add_major_node();
        //self.add_minor_node();
        new bulletPoint('college_major_wrapper'+self.college_id+'_'+degree_id, 'rb_college_'+self.college_id+'_d'+degree_id+'_major_cnt', 0, 'rb_college_'+self.college_id+'_d'+degree_id+'_major_', true, 'college_major_input'
                        ,'college_form_element_'+self.college_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();
        new bulletPoint('college_minor_wrapper'+self.college_id+'_'+degree_id, 'rb_college_'+self.college_id+'_d'+degree_id+'_minor_cnt', 0, 'rb_college_'+self.college_id+'_d'+degree_id+'_minor_', true, 'college_minor_input'
                        ,'college_form_element_'+self.college_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();


        var degree_title = self.calc_new_degree_string();
                var default_degree_title = '(Enter degree type here) Example: B.S. or B.A.';
                $(self.edit_degree_button_id).innerHTML = degree_title;
                if (degree_title.substr(0, default_degree_title.length) == default_degree_title){
                    $(self.edit_degree_button_id).style.backgroundColor = '#FFFBBA';
                } else {
                    $(self.edit_degree_button_id).style.backgroundColor = false;
                }
                
        self.edit_degree();
        
        new bulletPoint('college_accomplishments_wrapper'+self.college_id+'_'+degree_id, 'rb_college_'+self.college_id+'_d'+degree_id+'_ha_cnt', 0, 'rb_college_'+self.college_id+'_d'+degree_id+'_ha_', true, 'college_accomplishment_input'
                        ,'college_form_element_'+self.college_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();

        new bulletPoint('college_extracurriculars_wrapper'+self.college_id+'_'+degree_id, 'rb_college_'+self.college_id+'_d'+degree_id+'_extracurricular_cnt', 0, 'rb_college_'+self.college_id+'_d'+degree_id+'_extracurricular_', true, 'college_extracurricular_input'
                        ,'college_form_element_'+self.college_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();

        
    }

    if (self.is_college_set == true){
        self.initCollegeEvents();
    }


}

function highSchoolObject(high_school_id, high_school_data_exists, is_high_school_set){
    /*
     * -add organization
     * get count
     * add organization html
     * blinddown
     * init observers(id)
     * add hidden inputs
     * count++
     *
     */
     var self = this;
     this.high_school_id = high_school_id;
     this.high_school_wrapper_id = 'high_schools_section_wrapper';
     this.hidden_inputs_wrapper_id = 'high_school_hidden_info';


     this.add_high_school = function(){
         var html;
         var high_school_id = get_high_school_cnt();

         new Ajax.Request(''+window.ra_app_dir+'core/lib/html/get_high_school_html.php',
          {
            method:'get',
            parameters: {'high_school_id':high_school_id},
            onCreate: function(){
              var add_org_button_id = 'add_high_school_button';
              $(add_org_button_id).down('.add_button_middle').innerHTML = 'Loading...';
            },
            onComplete: function(transport){
              var add_org_button_id = 'add_high_school_button';
              html = transport.responseText;

              $(self.high_school_wrapper_id).insert(html);
//                var a = new collegeObject(id+1, false, false);
//                a.add_college_button();

                //self.initCollegeEvents();
                observeForm('high_school_object'+high_school_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php');
                //initObservers();
                //alert('high_school_wrapper'+high_school_id);
                new observerLoader().loadFromWrapper('high_school_object'+high_school_id);
                
                self.insert_inputs(high_school_id);
                new deleteObject('high_school_object'+high_school_id).init();
                new bulletPoint('high_school_accomplishments_wrapper'+high_school_id, 'rb_hs_'+high_school_id+'_ha_cnt', 0, 'rb_hs_'+high_school_id+'_ha_', true, 'high_school_accomplishment_input'
                        ,'high_school_accomplishments_wrapper'+high_school_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();
                new bulletPoint('high_school_extracurriculars_wrapper'+high_school_id, 'rb_hs_'+high_school_id+'_extracurricular_cnt', 0, 'rb_hs_'+high_school_id+'_extracurricular_', true, 'high_school_extracurricular_input'
                        ,'high_school_extracurriculars_wrapper'+high_school_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();
                  
                setTimeout(function(){
                    $(add_org_button_id).down('.add_button_middle').innerHTML = 'Add a high school';
                    Effect.BlindDown('high_school_object'+high_school_id);
                    high_school_id++;
                    set_high_school_cnt(high_school_id);
                }, 300);

                  

                

                
            },
            onFailure: function(){}
          });


     }

     this.insert_inputs = function(high_school_id){
         $(self.hidden_inputs_wrapper_id).insert('<input id="rb_hs_'+high_school_id+'_ha_cnt" name="rb_hs_'+high_school_id+'_ha_cnt" value="1" type="hidden"/>');
         $(self.hidden_inputs_wrapper_id).insert('<input id="rb_hs_'+high_school_id+'_extracurricular_cnt" name="rb_hs_'+high_school_id+'_extracurricular_cn" value="1" type="hidden"/>');
     }

     this.init_add_high_school_button = function(){
         var add_org_button_id = 'add_high_school_button';

         $(add_org_button_id).observe('click', function(){
             self.add_high_school();
         });
     }

     this.init = function(){
        var high_school_id = self.high_school_id;
        new deleteObject('high_school_object'+high_school_id).init();
        new bulletPoint('high_school_accomplishments_wrapper'+high_school_id, 'rb_hs_'+high_school_id+'_ha_cnt', 0, 'rb_hs_'+high_school_id+'_ha_', true, 'high_school_accomplishment_input'
            ,'high_school_accomplishments_wrapper'+high_school_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();
        new bulletPoint('high_school_extracurriculars_wrapper'+high_school_id, 'rb_hs_'+high_school_id+'_extracurricular_cnt', 0, 'rb_hs_'+high_school_id+'_extracurricular_', true, 'high_school_extracurricular_input'
            ,'high_school_extracurriculars_wrapper'+high_school_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php').init_bullet_point();
     }




}

function testObject(test_id, is_test_set){
    /*
     * -add organization
     * get count
     * add organization html
     * blinddown
     * init observers(id)
     * add hidden inputs
     * count++
     *
     */
     var self = this;
     this.test_id = test_id;
     this.test_wrapper_id = 'st_section_wrapper_ul';
     this.hidden_inputs_wrapper_id = 'st_hidden_info';
     this.is_test_set = is_test_set;
     this.typeahead_url = ''+window.ra_app_dir+'core/db/actions/typeahead_tests.php'

     this.add_test = function(){
         var html;
         var test_id = get_test_cnt();
         //alert(test_id);
         new Ajax.Request(''+window.ra_app_dir+'core/lib/html/get_test_html.php',
          {
            method:'get',
            parameters: {'test_id':test_id},
            onComplete: function(transport){
              html = transport.responseText;

              $(self.test_wrapper_id).insert(html);
//                var a = new collegeObject(id+1, false, false);
//                a.add_college_button();
                //alert('test_name'+test_id);

                

                $('test_name'+test_id).value = 'Start typing the name of your test...';
                $('test_name'+test_id).focus();
                var reset_fx = function(event){
                    event.element().value = '';
                    event.element().stopObserving('keypress', reset_fx);
                }
                $('test_name'+test_id).observe('keypress', reset_fx);

                self.init_typeahead(test_id);


                observeForm(self.test_wrapper_id, 'form_education', ''+window.ra_app_dir+'core/db/actions/update_education.php');
                //initObservers();
                //alert('test_wrapper'+test_id);
                new observerLoader().loadFromWrapper(self.test_wrapper_id);
                new deleteObject('test_name'+test_id+'_li', 'bullet').init();
                //Effect.BlindDown('test_object'+test_id);
                //self.insert_inputs(test_id);
                  test_id++;
                  set_test_cnt(test_id);
            },
            onFailure: function(){}
          });


     }

     this.init_typeahead = function(test_id){
         new Autocomplete('test_name'+test_id, {
            serviceUrl:self.typeahead_url,
            minChars:3,
            maxHeight:400,
            width:400,
            deferRequestBy:100
        });
     }

     this.insert_inputs = function(test_id){
         $(self.hidden_inputs_wrapper_id).insert('<input id="rb_hs_'+test_id+'_ha_cnt" name="rb_hs_'+test_id+'_ha_cnt" value="1" type="hidden"/>');
         $(self.hidden_inputs_wrapper_id).insert('<input id="rb_hs_'+test_id+'_extracurricular_cnt" name="rb_hs_'+test_id+'_extracurricular_cn" value="1" type="hidden"/>');
     }

     this.init_add_test_button = function(){
         var add_org_button_id = 'add_test_button';

         $(add_org_button_id).observe('click', function(){
             self.add_test();
         });
     }




}

function organizationObject(organization_id, organization_data_exists, is_organization_set){
    /*
     * -add organization
     * get count
     * add organization html
     * blinddown
     * init observers(id)
     * add hidden inputs
     * count++
     *
     */
     var self = this;
     this.organization_id = organization_id;
     this.organization_wrapper_id = 'form_organization';
     this.hidden_inputs_wrapper_id = 'organization_hidden_info';


     this.add_organization = function(){
         var html;
         var organization_id = get_organization_cnt();

         new Ajax.Request(''+window.ra_app_dir+'core/lib/html/get_organization_html.php',
          {
            method:'get',
            parameters: {'organization_id':organization_id},
            onComplete: function(transport){
              html = transport.responseText;
              
              $(self.organization_wrapper_id).insert(html);
//                var a = new collegeObject(id+1, false, false);
//                a.add_college_button();

                //self.initCollegeEvents();
                observeForm('organization_wrapper'+organization_id, self.organization_wrapper_id, ''+window.ra_app_dir+'core/db/actions/update_organization.php');
                //initObservers();
                //alert('organization_wrapper'+organization_id);
                new observerLoader().loadFromWrapper('organization_wrapper'+organization_id);
                Effect.BlindDown('organization_wrapper'+organization_id);
                new deleteObject('organization_wrapper'+organization_id).init();
                self.insert_inputs(organization_id, 0);
                new bulletPoint('organization_responsibility_wrapper'+organization_id+'_0', 'rb_organization_'+organization_id+'_p0_bullet_cnt', 0, 'rb_organization_'+organization_id+'_p0_bullet_', true, 'organization_responsibility_input'
                        ,'organization_responsibility_wrapper'+organization_id+'_0', 'form_organization', ''+window.ra_app_dir+'core/db/actions/update_organization.php').init_bullet_point();
                  organization_id++;
                  set_organization_cnt(organization_id);
               
            },
            onFailure: function(){}
          });
          

     }

     this.insert_inputs = function(organization_id, position_id){
         $(self.hidden_inputs_wrapper_id).insert('<input id="rb_organization_'+organization_id+'_position_cnt" name="rb_organization_'+organization_id+'_position_cnt" value="1" type="hidden"/>');
         $(self.hidden_inputs_wrapper_id).insert('<input id="rb_organization_'+organization_id+'_p'+position_id+'_bullet_cnt" name="rb_organization_'+organization_id+'_p'+position_id+'_bullet_cnt" value="1" type="hidden"/>');
     }

     this.init_add_organization_button = function(){
         var add_org_button_id = 'add_organization_button';

         $(add_org_button_id).observe('click', function(){
             self.add_organization();
         });
     }

     this.init = function(){
         var organization_id = self.organization_id;
         new bulletPoint('organization_responsibility_wrapper'+organization_id+'_0', 'rb_organization_'+organization_id+'_p0_bullet_cnt', 0, 'rb_organization_'+organization_id+'_p0_bullet_', true, 'organization_responsibility_input'
                        ,'organization_responsibility_wrapper'+organization_id+'_0', 'form_organization', ''+window.ra_app_dir+'core/db/actions/update_organization.php').init_bullet_point();
         new deleteObject('organization_wrapper'+self.organization_id).init();
     }




}

function bulletPoint(wrapper_id, counter_id, position, elem_id, is_set, html_class, form_wrapper_id, form_id, submit_url){

    var self = this;
    this.wrapper_id = wrapper_id;
    this.counter_id = counter_id;
    this.counter = parseInt($(counter_id).value);
    this.position = position;
    this.elem_id = elem_id;
    if (is_set !== undefined){
        this.is_set = is_set;
    } else {
        this.is_set = false;
    }
    this.html_class = html_class;
    this.form_wrapper_id = form_wrapper_id;
    this.form_id = form_id;
    this.submit_url = submit_url;


    this.add_bullet_point = function(){
        //var position = self.position
        var html = '<li id="'+self.elem_id+(parseInt($(self.counter_id).value))+'_li"><textarea id="'+self.elem_id+(parseInt($(self.counter_id).value))+'" name="'+self.elem_id+(parseInt($(self.counter_id).value))+'" class="'+self.html_class+'"></textarea></li>';

        $(self.wrapper_id).insert(html);

        self.update_bullet_point(self.elem_id+($(self.counter_id).value)+'_li');
        $(self.counter_id).value = parseInt($(self.counter_id).value) + 1;
    }

    this.update_bullet_point = function(li_id){
        /*
         *  add delete node
         */

        new observerLoader().loadFromWrapper(self.wrapper_id);
        observeForm(self.form_wrapper_id, self.form_id, self.submit_url);
        new deleteObject(li_id, 'bullet').init();
    }

    this.init_bullet_points = function(){
        $$('#'+self.wrapper_id+' li').each(function(li){
            new deleteObject(li.readAttribute('id'), 'bullet').init();
        });
        new observerLoader().loadFromWrapper(self.wrapper_id);
        observeForm(self.form_wrapper_id, self.form_id, self.submit_url);
    }


    this.init_bullet_point = function(){
        var button_id = self.wrapper_id + '_add_button';
        if ($(button_id) == undefined){
            alert(button_id);return false;
        }
        self.init_bullet_points();
        $(button_id).observe('click', self.add_bullet_point);
    }


}

function deleteObject(elem_id, style){
    
    var self = this;
    this.elem_id = elem_id;
    this.delete_button_wrapper_id = elem_id+'_delete';
    this.delete_button;
    this.style = style;


    this.insert_delete_button = function(){
        switch (self.style){

            case 'bullet':
                var html = '<div id="'+self.delete_button_wrapper_id+'" class="delete_object_button_bullet">'+
                    '<img src="'+window.ra_img_url+'delete_bullet.png"/>'+
                    '</div>';
                break;
            default :
                var html = '<div id="'+self.delete_button_wrapper_id+'" class="delete_object_button">'+
                    '<img src="'+window.ra_img_url+'delete.png"/>'+
                    '</div>';
                break;

        }
        
        $(self.elem_id).insert(html);
    }

    this.delete_object = function(){
        if ($(self.elem_id).prototip != undefined){
            $(self.elem_id).prototip.remove();
        }
        if ($(self.elem_id).down('input') != undefined){
            if ($(self.elem_id).down('input').prototip != undefined){
                $(self.elem_id).down('input').prototip.remove();
            }
        }
        if ($(self.elem_id).down('textarea') != undefined){
            if ($(self.elem_id).down('textarea').prototip != undefined){
                $(self.elem_id).down('textarea').prototip.remove();
            }
        }

        $(self.elem_id).stopObserving();
        $(self.delete_button_wrapper_id).stopObserving();
        new Effect.Opacity(self.elem_id,{to: 0, duration: 0.3});
        setTimeout(function(){
            $(self.elem_id).remove();
        }, 600);
    }

    this.display_button = function(){
        $(self.delete_button_wrapper_id).style.display = 'block';
    }

    this.hide_button = function(){
        $(self.delete_button_wrapper_id).style.display = 'none';
    }


    this.init = function(){
        if ($(self.elem_id) == undefined){
            alert(self.elem_id);return false;
        }
        $(self.elem_id).setStyle({position : 'relative'});
        self.insert_delete_button();

        self.delete_button = $(self.delete_button_wrapper_id).down('img');

        $(self.elem_id).observe('mouseover', self.display_button);

        $(self.elem_id).observe('mouseout', self.hide_button);

        $(self.delete_button_wrapper_id).observe('mouseover', self.display_button);

        $(self.delete_button_wrapper_id).observe('mouseout', self.hide_button);

        self.delete_button.observe('click', self.delete_object);
    }


}


function disable_tips(){
    $$('input').each(function(input){
        Tips.remove(input);
    });

    $$('textarea').each(function(input){
        Tips.remove(input);
    });
}

function remove_empty_bullets(){
    $$('#form_wrapper li input').each(function(input){
        if (input.value == ''){
            var li = input.up('li');
            if (li != undefined){
                li.remove();
            }
        }
    });

    $$('#form_wrapper li textarea').each(function(input){
        if (input.value == ''){
            var li = input.up('li');
            if (li != undefined){
                li.remove();
            }
        }
    });

    for (var i = 1; i < 5; i++){
        if ($$('#skills_row'+i+' li').length == 0){
            $('skills_row'+i).remove();
        }
    }


}

function remove_empty_sections(){
    if ($('objective_input').value == ''){
        $('objective_wrapper').remove();
    }

    var education_delete_cnt = 0;
    if($$('div#colleges_section_wrapper div.college_object_wrapper').length == 0){
        $('colleges_section_wrapper').remove();
        education_delete_cnt++;
    }

    if($$('div#high_schools_section_wrapper div.college_object_wrapper').length == 0){
        $('high_schools_section_wrapper').remove();
        education_delete_cnt++;
    }

    if($$('#st_section_wrapper_ul li').length == 0){
        $('st_section_wrapper').remove();
        education_delete_cnt++;
    }

    if (education_delete_cnt == 3){
        $('education_wrapper').remove();
    }

    if($$('#form_organization div.organization_wrapper').length == 0){
        $('experience_wrapper').remove();
    }

    if($$('#skills_section li').length == 0){
        $('skills_wrapper').remove();
    }

}


function disable_edit_mode(){
    disable_tips();
    $$('input').each(function(input){
        input.stopObserving();
        //input.writeAttribute('disabled', 'true');
//        input.disabled = true;
        input.readOnly = true;
        input.setStyle({color: '#000', cursor: 'pointer'});
    });

    $$('textarea').each(function(textarea){
        textarea.stopObserving();
        textarea.readOnly = true;
//        textarea.writeAttribute('disabled', 'true');
//        textarea.disabled = true;
        textarea.setStyle({color: '#000', cursor: 'pointer'});
    });

    $$('.add_object_button').each(function(button){
        button.remove();
    });


//    $('add_high_school_button').remove();
//    $('add_test_button').remove();
//    $('add_organization_button').remove();
//    $$('.selection_wrapper').each(function(college_network){
//        college_network.style.display = 'none';
//    });

        $$('#form_wrapper textarea').each(function(textarea) {
          new Widget.Textarea(textarea);
        });

    $$('div.college_major_wrapper').each(function(degree){
        degree.style.color = "#000000";
    });

   

//    if($$('.organization_wrapper').length == 0){
//        $('experience_wrapper').remove();
//    }


    /*
     * Remove all buttons here
     */
}

function scrollListObject(){
    
    var self = this;

    this.toggle_list_button_id = 'toggle_comments_list_button';
    this.hover_fx_id = 'commenter_bar_wrapper';
    this.list_wrapper_id = 'commenter_list_wrapper';
    this.prev_button_id = 'commenter_prev_button';
    this.next_button_id = 'commenter_next_button';

    this.last_node_selected = null;
    this.head_node = null;
    this.tail_node = null;
    this.display_max = 3;

    this.is_list_enabled = true;


    this.toggleTips = function(event){
        if (event.element().readAttribute('class') != 'author_wrapper'){
            var elem = event.element().up('li');
        } else {
            var elem = event.element();
        }
        

//        if (self.last_node_selected != null){
//            alert(self.last_node_selected.readAttribute('id'));
//        } else {
//            alert('null');
//        }
        Tips.hideAll();


        if (self.last_node_selected != null && elem.readAttribute('id') == self.last_node_selected.readAttribute('id')){
            self.unselect(elem);
        } else if (self.last_node_selected != null && elem.readAttribute('id') != self.last_node_selected.readAttribute('id')){
            self.unselect(self.last_node_selected);
            self.select(elem);
        } else if (self.last_node_selected == null){
            self.select(elem)
        }

    }

    this.select = function(elem){
        //show tooltips for elem
        //Tips.hideAll();
        self.decorate(elem, 'select');
        self.last_node_selected = elem;
    }

    this.unselect = function(elem){
        //hide tooltips for elem
        self.decorate(elem, 'unselect');
        self.last_node_selected = null;
    }

    this.decorate = function(elem, style){
        switch (style){
            case 'select':
                elem.setStyle({border: '5px solid #8cc63e'});
                break;

            case 'unselect':
                elem.setStyle({border: '5px solid #CCCCCC'});
                break;
        }
    }
    
    this.hide_tips = function(){
        Tips.hideAll();
    }

    this.scroll = function(direction){
        switch (direction){
            case 'down':
                if (self.tail_node.next('li') !== undefined && self.is_scrollable()){
                    new Effect.SlideUp(self.head_node, {duration: 0.4});
                    self.shift_nodes('down');
                }
                break;
            case 'up':
                if (self.head_node.previous('li') !== undefined && self.is_scrollable()){
                    new Effect.SlideDown(self.head_node.previous('li'), {duration: 0.4});
                    self.shift_nodes('up');
                }
                break;
        }
    }
    
    this.shift_nodes = function(direction){
        if (direction == 'up'){
            self.head_node = self.head_node.previous('li');
            self.tail_node = self.tail_node.previous('li');
        } else if (direction == 'down'){
            self.head_node = self.head_node.next('li');
            self.tail_node = self.tail_node.next('li');
        }
    }

    this.is_scrollable = function(){
        var li_size = $$('#'+self.list_wrapper_id+' li').length;

        if (li_size <= self.display_max){
            return false;
        } else {
            return true;
        }
    }
    
    this.toggle_list = function(){
//        if (window.ra_last_tab != 'form_wrapper'){
//            return false;
//        }
        if (self.is_list_enabled){
            self.disable_list();
        } else {
            self.enable_list();
        }
    }

    this.enable_list = function(){
        Tips.hideAll();
        new Effect.Appear(self.hover_fx_id, {to: 1, duration: 0.6});
        self.is_list_enabled = true;
        //show 'disable' on toggle_commenter_bar
        $(self.toggle_list_button_id).down('.menu_bar_button_middle').innerHTML = 'Hide Comments';
    }

    this.disable_list = function(){
        Tips.hideAll();
        new Effect.Fade(self.hover_fx_id, {to: 0, duration: 0.6});
        self.is_list_enabled = false;
        if (self.last_node_selected != null){
            self.unselect($(self.last_node_selected));
        }
        //show 'Enable' on toggle_commenter_bar
        $(self.toggle_list_button_id).down('.menu_bar_button_middle').innerHTML = 'Show Comments';
    }

    this.init = function(){
        self.head_node = $(self.list_wrapper_id).childElements()[0];
        self.tail_node = $(self.list_wrapper_id).childElements()[self.display_max - 1];

        $$('#'+self.list_wrapper_id+' li').each(function(li){
            li.observe('click', self.toggleTips);
        });

        $(self.list_wrapper_id).setStyle({opacity: 0.3});
        $(self.hover_fx_id).observe('mouseover', function(event){
            var queue = Effect.Queues.get('author_list_fade_fx');
                queue.each(function(effect) {effect.cancel();});

            new Effect.Opacity(self.list_wrapper_id, 
                {to: 1.0, duration: 0.3, queue: {position: 'front', scope: 'author_list_fade_fx', limit: 1}}
            );
                
        });

        $(self.hover_fx_id).observe('mouseout', function(event){
            var queue = Effect.Queues.get('author_list_fade_fx');
                queue.each(function(effect) {effect.cancel();});
                
            new Effect.Opacity(self.list_wrapper_id, 
                {to: 0.3, duration: 0.3, queue: {position: 'front', scope: 'author_list_fade_fx', limit: 1}}
            );
                
        });

        var scroll_up_fx = function(){
            self.scroll('up');
        };

        if ($(self.list_wrapper_id).childElements().length > self.display_max){
            $(self.prev_button_id).observe('click', scroll_up_fx);

            var scroll_down_fx = function(){
                self.scroll('down');
            }
            $(self.next_button_id).observe('click', scroll_down_fx);

            
        } else {
            $(self.prev_button_id).style.display = 'none';
            $(self.next_button_id).style.display = 'none';
        }
        $(self.toggle_list_button_id).observe('click', self.toggle_list);
        
//        $$('div#tabs_menu div').each(function(tab){
//           tab.observe('click', self.disable_list);
//        });
    }
    
    
}


function get_tip_comment_template(id, class_name){

    switch(id){
        case 'header_wrapper':
            return {
                title: 'Comment on the header',
                radius: 4,
                stem: 'leftTop',
                hook: {tip: 'topLeft', target: 'topRight'},
                offset: {x: 10, y: 0},
                showOn: 'click',
                hideOn: false,
                borderColor: '#8cc63e'
            };
            break;
        case 'objective_wrapper':
            return {
                title: 'Comment on the objective',
                radius: 4,
                stem: 'leftTop',
                hook: {tip: 'topLeft', target: 'topRight'},
                offset: {x: 10, y: 60},
                showOn: 'click',
                hideOn: false,
                borderColor: '#8cc63e'
            };
            break;
        case 'st_section_wrapper':
            return {
                title: 'Comment on the test scores',
                radius: 4,
                stem: 'leftTop',
                hook: {tip: 'topLeft', target: 'topRight'},
                offset: {x: 10, y: 60},
                showOn: 'click',
                hideOn: false,
                borderColor: '#8cc63e'
            };
            break;
        case 'skills_section':
            return {
                title: 'Comment on the skills and interests',
                radius: 4,
                stem: 'leftTop',
                hook: {tip: 'topLeft', target: 'topRight'},
                offset: {x: 10, y: 50},
                showOn: 'click',
                hideOn: false,
                borderColor: '#8cc63e'
            };
            break;
    }

    switch(class_name){
        case 'college_object_comment_input':
            return {
                title: 'Comment on this college',
                radius: 4,
                stem: 'leftTop',
                hook: {tip: 'topLeft', target: 'topRight'},
                offset: {x: 10, y: 70},
                showOn: 'click',
                hideOn: false,
                borderColor: '#8cc63e'
            };
            break;
        case 'hs_object_comment_input':
            return {
                title: 'Comment on this high school',
                radius: 4,
                stem: 'leftTop',
                hook: {tip: 'topLeft', target: 'topRight'},
                offset: {x: 10, y: 60},
                showOn: 'click',
                hideOn: false,
                borderColor: '#8cc63e'
            };
            break;
        case 'organization_comment_input':
            return {
                title: 'Comment on this position',
                radius: 4,
                stem: 'leftTop',
                hook: {tip: 'topLeft', target: 'topRight'},
                offset: {x: 10, y: 10},
                showOn: 'click',
                hideOn: false,
                borderColor: '#8cc63e'
            };
            break;
    }
}


//create this object after tip call
function commentBoxNode(textarea, prototip_target, mode){
    var self = this;

    this.mode = mode;

    this.textarea = textarea;
    this.prototip_target = prototip_target;
    this.form = self.textarea.up('form');
    this.toggle_button = self.textarea.up('.comment_container').down('.comment_form_menu .toggle_comment');
    this.delete_button = self.textarea.up('.comment_container').down('.comment_form_menu .delete_comment');
    this.last_action = null;

    this.is_hidden = false;
    this.is_tip_init = false;
    //var prototip_container = self.textarea.up('.prototip');

    this.hide_comment = function(){
        new Effect.BlindUp(self.textarea, {scaleTo : 0, duration: 0.5});
        self.is_hidden = true;
        self.change_toggle_button();
    }

    this.show_comment = function(){
        new Effect.BlindDown(self.textarea, {scaleTo : 100, duration: 0.5});
        self.is_hidden = false;
        self.change_toggle_button();
    }

    this.change_toggle_button = function(){
        if (self.is_hidden){
            self.toggle_button.innerHTML = '(show)';
        } else {
            self.toggle_button.innerHTML = '(hide)';
        }
    }

    //this should be binded after the tip call
    this.delete_comment = function(){
        self.textarea.value = '';
        //self.hide_comment();
        new Effect.Opacity(self.textarea.up('.prototip'),{to: 0, duration: 0.5});
        var delete_fx = function(){
            self.prototip_target.prototip.hide();
            self.textarea.up('.prototip').setStyle({opacity: 1});
            self.show_comment();
        }
        
        setTimeout(delete_fx, 600);
        self.is_tip_init = false;
    }


    this.toggle_comment = function(){
        if (self.is_hidden){
            setTimeout(self.show_comment, 400);
        } else {
            setTimeout(self.hide_comment, 400);
        }
    }

    this.init = function(){
        if (self.mode == 'commenter'){
            self.textarea.observe('blur', function(){
                self.hide_comment();
                self.last_action = 'blur';
            });
            self.prototip_target.observe('click', function(){
                if (self.last_action != 'blur' && self.is_tip_init){
                    self.toggle_comment();
                }

                self.last_action = 'click';
                self.is_tip_init = true;
            });
            self.toggle_button.observe('click', function(){
                if (self.last_action != 'blur'){
                    self.toggle_comment();
                }
                self.last_action = 'click';
            });
            self.delete_button.observe('click', self.delete_comment);

            
        }
    }


}

function commentSubmitObject(target_fb_id){

    var self = this;

    this.comment_forms = $$('form.comment_data_form');
    this.comment_submit_button_id = 'submit_comments_button';
    this.submit_url = ''+window.ra_app_dir+'core/db/actions/comments/update_comments.php';
    //this.submit_url = '/sandbox/print_arr.php';
    this.target_fb_id = target_fb_id;

    this.submit_comments = function(){

        var form_data = {};
        self.comment_forms.each(function(form){
            var form_node = form.serialize(true);
            for (attrname in form_node) {
                form_data[attrname] = form_node[attrname];
            }
        });

        new Ajax.Request(self.submit_url,
          {
            method:'post',
            parameters: form_data,
            onCreate: function(){
                self.decorate(self.comment_submit_button_id, 'submit_comments_loading');
            },
            onComplete: function(transport){
              //html = transport.responseText;
                self.decorate(self.comment_submit_button_id, 'submit_comments_done');
                if (self.target_fb_id != null){
                    //alert(self.target_fb_id);
                    var msg = window.ra_gave_feedback_message;
                    var caption = window.ra_gave_feedback_caption;
                    var url = window.ra_server_url+window.ra_app_dir;
                    var img = window.ra_gave_feedback_image_url;
                    var callback = create_action_dialog_gave_feedback;
                    create_wall_post(self.target_fb_id, msg, caption, img, url, callback);
                }
                
            },
            onFailure: function(){}
          });

    }

    this.decorate = function (elem_id, style){
        if (style == 'submit_comments_loading'){
            $(elem_id).down('.menu_bar_button_middle').innerHTML = 'Saving Comments...';
        }

        if (style == 'submit_comments_done'){
            $(elem_id).down('.menu_bar_button_middle').innerHTML = 'Comments Saved!';

        }
    }

    this.init = function(){
        $(self.comment_submit_button_id).observe('click', self.submit_comments);
    }


}

function resumeSubmitObject(){

    var self = this;

    this.forms = $$('div#form_wrapper form');
    this.submit_button_id = 'finish_resume_button';
    this.submit_url = ''+window.ra_app_dir+'core/db/actions/save_resume.php';
    //this.submit_url = '/sandbox/print_arr.php';

    this.save_resume = function(){

        var form_data = {};
        self.forms.each(function(form){
            var form_node = form.serialize(true);
            for (attrname in form_node) {
                form_data[attrname] = form_node[attrname];
            }
        });

        new Ajax.Request(self.submit_url,
          {
            method:'post',
            parameters: form_data,
            onCreate: function(){
                self.decorate(self.submit_button_id, 'loading');
//                if ($(self.submit_button_id).prototip != null){
//                    $(self.submit_button_id).prototip.remove()
//                }
//
//                new Tip(self.submit_button_id, $('finish_resume_button_dialog'), {
//                      title: 'Resume saved!',
//                      radius: 4,
//                      stem: 'rightBottom',
//                      hook: { tip: 'bottomRight', target: 'topLeft'},
//                      offset: { x: -20, y: 20 },
//                      hideOthers: false,
//                      hideOn: { element: 'tip', event: 'click' },
//                      showOn: 'focus',
//                      width: 320
//                    });
            },
            onComplete: function(transport){
              //html = transport.responseText;
                self.decorate(self.submit_button_id, 'done');
                //show dialog box
                

//                setTimeout(function(){$(self.submit_button_id).prototip.show();}, 300);
                //alert($('finish_resume_button_dialog').up('div.prototip'));
                $(self.submit_button_id).prototip.show();
                setTimeout(function(){$('finish_resume_button_dialog').up('div.prototip').style.position = 'fixed';}, 100);
                
                
                $('finish_resume_button_dialog').observe('click', function(){
                    //                    $('finish_resume_button_dialog').up('div.prototip').style.display = 'none';
                    $(self.submit_button_id).prototip.hide();
                });
                $('action_box_wrapper').fade({
                    duration: 0.6
                });
                init_menu_bar_fx();
            },
            onFailure: function(){}
          });

    }

    this.decorate = function (elem_id, style){
        if (style == 'loading'){
            $(elem_id).down('.menu_bar_button_middle').innerHTML = 'Saving Resume...';
        }

        if (style == 'done'){
            $(elem_id).down('.menu_bar_button_middle').innerHTML = 'Resume Saved!';
            setTimeout(function(){
                $(elem_id).down('.menu_bar_button_middle').innerHTML = 'Save Resume';
            }, 3000);
        }
    }

    this.init = function(){
        $(self.submit_button_id).observe('click', self.save_resume);
    }


}

function create_wall_post(target_id, msg, caption, img, url, callback){
//    if (msg == null){
//        msg = 'I just created my resume using '+window.ra_full_app_name+'. Check it out!';
//    }
    if (img == null){
        img = window.ra_share_image_url;
    }
    if (caption == null){
        caption = '';
    }

    var attachment = {'name':msg, 'href':url, 'caption':caption, 'media':[{'type':'image','src':img,'href': url}]};
    var action_links = window.ra_action_links;
    FB.Connect.streamPublish(msg, attachment, action_links, target_id, null, callback, false);
}




//function publish_wall_post(target_id, msg, callback){
//    if (msg == null){
//        msg = 'I just commented on your resume. Check it out!';
//    }
//    var attachment = {'media':[{'type':'image','src':window.ra_feedback_image_url,'href':''+window.ra_server_url+window.ra_app_dir+''}]};
//    FB.Connect.streamPublish(msg, attachment, null, target_id, null, callback, false);
//}

function show_login_dialog(location){
        window.ra_redir = location;
        //load the lightview dialog
        Lightview.show({href: '#resume_owner_login_dialog_wrapper', options: {closeButton: false, autosize: true, overlayClose: false}});
//        FB.Connect.requireSession(function(){
//            window.location = location;
//        });
}

function show_login_loading(button){
    var html = '<div id="loading_wrapper"><img src="'+window.ra_img_url+'bar_loader.gif"/></div>';
    button.style.display = 'none';
    button.insert({after: html});

}

function update_permissions(post_id, exception, data){

    var url = ''+window.ra_server_url+window.ra_app_dir+'core/db/actions/user_info/update_permissions.php';

    var target_id = window.my_connections_target_id;
//    alert(target_id);
//    alert(post_id);
//    alert(exception);
    if (target_id == null || post_id == null || post_id == 'null' || exception != null){
        return false;
    }



    var form_data = {'ids[]' : target_id, 'send_message' : false};
    new Ajax.Request(url,
    {
        method:'post',
        parameters: form_data,
        onComplete: function(transport){
            //html = transport.responseText;
            //show dialog box
        },
        onFailure: function(){
            //alert('Something went wrong...');
            }
    });
}

function update_user_info(form_data){

    var submit_url = ''+window.ra_app_dir+'core/db/actions/user_info/update_user_info.php';

    new Ajax.Request(submit_url,
          {
            method:'post',
            parameters: form_data
          });
}

function create_action_dialog(type){
    $$('#welcome_content div.welcome_content_row').each(function(header){
        header.style.display = 'none';
    });
    $(type+'_header').style.display = 'block';
    if (type == 'canvas'){
        $$('div#action_dialog_wrapper div#resume_owner_welcome_dialog')[0].style.height = '170px';
        $$('div#action_dialog_wrapper div#welcome_footer')[0].style.display = 'none';
    } else {
        $$('div#action_dialog_wrapper div#resume_owner_welcome_dialog')[0].style.height = '230px';
        $$('div#action_dialog_wrapper div#welcome_footer')[0].style.display = 'block';
    }
    if (type == 'gave_advice'){
        $('create_resume_link').style.display = 'block';
        $('job_recs_link').style.display = 'block';
        $('job_recs_link').setStyle({'float' : 'right'});
        $('my_connections_link').style.display = 'none';
    } else if (type != 'third_party' && type != 'canvas'){
        $('create_resume_link').style.display = 'none';
        $('job_recs_link').style.display = 'block';
        $('job_recs_link').setStyle({'float' : 'left'});
        $('my_connections_link').style.display = 'block';
    }
    if (type == 'third_party'){
        $$('div#action_dialog_wrapper div#welcome_footer')[0].style.display = 'none';
        $('third_party_title').style.display = 'block';
        $('welcome_header').style.display = 'none';
    } else {
        $('third_party_title').style.display = 'none';
        $('welcome_header').style.display = 'block';
    }



    setTimeout(function(){
        if (type == 'canvas'){
            Lightview.show({href: '#action_dialog_wrapper', options: {closeButton: false, autosize: true, overlayClose: false}});
        } else {
            Lightview.show({href: '#action_dialog_wrapper', options: {closeButton: 'small', autosize: true}});
        }
    }, 600);

    
}

function create_action_dialog_gave_feedback(){
//    window.ra_scroll_list.disable_list();
    Tips.hideAll();
    create_action_dialog('gave_advice');
}

function get_job_recs(form_id){
    var form = $(form_id);
    var jobs_canvas = $('job_disco_frame');

    new Ajax.Request(''+window.ra_server_url+'/JobsCola/job_rec_index/preview.php',
          {
            method:'get',
            parameters: form.serialize(true),
            onComplete: function(transport){
              var html = transport.responseText;
              jobs_canvas.innerHTML = html;
              if (!window.ra_has_searched_jobs){
                  setTimeout(function(){
                      $('job_disco_frame').prototip.show();
                  }, 200);
              }
              $('job_search_dialog_search_button_loading').style.display = 'none';
              $('job_search_dialog_search_button').style.display = 'block';
              window.ra_has_searched_jobs = true;
            },
            onFailure: function(){}
          });
}

function set_job_page_num(num){
    $('pn').value = num;
    $('job_results_wrapper').innerHTML = '';
    $('loading_wrapper').style.display = 'block';
    get_job_recs('job_search_dialog_form');
}

function show_canvas_dialog(){
    create_action_dialog('canvas');
}










