//
// Basic Blissport Accordion Object
//

/*-----------------------------------------------------------------------------------------------*/

if (typeof Effect == 'undefined') { 
	throw("blissportaccordion.js requires including script.aculo.us' effects.js library!");
}

var BlissportAccordion = Class.create({
  
  duration: null,
  animating: false,
  container: null,
  pairs: [],
  
	initialize: function(container, options) {
	  if (!$(container)) {
	    throw(container+" doesn't exist!");
	    return false;
	  }
	  
		this.options = Object.extend({
			resizeSpeed: 8,
			selectors: {
				toggle: '.toggle',
				content: '.content'
			},
			order: null,
			show: null,
			size: {
			  width: null,
			  height: null
			},
			fixes: {
			  opacity: true
			},
			vertical: true,
			horizontal: false
		}, options || {});
		
		this.container = $(container);
		
		if (this.options.fixes.opacity) {
		  this.container.setStyle({
		    opacity: 0.99999
		  });
		}
		
		this.duration = ((11-this.options.resizeSpeed)*0.15);

    var toggles = $$('#'+container+' '+this.options.selectors.toggle);
    var contents = $$('#'+container+' '+this.options.selectors.content);
    for (var x = 0; x < toggles.length; x++) {
      if (this.options.order && this.options.order[x]-1 <= x) {
        pair = {
          toggle: $(toggles[x]), 
          content: $(contents[this.options.order[x]-1])
        };
      } else {    
        pair = {
          toggle: $(toggles[x]),
          content: $(contents[x])
        };
      }
      
      Event.observe(pair.toggle, 'mouseover', this.onMouseover.bindAsEventListener(this, x, pair), true);
      Event.observe(pair.toggle, 'mouseout', this._onMouseout.bindAsEventListener(this, x, pair), true);
      Event.observe(pair.toggle, 'click', this.onClick.bindAsEventListener(this, x, pair), true);

      
      this.pairs.push(pair);
    }
    
	},
		
  onClick: function(event, index, pair) {
    if (pair.content.getStyle('display') == 'block') {
      this.deactivate(event, index, pair);
    } else {
      this.activate(event, index, pair);
    }
  },
    
	activate: function(event, index, pair) {
    this.onOpen(event, index, pair);
	},

	deactivate : function(event, index, pair) {
    this.onClose(event, index, pair);
	},
	
  // Private Methods
  
  _isChildOf: function(parent, child) {
    if( child != null ) {     
      while( child.parentNode ) {
        if( (child = child.parentNode) == parent ) {
          return true;
        }
      }
    }
    return false;
  },  
  
  _onMouseout: function (event, index, pair) {

    var element = Event.element(event);
    
    if(event.toElement) {       
      var target = event.toElement;
    } else if(event.relatedTarget) {        
      var target = event.relatedTarget;
    }
    
    if(!this._isChildOf(element, target) && element != target) {
      this.onMouseout(event, index, pair);
    }  
  }
	
});

var BlissportVerticalAccordion = Class.create(BlissportAccordion, {

  calendarExecuter: null,
  calendars: {
    dd: null,
    rd: null
  },
  calendarToggles: {
    dd: null,
    rd: null
  },
  showTools: false,
  counter: 0,
  
  initialize: function($super, container, options) {
    var found_something = false;
		if(has_matches == false) {
		  $$('#match_tool input[type=checkbox]').each(function(f) {
		    if(f.getValue() != null && found_something==false) {
		      found_something=true;
		    }
      });  
		}
		if(found_something) {
		  this.submitForm();
		}
    $super(container, options);

    this.pairs.each(function(pair){
      
      pair.content.setStyle({
        display: 'none',
        height: this.options.vertical ? '0px' : 'auto'       
      });
      
      var children = pair.content.descendants();
      for (var x = 0; x < children.length; x++) {
        if (children[x] && children[x].hasClassName('blissport_accordion_close')) {
          Event.observe(children[x], 'click', this.onClose.bindAsEventListener(this, null, pair))
        }
      }
          
      pair.toggle.makePositioned();
      pair.content.makePositioned();
      
      this.checkContent(pair);
      
      if (this.options.showIt && this.options.showIt[this.counter]) {
        this.onOpen(null, null, pair);
      } else {
        this.onClose(null, null, pair);    
      }
      
      this.counter = this.counter+1;
    }.bind(this));
    
    this.calendarExecuter = new PeriodicalExecuter(this.checkCalendars.bind(this), 1);
    this.calendarToggles.dd = $('dd_toggle');
    this.calendarToggles.rd = $('rd_toggle');
    this.calendars.dd = $('property[dd]').value;
    this.calendars.rd = $('property[rd]').value;

	var self=this;

    Event.observe(this.options.form, 'change', this.updateAccordion.bindAsEventListener(this, false), false);
		$$('input.checkbox').each( function(checkbox) { Event.observe(checkbox, 'click', self.updateAccordion.bindAsEventListener(self, false), false); } );
		
	  $$('.submit_match_button').each ( function(obj) { Event.observe(obj, 'click', self.submitForm.bind(this), false); });
    // Event.observe('cm_type_city', 'click', this.submitForm.bind(this), false);
		
  },
  
  checkCalendars: function() {
    if ($('property[dd]').value != this.calendars.dd) {
      this.calendars.dd = $('property[dd]').value;
      this.updateAccordion(null, this.calendarToggles.dd);
    }
    if ($('property[rd]').value != this.calendars.rd) {
      this.calendars.rd = $('property[rd]').value;
      this.updateAccordion(null, this.calendarToggles.rd);
    }
  },
  
  updateAccordion: function(event, toggle) {

    if (toggle) {
      var content = toggle.next('dd');
      var pair = {
        toggle: toggle,
        content: content
      };      
    } else {
      var content = Event.element(event).up('dd');
      var pair = {
        toggle: content.previous(0),
        content: content
      };
    }
    
    if (pair.content.id) {
      var inputs = $$('#'+pair.content.id+' input');
      for (var x = 0; x < inputs.length; x++) {
        if (inputs[x] == Event.element(event)) {
          
          if (inputs[x].hasClassName('parent')) {
            var checked = inputs[x].checked;
            x = x+1;
            while (inputs[x].hasClassName('child')) {
              inputs[x].checked = checked;
              x = x+1;
            }
            break;
          } else if (inputs[x].hasClassName('child')) {
            var setParent = inputs[x].checked;
            var y = x-1;
            var z = x+1;
            while (inputs[y].hasClassName('child')) {
              if (!inputs[y].checked) {
                setParent = false;
              }
              y = y-1;
            }
            while (inputs[z].hasClassName('child')) {
              if (!inputs[z].checked) {
                setParent = false;
              }
              z = z+1;
            }
            inputs[y].checked = setParent;
            break;
          }
        }
      }
    }
    
    this.checkContent(pair);
    
    var backgroundPosition = pair.toggle.hasClassName('active') ? -54 : -36;
    pair.toggle.setStyle({
      backgroundPosition: 'right '+parseInt(backgroundPosition)+'px',
      backgroundColor: '#414344',
      border: '1px solid #414344',
      color: '#FECB00'
    });
    
	var self = this;
    
  },
  
  checkContent: function(pair) {
    pair.toggle.removeClassName('active');
    pair.toggle.down('span').innerHTML = "";
    
    var children = pair.content.descendants();
    for (var x = 0; x < children.length; x++) {
      if ((children[x].tagName == "INPUT" || children[x].tagName == "SELECT") && (children[x].checked || children[x].selectedIndex > 0 || (children[x].type == "text" && children[x].value != ""))) {
        pair.toggle.addClassName('active');
        
        var backgroundPosition = pair.toggle.hasClassName('active') ? -18 : 0;
        pair.toggle.setStyle({
          backgroundPosition: 'right '+parseInt(backgroundPosition)+'px',
          backgroundColor: '#565859',
          border: '1px solid #565859',
          color: '#cfcfcf'
        });

        if (children[x].type == "radio" || children[x].type == "checkbox") {

          if (children[x].previous('label')) {
            var previous = children[x].previous('label');
            if (previous.getAttribute('for') == children[x].id) {

              if (pair.toggle.down('span').innerHTML == "") {
                pair.toggle.down('span').innerHTML = previous.innerHTML;
              } else {
                pair.toggle.down('span').innerHTML += ", "+previous.innerHTML;
              }
              
            }
          }
          
          if (children[x].next('label')) {
            var next = children[x].next('label');
            if (next.getAttribute('for') == children[x].id) {

              if (pair.toggle.down('span').innerHTML == "") {
                pair.toggle.down('span').innerHTML = next.innerHTML;
              } else {
                pair.toggle.down('span').innerHTML += ", "+next.innerHTML;
              }
              
            }
          }

        } else if (children[x].type == "text") {
          if (pair.toggle.down('span').innerHTML == "") {
            pair.toggle.down('span').innerHTML = children[x].value;
          } else {
            pair.toggle.down('span').innerHTML += ", "+children[x].value;
          }
        } else if (children[x].tagName == "SELECT") {
          if (pair.toggle.down('span').innerHTML == "") {
            pair.toggle.down('span').innerHTML = children[x].options[children[x].selectedIndex].text;
          } else {
            pair.toggle.down('span').innerHTML += ", "+children[x].options[children[x].selectedIndex].text;
          }
        }
                
      }
    }
  },
  
  submitForm: function() { 
	
	$('sort_hidden_field').setAttribute('value', $('sort_select').getValue() );
    queryString = $('match_form').serialize();

    new Effect.Parallel([
      new Effect.Appear('match-loading', {
        sync: true
      }),
      new Effect.Appear('match-results-overlay', {
        sync: true,
        to: 0.7
      })
    ] , {
      duration: 0.6,
      beforeStart: function() {
        $('match_form').disable();

        $('match-results-overlay').setStyle({
          width: $('match-results-container').getWidth()+'px',
          height: $('match-results-container').getHeight()+'px'
        });

        $('match-results').setStyle({
          height: $('match-results-container').getHeight()+'px'
        });

        $('main-content').setStyle({
          height: $('main-content').getHeight()+'px',
          overflow: 'hidden'
        });        
      },
      afterFinish: function() {
        new Ajax.Request('/match/index', {
          method: 'get', 
          parameters: queryString,
          onCreate: function() {
            $('match_form').disable();
          },
          onComplete: function() {
            $('match_form').enable();            
          },
          onSuccess: function() {

            $('main-content').setStyle({
              height: 'auto'
            });

            $('match-results-container').setStyle({
              background: 'none'
            });
            
            $('match-results-count').setStyle({
              display: 'inline'
            });
            
            $('match-results-phrase').setStyle({
              display: 'inline'
            });

            var effects = [];
            
            if (!this.showTools) {
              effects.push(
                new Effect.Appear('match-sort', {
                  sync: true
                })
              );
              this.showTools = true;
            }
            
            effects.push(
              new Effect.Fade('match-loading', {
                sync: true
              })
            );
            
            effects.push(
              new Effect.Fade('match-results-overlay', {
                sync: true
              })              
            );
            
            new Effect.Parallel(effects , {
              duration: 0.6,
              afterFinish: function() {
                $('match-results-overlay').setStyle({
                  width: 'auto',
                  height: 'auto'
                });

								$('match-results-container').setStyle({
                  zIndex: '1001' // fixes issue with IE6 rendering properties unclickable after a search
                });
                

                $('match-results').setStyle({
                  height: 'auto'
                });
              },
              queue: {
                position: 'end', 
                scope: 'matchResults'
              }
            });
          }
        });
      },
      queue: {
        position: 'end', 
        scope: 'matchResults'
      }
    });

  },
  
  onMouseover: function(event, index, pair) {
    
    if (pair.content.getStyle('display') == 'block') {
      return false;
    }
    
    var backgroundPosition = pair.toggle.hasClassName('active') ? -18 : 0;
    pair.toggle.setStyle({
      backgroundPosition: 'right '+parseInt(backgroundPosition-72)+'px',
      backgroundColor: '#414344',
      border: '1px solid #414344',
      color: '#ffffff'
    });
  },
  
  onMouseout: function(event, index, pair) {
    if (pair.content.getStyle('display') == 'block') {
      return false;
    }

    var backgroundPosition = pair.toggle.hasClassName('active') ? -18 : 0;
    pair.toggle.setStyle({
      backgroundPosition: 'right '+parseInt(backgroundPosition)+'px',
      backgroundColor: '#565859',
      border: '1px solid #565859',
      color: '#cfcfcf'
    });
  },
  
  onOpen: function(event, index, pair) {

    var backgroundPosition = pair.toggle.hasClassName('active') ? -18 : 0;
    pair.toggle.setStyle({
      backgroundPosition: 'right '+parseInt(backgroundPosition-36)+'px',
      backgroundColor: '#414344',
      border: '1px solid #414344',
      color: '#FECB00'
    });
    
    pair.content.setStyle({
      display: 'block',
      overflow: 'hidden'
    });
    
    var effects = [];

    if (pair.toggle.getHeight() != 18) {
      effects.push(
        new Effect.Morph(pair.toggle, {
          sync: true,
          style: {
            height: 18+'px'
          }
        })
      );
    }

    effects.push(
      new Effect.Morph(pair.content, {
        sync: true,
        style: {
          height: (this.options.size.height ? this.options.size.height : pair.content.scrollHeight)+'px'
        }
      })
    );

    effects.push(
      new Effect.Appear(pair.content, {
        sync: true,
        from: 0.0,
        to: 0.99999
      })
    );
    
    new Effect.Parallel(effects, {
      duration: this.duration
    });    
  },
  
  onClose: function(event, index, pair) {
    
    var backgroundPosition = pair.toggle.hasClassName('active') ? -18 : 0;
    pair.toggle.setStyle({
      backgroundPosition: 'right '+parseInt(backgroundPosition)+'px',
      backgroundColor: '#565859',
      border: '1px solid #565859',
      color: '#cfcfcf'
    });
    
    var effects = [];

    if (pair.toggle.hasClassName('active')) {
      effects.push(
        new Effect.Morph(pair.toggle, {
          sync: true,
          style: {
            height: (18+pair.toggle.down('span').getHeight())+'px'
          }
        })
      );
    }
     
    effects.push(
      new Effect.Morph(pair.content, {
        sync: true,
        style: {
          height: '0px'
        }
      })
    );
    
    effects.push(
      new Effect.Fade(pair.content, {
        sync: true,
        to: 0.0
      })
    );
    
    new Effect.Parallel(effects, {
      duration: this.duration
    });    
  }
});