window.onload = initProfSearch;
function initProfSearch() {
  init_feedbackSlider();
  init_reviewSlider();
  init_rateSlider();

 commonSearchJs.init( profSearchJs, 'earningsSort', 1 );
 profSearchJs.doSearch(false, true);
 currHashUrl = getCurrHashParams();
  if( !isSafari() ) {
    checkHashChanged();
  }
}

function replaceContent(obj) {
  profSearchJs.replaceContent(obj);
}


var profSearchJs = {

  doSearch : function(resetform, initSearch) {
    if( !profSearchJs.checkIsProjectSearch() ) {
      if(resetform) {
        commonSearchJs.resetForm(profSearchJs);
      }
      profSearchJs.doProfSearch(initSearch);
    }
  },

  // Checks if the user changed the type dropdown to project; redirect if they have
  checkIsProjectSearch : function() {
    if( $('matchType').value == 'project' ) {
      //-- redirect search
      var mkey = $('matchKeywords').value;
      if( mkey == keywordsInit ) {
        mkey = '';
      }
      document.location.href = encodeURI("/p/?q=eolsearch&matchType=project#matchKeywords=" + mkey);
      return true;
    }
    return false;
  },

  doProfSearch : function(initSearch) {
    cancelRunningRequests();
    commonSearchJs.showBusy();
    if( (($('matchKeywords').value == '') ||
	 ($('matchKeywords').value == keywordsInit)) &&
        ($('sortBy').value == '') ) {
      $('sortOrder').value = 1;
      commonSearchJs.setSortArrow( 'earningsSort' );
    }
    var t = "&t=" + getDateTime();
    var params = this.getSrchParams();
    if( !initSearch ) {
      //-- For the initial search, no need to set the search params
      setHashParams( params );
    }
    curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/search/main/resultsprofile.php?matchType=profile&' + params + t, htmlCallback, null);
    curLoad = setInterval('isLoaded()', 10);

	sProfSearch();
	
 	switch ($('catFilter').value) {
		case "100":
			document.title = "Search Professionals on Elance | Elance "; break;
		case "10180":
		    document.title = "Search Professionals in Writing & Translation on Elance | Elance "; break;
		case "14000":
		    document.title = "Search Professionals in Architecture & Engineering on Elance | Elance "; break;
		case "10184":
		    document.title = "Search Professionals in Graphic Design & Art on Elance | Elance "; break;
		case "10183":
		    document.title = "Search Professionals in Website Development on Elance | Elance "; break;
		case "10178":
		    document.title = "Search Professionals in Sales & Marketing on Elance | Elance "; break;
		case "14125":
		    document.title = "Search Professionals in Audio, Video & Multimedia on Elance | Elance "; break;
		case "10182":
		    document.title = "Search Professionals in Software & Technology on Elance | Elance "; break;
		case "10179":
		    document.title = "Search Professionals in Administrative Support on Elance | Elance "; break;
		case "10186":
		    document.title = "Search Professionals in Management & Finance on Elance | Elance "; break;
		case "12517":
		    document.title = "Search Professionals in Training & Development on Elance | Elance "; break;
		case "10187":
		    document.title = "Search Professionals in Legal on Elance | Elance "; break;
																	
	}
  },


  setSrchParam : function(name, value) {
    if( name == 'sortBy' ) {
      //-- Remove any existing sort arrow
      commonSearchJs.resetSortingArrow();

      //-- Determine the sort order
      if( $('sortBy').value == value ) {
        $('sortOrder').value *= -1;
      } 
      else {
        $('sortOrder').value = 1;
      }

      //-- Set the sort arrow and reset the page
      commonSearchJs.setSortArrow(value);
      commonSearchJs.resetPage();
      profSearchJs.doProfSearch(false);
      return;
    }
    else if( name == 'page' ) {
      scrollTo(0,0);
    }
    $(name).value = value;
    if( commonSearchJs.checkResetPage( name ) ) {
      commonSearchJs.resetPage();
    }
    profSearchJs.doProfSearch(false);
  },


  getSrchParams : function() {

    var params = "";
    params += "page=" + $('page').value;
    if( $('matchKeywords').value != keywordsInit ) {
      params += "&matchKeywords=" + encodeURIComponent($('matchKeywords').value);
    }
    params += "&sortBy=" + $('sortBy').value;
    params += "&sortOrder=" + $('sortOrder').value;

    //-- filters
    params += "&profTypeFilter=" + $('profTypeFilter').value;
    params += "&catFilter=" + $('catFilter').value;
    params += "&feedbackFilter=" + $('feedbackFilter').value;
    params += "&reviewsFilter=" + $('reviewsFilter').value;
    params += "&minrateFilter=" + $('minrateFilter').value;
    params += "&locFilter=" + encodeURIComponent($('locFilter').value);

    //alert( params );
    return params;
  },


  /**
   * Reset the filters.  Typically called if a new search is executed.
   */
  resetFilters : function() {
    $('profTypeFilter').value = 'a';
    $('catFilter').value = 100;
    $('feedbackFilter').value = 0;
    $('reviewsFilter').value = 0;
    $('minrateFilter').value = 0;
    $('locEntered').value = '';
    $('locFilter').value = '';
    sliderfeedback.setValue(0);
    sliderreviews.setValue(0);
    sliderminrate.setValue(0);
  },


  replaceContent : function(obj) {
    $('results_placeholder').innerHTML = obj.responseText;
    $('pagenav_placeholder').innerHTML = $('pagenav_subsection').innerHTML;
    $('totalresults_placeholder').innerHTML = $('totalresults_subsection').innerHTML;
    $('debug_placeholder').innerHTML = $('debug_subsection').innerHTML;
    $('category_placeholder').innerHTML = $('category_subsection').innerHTML;
    $('proftype_placeholder').innerHTML = $('proftype_subsection').innerHTML;
    $('results_placeholder').innerHTML = $('results_subsection').innerHTML;

    commonSearchJs.extendLeftNav();
    commonSearchJs.showNotBusy();
  },


  /**
   * If user presses Enter while in keywords text field, 
   * reset filters and execute search.  If use presses Enter
   * while in location text field, execute search.
   */ 
  interceptKeypress : function( keypressEvent ) {
    if((keypressEvent.type == 'keypress') && (YAHOO.util.Event.getCharCode(keypressEvent) == 13)) { 
       if (objInFocus == 'matchKeywords') {
          YAHOO.util.Event.preventDefault(keypressEvent );
          commonSearchJs.resetForm(profSearchJs);
	        profSearchJs.doSearch(false, false);
       } else if (objInFocus == 'locEntered') {
          profSearchJs.setSrchParam('locFilter',$('locEntered').value);
          YAHOO.util.Event.preventDefault(keypressEvent );
          profSearchJs.doProfSearch(false);
      }
    }
  },


	/**
	* Set the initial form values to whatever values
	* are set in the hash of the URL
	*/
	initFormFields : function(args, defaultSortBy, defaultSortOrder) {
		for (var paramName in args) {
			if( paramName && args[paramName] ) {
				switch( paramName ) {
					case "feedbackFilter":
						set_feedbackSlider( args[paramName] );
						break;
					case "reviewsFilter":
						set_reviewsSlider( args[paramName] );
						break;
					case "minrateFilter":
						set_minrateSlider( args[paramName] );
						break;
					case "matchKeywords":
						$('matchKeywords').value = args[paramName];
						break;
					case "locFilter":
						document.srchResults.locFilter.value = args[paramName];
						document.srchResults.locEntered.value = args[paramName];
						break;
					default:
						$(paramName).value = args[paramName];
				}
			}
		}
	}

}


/**
 * Invite to Bid checkboxes
 */
function initContactMePanel() {
	closeContactMePanel = function() {
		currentContactPanel = -1;
	};

	// check to see if we're showing existing projects
	if ($('newPost')) {
		// existing projects UI
		height = "310px";
	} else {
		// start a new project UI
		height = "200px";
	}
	
	contactMePanel = 
			new YAHOO.widget.Panel("contactMePanel_YUI",
								   { width : "525px",
								     height: height,
								     fixedcenter : true,
								     visible : false,
								     constraintoviewport : true,
								     close : true,
								     draggable : true,
								     modal: false,
								     effect: { effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3}
								   } );
	contactMePanel.render();	
	contactMePanel.beforeHideEvent.subscribe(closeContactMePanel);
	removeClassName( contactMePanel.innerElement, 'displayNone' );
}

/**
 * Toggle display of the contactMe Panel.
 */
var currentContactPanel = -1;
var contactMePanel;
function getRequestQuote() {
	providerList = getInviteeList();
	
	if (providerList.length < 1) {
		// nothing to invite, bail
		return;
	}
	
	provider = 1;
	$('yui-nav').style.display = 'none';
	if( currentContactPanel == provider ) {
		currentContactPanel = -1;
		contactMePanel.hide();
	}
	else {
		if(!contactMePanel){
			initContactMePanel(providerList);
		} else {
			resetContactMePanel();
		}
		currentContactPanel = provider;
		$$('contactMePanel_YUI').removeClass('displayNone');
		contactMePanel.show();
	}
	$('contactMePanel_YUI_h').style.display = 'none';
	$('yui-content').style.backgroundImage = 'url(/media/images/4.0/dialogs/40px-gradient.png)';
	$('yui-content').style.backgroundRepeat = 'repeat-x';

	if ($('existingProjectButton')) {
		// existing projects
		if (providerList.length > 1) {
			sellers = "new Array("+ providerList.toString() +")";
		} else {
			sellers = providerList.toString();
		}
		jsHref = "javascript:inviteUser("+ $('buyerUserid').innerHTML +", "+ sellers +");";
		$('existingProjectButton').setAttribute('href', jsHref);
	} else if ($('newProjectButton')){
		// new project
		providerParams = providerList.toString().replace(/,/g, '_');
		$('newProjectButton').href = '/postjob?inviteId=' + providerParams;
	}
}

function getInviteeList() {
	baseId = 'cbxProviders_';
	pageLoc = window.location.hash.search(/page=/);
	pageLocEnd = window.location.hash.substr(pageLoc).search(/&/);

	// extract page num out of hash
	if (pageLoc !== -1) {
		pageLoc += 5;	// skip over 'page='
		if (pageLocEnd === -1) {
			pageNum = window.location.hash.substr(pageLoc);
		} else {
			pageLocEnd -= 5;	// more skipping
			pageNum = window.location.hash.substr(pageLoc, pageLocEnd);
		}
	} else {
		pageNum = 1;
	}

	// 25 results per page at the moment
	i = 1 + ((pageNum - 1) * 25);
	var inviteeList = new Array();
	while($(baseId + i)) {
		if ($(baseId + i).checked) {
			inviteeList.push($(baseId + i).value);
		}
		++i;
	}
	
	return inviteeList;
}
