


// current interval being run
var curLoad = null;
// current asyncronous request being waited for, used in isLoaded()
var curAsyncRef = null;
// current javascript code to be eval-ed when isLoaded succeeds
var curWaitingCode = null;
var keywordsInit = 'Enter search keywords';
var keywordsTouched = false;
var locTextEntered = false;
var requestInProgress = false;
var slidersActive = false;

var commonSearchJs = {

  init : function( searchObj, defaultSortBy, defaultSortOrder ) {
    var args = getArgsFromHash();
    searchObj.initFormFields(args, defaultSortBy, defaultSortOrder);

    //-- Only sort if specified or no keywords
    if((args.matchKeywords == '') 
	|| (args.matchKeywords == keywordsInit)
	|| (args.sortBy)) {
      $('sortOrder').value = args.sortOrder ? args.sortOrder : defaultSortOrder;
      commonSearchJs.setSortArrow( args.sortBy ? args.sortBy : defaultSortBy );
    }
    commonSearchJs.initKeywords(args.matchKeywords ? args.matchKeywords : '');

    YAHOO.util.Event.addListener(document, "keypress", searchObj.interceptKeypress);
  },

  showBusy : function() {
    requestInProgress = true;
    document.body.style.cursor = 'wait';    
    $("progressbar").className = "progressbaron";
    $("progressbartext").innerHTML = "Searching...";
  },

  showNotBusy : function() {
    document.body.style.cursor = 'default';    
    $("progressbar").className = "progressbaroff";
    $("progressbartext").innerHTML = "";
    requestInProgress = false;
  },

  checkResetPage : function( field ) {
    if( field == 'page' ) {
      return false;
    }
    else {
      return true;
    }
  },

  resetForm : function( searchObj ) {
    commonSearchJs.resetPage();
    commonSearchJs.resetSortingArrow();
    $('sortBy').value = '';
    $('sortOrder').value = 1;
    searchObj.resetFilters();
  },

  resetPage : function() {
    $('page').value = 1;
  },

  resetSortingArrow : function() {
    var prevSort = $('sortBy').value;
    if( prevSort ) {
      var sortArrow = $(prevSort + "Arrow");
      sortArrow.className = "sortSpacer";
    }
  },

  /**
   * Set the sort direction (asc or desc) and sortBy field
   */
  setSortArrow : function(sortBy) {
    if( sortBy ) {
      $('sortBy').value = sortBy;
      var sortArrow = $(sortBy + 'Arrow');     
      if( $('sortOrder').value == 1 ) {
        sortArrow.className = 'sortDown';
      }
      else {
        sortArrow.className = 'sortUp';
      }  
    }
  },

  initKeywords : function( defaultKeywords ) {
    if( defaultKeywords == '' ) {
      $('matchKeywords').value = keywordsInit;
      $('matchKeywords').className = 'keywordslight';
    }
    else {
      //-- URL has keywords already, so use those
      $('matchKeywords').className = 'keywordsdark';
      keywordsTouched = true;
    }
  },

  clearKeywords : function() {
    $('matchKeywords').className = 'keywordsdark';
    $('matchKeywords').value = '';
  },

  clearLocFilter : function() {
    $('locEntered').value = '';
    $('locFilter').value = '';
  }
}

var objInFocus = '';

function setObjInFocus( obj ) {
  objInFocus = obj;
  if( obj == 'matchKeywords' ) {
    if( !keywordsTouched ) {
      commonSearchJs.clearKeywords();      
    }   
    keywordsTouched = true;
  } else if (obj == 'locEntered') {
    if(!locTextEntered) {
      commonSearchJs.clearLocFilter();      
    }   
    locTextEntered = true;
  }
}

function removeObjInFocus() {
  objInFocus = '';
}

//-- MSE only available in debug mode
function toggleMSE(id) {
  if( $('explainBox'+id).style.display == 'none' ){
		$('explainBox'+id).style.display = '';
	}
  else {
		$('explainBox'+id).style.display = 'none';
	}
}

var contactMePanel;
var contactMeTabs;
var closeContactMePanel;
var currentContactPanel = -1;
var callSessionId;
var callWS;
var tabChat, tabCall;
var checkTabsLoadedInterval;

function initContactMePanel() {


closeContactMePanel = function() {
    currentContactPanel = -1;
    resetContactMePanel();
		deactivateContactMeAgentMode(); // always turn this off on close!
  };

  contactMePanel = new YAHOO.widget.Panel("contactMePanel_YUI", 
    { width : "525px",
      height: "370px",
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      close : true,
      draggable : true,
      modal: false,
      effect: {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3}
    } );

  contactMeTabs = new YAHOO.widget.TabView("contactMe_tabs");
  //setContactMeBody("ContactMeInvite");
  contactMePanel.render();
  contactMePanel.beforeHideEvent.subscribe(closeContactMePanel);
	removeClassName( contactMePanel.innerElement, 'displayNone' );
  return true;
}


/**
 * When the user is not logged in, show sign in dialog.
 */
function notLoggedInDialog() {
    //TODO to implement
}


/**
 * Toggle display of the contactMe Panel.
 */
function toggleContactMePanel(provider,agentMode) {
  if( currentContactPanel == provider ) {
    currentContactPanel = -1;
    contactMePanel.hide();
  } else {
    if(!contactMePanel){
        initContactMePanel();
				contactMePanel.provider = provider;
    }
    currentContactPanel = provider;
    contactMePanel.show();
		// If agent mode requested, turn it on
		if( agentMode ){ activateContactMeAgentMode(); }
		checkTabsLoadedInterval = setInterval( 'checkTabsLoaded()', 50 );
  }
}

/**
 * Reset Panel 
 */
function resetContactMePanel() {
	if (contactMePanel) {
		// reset any clicked radio buttons
		i = 0;
		while($('existing'+ i)) {
			$('existing'+ i++).checked = false;
		}

		$('inviteContent').style.display = '';
		$('inviteConfirm').style.display = 'none';
		$('inviteSuccessMessage').style.display = '';
		$('inviteFailureMessage').style.display = 'none';
	}
}

function cancelContactMe(){
	if(contactMePanel){
		currentContactPanel = -1;
		callSessionId=null;
		callWS=null;
		contactMePanel.hide();
		resetContactMePanel();
	}
}

function setContactMeBody(tab){
if(contactMePanel){
    contactMePanel.setHeader($(tab+'Header').innerHTML);
    contactMePanel.setBody($(tab+'Body').innerHTML);
}
}

function activateTab(index){
if(contactMeTabs.getTab(index))
    contactMeTabs.set('activeIndex',index);
}


/*** Tab Related Functions ***/

// Checks if tabs are loaded, calls checkTabs and clears interval if so
function checkTabsLoaded() {
	if( window.contactMeTabs  ) {
		clearInterval( checkTabsLoadedInterval );

		if( !tabChat ) { tabChat = contactMeTabs.getTab(1); }
		if( !tabCall ) { tabCall = contactMeTabs.getTab(2); }

		checkTabs(contactMePanel.provider);
	}
}

// Makes call to AHR to check which tabs are avail for this user
function checkTabs(username) {
	var url = "/php/myelance/main/contactMeAHR.php?ctx=contactMe&mode=checktabs&view_person="+username+'&t='+getDateTime();
	 YAHOO.util.Connect.asyncRequest('get',
          url,
          {success: tabCheckSuccess, failure:tabCheckFailure});
};

// Handle success case for the above
function tabCheckSuccess(response) {
	var responseObj = Json.evaluate( response.responseText );

	if( responseObj.rc == '1' ) {
	
		// Add the tabs back in, then remove them selectively
		contactMeTabs.addTab(tabChat);
		contactMeTabs.addTab(tabCall);

		if( !responseObj.canChat ) {
			// If we are removing the active tab, set active to 0
			if( contactMeTabs.get('activeTab') == tabChat ) { activateTab(0); }
			contactMeTabs.removeTab(tabChat);
		}

		if( !responseObj.canCall ) {
			// If we are removing the active tab, set active to 0
			if( contactMeTabs.get('activeTab') == tabCall ) { activateTab(0); }
			contactMeTabs.removeTab(tabCall);
		}

	}
};

// handle failure case for the above
function tabCheckFailure(){
	//do nothing, in good faith. 
};


var URL_BASE;
function connectCall(from_phone, username, url_base){
    URL_BASE = url_base;
    clearStatus();
    var result=true;
    if(callSessionId=="IN-PROGRESS"){
        result=confirm("Call in progress, making another call may disonnect the current call. Do you want to continue?");
    }
    if(result){
        if(!validatePhone(from_phone)){
            return;
        }
        from_phone = document.CallForm.from_phone.value;
        callSessionId="IN-PROGRESS";
        setCallStatus("Connecting...");
        //Connect Call, get Session ID
        var url = "/php/myelance/main/call.php?ctx=contactMe&mode=call&view_person="+username+"&from_phone="+from_phone+'&t='+getDateTime();
        YAHOO.util.Connect.asyncRequest('get',
          url,
          {success: callResult, failure:callFailure});
    }
}

function validatePhone(phone){
		var p = phone.replace(/[^\d\+]/g, "");
		if (p.substr(0, 3) != "011" && p.substr(0, 1) != "+") {
			if (p == "911") {
				alert("Calls to 911 emergency services cannot be completed. Please dial the number directly from your landline or cell phone");
				document.CallForm.from_phone.focus();
				return false;
			}
			if (p == "411") {
				alert("Calls to 411 directory assistance services cannot be completed. Please dial the number directly from your landline or cell phone");
				document.CallForm.from_phone.focus();
				return false;
			}
			if (!p.match(/^\+?1?[2-9]\d{2}[2-9]\d{6}$/)) {
				alert("The phone number you entered is incorrect.\n\n" +
							"Valid US phone numbers should be a total of 10-digits in length\n" +
							"and neither the area code or 7-digit phone number can start with the number \"1\".");
				document.CallForm.from_phone.focus();
				return false;
			}
		}
		if (p.substr(0, 1) == "+") p = p.substr(1);
        document.CallForm.from_phone.value = p;
	return true;
}

function cancelCall(){
    if(callSessionId){
        if(callSessionId!='IN-PROGRESS'){
        //disconnect call
        var answer = confirm("Call is in progress. Do you want to disconnect?");
        if(answer){
            var url = "/php/myelance/main/call.php?ctx=contactMe&mode=cancel&call_sk="+callSessionId+'&call_WS='+callWS+'&t='+getDateTime();
             YAHOO.util.Connect.asyncRequest('get',
          	url);
        }else{
            return;
        }
        }
        callSessionId=null;
    }
    clearStatus();
    cancelContactMe();
}

function callResult(tspt){
   var response = tspt.responseText;
   var data = response.split(' ');
   if(data[0]=='OK'){
       callSessionId=data[1];
       callWS = data[2];
       //initiate call status
       setCallStatus("");
       getCallStatus();
       isCallInProgress();
   }else{
       //TODO - Set Error Message
    setCallStatus(response);
    callSessionId=null;
   }
}
function clearStatus(){
    setCallStatus("");
    var sframe = $('callStatusFrame');
    sframe.src="";
}
function callFailure(){
    setCallStatus("<span class='errortext'> Internal Error, cannot connect call, please try again at a later time. ");
    callSessionId=null;
}

//get call status from provider
function getCallStatus(){
    if(callSessionId!=null){
        var iframe = "https://service.ringcentral.com/ringout.asp?cmd=status&format=html&css="+escape(URL_BASE+"/styles/ringCentralStatus.css")+"&sessionid="+callSessionId+"&WS="+callWS+'&t='+getDateTime();
        var sframe = $('callStatusFrame');
        sframe.src=iframe;
        setTimeout("getCallStatus()", 5000);
    }
}

function isCallInProgress(){
    if(callSessionId){
      YAHOO.util.Connect.asyncRequest('get',
          '/php/myelance/main/call.php?ctx=contactMe&mode=status&call_sk='+callSessionId+'&call_WS='+callWS+'&t='+getDateTime(),
          {success: updCallSession, failure:updCallSession});
      setTimeout("isCallInProgress()", 30000);
    }
}

function updCallSession(tspt){
   if(!tspt.responseText || tspt.responseText!=1){
       callSessionId=null;
   }
}

function setCallStatus(statusText){
    $('callStatus').innerHTML="<div style='float:left;'><b>Call Status</b>:</div><div style='float:left'>"+statusText+"</div>";
}

function saveChatStatus(){
	availablestatus = document.getElementsByName("availability");
	if(availablestatus[0].checked) {
		toggleChatStatus('1');
		$('available').attributes['onclick'].value = '';
		$('notavailable').attributes['onclick'].value = 'javascript:enableChatStatus();';
	} else {
		toggleChatStatus('0');
		$('notavailable').attributes['onclick'].value = '';
		$('available').attributes['onclick'].value = 'javascript:enableChatStatus();';
	}
	$('confirmdiv').removeClass('displayNone');
	$('save_action').addClass('btn-small-disabled');
	$('save_action').removeClass('btn-small-normal');
	$('save_action').attributes['href'].value = 'javascript:void(0)';
}

function enableChatStatus(){
	$('save_action').addClass('btn-small-normal');
	$('save_action').removeClass('btn-small-disabled');
	$('save_action').attributes['href'].value = 'javascript:saveChatStatus();';
}

function cancelChatStatus(){
	window.location.href = '/settings';
}

function toggleChatStatus(chatState){
        var username = getCookie("userid");
        var d = new Date();
                YAHOO.util.Connect.asyncRequest('get',
                   '/php/userplane/main/chat.php?ctx=myelance&userid='+username + '&chatstate=' + chatState + '&t='+d.getTime(),
                    {success: updateMyElanceChat});
}

function updateMyElanceChat(resp){
    if(resp.responseText.length >0){
		var resObj = eval('({' + resp.responseText + '})');
		if(resObj.prefEnabled != 'N'){
			if($("EnableChatSubText")) {
				document.getElementById("EnableChatSubText").innerHTML = resObj.html;
				document.getElementById("EnableChatSubText").href = 'javascript:toggleChatStatus(\'' + resObj.state + '\');';
			}
		}
        
	} else {
		alert('Failed to Toggle your chat status, please call Elance customer support and report this problem.');
	}

}


/*** AGENT STUFF ***/

// Turn on extra stuff for agent mode
function activateContactMeAgentMode(){
	$('agentNotice').removeClass('displayNone');
	$('inviteAgentSuccessMessage').removeClass('displayNone');
}

// turn off extra stuff for agent mode. Called when the panel is closed
function deactivateContactMeAgentMode(){
	$('agentNotice').addClass('displayNone');
	$('inviteAgentSuccessMessage').addClass('displayNone');
}


if( isExplorer() && window.location.hash ) {
	document.location.href = window.location.href;
}
window.onload = initProfSearch;

var htmlCallback = {
	success: replaceContent,
	upload: replaceContent,
	failure: ajaxFailure
}

function initProfSearch() {
  init_feedbackSlider();
  init_reviewsSlider();
  init_minrateSlider();
  commonSearchJs.init( profSearchJs, 'earningsSort', 1 );
  // We need to do this AFTER init form fields!
  init_locationTabs();
  profSearchJs.doSearch(false, true);
  currHashUrl = getCurrHashParams();
  if( !isAppleSafari() ) {
    checkHashChanged();
  }
}

// Initialize location search tabs (Init form fields first!)
var locationTabView;
function init_locationTabs() {
	// Set open tab based on what param is set
	if( $('regionFilter').value ) { 
		addClassName($('ltabheader1'),'selected');
	} else if( $('zipFilter').value ) { 
		addClassName($('ltabheader2'),'selected');
	} else if( $('locFilter').value ) { 
		addClassName($('ltabheader3'),'selected');
	} else { 
		// default
		addClassName($('ltabheader1'),'selected');
	} 
	
	locationTabView = new YAHOO.widget.TabView('location_tabs');
	removeClassName($('location_tabs'), 'displayNone');
}

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("/php/search/main/eolsearch.php?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);
 	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 Engineering & Manufacturing on Elance | Elance "; break;
		case "10184":
		    document.title = "Search Professionals in Design & Multimedia on Elance | Elance "; break;
		case "10183":
		    document.title = "Search Professionals in Website & Programming on Elance | Elance "; break;
		case "10178":
		    document.title = "Search Professionals in Sales & Marketing on Elance | Elance "; break;
		case "10179":
		    document.title = "Search Professionals in Admin Support on Elance | Elance "; break;
		case "10186":
		    document.title = "Search Professionals in Finance & Management 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 {
          if(value =='locSort' || value == 'nameSort'){
            $('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
    if($('amexFilter')) {
	params += "&amexFilter=" + $('amexFilter').checked;
    }
    params += "&bizFilter=" + $('bizFilter').checked;
    params += "&catFilter=" + $('catFilter').value;
    params += "&indFilter=" + $('indFilter').checked;
    params += "&premierFilter="	+ $('premierFilter').checked;
    params += "&feedbackFilter=" + $('feedbackFilter').value;
    params += "&reviewsFilter=" + $('reviewsFilter').value;
    params += "&minrateFilter=" + $('minrateFilter').value;
    params += "&locFilter=" + encodeURIComponent($('locFilter').value);
    params += "&regionFilter=" + encodeURIComponent($('regionFilter').value);
    params += "&zipFilter=" + encodeURIComponent($('zipFilter').value);
    params += "&zipRadiusFilter=" + encodeURIComponent($('zipRadiusFilter').value);
    params += "&skillFilter="	+ encodeURIComponent($('skillFilter').value);
    params += "&groupFilter="   + encodeURIComponent($('groupFilter').value);

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


  /**
   * Reset the filters.  Typically called if a new search is executed.
   */
  resetFilters : function() {
    if($('amexFilter')) {
        $('amexFilter').checked = '';
    }
    $('bizFilter').checked = '';
    $('catFilter').value = 100;
    $('indFilter').checked = '';
    $('premierFilter').checked = '';
    $('feedbackFilter').value = 0;
    $('reviewsFilter').value = 0;
    $('minrateFilter').value = 0;
    $('regionEntered').value = '';
    $('regionFilter').value = '';
    $('zipEntered').value = '';
    $('zipFilter').value = '';
    $('zipRadiusFilter').value = '50';
    $('locEntered').value = '';
    $('locFilter').value = '';
    $('skillFilter').value = '';
    sliderfeedback.setValue(0);
    sliderreviews.setValue(0);
    sliderminrate.setValue(0);
  },


  replaceContent : function(obj) {
    $('results_placeholder').innerHTML = obj.responseText;
    $('pagenav_placeholder').innerHTML = $('pagenav_subsection').innerHTML;
    $('groupimage_placeholder').innerHTML = $('groupimage_subsection').innerHTML;
    $('group_placeholder').innerHTML = $('group_subsection').innerHTML;
    $('totalresults_placeholder').innerHTML = $('totalresults_subsection').innerHTML;
    $('debug_placeholder').innerHTML = $('debug_subsection').innerHTML;
    $('category_placeholder').innerHTML = $('category_subsection').innerHTML;
    $('results_placeholder').innerHTML = $('results_subsection').innerHTML;
    commonSearchJs.showNotBusy();
		checkInviteToBidReloaded();
  },


  /**
   * 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 == 'zipEntered') {
          setLocationFilter(2);
          YAHOO.util.Event.preventDefault(keypressEvent );
          profSearchJs.doProfSearch(false);
       } else if (objInFocus == 'locEntered') {
          setLocationFilter(3);
          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;
					case "zipFilter":
						document.srchResults.zipFilter.value = args[paramName];
						document.srchResults.zipEntered.value = args[paramName];
						break;
 					case "zipRadiusFilter":
						document.srchResults.zipRadiusFilter.value = args[paramName];
						break;
					case "regionFilter":
						document.srchResults.regionFilter.value = args[paramName];
						document.srchResults.regionEntered.value = args[paramName];
						break;
 					case "premierFilter":
						if( args[paramName] == 'true' ) {
							document.srchResults.premierFilter.checked = args[paramName];
						}
						break;
 					case "bizFilter":
						if( args[paramName] == 'true' ) {
							document.srchResults.bizFilter.checked = args[paramName];
						}
						break;
 					case "indFilter":
						if( args[paramName] == 'true' ) {
							document.srchResults.indFilter.checked = args[paramName];
						}
						break;
 					case "amexFilter":
						if( document.srchResults.amexFilter ) {
							if( args[paramName] == 'true' ) {
								document.srchResults.amexFilter.checked = args[paramName];
							}
						}
						break;
					case "skillFilter":
						document.srchResults.skillFilter.value = args[paramName];
						break;
					default:
						if($(paramName)){ $(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) {
        alert('Please select at least one provider.');
		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(querystring) {
	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) {
			var val = $(baseId + i).value;
			if( querystring ){
				inviteeList.push( 'cbxProviders_' +i+ '=' +val );
			} else {
				inviteeList.push(val);
			}
		}
		++i;
	}
	
	return inviteeList;
}

// Causes the page to reload with the current invitees in the hash arguments. See the following 
// function for more info.
function reloadWithInvitees(){
	var param = '&invitees=' + getInviteeList(true).toString();
	var t = "&t=" + getDateTime(); // Ensure clean load 
	url = '/php/search/main/eolsearch.php?matchType=profile' + t + '#'+ getCurrHashParams() + param;
	// If we dont pause, the browser can navigate to the new page before setting cookie == bad
	setTimeout('window.location.href = url;', 500);
}

// Checks if the page has been reloaded with invited providers. This means we need to check those 
// boxes, then show the request proposal dialog
function checkInviteToBidReloaded() {
	var args = getArgsFromHash();
	if( !args.invitees ){ return; }

	// the data is like "cbxProviders_1=12345,cbxProviders_2=67890"
	var pairs = args.invitees.split(",");
	for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if( pos == -1 ) continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		value = decodeURIComponent(value);
		if( $(argname) ){ $(argname).checked = true; }
	}
	getRequestQuote();
}

// sets location filter based on mode argument. Also clears all 3 before starting
function setLocationFilter(mode) {
	// Clear all 3 location filters (the hidden tags, not the form tags)
	$('regionFilter').value = '';
	$('zipFilter').value = '';
	$('locFilter').value = '';

	switch(mode) {
		case 1:
			profSearchJs.setSrchParam('regionFilter', $('regionEntered').value);
		break;
		case 2:
			profSearchJs.setSrchParam('zipFilter', $('zipEntered').value);
		break;
		case 3:
			profSearchJs.setSrchParam('locFilter', $('locEntered').value);
		break;
	}
}

var profileExpandedTab=[];
var currentId ='';
/** Expand and collapse skills by ID
var loaded
 */
function toggleSkills(id, catid) {
    if(profileExpandedTab[''+id+'_'+catid] && profileExpandedTab[''+id+'_'+catid]!='Skills'){
        toggleTeam(id, catid);
    }

    if( $('skillsBox'+id+'_'+catid).style.display == 'none' ){
        profileExpandedTab[''+id+'_'+catid] = 'Skills';
				//-- Only call getSkills if there is no previous data
				if( $('skills'+id+'_'+catid).innerHTML.length == 0 || 
						$('skills'+id+'_'+catid).innerHTML.match('ajax-loader') ) { 
	        //check if certified skill is selected
  	      if($('skillFilter').value > 0) {
    	    	getSkills(1, id, catid, $('skillFilter').value, 1, 'master');
      	  }
        	else {
        		getSkills(1, id, catid, '', '');
	        }
				}
        $('skillsButton'+id+'_'+catid).addClass('profilebuttonminus');
        $('skillsBox' + id+'_'+catid).style.display = '';
    } else {
        profileExpandedTab[''+id+'_'+catid] = '';
        $('skillsButton'+id+'_'+catid).removeClass('profilebuttonminus');
        $('skillsBox' + id+'_'+catid).style.display = 'none';
    }
}

// Get skills content from server
function getSkills(page, id, catid, skillFilter, skillCertified, skillType){
  if( page == undefined || page == null ){ page = 1; }
  if(!skillType){ skillType = ''; }

  cancelRunningRequests();
  $('skills'+id+'_'+catid).innerHTML = $('ajaxLoader').innerHTML;

  var t = "&t=" + getDateTime();
  var params = "userid="+id+'&catid='+catid+'&skillFilter='+skillFilter+'&skillCertified='+skillCertified+'&skillType='+skillType+"&page="+page;
  currentId = ''+id+'_'+catid;
  curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/provider_skills.php?'+ params, {success:replaceSkillsContent, failure:ajaxFailure}, null);
}

// onSuccesss handler for the above
function  replaceSkillsContent(obj){
  $('skills'+currentId).innerHTML = obj.responseText;
}

/** Expand and collapse team by ID
 */
function toggleTeam(id, catid) {
    if(profileExpandedTab[''+id+'_'+catid] && profileExpandedTab[''+id+'_'+catid]!='Team'){
        toggleSkills(id, catid);
    }

    if ($('teamBox'+id+'_'+catid).style.display == 'none') {
        profileExpandedTab[''+id+'_'+catid] = 'Team';

				//-- Only call getTeam if there is no previous data
				if( $('team'+id+'_'+catid).innerHTML.length == 0 || 
						$('team'+id+'_'+catid).innerHTML.match('ajax-loader') ) { 
					//check if certified skill is selected
  	      if($('skillFilter').value > 0) {
    	    	getTeam(1, id, catid, $('skillFilter').value, 1, 'master');
      	  }
        	else {
        		getTeam(1, id, catid, '', '');
	        }
				}
        $('teamButton'+id+'_'+catid).addClass('profilebuttonminus');
        $('teamBox'+id+'_'+catid).style.display = '';
    } else {
        profileExpandedTab[''+id+'_'+catid] = '';
        $('teamButton'+id+'_'+catid).removeClass('profilebuttonminus');
        $('teamBox' + id+'_'+catid).style.display = 'none';
    }
}

// Get team content from server
function getTeam(page, id, catid, skillFilter, skillCertified, skillType){
    if( page == undefined || page == null ){ page = 1; }
    if(!id){ id = currentId; }
    if(!skillType){ skillType = ''; }

    cancelRunningRequests();
    $('team'+id+'_'+catid).innerHTML = $('ajaxLoader').innerHTML;

    var t = "&t=" + getDateTime();
    var params = "userid="+id+'&catid='+catid+'&page=1&mode=search&sort=&skillFilter='+skillFilter+'&skillCertified='+skillCertified+'&skillType='+skillType+"&page="+page;
    currentId = ''+id+'_'+catid;
    curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/provider_team.php?'+ params, {success:replaceTeamContent, failure:ajaxFailure}, null);
}

// OnSuccess handler for the above
function  replaceTeamContent(obj){
    document.getElementById('team'+currentId).innerHTML = obj.responseText;    
}

// Changes the page of the agent list for team tab.
function changeAgentListPage(page,id, filter,certified, catid){
    var sCertified='';
    if(certified){
            sCertified=1;
            filter = document.getElementById('filter'+id+'_'+catid).value;
    }
    filter = document.getElementById('filter'+id+'_'+catid).value;
    if(document.getElementById('certified'+id+'_'+catid).checked) sCertified=1;
    getTeam(page, id, catid, filter, sCertified);
}

// Changes the page of the skill list for team tab.
function changeSkillListPage(page,id, filter,certified, catid){
    var sCertified='';
    if(certified){
        sCertified=1;
        filter = document.getElementById('skillfilter'+id+'_'+catid).value;
    }
    filter = document.getElementById('skillfilter'+id+'_'+catid).value;
    if(document.getElementById('skillcertified'+id+'_'+catid).checked) sCertified=1;
    getSkills(page, id, catid, filter, sCertified);
}
