


/* The reason these variables are here is because these are functions or globally referenced
   variable names that are used in Gallery. In order for onclick calls to properly function
   we need to introduce these objects into the javascript namespace so when we eval them in
   replaceContent that they will exist outside of replaceContent
*/
var sel = null;
var list = null;
var html = null;
var save = null;
var doclick = null;
var addOne = null;
var fileIndex = null;
//var background = null;
//var editWindow = null;
var setCheck = null;


/**
    sortItem:
    1 - comments
    2 - category
    3 - amount
    4 - date
    5 - feedback

    userType:
    1 - provider
    2 - buyer
 */
function historySort(sortItem, userType, start, changeSort) {
	if (changeSort) {
		// default to sorting from high to low
		if (sortColumn == sortItem) {
			sortDesc = !sortDesc;
		} else {
			sortDesc = true;
		}
	}
    changeSort = (changeSort == undefined)?true:changeSort;
    sortColumn = (sortItem == undefined)?sortColumn:sortItem;  // save global to keep track of column that is sorted
    historyStart = (start == undefined)?1:start;   // save global to keep track of what page we're viewing

    if (!sortColumn) {
        // default to date
        sortColumn = 4;
    }

    // get filters
    var feedbackOnly = '';
    var feedbackGiven = '';
    var rating = '';
    var timeframe = '';
    var category = '';
    var subcategory = '';
	var ratingDropdown = $('ratingDropdown');
	var timeframeDropdown = $('timeframeDropdown');
	var categoryDropdown = $('categoryDropdown') || $('categorySelectionDropdown');
	var givenFeedback = $('feedbackGiven');
        var subcategoryDropdown = $('subcategoryDropdown');
    var feedbackTab = $('feedbackReceivedTab');
    
    if (ratingDropdown && ratingDropdown.selectedIndex != 0) {
        rating = '&rating='+ $('ratingDropdown').selectedIndex;
    }
    if (timeframeDropdown && timeframeDropdown.selectedIndex != 0) {
        timeframe = '&timeframe='+ $('timeframeDropdown').selectedIndex;
    }
    if (categoryDropdown && categoryDropdown.selectedIndex > 0) {
        category = '&category='+ categoryDropdown.options[categoryDropdown.selectedIndex].value;
        if (subcategoryDropdown && subcategoryDropdown.selectedIndex > 0) {
            subcategory = '&subcategory='+ subcategoryDropdown.options[subcategoryDropdown.selectedIndex].value;
        }
    }
    if (feedbackTab && feedbackTab.className == 'tabbigselected') {
        // only show projects with feedback
        feedbackOnly = '&feedbackOnly=1';
    }
	if (userType == 2) {
		if (givenFeedback && givenFeedback.className == 'tabbigselected') {
			feedbackGiven = '&feedback=1';
		} else {
			feedbackGiven = '&feedback=2';
		}
	}
    if ($('collapse')) {
        // expand the feedback
        expand = '&expand=1';
    } else {
        // collapse the feedback
        expand = '&expand=0';
    }

    replaceId = 'ratingHistory';
    document.body.style.cursor = 'wait';

    contentReplaced = false;
    if (2 == userType) { 
      if ( givenFeedback.className != 'tabbigselected') {
         curWaitingCode = '$("sortCol'+ sortColumn +'").className = '+ (sortDesc?'"sortDown"':'"sortUp"') +'; $("feedbackCountReceived").innerHTML = "(" + $("hiddenFeedbackCount").innerHTML + ")"; $("feedbackCount").innerHTML = \'\'; displayTopPagination(); setRNavHeight();';
       } else { 
         curWaitingCode = '$("sortCol'+ sortColumn +'").className = '+ (sortDesc?'"sortDown"':'"sortUp"') +'; $("feedbackCountReceived").innerHTML = \'\'; $("feedbackCount").innerHTML =  "(" + $("hiddenFeedbackCount").innerHTML + ")&nbsp;"; displayTopPagination(); setRNavHeight();';
      }
    } else {
       curWaitingCode = '$("sortCol'+ sortColumn +'").className = '+ (sortDesc?'"sortDown"':'"sortUp"') +'; $("feedbackCount").innerHTML = $("hiddenFeedbackCount").innerHTML; displayTopPagination(); setRNavHeight();';
    }
    cancelRunningRequests();
    userid = getUserId();
    curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/history.php?&userid='+ userid +'&sort='+ sortColumn +'&usertype='+ userType +'&start='+ historyStart +'&desc='+ (sortDesc?1:0) + rating + timeframe + category + subcategory + feedbackGiven + expand + feedbackOnly + '&t='+ getDateTime(), htmlCallback, null);
    curLoad = setInterval('isLoaded()', 100);
}

function toggleAllHistoryItems(el) {
    if (el.id == 'expand' || el.id == '') {
        expanding = true;
    } else {
        expanding = false;
    }
    
    var expandAllText = $('expandAllText');
    
    if (expanding) {
        el.id = 'collapse';
        visGroup1 = '';
        visGroup2 = 'none';
        expandAllText.innerHTML = 'Collapse All';
    } else {
        el.id = 'expand';
        visGroup1 = 'none';
        visGroup2 = '';
        expandAllText.innerHTML = 'Expand All';
    }

    incrementListDomToggle('expanded', 'style.display', visGroup1, undefined);
    incrementListDomToggle('charts', 'style.display', visGroup1, undefined);
    incrementListDomToggle('collapsed', 'style.display', visGroup2, undefined);
    incrementListDomToggle('collapseMinusImg', 'style.display', visGroup1, undefined);
    incrementListDomToggle('expandPlusImg', 'style.display', visGroup2, undefined);
	
	var buyerComments = document.getElementsByName('comment');
	var label;
	for (i = 0; i < buyerComments.length; ++i) {
		label = $('buyerLabel'+i);
		if (!buyerComments[i].innerHTML.trim().length) {
			// if there are no comments, then hide the static text
			label.style.display = 'none';
		}
	}

	var providerComments = document.getElementsByName('providerComment');
	for (i = 0; i < providerComments.length; ++i) {
		label = $('providerLabel'+i);
		if (!providerComments[i].innerHTML.trim().length) {
			// if there are no comments, then hide the static text
			label.style.display = 'none';
		}
	}

    setRNavHeight();
}

function toggleHistoryItem(el) {
    // the id of the element we pass in here is of the form feedbackRow## and "feedbackRow"
    // is 11 characters
    var id = el.id.substring(6);
    var collapseImg = $('collapseMinusImg'+id).style.display;
    if (collapseImg == 'none') {
        // expand
        $('collapseMinusImg'+id).parentNode.parentNode.style.height = '';
        // hide static labels if there is nothing to label
//        if (!$('buyer'+ id).innerHTML.trim().length) {
//            $('buyerLabel' + id).style.display = 'none';
//        }
        if ($('provider'+ id) && !$('provider'+ id).innerHTML.trim().length) {
            $('providerLabel' + id).style.display = 'none';
        }

        // expand
        $('expandPlusImg'+id).style.display = 'none';
        $('collapseMinusImg'+id).style.display = '';

        if ($('collapsed' + id)) {
            $('collapsed' + id).style.display = 'none';
        }
        if ($('expanded' + id)) {
            $('expanded' + id).style.display = '';
        }
        if ($('charts' + id)) {
            $('charts' + id).style.display = '';
        }
    } else {
        // collapse
        $('collapseMinusImg'+id).parentNode.parentNode.style.height = '30px';
        $('expandPlusImg'+id).style.display = '';
        $('collapseMinusImg'+id).style.display = 'none';

        if ($('collapsed' + id)) {
    		$('collapsed' + id).style.display = '';
        }
		if ($('expanded' + id)) {
            $('expanded' + id).style.display = 'none';
        }
        if ($('charts' + id)) {
		    $('charts' + id).style.display = 'none';
        }
    }

    setRNavHeight();
}

function editItem(editObj, folder) {
    if (!editObj) {
        // if we don't have an item, then open the folder
        if (globalAlbum) {
            editItem(globalAlbum, true);
        } else {
            return;
        }
    }
    // lame IE browser viewable area width/height check
    viewableAreaWidth = window.innerWidth;

    if (!viewableAreaWidth) {
        viewableAreaWidth = document.body.offsetWidth;
    }

    if (viewableAreaWidth < document.body.clientWidth) {
        viewableAreaWidth = document.body.clientWidth;
    }

    background = new YAHOO.widget.Overlay('overlayBackground', { x: 0,
                                                          y: 0,
                                                          width: viewableAreaWidth +"px",
                                                          height: windowHeight + yWindowOffset +"px",
                                                          visible: false,
                                                          zindex: 52
                                                        }
                                           );
    editWindow = new YAHOO.widget.Overlay("editWindow",
                                                 { x: viewableAreaWidth/2 - windowWidth/2,
                                                   y: yWindowOffset,
                                                   width: windowWidth +"px",
                                                   height: windowHeight +"px",
                                                   visible: false,
                                                   draggable: false,
                                                  zindex: 53
                                                 }
                                           );

    background.render();
    editWindow.render();

	// Define various event handlers for Dialog
	cancelRunningRequests();
	replaceId = 'editWindow';
    addCSS('/php/lib/gallery2/themes/matrix/local/theme.css');
	if (folder || null == editObj) {
		// I suppose if the user hits edit item we should just open the current folder for editing
	    YAHOO.util.Connect.asyncRequest('GET', '/php/lib/gallery2/main.php?g2_itemId='+ editObj +'&t='+ getDateTime(), galleryCallback, null);
	} else {
	    YAHOO.util.Connect.asyncRequest('GET', '/php/lib/gallery2/main.php?g2_view=core.ItemAdmin&g2_subView=core.ItemEdit&g2_itemId='+ editObj +'&t='+ getDateTime(), galleryCallback, null);
	}
	background.show();
	editWindow.show();
    
    if ($('overlayBackground')) {
        $('overlayBackground').style.backgroundColor = "#000";
        $('overlayBackground').style.filter = "alpha(opacity=50)";
    }
    

	YAHOO.util.Event.preventDefault("click");
    // bind the submit listener to "itemAdminForm" because all the forms in gallery
    // (that are accessible to us at least) have that id. We'd like to just bind the listener
    // to "editWindow" but IE has some weird bubbling issue with submit events
//	YAHOO.util.Event.addListener('editWindow', 'submit', handleSubmit, this, true);
	YAHOO.util.Event.addListener('editWindow', 'click', handleClick, this, true);
}

function handleClick(e) {
	var anchor = e.target;

    // IE madness
    if (!anchor) {
        anchor = window.event.srcElement;
        e = window.event;
    }

    if (curAsyncRef) {
        // don't accept clicks if we're processing
		YAHOO.util.Event.preventDefault(e);
        return;
    }

    if (anchor && ('submit' == anchor.type || 'image' == anchor.type) && 'input' == anchor.tagName.toLowerCase()) {
        YAHOO.util.Event.preventDefault(e);
        handleSubmit(e);
        return;
    }
    
	if ('a' != anchor.tagName.toLowerCase()) {
		anchor = anchor.parentNode;
	}

	if (!anchor) {
		return true;
	}

	if (anchor.onclick) {
		//alert('prevent event');
		YAHOO.util.Event.preventDefault(e);
	} else if ('a' == anchor.tagName.toLowerCase()) {
		//alert('prevent anchor');
		YAHOO.util.Event.preventDefault(e);
		replaceId = 'editWindow';
        
        contentReplaced = false;
        curWaitingCode = "YAHOO.util.Event.addListener('itemAdminForm', 'submit', handleSubmit, this, true); scroll(0,0);";
        cancelRunningRequests();
		curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', anchor.href +'&t='+ getDateTime(), htmlCallback, null);
        curLoad = setInterval('isLoaded()', 100);
    
        return false;
	}

	return true;
}

var lameYahooHack = null;
function handleSubmit(e) {
	var el = e.target;

    // IE madness
    if (!el) {
        el = window.event.srcElement;
        e = window.event;
    }

	YAHOO.util.Event.preventDefault(e);

	// find the form element
	while(el && !el.action) {
		el = el.parentNode;
	}

	// if there is no form element, then something is wrong, so just return
	if (!el) {
		return;
	}

	// check for file upload
	var fileUpload = false;
	var inputs = el.getElementsByTagName('input');
	numChildren = inputs.length;
	var postData = '';
	for(i = 0; i < numChildren; ++i) {
		if (inputs[i].type == 'file' && inputs[i].value.length > 0) {
			fileUpload = true;
//		} else if ('submit' == inputs[i].type && inputs[i].name != e.explicitOriginalTarget.name) {
			// we want to ignore submit buttons that we didn't click
//			continue;
		} else if (inputs[i].value.length > 0) {
			postData += '&'+ inputs[i].name +'='+ inputs[i].value;
		}
	}
	if (!fileUpload) {
		postData = null;
	} else {
		postData = postData.substr(1);
	}

	replaceId = 'editWindow';

	// YUI incorrectly assumes that the first submit in a form is the one we clicked on, so setting this
	// variable forces it to check that the element that received the click is the one it treats as
	// the submitter
    if (e.explicitOriginalTarget) {
        // Firefox
    	lameYahooHack = e.explicitOriginalTarget.name;
    } else if (document.activeElement) {
        // IE
        lameYahooHack = document.activeElement.name;
    } else {
        // Safari...trifecta!
        lameYahooHack = e.srcElement.getAttribute('name');
    }

	YAHOO.util.Connect.setForm(el.id, fileUpload);
	lameYahooHack = undefined;

    replaceId = 'editWindow';
    contentReplaced = false;
    
    cancelRunningRequests();
    postData += '&t='+ getDateTime();
    curWaitingCode = "YAHOO.util.Event.addListener('itemAdminForm', 'submit', handleSubmit, this, true); scroll(0,0);";
	curAsyncRef = YAHOO.util.Connect.asyncRequest('POST', el.action, htmlCallback, postData);
    curLoad = setInterval('isLoaded()', 100);
}


function getUserId() {
    userid = getGetParam('userid');
    if (!userid) {
        userid = $('profileUserId').innerHTML;
    }
    return parseInt(userid);
}

function displayTopPagination() {
    $('shownTopPagination').innerHTML = $('topPagination').innerHTML;
}


function loadSlowImages() {
    // if ($('aolStatusImage')) {
    // $('aolStatusImage').src = 'http://api.oscar.aol.com/SOA/key=el1Q9GEc5tINJiUS/presence/'+ $('aolStatusImage').name;
    // }
}

// dynamically set the height of the profile rnav based on the height of the main content
function setRNavHeight() {
	//set height to content length
    $('profileRNav').style.height = 'auto';
	$('profileMainContent').style.height = 'auto';
	
	mainContentHeight = $('profileMainContent').clientHeight;
	rNavHeight = $('profileRNav').clientHeight;
	
	//find the tallest content section and adjust the shorter one to match
	if( mainContentHeight > rNavHeight ) {
		pTop = $('profileRNav').style.paddingTop;
		pBot = $('profileRNav').style.paddingBottom;
		pTop = parseInt(pTop.substr(0, pTop.indexOf('px', 0)));
		pBot = parseInt(pBot.substr(0, pBot.indexOf('px', 0)));
			
		$('profileRNav').style.height = ( mainContentHeight - (pTop + pBot) ) + 'px';
	}
	else if( rNavHeight > mainContentHeight ) {
		$('profileMainContent').style.height = rNavHeight + 'px';
	}
}

function clickHandler(e) {
    if (!e) {
        // IE
        e = window.event;
    }

    if (e.target && e.target.onclick) {
        // if we have a onclick then just do that and NOTHING else
        e.stopPropagation();
        return false;
    }

    // do whatever else is default
}

function editProfileImage(action,context) {
	if(!context)
		context = '';
    // lame IE browser viewable area width/height check
    viewableAreaWidth = window.innerWidth;

    if (!viewableAreaWidth) {
        viewableAreaWidth = document.body.offsetWidth;
    }

    if (viewableAreaWidth < document.body.clientWidth) {
        viewableAreaWidth = document.body.clientWidth;
    }

    background = new YAHOO.widget.Overlay('overlayBackground', { x: 0,
                                                          y: 0,
                                                          width: viewableAreaWidth +"px",
                                                          height: windowHeight + yWindowOffset +"px",
                                                          visible: false,
                                                          zindex: 52
                                                        }
                                           );
    editWindow = new YAHOO.widget.Overlay("editWindow",
                                                 { x: viewableAreaWidth/2 - windowWidth/2,
                                                   y: yWindowOffset,
                                                   width: windowWidth +"px",
                                                   height: windowHeight +"px",
                                                   visible: false,
                                                   draggable: false,
                                                  zindex: 53
                                                 }
                                           );

    background.render();
    editWindow.render();

	// Define various event handlers for Dialog
	replaceId = 'editWindow';
    addCSS('/php/lib/gallery2/themes/matrix/local/theme.css');

    cancelRunningRequests();
    YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/profile_image.php?controller_action=' + action + '&context='+ context + '&t='+ getDateTime(), htmlCallback, null);
	
	background.show();
	editWindow.show();
    
    if ($('overlayBackground')) {
        $('overlayBackground').style.backgroundColor = "#000";
        $('overlayBackground').style.filter = "alpha(opacity=50)";
    }

	YAHOO.util.Event.preventDefault("click");
    // bind the submit listener to "itemAdminForm" because all the forms in gallery
    // (that are accessible to us at least) have that id. We'd like to just bind the listener
    // to "editWindow" but IE has some weird bubbling issue with submit events
//	YAHOO.util.Event.addListener('editWindow', 'submit', handleSubmit, this, true);
	YAHOO.util.Event.addListener('editWindow', 'click', handleClick, this, true);
}


/* Extremely generic function to toggle an attribute for dom items with the
 * same name between their default value and another value. Setting forced will
 * make the elements attribute to be set to forced
 * Using the variable "value" will swap between that value and blank (i.e. '')
 */
function listDomToggle(elName, changeAttribute, forced, value) {
    // beware that IE/Opera require getElementsByName to have id and name set to the same thing
    elList = document.getElementsByName(elName);
    for (i = 0; i < elList.length; i++) {
        item = 'elList[i].'+ changeAttribute;
		if (forced == undefined) {
	        eval(item +' = ('+ item +' == value)?"":value;');
		} else {
			eval(item +' = forced;');
		}
    }
}

/* Toggles innerHTML for DOM items with the same name between choice1 and choice2 while
 * using fuzzy string matching to account for white space
 */
function toggleText(elName, forced, choice1, choice2) {
    elList = document.getElementsByName(elName);
    for (i = 0; i < elList.length; i++) {
		if (forced == undefined) {
	        elList[i].innerHTML = (elList[i].innerHTML.indexOf(choice1) == -1)?choice1:choice2;
		} else {
			elList[i].innerHTML = forced;
		}
    }
}

function incrementListDomToggle(elName, changeAttribute, forced, value) {
    i = 0;
    while($(elName + i)) {
        var item = '$(elName + i).'+ changeAttribute;
        if (forced == undefined) {
            eval(item +' = ('+ item +' == value)?"":value;');
        } else {
            eval(item +' = forced;');
        }
        i++;
    }
}


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

var paginationCallback = {
	success: replacePaginationContent,
	failure: ajaxFailure
}

var galleryCallback = {
	success: replaceGalleryContent,
	failure: ajaxFailure
}


//this function includes all necessary js files for the application
function include(file)
{
	var script = document.createElement('script');
	script.src = file;
	script.id = file;
	script.type = 'text/javascript';
	script.defer = true;

	document.getElementsByTagName('head').item(0).appendChild(script);
}

function HelpBig( thisLink ) {
		var comwin = window.open(thisLink,'','width=800,height=480,scrollbars=1,resizable=1');
			comwin.focus();
}
window.onload = init;

// 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;
// sort asc or desc
var sortDesc = true;
// which column are we sorting
var sortColumn = null;
// which page of feedback/project history are we viewing
var historyStart = 0;
// are we sorting asc or desc
var sortDirection = 'desc';
// current tab we are on
var curProfileTab = -1;

// YAHOO overlay objects
var background = null;
var editWindow = null;

var profile_mode = null;

	var args = getArgsFromHash();
	var tab = args.tab;
function init() {
	var args = getArgsFromHash();
	var tab = args.tab;
	if(!tab) tab = 0;
	//check for edit mode
	if( $('profile_mode') ) {
		profile_mode = $('profile_mode').value;
	}
	if(tab == 0  && ($('tabContent').innerHTML).replace(/^\s*|\s*$/g,'') != '') {
		profileCategorySelection(100);
		setRNavHeight();
		return;
	}
	switch (tab) {
		case '0':
			providerTab('Profile');
		break;
		case '1':
			providerTab('Portfolio');
		break;
		case '2':
			if ( $('backUrlLink') && $('backUrlLink').href.match('eolsearch') ) {
				providerTab( 'Feedback', getSelectedProfile(), 0, -1, 1, -1 );
			}
			else {
				providerTab('Feedback');
			}
		break;
		case '3':
			// If we have skillFilter as an argument, set it now
			if( args.skillFilter ){
				$('skillFilter').value = args.skillFilter;
			}
			providerTab('Team', getSelectedProfile(), 0, -1, 0, -1);
			break;
		case '4':
			providerTab('Job History');
			break;
		default:
			providerTab('Profile');
		break;
	}

	// Handle contactMe Tab
	if( args.cmTab ) {
        cmLoad(args.cmTab);
	}
    //Handle interview Button
    canInterview();
	document.onclick = clickHandler;

}

function providerTab(selected) {
  providerTab( selected, getSelectedProfile(), 0, -1, 0, -1 );  
}
function displayAnchor(){
	var args = getArgsFromHash();
	
	switch (args.anchor){
		case 'credentials':
				var pos = $('credentials').getPosition();
				var yPos = (pos.y - 20);
				scroll(0, yPos);
		break;
		case 'skills':
				var pos = $('skills').getPosition();
				var yPos = (pos.y - 10);
				scroll(0, yPos);
		break;
	}
}

function providerTab(selected, catid, history, subcatid, timeframe, skillId) {
	catid  = catid || getSelectedProfile();
	history = history || 0;
	userid = getUserId();
	timeframe = timeframe || 0;
	skillId = skillId || -1;
	
	$('tabContent').innerHTML = '<div style="text-align: center; margin: 50px"><img src="/media/images/4.0/ajax-loader.gif"></div>';
	replaceId = 'tabContent';

	switch(selected) {
		case 'Profile':
			curProfileTab = 0;
			contentReplaced = false;
			
			var editParam = '';
			if( profile_mode == 'edit' ) {
				editParam = '&edit=true';
			}

			$('categorySelectionDropdown').disabled = true;
			curWaitingCode = "$('categorySelection').style.display = 'block'; profileCategorySelection("+ catid +"); $('providerCategoryText').innerHTML = 'Profile for:'; setRNavHeight(); $('categorySelectionDropdown').disabled = false; loadSlowImages();";
			cancelRunningRequests();
			curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/provider_profile.php?userid='+ userid + editParam + '&t='+ getDateTime(), htmlCallback, null);	
			curLoad = setInterval('isLoaded()', 100);
			selectTab(selected);
		break;
		case 'Portfolio':
			if (window.globalCarousel != undefined) {
			globalCarousel = null;
			}
			curProfileTab = 1;
			$('categorySelection').style.display = 'none';

			// load prerequisite javascript files before loading the content
			addJavascript('/scripts/profile/portfolio.js');

			// load portfolio.js last because we reference the DOM created by the above call
			// after it is loaded call pageLoad, which resides in the .js file, but make sure it
			// exists before calling it. Complicated but it works.
			curWaitingCode = "addCSS('/styles/portfolio.css'); addCSS('/styles/portfolio_more.css'); curLoad = setInterval('objExists(window.pageLoad, \"window.pageLoad()\")', 100); setRNavHeight(); loadSlowImages();";
			var editParam = '';
			if( profile_mode == 'edit' )
				editParam = '&edit=true';
			cancelRunningRequests();
			curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/provider_portfolio.php?userid='+ userid + editParam + '&t='+ getDateTime(), htmlCallback, null);	
			
			curLoad = setInterval('isLoaded()', 100);
			selectTab(selected);
		break;
		case 'Job History':
			curProfileTab = 4;
			contentReplaced = false;
		case 'Feedback':
			if (curProfileTab != 4) curProfileTab = 2;
			contentReplaced = false;
			
			$('categorySelectionDropdown').disabled = true;
			dropdownObj = $('categorySelectionDropdown');
			curWaitingCode = "$('categorySelection').style.display = 'block'; " + (history == 1 ? "projectHistoryFilter(true);" : "projectHistoryFilter(false);") + (timeframe == 1 ? "$('timeframeDropdown').selectedIndex = 1;" : "") + " loadFeedbackCategoryFilter(); feedbackCategorySelection("+ catid +"); categorySelection($('categorySelectionDropdown'), false); feedbackSubcategorySelection("+ subcatid +"); $('providerCategoryText').innerHTML = 'Feedback for:'; setRNavHeight(); $('categorySelectionDropdown').disabled = false; loadSlowImages();";

			cancelRunningRequests();
			curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/provider_ratings.php?userid='+ userid +'&usertype='+ getGetParam('usertype') +'&projectHistory='+history+'&t='+ getDateTime(), htmlCallback, null);	
			
			curLoad = setInterval('isLoaded()', 100);
			selectTab(selected);
			break;

		case 'Team':
			curProfileTab = 3;
			contentReplaced = false;
			$('categorySelection').style.display = 'none';

			// JS to run once team content is loaded
			var skillFilter = (skillId != '-1' ? skillId : $('skillFilter').value);
			curWaitingCode = "skillSelection('" + skillFilter + "'); setRNavHeight(); window.scrollTo(0,0);";

			// Get the page's settings and construct URL
			var teamPage = $('teamPage').value;
			var teamSort = $('teamSort').value;
			var skillCertified = $('skillCertified').value;
			var url = '/php/profile/main/provider_team.php?userid='+userid + '&page='+teamPage + '&sort='+teamSort + '&skillFilter='+skillFilter + '&skillCertified='+skillCertified + '&t='+getDateTime();

			// Cancel the current request [if any] and fire off our new request
			cancelRunningRequests();
			curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', url, htmlCallback, null);
			curLoad = setInterval('isLoaded()', 100);
			selectTab(selected);
			break;
	}
}

function skillSelection(id) {
         skillId = id || null;

         var dropdown = $('filter');
         if (skillId) {
                for (i = 0; i < dropdown.options.length; ++i) {
                        if (dropdown.options[i].value == skillId) {
                                dropdown.selectedIndex = i;
                                break;
                        }
                }

        }
}

function selectTab(id) {
	var temp = $('Profile');
	$('Profile').className='tabbigunselected clickable';
	
	if($('Portfolio'))
		$('Portfolio').className='tabbigunselected clickable';
		
	if($('Feedback'))
		$('Feedback').className='tabbigunselected clickable';

	if($('Team'))
		$('Team').className='tabbigunselected clickable';

	if($('Job History'))
		$('Job History').className='tabbigunselected clickable';

	$(id).className= 'tabbigselected';
}

function historyToggle(el, basicView) {
	var plusMinus = '-';
	var tableRow = '';

	if (basicView) {
		plusMinus = '+';
		tableRow = 'none';
	}

	listDomToggle('histToggleItems', 'style.display', tableRow);	// displays/hides table rows
	if (el.className == 'tabselected') {
		listDomToggle('viewChoice', 'className', undefined, 'tabselected'); // changes text color
	}
	toggleText('plusMinus', plusMinus);
}

// call correct category selection function based on what tab we're on
function categorySelection(obj, doSearch) {
	if ($('profileTab')) {
		profileCategorySelection();
	} else {
		// bind the top category dropdown to the bottom feedback dropdown and vice versa
		if (obj.id == 'categoryDropdown') {
			if ($('categorySelectionDropdown')) {
				$('categorySelectionDropdown').selectedIndex = obj.selectedIndex;
			}
		} else {
			if ($('categoryDropdown')) {
				$('categoryDropdown').selectedIndex = obj.selectedIndex;
			}
		}
	if (doSearch== undefined) {
		historySort(sortColumn, '1', 1, false);
	}
		loadFeedbackSubcategoryFilter();
		feedbackCategorySelection();
	}
}

function subcategorySelection() {
	historySort(null, 1, null);
}

function feedbackSubcategorySelection(subcatid) {
	subcatid = subcatid || null;
	dropdown = $('subcategoryDropdown');
	if (subcatid) {
		for (i = 0; i < dropdown.options.length; ++i) {
			if (dropdown.options[i].value == subcatid) {
				dropdown.selectedIndex = i;
				break;
			}
		}
	}
	historySort(null, 1, null);
}

function profileCategorySelection(catid) {
	// show/hide category specific items based on dropdown
	catid = catid || null;
	dropdown = $('categorySelectionDropdown');
	
	if (catid) {
		for (i = 0; i < dropdown.options.length; ++i) {
			if (dropdown.options[i].value == catid) {
				dropdown.selectedIndex = i;
				break;
			}
		}
	}
	
	catSel = dropdown.selectedIndex;
	displayStyle = 'displayTableCell';
	// elementList will contain a table cell for each row in the table in the following order:
	// category name, 6 mo pos feedback percentage, 6 mo # of reviews, 6 mo earnings, lifetime earnings
	elementList = document.getElementsByName('categoryTypeSummaryItem');

	if ($('categoryExperienceName')) {
		$('categoryExperienceName').innerHTML = dropdown.options[catSel].text;
	}

	// load subcategory experience
	catid = dropdown.options[catSel].value;
	increment = 3;
	if (0 == catSel) {
		// all categories
		catid = "All";
		increment = 4;
	}

	// load in experience data from hidden div
	subcatRows = $('experienceParentCat'+catid);
	subCatTableData = '<table width="100%"><tbody>';

    if (subcatRows) {
        if (subcatRows.childNodes.length > 0) {
            for(i = 0; i < subcatRows.childNodes.length; i += increment) {
                // get category id for link to feedback page, this is different if we're showing
                // all categories or just a single category
                if ("All" == catid) {
                    selectedCatid = subcatRows.childNodes[i+2].innerHTML;
                subcatid = subcatRows.childNodes[i+3].innerHTML;
                } else {
                    selectedCatid = catid;
                subcatid = subcatRows.childNodes[i+2].innerHTML;
                }
                subCatTableData += "<tr>"+ 
                                   "<td align='left' colspan='2'><span class='clickable' onclick='providerTab(\"Feedback\", "+ 
                                   selectedCatid +",1, " + subcatid + ")'>"+ 
                                   subcatRows.childNodes[i].innerHTML + " (" + subcatRows.childNodes[i+1].innerHTML + ")" +
                                   "</span></td></tr>";
            }
        } else {
            // no projects at all, give little error note to explain what the user is seeing
            subCatTableData = "No completed projects for this category";
        }
    } else {
        // if the user doesn't have any projects completed for the current category...
        if ($('experienceSubCatTable')) {
            subCatTableData = "No completed projects for this category";
        }
    }
    if ($('experienceSubCatTable')) {
        subCatTableData += '</tbody></table>';
        $('experienceSubCatTable').innerHTML = subCatTableData;
    }

	// if we've selected "All Categories" then we hide the category specific column
	if (0 == catSel) {
		displayStyle = 'displayNone';
	} else {
		elementList[0].firstChild.innerHTML = dropdown.options[catSel].text;
	}

	// display/hide premier icon - except for all categories we don't show it ever
	if (catSel) {
		var curCategory = $('hiddenAggData'+ parseInt(catSel)).childNodes;
		if (curCategory[14].innerHTML == 1) {
			$('providerProfilePremierIcon').style.display = 'inline';
		} else {
			$('providerProfilePremierIcon').style.display = 'none';
		}
	} else {
		$('providerProfilePremierIcon').style.display = 'none';
	}

	// Category specific general profile bin
	// map the table rows to the hidden span childNode numbers
	// ex: row #  : position of span that contains the data we need
	dataMap = { 1 : 0,		// category positive % (6mos)
				2 : 4,		// category reviews (6mos)
				3 : 5,		// total num of projects (6 mos)
				4 : 6,		// category earnings (6mos)
				5 : 13 };	// category earnings (lifetime)
	// go thru the table cells and set the data based on the dropdown selection and show/hide cell
	for (i = 0; i < elementList.length; ++i) {
		if (i > 0 && catSel != 0) {
			elementList[i].childNodes[0].innerHTML = $('hiddenAggData'+parseInt(catSel)).childNodes[dataMap[i]].innerHTML;
		}
		elementList[i].className = displayStyle;
	}

	elementList = document.getElementsByName('categoryAllSummaryItem');
	dataMap = { 0 : 0,		// all category positive % (6mos)
				1 : 4,		// all category reviews (6mos)
				2 : 5,		// total num of projects (6 mos)
				3 : 6,		// all category earnings (6mos)
				4 : 13 };	// all category earnings (lifetime)
	for (i = 0; i < elementList.length; ++i) {
		elementList[i].firstChild.innerHTML = $('hiddenAggData0').childNodes[dataMap[i]].innerHTML;
	}
}

function feedbackCategorySelection(catid) {
	// show/hide category specific items based on dropdown
	catid = catid || null;
	var dropdown = $('categorySelectionDropdown');

	if (catid) {
		for (i = 0; i < dropdown.options.length; ++i) {
			if (dropdown.options[i].value == catid) {
				dropdown.selectedIndex = i;
				break;
			}
		}
	}

	catSel = dropdown.selectedIndex;

	// elementList will contain a table cell for each row in the table in the following order:
	// category name, 6mo pos, lifetime pos, 6mo neutral, lifetime neutral, 6mo neg, lifetime neg,
	// 6mo reviews, lifetime reviews, 6mo accepted, lifetime accepted, 6mo earnings, lifetime earnings
	var elementList = document.getElementsByName('categoryTypeSummaryItem');

	// if we've selected "All Categories" then we hide the category specific column
	if (0 == catSel) {
		elementList[0].innerHTML = "All Categories";
	} else {
		elementList[0].innerHTML = dropdown.options[catSel].text;
	}

	// display/hide premier icon - except for all categories we don't show it ever
	if (catSel) {
		var curCategory = $('hiddenAggData'+ parseInt(catSel)).childNodes;
		if (curCategory[14].innerHTML == 1) {
			$('providerProfilePremierIcon').style.display = 'inline';
		} else {
			$('providerProfilePremierIcon').style.display = 'none';
		}
	} else {
		$('providerProfilePremierIcon').style.display = 'none';
	}

	// map the table rows to the hidden span childNode numbers
	// ex: row #  : position of span that contains the data we need
	dataMap = { 1 : 0,   // positive % (6mos)
				2 : 7,   // positive %
				3 : 4,   // total reviews (6mos)
				4 : 11,  // total reviews
				5 : 1,   // positive count (6mos) 
				6 : 8,   // positive count
				7 : 2,   // neutral count (6mos)
				8 : 9,   // neutral count
				9 : 3,   // negative count (6mos)
			   10 : 10,  // negative count
			   11 : 5,   // projects accepted (6mos)
			   12 : 12,  // projects accepted
			   13 : 6,   // earnings (6mos)
			   14 : 13}; // earnings
	dataMapLen = 14;

	// go thru the table cells and set the data based on the dropdown selection and show/hide cell
	for (i = 1; i <= dataMapLen; ++i) {
		elementList[i].innerHTML = $('hiddenAggData'+parseInt(catSel)).childNodes[(dataMap[i])].innerHTML;
	}
}

function replacePaginationContent(obj) {
	// default to sliderPagination
	$('sliderPagination').innerHTML = obj.responseText;
}

function replaceGalleryContent(obj) {
	// default to sliderPagination
	$('editWindow').innerHTML = obj.responseText;
}

function replaceContent(obj) {
	// we default to use tabContent
	if (!replaceId) {
//		replaceId = 'tabContent';
		return;
	}

	$(replaceId).innerHTML = obj.responseText;

	// run javascript that was run through AJAX calls inside Gallery (editWindow)
	if ('editWindow' == replaceId) {
		var scriptList = $('editWindow').getElementsByTagName('script');
		for (i = 0; i < scriptList.length; ++i) {
			eval(scriptList[i].innerHTML);
		}
	}

	replaceId = null;
	contentReplaced = true;
	document.body.style.cursor = 'auto';
	setTimeout('displayAnchor()',100);	
}

function loadFeedbackSubcategoryFilter() {
   var subcatFilter = $('subcategoryDropdown');
   var val =  $('categoryDropdown').value;
   var subcatData = $('hiddenSubcatData:' + val);
   var subcatStruct = $('subcategoryDropdown');
   while (subcatStruct.firstChild) {
		 subcatStruct.removeChild(subcatStruct.firstChild);
   }
   optionChild = document.createElement("option");
   optionChild.setAttribute("value", -1);
   optionChild.innerHTML = "All Subcategories";
   subcatFilter.appendChild(optionChild);

   if (null == subcatData) {
	  subcatFilter.selectedIndex = 0;
	  subcatFilter.disabled = true;
	  return false;
   } else {
	  subcatFilter.disabled = false;
   }
   
   var children = subcatData.childNodes;
   var str;
   for (var i = 0; i < children.length; i++) {
	   str = subcatData.childNodes[i].innerHTML; 
	   str = str.split(":"); 
	   optionChild = document.createElement("option");
	   optionChild.setAttribute("value", str[0]);
	   optionChild.innerHTML = str[1];
	   subcatFilter.appendChild(optionChild);
   }

	//-- Force IE to refresh dropdown, otherwise it might overlap other dropdowns
	subcatFilter.className = "";

}

function loadFeedbackCategoryFilter() {
	var categories = $('categorySelectionDropdown').options;
	var catFilter = $('categoryDropdown');
	if (categories && catFilter) {
		for(i = 0; i < categories.length; ++i) {
			optionChild = document.createElement("option");
			optionChild.setAttribute("value", categories[i].value);
			optionChild.innerHTML = categories[i].text;
			catFilter.appendChild(optionChild);
		}
	}
	//-- Force IE to refresh dropdown, otherwise it might overlap other dropdowns
	catFilter.className = "";
}

function projectHistoryFilter(allProjects) {
	$('ratingDropdown').parentNode.style.display = 'inline';

	$('ratingDropdown').selectedIndex = 0;

//	historySort(null, 1, null);
}

function requestQuote(username) {
	window.location = '/invite?invitation_yn=Y&cbxProviders_1=inv_providers='+ username;
}

function reloadCurrentTab() {
	switch(curProfileTab) {
		case 0:
			curProfileTab = "Profile";
		reloadWorkaround();
			return;
		break;
		case 1:
			curProfileTab = "Portfolio";
		reloadWorkaround();
			return;
		break;
		case 2:
			curProfileTab = "Feedback";
		reloadWorkaround();
			return;
		break;
		default:
			curProfileTab = "Profile";
		reloadWorkaround();
			return;
		break;
	}
	
	providerTab(curProfileTab);
}

// lame safari hack to get the page to reload
function reloadWorkaround() {
	oldHash = window.location.hash;
	var dateObj = new Date();

	// rip out existing '&t=####' parameter
	newHref = window.location.href.replace(/&t=\d+/, '');
	newHref = newHref.replace(/#.+/, '');

	newHref = newHref +'&t='+ dateObj.getTime() + oldHash;
	window.location.hash = '';
	window.location.href = newHref;
}

function getSelectedProfile() {
	var profile = $('categorySelectionDropdown');
	if (profile && profile.options[profile.selectedIndex]) {
		if (profile.selectedIndex) {
			return profile.options[profile.selectedIndex].value;
		}
		return '';
	} else {
		return getGetParam('catid');
	}
}

function loadContactInfo(el) {
	userid = getUserId();
	el.innerHTML = '<img style="margin-left:69px; height:24px;" src="/media/images/4.0/ajax-loader.gif"/>';
	contentReplaced = false;
	replaceId = 'contactDetails';
	curWaitingCode = '$("contactInfoButton").style.display = "none"; setRNavHeight();';
	cancelRunningRequests();
	curAsyncRef = YAHOO.util.Connect.asyncRequest('GET', '/php/profile/main/contactInfo.php?userid='+ userid +'&t='+ getDateTime(), htmlCallback, null);   
  	curLoad = setInterval('isLoaded()', 100);
    
	setRNavHeight();
}


// function to reload page with cmTab specified 
// will open with contact me panel up on the proper tab
function cmReload(cmTab) {
	var args = getArgsFromHash();

	var params = "";
	params += "tab=" + args.tab;
	params += "&cmTab=" + cmTab;
	
	setHashParams(params);
	window.location.reload();
}

function cmLoad(cmTab){
    if(cmTab==0 && !$('openJobs').innerHTML){
        inviteUser($('loggedInUser').innerHTML, $('viewUser').innerHTML);
    }else{
        toggleContactMePanel( document.getElementById("profileUsername").innerHTML );
        setTimeout('activateTab(' +cmTab+ ')', 100);
    }
}

// Changes the page of the agent list for team tab.
function changeAgentListPage(page,sort,filter,certified){
	if(page !== null ){ $('teamPage').value = page; }
	if(sort !== null ){
		if( $('teamSort').value == sort ){
			$('teamSort').value = '!'+sort;
		} else {
			$('teamSort').value = sort; 
		}
	}
	if(filter !== null ){ 
		$('skillFilter').value = filter;
		if( filter != '' ){ $('skillCertified').value = ''; }
	}
	if(certified !== null ){ 
		if( $('skillCertified').value == 1 ){
			$('skillCertified').value = '';
		} else {
			$('skillCertified').value = 1;
		}
	}
	providerTab('Team');
}

function canInterview() {
    var username = document.getElementById("profileUsername").innerHTML;
    var url = "/php/myelance/main/contactMeAHR.php?ctx=contactMe&mode=checktabs&view_person="+username+'&t='+getDateTime();
     YAHOO.util.Connect.asyncRequest('get',
          url,
          {success: interviewSuccess, failure:interviewFailure});
};

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

    if( responseObj.rc == '1' ) {
        if( !responseObj.canChat && !responseObj.canCall ) {
            //hide interview button
            $('interview').innerHTML='';
        }
    }
};

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

// Called when the user tries to verify country, but they dont have elance admin test or phone verif yet
function showCountryReqNotice(){
	initInfoDialog();
	showInfoDialog("countryReqNoticeTitle", "countryReqNoticeBody", "warn");
	return false;
}



YAHOO.namespace("extension");YAHOO.extension.Carousel=function(carouselElementID,carouselCfg){this.init(carouselElementID,carouselCfg);};YAHOO.extension.Carousel.prototype={UNBOUNDED_SIZE:1000000,init:function(carouselElementID,carouselCfg){this.carouselElemID=carouselElementID;this.carouselElem=YAHOO.util.Dom.get(carouselElementID);this.prevEnabled=true;this.nextEnabled=true;this.cfg=new YAHOO.util.Config(this);this.cfg.addProperty("orientation",{value:"horizontal",suppressEvent:true});this.cfg.addProperty("size",{value:this.UNBOUNDED_SIZE,suppressEvent:true});this.cfg.addProperty("numVisible",{value:8,suppressEvent:true});this.cfg.addProperty("firstVisible",{value:1,suppressEvent:true});this.cfg.addProperty("scrollInc",{value:8,suppressEvent:true});this.cfg.addProperty("animationSpeed",{value:0.25,suppressEvent:true});this.cfg.addProperty("animationMethod",{value:YAHOO.util.Easing.easeOut,suppressEvent:true});this.cfg.addProperty("animationCompleteHandler",{value:null,suppressEvent:true});this.cfg.addProperty("autoPlay",{value:0,suppressEvent:true});this.cfg.addProperty("wrap",{value:false,suppressEvent:true});this.cfg.addProperty("navMargin",{value:0,suppressEvent:true});this.cfg.addProperty("prevElementID",{value:null,suppressEvent:true});this.cfg.addProperty("nextElementID",{value:null,suppressEvent:true});this.cfg.addProperty("loadInitHandler",{value:null,suppressEvent:true});this.cfg.addProperty("loadNextHandler",{value:null,suppressEvent:true});this.cfg.addProperty("loadPrevHandler",{value:null,suppressEvent:true});this.cfg.addProperty("prevButtonStateHandler",{value:null,suppressEvent:true});this.cfg.addProperty("nextButtonStateHandler",{value:null,suppressEvent:true});if(carouselCfg){this.cfg.applyConfig(carouselCfg);}
this.numVisible=this.cfg.getProperty("numVisible");this.scrollInc=this.cfg.getProperty("scrollInc");this.navMargin=this.cfg.getProperty("navMargin");this.animSpeed=this.cfg.getProperty("animationSpeed");this.initHandler=this.cfg.getProperty("loadInitHandler");this.animationCompleteHandler=this.cfg.getProperty("animationCompleteHandler");this.size=this.cfg.getProperty("size");this.wrap=this.cfg.getProperty("wrap");this.animationMethod=this.cfg.getProperty("animationMethod");this.orientation=this.cfg.getProperty("orientation");this.nextElementID=this.cfg.getProperty("nextElementID");this.prevElementID=this.cfg.getProperty("prevElementID");this.autoPlay=this.cfg.getProperty("autoPlay");this.autoPlayTimer=null;this.firstVisible=this.cfg.getProperty("firstVisible");this.lastVisible=this.firstVisible;this.lastPrebuiltIdx=0;this.currSize=0;var carouselListClass="carousel-list";var carouselClipRegionClass="carousel-clip-region";var carouselNextClass="carousel-next";var carouselPrevClass="carousel-prev";this.carouselList=YAHOO.util.Dom.getElementsByClassName(carouselListClass,"ul",this.carouselElem)[0];if(this.nextElementID===null){this.carouselNext=YAHOO.util.Dom.getElementsByClassName(carouselNextClass,"div",this.carouselElem)[0];}else{this.carouselNext=YAHOO.util.Dom.get(this.nextElementID);}
if(this.nextElementID===null){this.carouselPrev=YAHOO.util.Dom.getElementsByClassName(carouselPrevClass,"div",this.carouselElem)[0];}else{this.carouselPrev=YAHOO.util.Dom.get(this.prevElementID);}
this.clipReg=YAHOO.util.Dom.getElementsByClassName(carouselClipRegionClass,"div",this.carouselElem)[0];if(this.isVertical()){YAHOO.util.Dom.addClass(this.carouselList,"carousel-vertical");}
this.scrollNextAnim=new YAHOO.util.Motion(this.carouselList,this.scrollNextParams,this.animSpeed,this.animationMethod);this.scrollPrevAnim=new YAHOO.util.Motion(this.carouselList,this.scrollPrevParams,this.animSpeed,this.animationMethod);if(this._isValidObj(this.carouselNext)){YAHOO.util.Event.addListener(this.carouselNext,"click",this._scrollNext,this);}
if(this._isValidObj(this.carouselPrev)){YAHOO.util.Event.addListener(this.carouselPrev,"click",this._scrollPrev,this);}
if(this._isValidObj(this.initHandler)){this.loadInitialEvt=new YAHOO.util.CustomEvent("onLoadInit",this);this.loadInitialEvt.subscribe(this.initHandler,this);}
this.nextHandler=this.cfg.getProperty("loadNextHandler");if(this._isValidObj(this.nextHandler)){this.loadNextEvt=new YAHOO.util.CustomEvent("onLoadNext",this);this.loadNextEvt.subscribe(this.nextHandler,this);}
this.prevHandler=this.cfg.getProperty("loadPrevHandler");if(this._isValidObj(this.prevHandler)){this.loadPrevEvt=new YAHOO.util.CustomEvent("onLoadPrev",this);this.loadPrevEvt.subscribe(this.prevHandler,this);}
if(this._isValidObj(this.animationCompleteHandler)){this.animationCompleteEvt=new YAHOO.util.CustomEvent("onAnimationComplete",this);this.animationCompleteEvt.subscribe(this.animationCompleteHandler,this);}
this.prevButtonStateHandler=this.cfg.getProperty("prevButtonStateHandler");if(this._isValidObj(this.prevButtonStateHandler)){this.prevButtonStateEvt=new YAHOO.util.CustomEvent("onPrevButtonStateChange",this);this.prevButtonStateEvt.subscribe(this.prevButtonStateHandler,this);}
this.nextButtonStateHandler=this.cfg.getProperty("nextButtonStateHandler");if(this._isValidObj(this.nextButtonStateHandler)){this.nextButtonStateEvt=new YAHOO.util.CustomEvent("onNextButtonStateChange",this);this.nextButtonStateEvt.subscribe(this.nextButtonStateHandler,this);}
YAHOO.util.Event.onAvailable(this.carouselElemID+"-item-1",this._firstElementIsLoaded,this);this._loadInitial();},clear:function(){this.moveTo(1);this._removeChildrenFromNode(this.carouselList);this.stopAutoPlay();this.firstVisible=1;this.lastVisible=1;this.lastPrebuiltIdx=0;this.currSize=0;this.size=this.cfg.getProperty("size");},reload:function(numVisible){if(this._isValidObj(numVisible)){this.numVisible=numVisible;}
this.clear();YAHOO.util.Event.onAvailable(this.carouselElemID+"-item-1",this._firstElementIsLoaded,this);this._loadInitial();},addItem:function(idx,innerHTML){var liElem=this.getCarouselItem(idx);if(!this._isValidObj(liElem)){liElem=this._createItem(idx,innerHTML);if (liElem.parentNode && liElem.parentNode.tagName){liElem.parentNode.appendChild(liElem);}else{this.carouselList.appendChild(liElem);}}else if(this._isValidObj(liElem.placeholder)){var newLiElem=this._createItem(idx,innerHTML);if (liElem.parentNode){liElem.parentNode.replaceChild(newLiElem,liElem);}else{this.carouselList.replaceChild(newLiElem,liElem);}}
if(this.isVertical()){YAHOO.util.Dom.setStyle(liElem,"height",liElem.offsetHeight+"px");}
return liElem;},insertBefore:function(refIdx,innerHTML){if(refIdx<1){refIdx=1;}
var insertionIdx=refIdx-1;if(insertionIdx>this.lastPrebuiltIdx){this._prebuildItems(this.lastPrebuiltIdx,refIdx);}
var liElem=this._insertBeforeItem(refIdx,innerHTML);if(this.firstVisible>insertionIdx||this.lastVisible<this.size){if(this.nextEnabled===false){this._enableNext();}}
return liElem;},insertAfter:function(refIdx,innerHTML){if(refIdx>this.size){refIdx=this.size;}
var insertionIdx=refIdx+1;if(insertionIdx>this.lastPrebuiltIdx){this._prebuildItems(this.lastPrebuiltIdx,insertionIdx+1);}
var liElem=this._insertAfterItem(refIdx,innerHTML);if(insertionIdx>this.size){this.size=insertionIdx;if(this.nextEnabled===false){this._enableNext();}}
if(this.firstVisible>insertionIdx||this.lastVisible<this.size){if(this.nextEnabled===false){this._enableNext();}}
return liElem;},scrollNext:function(){this._scrollNext(null,this);this.autoPlayTimer=null;if(this.autoPlay!==0){this.autoPlayTimer=this.startAutoPlay();}},scrollPrev:function(){this._scrollPrev(null,this);},scrollTo:function(newStart){this._position(newStart,true);},moveTo:function(newStart){this._position(newStart,false);},startAutoPlay:function(interval){if(this._isValidObj(interval)){this.autoPlay=interval;}
if(this.autoPlayTimer!==null){return this.autoPlayTimer;}
var oThis=this;var autoScroll=function(){oThis.scrollNext();};this.autoPlayTimer=setTimeout(autoScroll,this.autoPlay);return this.autoPlayTimer;},stopAutoPlay:function(){if(this.autoPlayTimer!==null){clearTimeout(this.autoPlayTimer);this.autoPlayTimer=null;}},isVertical:function(){return(this.orientation!="horizontal");},isItemLoaded:function(idx){var liElem=this.getCarouselItem(idx);if(this._isValidObj(liElem)&&!this._isValidObj(liElem.placeholder)){return true;}
return false;},getCarouselItem:function(idx){var elemName=this.carouselElemID+"-item-"+idx;var liElem=YAHOO.util.Dom.get(elemName);return liElem;},_firstElementIsLoaded:function(me){var ulKids=null; if (me.carouselList) { ulKids = me.carouselList.childNodes; } else if (document.getElementById('dhtml-carousel') && document.getElementById('dhtml-carousel').childNodes[1] && document.getElementById('dhtml-carousel').childNodes[1].childNodes[1]) { ulKids = document.getElementById('dhtml-carousel').childNodes[1].childNodes[1].childNodes;};var li=null;for(var i=0;i<ulKids.length;i++){li=ulKids[i];if(li.tagName=="LI"||li.tagName=="li"){break;}}
var liPaddingWidth;if(me.isVertical()){liPaddingWidth=parseInt(YAHOO.util.Dom.getStyle(li,"paddingLeft"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"paddingRight"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"marginLeft"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"marginRight"),10);var liPaddingHeight=parseInt(YAHOO.util.Dom.getStyle(li,"paddingTop"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"paddingBottom"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"marginTop"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"marginBottom"),10);me.scrollAmountPerInc=(li.offsetHeight+liPaddingHeight);me.clipReg.style.width=(li.offsetWidth+liPaddingWidth)+"px";me.clipReg.style.height=(me.scrollAmountPerInc*me.numVisible)+"px";me.carouselElem.style.width=(li.offsetWidth+liPaddingWidth*2)+"px";var currY=YAHOO.util.Dom.getY(me.carouselList);YAHOO.util.Dom.setY(me.carouselList,currY-me.scrollAmountPerInc*(me.firstVisible-1));}else{liPaddingWidth=parseInt(YAHOO.util.Dom.getStyle(li,"paddingLeft"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"paddingRight"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"marginLeft"),10)+
parseInt(YAHOO.util.Dom.getStyle(li,"marginRight"),10);/*me.scrollAmountPerInc=(li.offsetWidth+liPaddingWidth);me.carouselElem.style.width=((me.scrollAmountPerInc*me.numVisible)+me.navMargin*2)+"px";me.clipReg.style.width=(me.scrollAmountPerInc*me.numVisible)+"px";*/me.scrollAmountPerInc=86;me.carouselElem.style.width='686px';me.clipReg.style.width='686px';var currX=YAHOO.util.Dom.getX(me.carouselList);YAHOO.util.Dom.setX(me.carouselList,currX-me.scrollAmountPerInc*(me.firstVisible-1));}
YAHOO.util.Dom.setStyle(me.carouselElem,"visibility","visible");},_removeChildrenFromNode:function(node)
{if(!this._isValidObj(node))
{return;}
var len=node.childNodes.length;while(node.hasChildNodes())
{node.removeChild(node.firstChild);}},_prebuildLiElem:function(idx){var liElem=document.createElement("li");liElem.id=this.carouselElemID+"-item-"+idx;liElem.style.width="82px";liElem.placeholder=true;if (!this.carouselList) {this.carouselList=document.getElementById('carousel-list');}this.carouselList.appendChild(liElem);this.lastPrebuiltIdx=(idx>this.lastPrebuiltIdx)?idx:this.lastPrebuiltIdx;},_createItem:function(idx,innerHTML){var liElem=document.createElement("li");liElem.id=this.carouselElemID+"-item-"+idx;liElem.style.width="82px";liElem.innerHTML=innerHTML.replace(/\n/g, '<br/>');return liElem;},_insertAfterItem:function(refIdx,innerHTML){return this._insertBeforeItem(refIdx+1,innerHTML);},_insertBeforeItem:function(refIdx,innerHTML){var refItem=this.getCarouselItem(refIdx);if(this.size!=this.UNBOUNDED_SIZE){this.size+=1;}
for(var i=this.lastPrebuiltIdx;i>=refIdx;i--){var anItem=this.getCarouselItem(i);if(this._isValidObj(anItem)){anItem.id=this.carouselElemID+"-item-"+(i+1);}}
var liElem=this._createItem(refIdx,innerHTML);liElem.style.width="82px";var insertedItem=this.carouselList.insertBefore(liElem,refItem);this.lastPrebuiltIdx+=1;return liElem;},insertAfterEnd:function(innerHTML){return this.insertAfter(this.size,innerHTML);},_position:function(newStart,showAnimation){if(newStart>this.firstVisible){var inc=newStart-this.firstVisible;this._scrollNextInc(this,inc,showAnimation);}else{var dec=this.firstVisible-newStart;this._scrollPrevInc(this,dec,showAnimation);}},_scrollNext:function(e,carousel){if(carousel.scrollNextAnim.isAnimated()){return false;}
var currEnd=carousel.firstVisible+carousel.numVisible-1;if(carousel.wrap&&currEnd==carousel.size){var currAnimSpeed=carousel.animSpeed;carousel.scrollTo(1);}else if(e!==null){carousel.stopAutoPlay();carousel._scrollNextInc(carousel,carousel.scrollInc,(carousel.animSpeed!==0));}else{carousel._scrollNextInc(carousel,carousel.scrollInc,(carousel.animSpeed!==0));}},_scrollNextInc:function(carousel,inc,showAnimation){var currFirstVisible=carousel.firstVisible;var newEnd=carousel.firstVisible+inc+carousel.numVisible-1;newEnd=(newEnd>carousel.size)?carousel.size:newEnd;var newStart=newEnd-carousel.numVisible+1;inc=newStart-carousel.firstVisible;carousel.firstVisible=newStart;if((carousel.prevEnabled===false)&&(carousel.firstVisible>1)){carousel._enablePrev();}
if((carousel.nextEnabled===true)&&(newEnd==carousel.size)){carousel._disableNext();}
if(inc>0){if(carousel._isValidObj(carousel.nextHandler)){carousel.lastVisible=carousel.firstVisible+carousel.numVisible-1;carousel.currSize=(carousel.lastVisible>carousel.currSize)?carousel.lastVisible:carousel.currSize;var alreadyCached=carousel._areAllItemsLoaded(currFirstVisible,carousel.lastVisible);carousel.loadNextEvt.fire(carousel.firstVisible,carousel.lastVisible,alreadyCached);}
if(showAnimation){var nextParams={points:{by:[-carousel.scrollAmountPerInc*inc,0]}};if(carousel.isVertical()){nextParams={points:{by:[0,-carousel.scrollAmountPerInc*inc]}};}
carousel.scrollNextAnim=new YAHOO.util.Motion(carousel.carouselList,nextParams,carousel.animSpeed,carousel.animationMethod);if(carousel._isValidObj(carousel.animationCompleteHandler)){carousel.scrollNextAnim.onComplete.subscribe(this._handleAnimationComplete,[carousel,"next"]);}
carousel.scrollNextAnim.animate();}else{if(carousel.isVertical()){var currY=YAHOO.util.Dom.getY(carousel.carouselList);YAHOO.util.Dom.setY(carousel.carouselList,currY-carousel.scrollAmountPerInc*inc);}else{var currX=YAHOO.util.Dom.getX(carousel.carouselList);YAHOO.util.Dom.setX(carousel.carouselList,currX-carousel.scrollAmountPerInc*inc);}}}
return false;},_handleAnimationComplete:function(type,args,argList){var carousel=argList[0];var direction=argList[1];carousel.animationCompleteEvt.fire(direction);},_areAllItemsLoaded:function(first,last){var itemsLoaded=true;for(var i=first;i<=last;i++){var liElem=this.getCarouselItem(i);if(!this._isValidObj(liElem)){this._prebuildLiElem(i);itemsLoaded=false;}else if(this._isValidObj(liElem.placeholder)){itemsLoaded=false;}}
return itemsLoaded;},_prebuildItems:function(first,last){for(var i=first;i<=last;i++){var liElem=this.getCarouselItem(i);if(!this._isValidObj(liElem)){this._prebuildLiElem(i);}}},_scrollPrev:function(e,carousel){if(carousel.scrollPrevAnim.isAnimated()){return false;}
carousel._scrollPrevInc(carousel,carousel.scrollInc,(carousel.animSpeed!==0));},_scrollPrevInc:function(carousel,dec,showAnimation){var currLastVisible=carousel.lastVisible;var newStart=carousel.firstVisible-dec;newStart=(newStart<=1)?1:(newStart);var newDec=carousel.firstVisible-newStart;carousel.firstVisible=newStart;if((carousel.prevEnabled===true)&&(carousel.firstVisible==1)){carousel._disablePrev();}
if((carousel.nextEnabled===false)&&((carousel.firstVisible+carousel.numVisible-1)<carousel.size)){carousel._enableNext();}
if(newDec>0){if(carousel._isValidObj(carousel.prevHandler)){carousel.lastVisible=carousel.firstVisible+carousel.numVisible-1;carousel.currSize=(carousel.lastVisible>carousel.currSize)?carousel.lastVisible:carousel.currSize;var alreadyCached=carousel._areAllItemsLoaded(carousel.firstVisible,currLastVisible);carousel.loadPrevEvt.fire(carousel.firstVisible,carousel.lastVisible,alreadyCached);}
if(showAnimation){var prevParams={points:{by:[carousel.scrollAmountPerInc*newDec,0]}};if(carousel.isVertical()){prevParams={points:{by:[0,carousel.scrollAmountPerInc*newDec]}};}
carousel.scrollPrevAnim=new YAHOO.util.Motion(carousel.carouselList,prevParams,carousel.animSpeed,carousel.animationMethod);if(carousel._isValidObj(carousel.animationCompleteHandler)){carousel.scrollPrevAnim.onComplete.subscribe(this._handleAnimationComplete,[carousel,"prev"]);}
carousel.scrollPrevAnim.animate();}else{if(carousel.isVertical()){var currY=YAHOO.util.Dom.getY(carousel.carouselList);YAHOO.util.Dom.setY(carousel.carouselList,currY+
carousel.scrollAmountPerInc*newDec);}else{var currX=YAHOO.util.Dom.getX(carousel.carouselList);YAHOO.util.Dom.setX(carousel.carouselList,currX+
carousel.scrollAmountPerInc*newDec);}}}
return false;},_loadInitial:function(){this.lastVisible=this.firstVisible+this.numVisible-1;this.currSize=(this.lastVisible>this.currSize)?this.lastVisible:this.currSize;if(this.firstVisible==1){this._disablePrev();}
if(this.lastVisible==this.size){this._disableNext();}
if(this._isValidObj(this.initHandler)){var alreadyCached=this._areAllItemsLoaded(1,this.lastVisible);this.loadInitialEvt.fire(1,this.lastVisible,alreadyCached);}
if(this.autoPlay!==0){this.autoPlayTimer=this.startAutoPlay();}},_disablePrev:function(){this.prevEnabled=false;if(this._isValidObj(this.prevButtonStateEvt)){this.prevButtonStateEvt.fire(false,this.carouselPrev);}
if(this._isValidObj(this.carouselPrev)){YAHOO.util.Event.removeListener(this.carouselPrev,"click",this._scrollPrev);}},_enablePrev:function(){this.prevEnabled=true;if(this._isValidObj(this.prevButtonStateEvt)){this.prevButtonStateEvt.fire(true,this.carouselPrev);}
if(this._isValidObj(this.carouselPrev)){YAHOO.util.Event.addListener(this.carouselPrev,"click",this._scrollPrev,this);}},_disableNext:function(){if(this.wrap){return;}
this.nextEnabled=false;if(this._isValidObj(this.nextButtonStateEvt)){this.nextButtonStateEvt.fire(false,this.carouselNext);}
if(this._isValidObj(this.carouselNext)){YAHOO.util.Event.removeListener(this.carouselNext,"click",this._scrollNext);}},_enableNext:function(){this.nextEnabled=true;if(this._isValidObj(this.nextButtonStateEvt)){this.nextButtonStateEvt.fire(true,this.carouselNext);}
if(this._isValidObj(this.carouselNext)){YAHOO.util.Event.addListener(this.carouselNext,"click",this._scrollNext,this);}},_isValidObj:function(obj){if(null==obj){return false;}
if("undefined"==typeof(obj)){return false;}
return true;},debugMsg:function(msg)
{var debugArea=YAHOO.util.Dom.get("debug-area");if(!this._isValidObj(debugArea)){debugArea=document.createElement("div");debugArea.id="debug-area";document.body.appendChild(debugArea);}
debugArea.innerHTML=debugArea.innerHTML+"<br/>"+msg;},clearDebug:function()
{var debugArea=document.getElementById("debug-area");if(this._isValidObj(debugArea)){debugArea.innerHTML="";}}};


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');
}



var addToListDialog;


var currEleId = "";

function initaddToListDialog() {
  

	// Define various event handlers for Dialog
  var atlhandleSubmit = function() {
    this.submit();
  };
  var atlhandleCancel = function() {
    this.cancel();
  };
  var atlhandleSuccess = function(o) {
    var response = o.responseText;
    if( response.length > 0 && (response.indexOf('success') == -1)) {
      showInfoDialogText( $('addToListfailuretitle').innerHTML, response, 'WARN' ); 
    }
    else {
     // showInfoDialog( 'addToListsuccesstitle', 'addToListsuccessbody', 'INFO' );
	  displayOnWatchList();
    }
  };
  var atlhandleFailure = function(o) {
    showInfoDialog( 'addToListfailuretitle', 'addToListfailurebody', 'WARN' );
  };
  var closeaddToListDialog = function() {
    currentRownumDialog = -1;
    resetaddToListDialog();
  };

  addToListDialog = new YAHOO.widget.Dialog("addToListdialog", 
    { width : "400px",
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3},
      buttons : [ { text:"", handler:atlhandleSubmit, isDefault:true },
        { text:"", handler:atlhandleCancel } ]
    } );
					
  // Wire up the success and failure handlers
  addToListDialog.callback = { success: atlhandleSuccess, failure: atlhandleFailure };

  // Add validation
  addToListDialog.validate = function() {
    var data = this.getData();
    resetaddToListErrors();

    return true;
  };
  // Render the Dialog
  addToListDialog.render();
  addToListDialog.beforeHideEvent.subscribe( closeaddToListDialog, addToListDialog, true );
  addToListDialog.innerElement.style.display = '';

	// add button styles
	addToListDialog.firstButton.className = "submit";
	addToListDialog.lastButton.className = "cancel";
}


var currentRownumDialog = -1;

/**
 * When the user is not logged in, ask the user to log in.
 */
function atlnotLoggedInDialog() {
  showInfoDialog( 'atlnotloggedintitle', 'atlnotloggedinbody', 'INFO' );
}

function atlAlreadyAddedDialog(objName) {
  showInfoDialogText( $('atlalreadyaddedtitle').innerHTML, objName+' '+$('atlalreadyaddedbody').innerHTML, 'INFO' );
}

function notAuthorizedDialog() {
  showInfoDialogText( $('notauthorizedtitle').innerHTML, $('notauthorizedbody').innerHTML, 'WARN' );
}

/**
 * Toggle display of the addToList dialog.
 * If the user switches to another addToList dialog, reset the error msgs.
 */
function toggleaddToListDialog( objId, objType) {
  if( currentRownumDialog == objId ) {
    currentRownumDialog = -1;
    addToListDialog.hide();
  }
  else {
	if (!addToListDialog) {
		initaddToListDialog();
	}
    currentRownumDialog = objId;
    resetaddToListErrors();
    addToListDialog.show();
    $('addToListObjId').value = objId;
    $('addToListTitle').innerHTML = objType;
    $('addToListObjName').value = objType;
  }
}

/**
 * Reset the addToList dialog fields
 */
function resetaddToListDialog() {
  resetaddToListErrors();
 $("addToListObjId").value = '';
 $("comments").value = '';
}

/**
 * Reset the error messages on the addToList dialog.
 */
function resetaddToListErrors() {
}



function addToList(objId, objType, eleId){
   var url = '/php/myelance/main/addWatchList.php?mode=check&addToListObjType='+$('addToListObjType').value+'&addToListObjId='+objId+'&addToListObjName='+objType;
   var req = new Ajax(url,
   {
     asynchronous:true,
     method:'get',
     onSuccess: function(t){
         //set global var
		 currEleId = eleId;
		 var celldata = t.split('##');
         if (celldata[0].indexOf('NoAuth') == 0) { 
            notAuthorizedDialog();
            return;
         }
         
		 // check to see if we got no for our question, does the user already exist?
         if(celldata[0].indexOf('No') != -1){
			toggleaddToListDialog(celldata[1], celldata[2]);
         }else{
			 displayOnWatchList();
			 atlAlreadyAddedDialog(celldata[2]);
         }
     },
     onFailure: function(){ alert('Internal Error, Please check if you are currently logged in and try again.') }
   }
   );
   req.request();
}

function displayOnWatchList(){
	$(currEleId).getFirst().setStyle('display','');
	$(currEleId).getLast().setStyle('display','none');
}

function updateParent(){
	$(window.opener.document.getElementById('watchlistid')).getFirst().setStyle('display','');
	$(window.opener.document.getElementById('watchlistid')).getLast().setStyle('display','none');
}




var emailDialog;

// handle submit
function efhandleSubmit() {
        // Set waiting
        document.body.style.cursor = 'wait';
        var url = "/php/promo/main/emailToFriend.php?"+Object.toQueryString( {emailObjId: $('emailObjId').value,
					 emailObjType: $('emailObjType').value,
					 recipients: $('recipient_list').value,
					 emailbody: $('emailbody').value,
					 copy: $('copy').checked} );

	// Fire off AJAX
	var req = new Ajax(url,
	  {
	    asynchronous:true,
	    method:'get',
	    onSuccess: function(u){
		if(u.match(/Error/i)){
		    showInfoDialogText( $('emailfailuretitle').innerHTML, u, 'WARN' ); 
		}else{
			emailDialog.hide();
			resetEmailDialog(); 
			showInfoDialogText( $('emailsuccesstitle').innerHTML,u+$('emailwhatnext').innerHTML , 'INFO' );
		}
	     },
	     onFailure: function(){ alert('Internal Error, Please check if you are currently logged in and try again.') }
	   }
	   );
	req.request();
	document.body.style.cursor = 'default';
};

function efhandleCancel(){
	emailDialog.hide();
        resetEmailDialog();
};

function initEmailDialog() {
  // Define various event handlers for Dialog
  var handleSubmit = function() {
    this.submit();
  };
  var handleCancel = function() {
    this.cancel();
  };
  var handleSuccess = function(o) {
    var response = o.responseText;
    response = response.replace(/^\s*/, "").replace(/\s*$/, "");
    if( response !== '') {
      $("emailErrorMsg").innerHTML = response;
      showInfoDialogText( $('emailfailuretitle').innerHTML, response, 'WARN' ); 
    }
    else {
      showInfoDialog( 'emailsuccesstitle', 'emailsuccessbody', 'INFO' );
    }
  };
  var handleFailure = function(o) {
    showInfoDialog( 'emailfailuretitle', 'emailfailurebody', 'WARN' );
  };
  var closeEmailDialog = function() {
    currentRownumDialog = -1;
    resetEmailDialog();
};

  emailDialog = new YAHOO.widget.Dialog("emaildialog", 
    { width : "360px",
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3}
    } );

					
  // Wire up the success and failure handlers
  emailDialog.callback = { success: efhandleSubmit, failure: handleFailure };

  // Render the Dialog
  emailDialog.render();
  emailDialog.beforeHideEvent.subscribe( closeEmailDialog, emailDialog, true );
	removeClassName( emailDialog.innerElement, 'displayNone' );
}


var currentRownumDialog = -1;

/**
 * When the user is not logged in, ask the user to log in.
 */
function notLoggedInDialog() {
  showInfoDialog( 'notloggedintitle', 'notloggedinbody', 'INFO' );
}

/**
 * When there is no profile
 */
function noProfile() {
  showInfoDialog( 'emailnoprofiletitle', 'emailnoprofilebody', 'INFO' );
}

/**
 * Toggle display of the email dialog.
 * If the user switches to another email dialog, reset the error msgs.
 */
function toggleEmailDialog( objId, objTitle, objUrl ) {
  if( currentRownumDialog == objId ) {
    currentRownumDialog = -1;
	emailDialog.hide();
  }
  else {
	if (!emailDialog) {
	    initEmailDialog();
	}
    currentRownumDialog = objId;
    resetEmailErrors();
    emailDialog.show();
 //   $('emailTitle').innerHTML = objTitle;
    $('emailObjId').value = objId;
    $('emailUrl').value = objUrl;
    var content = $('emailtemplate').innerHTML;
    $("emailbody").value = content.replace(/<br>/gi,'\n')+'\n';
  }
}

/**
 * Reset the email dialog fields
 */
function resetEmailDialog() {
        resetEmailErrors();
	$("recipient_list").value = '';
	$("emailbody").value = $('emailtemplate').innerHTML;
 	document.emailfriendform.emailbody.value = '';
 	simpleTextCounter(document.emailfriendform.emailbody,$('charLimit'),1000);
}

/**
 * Reset the error messages on the email dialog.
 */
function resetEmailErrors() {
  $("recipient_list").className = '';
  $("emailbody").className = '';
  $("emailErrorMsg").innerHTML = '';
}


function up_launchWM( userID, destinationUserID, bidID, context )
{
	up_localUserID = userID;
	if((bidID === null) ||
	   (bidID == undefined))
		bidID = '';
	if ((context === null) ||
	    (bidID == undefined))
	    context = 'unknown';			
	var url = '/userplane/wm_ads.php?strDestinationUserID=' + destinationUserID +
			  '&userID=' + userID +
			  '&bidID=' + bidID +
			  '&context=' + context; 
			  	
	window.open( url, "WMWindow_" + up_replaceAlpha(userID) + "_" + up_replaceAlpha(destinationUserID), "width=370,height=617,toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable=1" );
}
function up_launchUL()
{		
	window.open( "/userplane/ul_ads.php" , "ULWindow" , "width=200,height=750,toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable=1" );
}
function up_replaceAlpha( strIn )
{
	var strOut = "";
	for( var i = 0 ; i < strIn.length ; i++ )
	{
		var cChar = strIn.charAt(i);
		if( ( cChar >= 'A' && cChar <= 'Z' )
			|| ( cChar >= 'a' && cChar <= 'z' )
			|| ( cChar >= '0' && cChar <= '9' ) )
		{
			strOut += cChar;
		}
		else
		{
			strOut += "_";
		}
	}
	
	return strOut;
}



var phoneVerifPanelIframeLoaded = false;
var phoneVerifPanel;     // Panel for verif


// Removes loading image from signIn Panel body [once its loaded]
function phoneVerifIframeLoaded(arg) {
        // Remove loading image
  var body = document.getElementById('phoneVerifPanelBody');
        for (var i = 0; i < body.childNodes.length; i++) {
                var child = body.childNodes[i];
                if( child.id && child.id == 'phoneVerifPanelIframeLoading' ) {
                        body.removeChild(child);
                        break;
                }
        }
}


function phoneVerifLoad(){
	if (!phoneVerifPanel) {initPhoneVerif(); }
	phoneVerifPanel.show();
}

function closePhoneVerifPanel(reload){
	phoneVerifPanel.hide();
	if(reload == null) {
		window.location.reload();
	}
}

function initPhoneVerif(){
                var pvhandleOpen = function() {
                // If the iframe is loaded already, we can skip out.
                //if (phoneVerifPanelIframeLoaded ) { return; }


                // Set onAvaible event to remove loading image
                YAHOO.util.Event.onAvailable('phoneVerifPanelIframe1', phoneVerifIframeLoaded);
               
		// reload 
		var tail='?r+'+Math.round(Math.random*10000);
 
		// create iFrame
                var iFrame;
                iFrame = document.createElement("iframe");
                iFrame.setAttribute("src", '\/phoneverififrame?'+tail);
                iFrame.setAttribute("scrolling", "no");
                iFrame.setAttribute("frameBorder", "0");
                iFrame.setAttribute("id", 'phoneVerifPanelIframe1');
                iFrame.setAttribute("class", "phoneverifpanelsecure"); // for firefox
                iFrame.setAttribute("className", "phoneverifpanelsecure"); // For silly IE
		iFrame.setAttribute("style", "height: 165px");

                // Load it into panel
                document.getElementById('phoneVerifPanelBody').appendChild(iFrame);

		phoneVerifPanelIframeLoaded = true;
		}
		
		var pvhandleClose = function() {
			// We need to do this on close for IE to cooperate!
			resetError("phoneError");
			document.getElementById('phoneVerifPanelBody').removeChild($('phoneVerifPanelIframe1'));
		}


		phoneVerifPanel = new YAHOO.widget.Panel("phoneVerifPanelDiv",
			{ fixedcenter : true,
				visible : false,
				constraintoviewport : true,
				effect:{ effect: YAHOO.widget.ContainerEffect.FADE, duration: 0.3 },
				draggable: true,
				/**** Bug 61013 ****/
				close: false
			}
		);
		

		// Render, add open event
		phoneVerifPanel.render();
		phoneVerifPanel.beforeShowEvent.subscribe( pvhandleOpen, phoneVerifPanel, true );
		phoneVerifPanel.beforeHideEvent.subscribe( pvhandleClose, phoneVerifPanel, true );
		removeClassName( phoneVerifPanel.innerElement, 'displayNone' );
//pvhandleOpen();
}

function resizeIFrame(height){
	if(!height) { height = 0;}
	var base = 165 + height; 
	$('phoneVerifPanelIframe1').style.height = base +  'px';
	base = base +45; 
	$('phoneVerifPanelDiv').style.height = base + 'px';
}



function advanceTrain (response) {
	if (response.status == 'success') {
        window.location.href = response.data.returnUrl;
   	}
}

function handleSuccess( obj) {
    var response = eval('(' + obj + ')');
	if( response.status == 'success' ) {
    	advanceTrain(response);
  	} else if ( response.status == 'error' ) {
     	displayErrors( response );
  	}
}

function handleError(obj) {
	
}

function handleNoThanksSuccess (obj) {
	var response = eval('(' + obj + ')');	
	if( response.status == 'success' ) {
		if($('AmexWorkroomReminder')) {
			$('AmexWorkroomReminder').addClass('displayNone');
		} else{
			advanceTrain(response);
		}
	} else if ( response.status == 'error' ) {
        displayErrors( response );
        }	
}

function handleLogoOptSuccess(obj) {
	var response = eval('(' + obj + ')');
	if( response.status == 'success' ) {
		window.location.reload();
	}
}

function displayErrors( response) {
    $(response.errorMsgsEl).removeClass( 'displayNone' );
    $( response.errorMsgsEl + 'List' ).innerHTML = '';
    if (response.errorMsgs) {
        for( var i = 0; i < response.errorMsgs.length; i++ ) {
        	$( response.errorMsgsEl + 'List' ).innerHTML += response.errorMsgs[i];
        }
    }
    if( response.errorIds ) {
        for( var j = 0; j < response.errorIds.length; j++ ) {
            if( $(response.errorIds[j]).getAttribute("type") == 'error' ) {
                $(response.errorIds[j]).addClass( 'highlightError' );
            }
        }
    }
    window.scroll(0,0);
}

//Ajax call to update the note of a watched item
function handleAcceptance(AmexOpenAction) {
	$('csphone').value = $('csphone1').value + $('csphone2').value + $('csphone3').value;
	$code = $('amexcode').toQueryString();
	$code += '&action=agree';
	if (!AmexOpenAction) {
		AmexOpenAction = 'myelance';
	}
	$code += '&AmexOpenAction='+AmexOpenAction;
	
	var options = {
        method: 'post',       
        postBody: $code,
        onSuccess: function(res) { 	$('AmexInterstitialError').addClass('displayNone');
        							handleSuccess(res); },
        onFailure: flowHandleError
    }
    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
    request.request();	
}

function handleToggleLogo() {
	var answer = confirm("The American Express OPEN(SM) logo will no longer display on your profile. Are you sure?");
	
	if (answer) {
	    $opt = $('amexlogoopt').toQueryString();
		$opt += '&action=togglelogo';
	    var options = {
	        method: 'post',
	        postBody: $opt,
	        onSuccess: function(res) { handleLogoOptSuccess(res); },
	        onFailure: handleError
	    }
	    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
	    request.request();
	} else {
		$('amexlogoopted').checked = true;
	}
}

function handleNoThanks(AmexOpenAction) {
	$code='action=opt_out';
	$code += '&AmexOpenAction='+AmexOpenAction;
	
    var options = {
        method: 'post',
        postBody: $code,
        onSuccess: function(res) { handleNoThanksSuccess(res);},
        onFailure: handleError
    }
    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
    request.request();
}

function handleAmexSignIn(context) {
    amexCookie = getAmexCookie();
	if (amexCookie == 15601 || amexCookie == 15606 || amexCookie ==15608) {
		window.location='/php/partner/main/AmexInterstitial.php?AmexOpenAction='+context;
	} else {
		window.location='/myelance';
	}
}

function handleSkipNow() {
    $code='action=noaction';
    var options = {
        method: 'post',
        postBody: $code,
        onSuccess: function(res) { flowHandleSuccess(res, 1);},
        onFailure: handleError
    }
    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
    request.request();
}


function enableBtn( buttonEnabled, buttonDisabled ) {
	if( buttonEnabled ) {
    	buttonEnabled.removeClass( 'displayNone' );
   	}
    if( buttonDisabled ) {
    	buttonDisabled.addClass( 'displayNone' );
    }
}

function setAmexVisitorCookie() {
	var hasAmexCookie = getAmexCookie() != null;
	if( !hasAmexCookie || getAmexCookie()== 15603) {
		var ridval = getGetParam( "rid" );
		if ( ridval != "" && ridval.length <= 6 ) {
			//-- Visitor with rids are from AMEX invitation: set 1 day cookie
			setCookie( "partner", "15606", "45", "/", ".elance.com", false );
		} else {
			//-- Visitor without rids are from Elance site: set 1 hour cookie
			document.cookie = "partner=15606;path=/;domain=.elance.com;";
		}
	}
}


function setAmexRSVPCookie() {
	var rsvp = getGetParam("amexrsvp");
	if( rsvp != "" && rsvp.length <=10 ) {
		setCookie( "amexrsvp", rsvp, "0.5", "/", ".elance.com", false );
	}
}


function getAmexCookie() {
	return getCookie('partner');
}

function getPartnerCookie() {
        return getCookie('partner2');
}

function handlePartnerOnReg(){
	$('bizTypeRadio').checked = true; 
	handleTypeChange('biz') ;
	$('bizSmall').checked = true; 
	$('category6').checked = true; 
	$('usermanagement').checked = false;
	handleMembershipChange(); 
	var promocode = getCookie('promocode');
	if(promocode) {
		$('promoCode').value = promocode;
		submitPromo();
	}
		
}

function landingRedirect() {
	var url = document.URL;
	var elance = /elance\.com\/$/;

	var olsbPartner = getPartnerCookie();
	var isOlsbPartner = (olsbPartner == 15622 || olsbPartner == 15623);

	if(url.match('/p/landing/') && url.indexOf('provider')>0 && !url.match('olsb') && isOlsbPartner) {
		window.location.href = '/officeliveprovider';
		return;
	}
	if(isOlsbPartner && (url.match(elance)  || url.match('/p/landing/') && url.indexOf('buyer')>0 && !url.match('olsb'))) {
		if(olsbPartner == 15622) {
                	window.location.href = '/officelivebuyerpromo';
			return;
                } else if(olsbPartner == 15623){
			window.location.href = '/officelivebuyer';
		}
		return;
        }
	if(url.match('olsb')) return;

	amexCookie = getAmexCookie();
	if ((url.match(elance) || url.match('/p/landing/') && !url.match('open')) && 
		(amexCookie == 15601 || amexCookie == 15606 || amexCookie ==15608)) {
		var open = '';
		if (url.indexOf('provider')>0) {
			open = 'openlogo/';
		} else {
			open = 'open/';
		}
		if(url.match(elance)) {
			window.location.href = 'open';
		} else {
			window.location.href = url.substring(0,url.indexOf('/p/landing/')+11) + open + url.substring(url.indexOf('/p/landing/')+11, url.length);
		}
	}
}

function hideBannerPopup( userType ) {
  	$('amex'+userType+'MoreInfoBox').addClass('visibilityHidden');
	$('amex' + userType + 'MoreInfoClosed').removeClass('visibilityHidden');
}

function showBannerPopup( userType ) {
  	$('amex'+userType+'MoreInfoBox').removeClass('visibilityHidden');
	$('amex' + userType + 'MoreInfoClosed').addClass('visibilityHidden');
}

function noThanksPartner( divid ) {
	var options = {
                method: 'post',
                onSuccess: function(res) { $( divid ).addClass('displayNone') },
                onFailure: handleError
        }
        var request = new Ajax('/php/partner/main/PartnerInterstitialAHR.php?action=nothanks&type='+divid, options);
        request.request();	
}

function clearGroup ( groupid ) {
	var options = {
		method: 'post',
                onSuccess: function(res) { 
					if($('recommended_count')) {
						if($( 'recommended_count' ).value == 0 ) {
							$('recommended_list').addClass('displayNone');
						} else {
							$( 'recommended_count' ).value = $( 'recommended_count' ).value - 1;
						}
					}
					if($( 'group' + groupid )) $( 'group' + groupid ).addClass('displayNone'); 
					},
                onFailure: handleError
        }
	curAsyncReq = new Ajax('/php/groups/main/groupAHR.php?action=ClearGroup&groupId='+groupid+'&t=' + getDateTime(), options);
	curAsyncReq.request();
}



var AmexOpenDialog;

function initAmexOpenDialog() {
  

	// Define various event handlers for Dialog
  var handleAccept = function() {
	$('action').value = 'agree';
	$('csphone').value = $('csphone1').value + $('csphone2').value + $('csphone3').value;
	var postData = $('AmexOpenform').toQueryString();
	var options = {
		method: 'post',
		postBody: postData,
		onSuccess: function(req) {handleSuccess(req);},
		onFailure: function(req) {handleFailure(req);}
    }
	var request =  new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
	request.request();
  };
  var handleNoThanks = function() {
  	$('action').value = 'opt_out';
    var postData = $('AmexOpenform').toQueryString();
    var options = {
        method: 'post',
        postBody: postData,
        onSuccess: function(req) {handleSuccess(req);},
        onFailure: function(req) {handleFailure(req);}
    }
    var request =  new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
    request.request();
  };
  var handleSuccess = function(obj) {
	var response = eval('(' + obj + ')');
	if( response.status == 'success' ) {
		//advanceTrain(response);a
		AmexOpenDialog.hide();
		
		if (response.data.AmexOpenAction == 'post') {
			if( response.stage == 'accept' ) {	
				//-- Force AMEX credit card
				$('deposit').style.display = 'none';
				$('depositAmex').style.display = 'block';
				$('ccTypeFieldErr').style.display = 'none';
				$('creditcard').checked = true;
				$('amex').checked = true;
				$('ccType').selectedIndex = 2;
				new Reg().paymentSelected('creditcard');
			}
			
			$('AmexActivateAccountBanner').addClass('displayNone');
			if ( response.stage == 'accept') { 
				$('AmexActivateAccountAcceptBanner').removeClass('displayNone');
				$('AmexActivateAccountOptOutBanner').addClass('displayNone');
			} else if (response.stage == 'opt_out') {
				$('AmexActivateAccountOptOutBanner').removeClass('displayNone');
			}
			$('AmexInterstitialError').addClass('displayNone');
		} else if (response.data.AmexOpenAction == 'profile') {
			//This is the only possibility
			if (response.stage == 'opt_out' ) {
			} else {
				$('AmexOpenJoin').addClass('displayNone');
				$('AmexOptionProfile').removeClass('displayNone');
			}
			window.location.reload();
		}
		else {
			window.location.reload();
		}
	} else {
		$('AmexInterstitialError').removeClass('displayNone');
	}
  };
  var handleFailure = function(o) {
	  
  };
  var closeAmexOpenDialog = function() {
    currentRownumDialog = -1;
    resetAmexOpenDialog();
  };

  AmexOpenDialog = new YAHOO.widget.Dialog("AmexOpendialog", 
    { width : "650px",
      fixedcenter : false,
      visible : false, 
      constraintoviewport : false,
	  modal:true,
	  draggable: true,
	  context: ['maincontent','tl','tl'],
	  underlay: 'none',
      effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3},
      buttons : [ 	{ text:"", handler:handleAccept, isDefault:true },
        			{ text:"", handler:handleNoThanks } ]
    } );
					
  // Wire up the success and failure handlers
  AmexOpenDialog.callback = { success: handleSuccess, failure: handleFailure };

  // Add validation
  AmexOpenDialog.validate = function() {
    var data = this.getData();
    resetAmexOpenErrors();

    return true;
  };
  // Render the Dialog
  AmexOpenDialog.render();
  AmexOpenDialog.beforeHideEvent.subscribe( closeAmexOpenDialog, AmexOpenDialog, true );
  AmexOpenDialog.innerElement.style.display = '';

	// add button styles
	AmexOpenDialog.firstButton.className = "amexAccept";
	AmexOpenDialog.lastButton.className = "amexNoThanks";
	
	scrollTo(0,0);
}


var currentRownumDialog = -1;

/**
 * Toggle display of the AmexOpen dialog.
 * If the user switches to another AmexOpen dialog, reset the error msgs.
 */
function toggleAmexOpenDialog( objId) {
  if( currentRownumDialog == objId ) {
    currentRownumDialog = -1;
    AmexOpenDialog.hide();
  }
  else {
	if (!AmexOpenDialog) {
		initAmexOpenDialog();
	}
    currentRownumDialog = objId;
    resetAmexOpenErrors();
    AmexOpenDialog.show();
  }
}

/**
 * Reset the AmexOpen dialog fields
 */
function resetAmexOpenDialog() {
  	resetAmexOpenErrors();
}

/**
 * Reset the error messages on the AmexOpen dialog.
 */
function resetAmexOpenErrors() {
	$('AmexInterstitialError').addClass('displayNone');
}
