if (typeof Event.observe == 'function') {
  Event.observe(document, 'dom:loaded', function(e){
    var field = new DefaultBlankField($('search-form-input'), 'Search...');
  });
}

Stats.insert = function ( stats ) {
  for ( var id in stats ) { $('projStat' + id).update( stats[id] ); }
}

/***
 * Extensions to Prototype.
 */
Element.addMethods({
  
  _showV : function(el) {
    var el = $( el );
    el.setStyle({ visibility : 'visible' });
    return el;
  },

  _hideV : function(el) {
    var el = $( el );
    el.setStyle({ visibility : 'hidden' });
    return el;
  },
  
  backgroundOn : function(el) {  
    $(el).setStyle({
      backgroundImage:$(el).getStyle('backgroundImage').replace('Off','On')
    });
    
    if ($(el).getStyle('filter')) {
      $(el).setStyle({
        filter:$(el).getStyle('filter').replace('Off','On')
      });
    }
  },
  
  backgroundOff : function(el) {
    $(el).setStyle({
      backgroundImage:$(el).getStyle('backgroundImage').replace('On','Off')
    });
    
    if ($(el).getStyle('filter')) {
      $(el).setStyle({
        filter:$(el).getStyle('filter').replace('On','Off')
      });
    }
  }
  
});



var DefaultBlankField = Class.create();
DefaultBlankField.prototype = {
	_default	: null,
	_fld	    : null,
	initialize : function(obj, def) {
		this._fld	    = obj;
		this._default = def;
    if (!$(this._fld)) { return; }
		
		if ($F(this._fld) === '') { this.setField(def); }
		var self = this;

		Event.observe($(this._fld), 'focus', function(evt) {
			if (self.getValue() == self.getDefault()) {
				self.setField('');
			}
		});

		Event.observe($(this._fld), 'blur',function(evt) {
			if (self.getValue() === '') {
				self.setField(self.getDefault());
			}
		});
	}, 
	getDefault : function() {
		return this._default;
	},
	getValue : function() {
		return $F(this._fld);
	},
	setField : function(val) {
		$(this._fld).value = val;
	}
};


function jsonTransport(transport) {
	try {
		var t = transport.responseJSON;
	} catch (e) {}
	return t;
}

PopUpMgr = {
  _instances   : $H({}),
  _outerZIndex : 500,
  _innerZIndex : 501,
  _pops        : new Array(),
  add : function(passed_params) {
    var params = $H({
      instance    : 'pop',
      outerZIndex : this._outerZIndex,
      innerZIndex : this._innerZIndex
    });
    
    var passed_params = (passed_params) ? passed_params : $H({});

    // override defaults with what user passes
    var params = params.merge(passed_params);
    
    var pop = new PopUp(params);
    
    pop.create();
    
    // increments z-index so next pop won't cover prior one
    this._outerZIndex++;
    this._outerZIndex++;
    this._innerZIndex++;
    this._innerZIndex++;
    
    this._pops.push(pop);
    this._instances.set(params.get('instance'),pop);
    
    
    
    return this._instances.get(params.get('instance'));
  },
  
  removeTop : function(e) {
    if (e.keyCode != Event.KEY_ESC) { return; }

    var pop_key      = PopUpMgr._pops.length-1;
    var instance_key = PopUpMgr._pops[pop_key].getInstanceKey();
    
    PopUpMgr._delete(pop_key,instance_key);
    
    PopUpMgr._compact();

  },
  
  _compact : function() {
    this._pops = this._pops.compact();
    
    if (this._pops.length == 0) {
      PopUpMgr.allCleared();
    }
  },
  
  _delete : function(pop_key,instance_key) {
    // remove DOM node
    this._pops[pop_key]._remove();
    
    // remove instance by key gotten from instance parameter in PopUp
    this._instances.unset(instance_key);
    
    // delete out of array
    this._pops[pop_key] = null;
    delete(this._pops[pop_key]);
  },
  
  update : function(instance,html) {
    instance._update(html);
  },
  
  getInstance : function(instance) {
    return this._instances.get(instance);
  },
  
  remove : function (instance) {
    var instance_key;
    for (var i =0;i<this._pops.length;i++) {
      
      if (instance == this._pops[i]) {
        instance_key = this._pops[i].getInstanceKey();
        
        this._delete(i,instance_key);
      }
    }
    
    this._compact();
  },
  
  allCleared : function() {
    Event.stopObserving(window,'scroll',PopUpMgr.positionAll);
    Event.stopObserving(window,'resize',PopUpMgr.positionAll);
    Event.stopObserving(window,'keyup',PopUpMgr.removeTop);
    Event.stopObserving(document.body,'keyup',PopUpMgr.removeTop);
  },
  
  removeAll : function() {
    var instance_key;
    for (var i =0;i<this._pops.length;i++) {
      instance_key = this._pops[i].getInstanceKey();
      this._pops[i]._remove();
      this._instances.unset(instance_key);
      this._pops[i] = null;
      delete(this._pops[i]);
    }
    
    this._pops = new Array();
    this.allCleared();
  },
  
  position : function (instance) {
    for (var i =0;i<this._pops.length;i++) {
      if (instance == this._pops[i]) {
        this._pops[i].position();
      }
    }
  },
  
  positionAll : function() {
    for (var i =0;i<PopUpMgr._pops.length;i++) {
      PopUpMgr._pops[i].position();
    }
  }
}; // PopUpMgr

PopUp = Class.create();
PopUp.prototype = {
  _params : null,   // passed when created
  _innerDiv : null, // object of div where contents are displayed
  _outerDiv : null, // object of div that surrounds contents
  _shim     : null, // object of iframe
	initialize : function(passed_params) {
    var input = '<div class="popup-inner-pad">Loading...</div>';
    // default parameters
    var params = $H({
      draggable       : false,    // can window be dragged
      draggableHandle : '',       // id of specific handle for dragging
      clearOthers     : true,     // call mgr to clear prior popups 
      outerDiv        : true,     // should an outer div be created (disabled when draggable == true)
      outerZIndex     : 500,      // for layering of outer div
      outerPad        : 30,       // for fake padding of outer div
      innerZIndex     : 501,      // for laying of inner div
      input           : input,    // string to update inner div for direct mode, markup must have wrapper setting width and height
      instance        : 'pop',    // for manager to grab instance out of scope
      observeScroll   : true,     // should we position on scroll
      observeResize   : true,     // should we position on resize
      observeKeyUp    : true      // should we close on escape
    });
    
    var passed_params = (passed_params) ? passed_params : $H({});
    
    // override defaults with what user passes
    var params = params.merge(passed_params);
    
    if (params.get('afterWindowCreated')) {
      this.afterWindowCreated = params.get('afterWindowCreated');
    }
    
    if (params.get('afterCorrectPNG')) {
      this.afterCorrectPNG = params.get('afterCorrectPNG');
    }
    
    if (params.get('lastCall')) {
      this.lastCall = params.get('lastCall');
    }
    
    this._params = params;
  },
  
  // will make popup show on screen
  create : function() {
    if (this._params.get('clearOthers') == true) {
      PopUpMgr.removeAll();
    }
    this.createWindow();
    this.afterWindowCreated();
    
    this.populateWindow();
    
    if (this._params.get('observeScroll')) {
      Event.observe(window,'scroll',PopUpMgr.positionAll);
    }
    
    if (this._params.get('observeResize')) {
      Event.observe(window,'resize',PopUpMgr.positionAll);
    }
    
    if (this._params.get('observeKeyUp')) {
      Event.observe(window,'keyup',PopUpMgr.removeTop);
      Event.observe(document.body,'keyup',PopUpMgr.removeTop);
    }
    
  },
  
  createWindow : function() {
    this._innerDiv = $(document.createElement('div'));
    document.body.appendChild(this._innerDiv);
    this._innerDiv.setStyle({
      position : 'absolute',
      zIndex   :  this._params.get('innerZIndex')
    });
    
    if(Prototype.Browser.IE) {
      var b_version= (navigator.appVersion) ? navigator.appVersion : false;
      
      
      b_version =  (b_version && typeof(b_version) == 'string')
                    ? parseFloat(b_version.replace(/.+MSIE\s([^;]+);.+/,"$1"))
                    : false;
      
      if (b_version && b_version < 7) {
        var shimHTML = '<iframe src="#" id="'+this._params.get('instance')+'_shim" style="position:absolute;width:100px;height:120px;top:0px;left:0px;border:none;display:block;z-index:500"></iframe>';
        document.body.insert({bottom:shimHTML});
        this._shim = $(this._params.get('instance')+'_shim');
        this._shim.setStyle({
          position : 'absolute',
          display: 'block',
          zIndex   :  0,
          border:'none'
          
        });
      }
    }
    this._innerDiv.addClassName('popup-inner');
    
    
  },
  
  _shimClone : function() {
    if (this._shim) {
      this._shim.clonePosition(this._innerDiv);
      this._shim.setStyle({
        position : 'absolute',
        display  : 'block',
        zIndex   :  0,
        border   : 'none'
        
      });
    }
  },
  
  _update : function(html) {
    this._innerDiv.update(html);
    var self = this;
    if (this._params.get('draggable')) {
      this._drag     = new Draggable(this._innerDiv, {starteffect : '', endeffect : '', handle : this._params.get('draggableHandle'),
      onDrag: function(e) {self._shimClone(); }});
    }
    this.afterInnerPopulated();

    // if the png function is defined, run it
    if( typeof correctPNG == 'function' ) {
      correctPNG();
      this.afterCorrectPNG();
    }
  },
  
  afterCorrectPNG : function() { },
  
  populateWindow : function() {
    this._innerDiv.update(this._params.get('input'));
    this.afterInnerPopulated();
  },
  
  afterInnerPopulated : function() {
    this.position();
    this.lastCall();
  },

  // fires after window is created, before updating contents
  afterWindowCreated : function() {}, 
  
  // fires last, after everything else is completed
  lastCall           : function() {},

  // creates layer behind inner for transparency effects
  createOuterDiv : function() {
    this._outerDiv = $(document.createElement('div'));
    document.body.appendChild(this._outerDiv);
    this._outerDiv.setStyle({
      position : 'absolute',
      zIndex   :  this._params.get('outerZIndex')
    });
    this._outerDiv.addClassName('popup-outer');
  },
  
  position : function() {
    // gather height and width of elements for positinoing 
    var innerHeight = this._innerDiv.getHeight();
		var innerWidth  = this._innerDiv.getWidth();
    var viewWidth   = document.viewport.getWidth();
    var viewHeight  = document.viewport.getHeight();
    var scrollPos   = document.viewport.getScrollOffsets();
    var scrollPosX  = scrollPos[0];
    var scrollPosY  = scrollPos[1];	
    var ScrollWin   = null;
    
    // vertically center _innerDiv
    ScrollWin       = scrollPosY + (viewHeight/2);
    var newInnerTop = (ScrollWin) - (innerHeight/2);
    
    // horizontally center _innerDiv
    ScrollWin        = scrollPosX + (viewWidth/2);
    var newInnerLeft = (ScrollWin) - (innerWidth/2);
    
    this._innerDiv.setStyle({top:newInnerTop+'px',left: newInnerLeft+'px'});
    this._shimClone();
    
    if (!this._outerDiv && this._params.get('outerDiv') == true && this._params.get('draggable') == false) {
      this.createOuterDiv(); 
    }
    
    if (this._outerDiv) {
      var outerPad = this._params.get('outerPad');
      var outerOffset = (outerPad/2) - outerPad;
      this._outerDiv.clonePosition(this._innerDiv, {
        offsetLeft: outerOffset,
        offsetTop: outerOffset
      });
      
      this._outerDiv.setStyle({
        width  : (innerWidth+outerPad)+'px',
        height : (innerHeight+outerPad)+'px'
      });
      
      
    }
    
    if (Prototype.Browser.IE) { $$('select.hidden').each(function(el){$(el).hide()}); } // ie 6 fix
  },
  
  _remove : function() {
    if (this._innerDiv) this._innerDiv.remove();
    if (this._outerDiv) this._outerDiv.remove();
    if (this._shim)     this._shim.remove();
    this._innerDiv = null;
    this._outerDiv = null;
    this._shim     = null;
    if (Prototype.Browser.IE) { $$('select.hidden').each(function(el){$(el).show()}); } // ie 6 fix
  },
  
  getInstanceKey : function() {
    return this._params.get('instance');
  }


}

Lang = {
  page : null,
  TRANS_ENDPOINT : 'http://www.swatchmtvplayground.com/behance/languagehelpers/',
  LOCAL_ENDPOINT : '/changeLanguagePref',
  /**
   * whenever the dropdown is changed, detect the value,
   * disable if en, and make sure to save the value of en.
   */
  onChange : function (el) {
      var parts   = el.value.split('|');
      var cc      = parts[0];
      var value   = parts[1];

      // Save the user's preference
      new Ajax.Request(Lang.LOCAL_ENDPOINT, {
        parameters : 'lang_pref='+value
      });
      
      $$('a.lang').each(function(a){
          a.setAttribute('href', a.getAttribute('value').replace('[lang]', cc ) )
      })
      
      if( value == 'en' ) {
        $('lang-img').hide();
        $('lang-img-disabled').show();
      } else {
        $('lang-img').show();
        $('lang-img-disabled').hide();
      }
  },
  openAndSave : function(page) {
    // if you set the page through AJAX, override the onclick
    var page    = (this.page) ? this.page : page; 
    var ccvalue = $F('lang_dropdown');
 
    if (ccvalue != '') {
      var parts   = ccvalue.split('|');
      var cc      = parts[0];
      var value   = parts[1];
      
      $('lang_dropdown').setStyle({border:'solid 1px #CCC'});

      // If language is English, do not open the popup 
      if( value != 'en' ) {
        window.open(Lang.TRANS_ENDPOINT+cc+'/'+cc+'-'+page+'.jpg');
      }
      
      // Save the user's preference
      new Ajax.Request(Lang.LOCAL_ENDPOINT, {
        parameters : 'lang_pref='+value
      });
    } else {
      $('lang_dropdown').setStyle({border:'solid 1px #FF0000'});
    }
  },
  
  setPageByAlias : function(alias) {
    var page;
    switch (alias) {
      case 'image' : 
        page = 'profile-image';
        break;
      default :
        page = alias;
    }
    
    
    Lang.page = page;
  }
} // Lang 

function selectSearch(name, elm) {
	
	qs = window.location.search;
	qs = new Hash( qs.toQueryParams() );
	qs.unset('page');
	qs.unset('x');
	qs.unset('y');
	
	qs.set(name, elm.value);
	
	//nuke the defaults
	if(elm.value=="All Circles") 					qs.unset( "circle" ); 
	if(elm.value=="All Creative Fields") 	qs.unset( "field" );
	if(elm.value=="Past Curators") 				qs.unset( "curator" );
	
	if(elm.name!='curator') qs.unset('curator');
	
	qs = qs.toQueryString();
	qs = qs.replace(/%2B/g, '+');
	window.location = (window.location.pathname + '?' + qs);

}

var DropDown = Class.create();
DropDown.prototype = {
  _name               : null,
  
  initialize: function(name, myOps){

    this._options = Object.extend( {
      'moveDown'   : 0,
      'moveLeft'   : 0,
      'convention': name+'_Op_'
    }, myOps || {} );
    
    this._options = $H(this._options);

    this._name = name;
    this._body = $(document.body);

    if (this._options.get('defaultSelection')) {
      var objID = this._options.get('convention')+this._options.get('defaultSelection');
      this.makeSelection($(objID));
    }
    
    this.toggleOptionsListener = this.toggleOptions.bindAsEventListener(this);
    Event.observe($(this._name), 'click', this.toggleOptionsListener);

    
    this.decideCloseListener = this.decideClose.bindAsEventListener(this);

    //make sure everything is showing at start (safari fix)
    $$("#" + this._name + "_options .dropOption").each(function(el){
      el.style.display = 'block';
    });

    
  },
  stopDrop : function() {
    var self = this;
    Event.stopObserving( this._body, 'click', self.decideCloseListener );
  },
  decideClose : function (evt) {
  
    var clickedOn = Event.element(evt);
    var dropdown  = $(this._name);
    var options   = $(this._name+'-options');
    
    if (options.getStyle('display') == 'block' && clickedOn.id != this._name && clickedOn.id != this._name+'-options'
          && typeof(clickedOn.up('#'+options.id)) == 'undefined'
        ) {
      this.toggleOptions();
    }
    
  },

  decideShown : function (selEle) {
    var self = this;
    if ($(this._name+'-options')) {
      var dropOptions = $$("#"+this._name+"-options li");
      for (var i=0;i<dropOptions.length;i++) {
        var el = dropOptions[i];
        if (selEle.id == el.id) {
          if ($(self._name)) $(self._name).update(el.innerHTML);
          el.style.display = 'none';
        } else {
          el.style.display = 'block';
        }
      }
    }
  },
  
  callMakeSelection : function(el) {
    this.makeSelectionClone	=	this.makeSelection.bindAsEventListener(this);
    $(el).onclick	          =	this.makeSelectionClone;
  },
  
  makeSelection : function(el) {
    var curID = $(el).id;
    if (el.id != '') {
      var curSelection = curID.replace(this._options.get('convention'), '');
      this.setDropSelection(curSelection);
      
      this.decideShown(el);
      
      if ($(this._name+'-options').getStyle('display') == 'block') this.toggleOptions();
      
      
    }
    
  },
  
  setDropSelection : function(id) {
    this._lastDropSelection	= this._dropSelection;
    this._dropSelection	    = id;
    return this._dropSelection;
  },
  
  getDropSelection : function() {
    return this._dropSelection;
  },
  
  toggleOptions : function() {
    var options = $(this._name+'-options');
    
    if ( options.visible() ) {
      Effect.SlideUp(options, { duration : .15, queue : {position : 'end', scope : this._name } });
      Event.stopObserving(this._body, 'click', this.decideCloseListener);
      
      if( typeof this._options.get('selectCallback') == 'function' ) {
        this._options.get('selectCallback')( this.getDropSelection() ) ;
      }
      
    } else {
      var dropDown = $( this._name );
      
      var h = dropDown.getHeight();
      var c = dropDown.cumulativeOffset();

//      if (this._options.moveLeft) {
//        c[0] = this._options.moveLeft ;
//      }

      if (this._options.moveDown) {
        c[1] =  parseInt(c[1]) + parseInt(this._options.moveDown); 
      }
      
      // options.style.top = (h+c[1])+'px';
      options.style.left = this._options.get('moveLeft')+'px';
  
  
      Effect.SlideDown(options, { duration : .15, queue : {position : 'end', scope : this._name } });
      Event.observe(this._body, 'click', this.decideCloseListener);
    }
    
    
  },
  
  getValue : function() {
    return this._dropSelection;
  }

}

DropDownHelper = {
  mouseover : function( el ) {
  	$(el).setStyle({
  		backgroundColor	: PES_COLOR,
  		color			  : '#000',
  		cursor			: 'hand',
  		cursor			: 'pointer'
  	})  
  },

  mouseout : function( el ) {
  	$(el).setStyle({
  		backgroundColor	: '#fff',
  		color			      : '#4C4C4C',
  		cursor			    : 'default'
  	})
  }
}
