// has the async call returned and replaced the content in the page yet?
var contentReplaced = null;
// id to replace content in
var replaceId = null;

var yWindowOffset = 70;
var windowHeight = 1700;
var windowWidth = 800;

var collapseText = "Collapse All";
var expandText = "Expand All";

// used to not collapse expanded project history details
// when clicking on the project link
var followProjectLink = false;

function objExists(obj, code) {
    // checks for 'obj' in javascript (can be a function, object, variable),
    // if it exists then execute code
    // clears the current interval and executes the code
    if (obj != undefined) {
        clearInterval(curLoad);
        curLoad = null;
        eval(code);
    }
}

function elementExists(element, code) {
    // checks for 'element' in the DOM, and once it exists
    // clears the current interval and executes code
    if ($(element)) {
        clearInterval(curLoad);
        curLoad = null;
        eval(code);
    }
}

function isLoaded() {
    // used with asyncRequest, only succeeds when the ajax request is complete
    // useful for guaranteeing that certain DOM objects will exist
    if (!contentReplaced || !curLoad || !curAsyncRef || YAHOO.util.Connect.isCallInProgress(curAsyncRef)) {
        return;
    }

    clearInterval(curLoad);
    curLoad = null;
    curAsyncRef = null;
    
    // saving this locally allows more than one use of isLoaded to be used at once...
    // how handy eh?
    localWaitingCode = curWaitingCode;
	curWaitingCode = null;
    eval(localWaitingCode);
}

// Since sign-in includes elanceUtil on every page, make sure this is defined to avoid error.
if( !self.replaceContent ) {
	self.replaceContent = function() {};
	self.replacePaginationContent = function() {};
	self.replaceGalleryContent = function() {};
}

var dummyCallback = {
    success: function () {},
    failure: function () {}
}

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

var jsCallback = {
    success: addJavascript,
    failure: ajaxFailure
}

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

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

/* 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;

function addJavascript(filename) {
    var head = document.getElementsByTagName('head').item(0);
    var tempEl = $(filename);

    if (tempEl) {
        if (filename == '/php/lib/carousel/carousel_ajax_load.js') {
            head.removeChild(tempEl);
        } else {
            return;
        }
    }

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.id = filename;
    script.src = filename;
    head.appendChild(script);
}

function addCSS(filename) {
    var head = document.getElementsByTagName('head').item(0);
    var tempEl = $(filename);

    if (tempEl) {
        return;
    }

    var link = document.createElement('link');
    link.type = 'text/css';
    link.id = filename;
    link.href = filename;
    link.rel = 'stylesheet';
    head.appendChild(link);
}

function ajaxFailure(obj) {
    //-- Do nothing
    // alert('AJAX call failed!');
}

/**
    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';
		}
	}

    rows = $('feedbackTable').rows.length - 1;
    for (i = 0; i < rows; ++i) {
        linkifyProjectName($('feedbackRow'+ i), expanding);
    }

    setRNavHeight();
}

/** Expand and collapse text details by ID
 */
function toggleDetails(el) {
    // the id of the element we pass in here is of the form detailsButton## and "detailsButton"
    // is 13 characters
    var id = el.id.substring(13);

    if ($('detailsPlus' + id).style.display == '') {
    	document.getElementById('detailsButtonGen' + id).style.position = 'relative';
    	document.getElementById('detailsButtonGen' + id).style.zIndex = '2';
        $('detailsPlus' + id).style.display = 'none';
        $('detailsMinus' + id).style.display = '';
        $('detailsBox' + id).style.display = '';
    } else if ($('detailsMinus' + id).style.display == '') {
        $('detailsPlus' + id).style.display = '';
        $('detailsMinus' + id).style.display = 'none';
        $('detailsBox' + id).style.display = 'none';
    }
}

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(11);
    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 = '';
        }
        linkifyProjectName(el, true);
    } 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';
        }
        linkifyProjectName(el, false);
    }

    setRNavHeight();
}

/** Collapses an element using a YAHOO animation in time seconds by height
 */
function collapseHeight(id, animation, time) {
    // default params
    animation = animation || YAHOO.util.Easing.easeOut;
    time = time || 1;

    el = $(id);

    var anim = new YAHOO.util.Anim(el.id, {height: { to: 0 }}, time, animation);

    evalText = '$("'+ id +'").style.lineHeight = 0';
    anim.animate();
    setTimeout(evalText, (time*500));
}

/** Expand an element using a YAHOO animation in time seconds by height
 */
function expandHeight(id, animation, time) {
    // default params
    animation = animation || YAHOO.util.Easing.easeOut;
    time = time || 1;

    el = $(id);

    // get height by making the object visible for a split second...kludgey
    el.style.position = 'absolute';
    el.style.top = 100000;
    el.style.display = '';
    el.style.lineHeight = 'normal';
    regHeight = el.scrollHeight;
    el.style.height = '0px';
    el.style.lineHeight = 0;    // for IE awesomeness
    el.style.position = 'static';
    var anim = new YAHOO.util.Anim(el.id, {height: { to: regHeight }}, time, animation);

    anim.animate();
    el.style.lineHeight = 'normal';
}

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

/** Call before a asynchronous request to prevent ajax weirdness
 */
function cancelRunningRequests() {
    if (curAsyncRef) {
        YAHOO.util.Connect.abort(curAsyncRef, null, null);
    }
}

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;
    // }
}

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 ) {
		pTop = $('profileMainContent').style.paddingTop;
		pBot = $('profileMainContent').style.paddingBottom;
		pTop = parseInt(pTop.substr(0, pTop.indexOf('px', 0)));
		pBot = parseInt(pBot.substr(0, pBot.indexOf('px', 0)));
		
		$('profileMainContent').style.height = ( rNavHeight - (pTop + pBot) ) + 'px';
	}
}

var projectURL = null;

function linkifyProjectName(obj, linkify) {
    if (!obj) {
        // linkify an object that doesn't exist? I don't think so
        return;
    }
    projectNameObj = $('project'+ obj.id.substr(11));

    if (linkify) {
        link = 'http://'+ window.location.host + projectNameObj.lang;
        newProjectNameObj = document.createElement('a');
        newProjectNameObj.href = link;
        newProjectNameObj.innerHTML = projectNameObj.innerHTML;
        newProjectNameObj.id = projectNameObj.id;
        newProjectNameObj.lang = projectNameObj.lang;
        newProjectNameObj.setAttribute('onclick', function() { followProjectLink = true; window.location.href = this.lang; });
        newProjectNameObj.onclick = function() { followProjectLink = true; window.location.href = this.lang; };
    } else {
        newProjectNameObj = document.createElement('span');
        newProjectNameObj.lang = projectNameObj.lang;
        newProjectNameObj.innerHTML = projectNameObj.innerHTML;
        newProjectNameObj.id = projectNameObj.id;
    }
    projectNameObj.parentNode.replaceChild(newProjectNameObj, projectNameObj);
}

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
}

/** Call external chat presences on when Contact Info (View) button is clicked
 */
function lazySetChatIcons() {
    if ( $('yahoo_im') ) {
	$('yahoo_im').src = $('yahoo_im').lang;
    }
    if ( $('skype_im') ) {
	$('skype_im').src = $('skype_im').lang;
    }
    if ( $('icq_im') ) {
	$('icq_im').src = $('icq_im').lang;
    }
    if ( $('aol_im') ) {
	$('aol_im').src = $('aol_im').lang; 
    } 
    if ( $('msn_im') ) {
	$('msn_im').src = $('msn_im').lang;
    }
}

function editProfileImage(action) {
    // 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 + '&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);
}

var inviteCallback = {
	success: inviteSuccess,
	failure: ajaxFailure
}

function inviteSuccess(response) {
	var result = eval('('+ response.responseText +')');
	if (result.status == 'success' && result.data.length) {
		$('inviteeList').innerHTML = result.data.toString().replace(/,/, ', ');
		$('inviteContent').style.display = 'none';
	} else {
		$('inviteSuccessMessage').style.display = 'none';
		$('inviteFailureMessage').style.display = '';
		$('inviteContent').style.display = 'none';
	}
}

function inviteUser(buyerId, sellerId) {
	url = '';
	i = 0;
	while($('existing'+i)) {
		if ($('existing'+i).checked) {
			url = $('existingLink'+i).href;
			break;
		}
		++i;
	}

	// if we're inviting multiple sellers, this will comma deliminate them
	sellerId = sellerId.toString();

	if (url.length) {
		jobId = url.substr(url.search(/jobid=/)+6);
	} else {
		window.location.href = '/postjob?inviteId='+ sellerId.replace(/,/g, '_');
		return;
	}

	if (jobId) {
		var date = new Date();
		YAHOO.util.Connect.asyncRequest('GET',
										'/php/profile/main/inviteAHR.php?jobId='
										+jobId+'&buyerId='+buyerId+
										'&sellerId='+sellerId+
										'&t='+ date.getTime(),
										inviteCallback,
										null);
	}
}
/* 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++;
    }
}

// whitespace trimmers -- borrowed from here: http://www.codingforums.com/showthread.php?p=178098
String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

String.prototype.ltrim=function(){
    return this.replace(/^\s*/g,'');
}

String.prototype.rtrim=function(){
    return this.replace(/\s*$/g,'');
}


/**
 * Obtained from: http://www.netlobo.com/url_query_string_javascript.html
 */
function getGetParam(name) {
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null ) {
    return "";
  }
  else {
    return results[1];
  }
}


/**
 * Returns the time in milliseconds since 01/01/1970
 */
function getDateTime() {
  var d = new Date();
  var t = d.getTime();
  return t;
}


/**
 * Parses '&' separated name=value arg pairs from 
 * the query string of the URI.
 *
 * Example:
 * var args = getArgs();
 * var q = args.q || '';
 * var n = args.n ? parseInt(args.n) : 10;
 */
function getArgs() {
  var args = new Object();
  var query = location.search.substring(1);
  var pairs = query.split("&");
  for(var i = 0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf('=');
    if( pos == -1 ) continue;
    var argname = pairs[i].substring(0,pos);
    var value = pairs[i].substring(pos+1);
    value = decodeURIComponent(value);
    args[argname] = value;
  }
  return args;
}


/**
 * Parses '&' separated name=value arg pairs from 
 * the hash string of the URI.
 *
 * Example:
 * var args = getArgsFromHash();
 * var q = args.q || '';
 * var n = args.n ? parseInt(args.n) : 10;
 */
function getArgsFromHash() {
  var args = new Object();
  var query = location.hash.substring(1);
  var pairs = query.split("&");
  for(var i = 0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf('=');
    if( pos == -1 ) continue;
    var argname = pairs[i].substring(0,pos);
    var value = pairs[i].substring(pos+1);
    value = decodeURIComponent(value);
    args[argname] = value;
  }
  return args;
}


/**
 * Sets the anchor part of the URL.  
 * Safari has an issue with setting the hash to 
 *  the same value as the existing hash.
 * Store the current hash in currHashUrl for use in checkHashChanged.
 */
var currHashUrl;
function setHashParams( newHash ) {
  if( getCurrHashParams() != newHash ) {
    window.location.hash = newHash;
    currHashUrl = getCurrHashParams();
  }
  return true;
}


/**
 * Gets the current anchor portion of the URL.
 * In some browsers, this returns the #, so remove it.
 */
function getCurrHashParams() {
  var h = window.location.hash;
  if( h.search(/#/) == 0 ) {
    h = h.substring(1);
  }
  return h;
}


function isSafari() {
  return( navigator.appVersion.indexOf( 'Safari' ) != -1 );
}


/**
 * If the hash of the current URL has changed from what was set
 *  using setHashParams(), then reload the page.
 * Before calling the first time, set currHashUrl = getCurrHashParams()
 */
function checkHashChanged() {
  if( getCurrHashParams() != currHashUrl && !requestInProgress ) {
    window.location.reload();
    return;
  }
  var t = setTimeout("checkHashChanged()", 500);
}


/**
 * Get other elements in the form that YUI did not set in getData().
 * [fixed in newer versions of YUI]
 */ 
function getMoreData(form, data) {
	if (!form) { return; }
	if (!data) { data = {}; }
	for (var i = 0; i < form.elements.length; i++) {
		var formItem = form.elements[i];
		if (!formItem || data[formItem.name] != undefined ) {
			continue;
		}

		// Catch checked radios and password fields
		if (formItem.type == "radio") {
			if (formItem.checked == true) { data[formItem.name] = formItem.value; }
		} else if (formItem.type == "password") {
			data[formItem.name] = formItem.value;
		}
	}
}


/**
 * Checks if an email address is valid.
 * Thanks to: http://www.totallyphp.co.uk/code/validate_an_email_address_using_regular_expressions.htm
 */
function isValidEmailAddress( email ) {
	if (email == "" || 
			email.search(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i) == -1	) {
			return false;
	}
	return true;
}

/**
 * Gets error message from element with objectId and sticks it in element with locationId
 */
function setErrorFromId(locationId, objectId) {
	var error = $( objectId ).innerHTML;
	setErrorText( locationId, error );
}

/**
 * Sticks text in element with locationId
 */
function setErrorText(locationId, text) {
	var location = $( locationId );
	location.innerHTML = text
	if (text == '') {
		location.style.display = 'none'
	} else {
		location.style.display = 'block'
	}
}

/**
 * Clear text in element with locationId
 */
function resetError(locationId) {
	setErrorText( locationId, "");
}


function createWindow(u,n,w,h,r) {
	args = 'width='+w+',height='+h+',resizable=no,scrollbars=yes,status=0';
	remote = window.open(u,n,args);
	if( remote != null ) {
		if (remote.opener == null) {
			remote.opener =  self ;
		}
	}
	if( r == 1 ) { return remote; }
}

var attw =null;

function Attach( url ) {
	if( !attw || attw.closed ) {
		attw = createWindow( url,  'attachwin', 450, 450, 1) ;
	}
	attw.focus();
}


function showBusy( buttonEnabled, buttonDisabled ) {
	document.body.style.cursor = 'wait';
	if( buttonEnabled ) {
		buttonEnabled.addClass( 'displayNone' );
	}
	if( buttonDisabled ) {
		buttonDisabled.removeClass( 'displayNone' );
	}
}


function hideBusy( buttonEnabled, buttonDisabled ) {
	document.body.style.cursor = 'default';
	if( buttonEnabled ) {
		buttonEnabled.removeClass( 'displayNone' );
	}
	if( buttonDisabled ) {
		buttonDisabled.addClass( 'displayNone' );
	}
}


/**
 * Remove a css class from an element, but leave it's other css classes
 */
function removeClassName( el, cssClass ) {
	var start = el.className.toLowerCase().indexOf( cssClass.toLowerCase() );
 	if( start == -1 ) {
 		return;
 	}
 	var end = start + cssClass.length;
 	var last = el.className.length;
 	el.className = el.className.substring(0,start-1) + el.className.substring(end,last);
}
  
  
/**
 * Add a css class to an element, but only if it doesn't already exist
 */
function addClassName( el, cssClass ) {
 	var exists = el.className.toLowerCase().indexOf( cssClass.toLowerCase() );
 	if( exists >= 0 ) {
 		return;
 	}
 	else {
 		el.className += ' ' + cssClass;
 	}
 }

var emailDialog;



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 !== '') {
      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 : "400px",
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3},
      buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
        { text:"Cancel", handler:handleCancel } ]
    } );
					
  // Wire up the success and failure handlers
  emailDialog.callback = { success: handleSuccess, failure: handleFailure };

  // Add validation
  emailDialog.validate = function() {
    var data = this.getData();
    resetEmailErrors();
    //-- At least one email address
    if(data.email1 == "" && data.email2 == "" && data.email3 == "" && data.email4 == "") {
      $("emailErrorMsg").innerHTML = "Please enter at least one email address.";
      $("email1").className = "highlightInput";
      return false;
    } 
    //-- No more than 4000 characters in body
    if(simpleTextCount(document.emailfriendform.emailbody) > 4000) {
      $("emailErrorMsg").innerHTML = "Please shorten your message to 4000 characters or less.";
      $("emailbody").className = "highlightInput";
      return false;
    } 

    return true;
  };

  // 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 ) {
  if( currentRownumDialog == objId ) {
    currentRownumDialog = -1;
    emailDialog.hide();
  }
  else {
	if (!emailDialog) {
	    initEmailDialog();
	}
    currentRownumDialog = objId;
    resetEmailErrors();
    emailDialog.show();
    $('emailTitle').innerHTML = objTitle;
    $('emailObjId').value = objId;
  }
}

/**
 * Reset the email dialog fields
 */
function resetEmailDialog() {
  resetEmailErrors();
  $("email1").value = '';
  $("email2").value = '';
  $("email3").value = '';
  $("email4").value = '';
  $("emailbody").value = '';
  document.emailfriendform.emailbody.value = '';
  simpleTextCounter(document.emailfriendform.emailbody,$('charLimit'),4000);
}

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

var handleHide = function() {
  this.hide();
}

var infoDialog;

/**
 * Initialize the info dialog
 */
function initInfoDialog() {
infoDialog = new YAHOO.widget.SimpleDialog("infodialog",  
    { width: "400px", 
      fixedcenter: true, 
      visible: false, 
      draggable: false, 
      close: true, 
      constraintoviewport: true, 
      effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.4},
      buttons: [ { text:"Ok", handler:handleHide, isDefault:true } ] 
    } ); 
	infoDialog.render(document.body);
	removeClassName( infoDialog.innerElement, 'displayNone' );
}

/**
 * Show the info dialog using element IDs
 */
function showInfoDialog( titleId, bodyId, type ) {
	if (!infoDialog) {
		initInfoDialog();
	}
	var titleText = $( titleId ).innerHTML;
	var bodyText = $( bodyId ).innerHTML;
	showInfoDialogText( titleText, bodyText, type );
}


/**
 * Show the info dialog using the text provided
 */
function showInfoDialogText( titleText, bodyText, type ) {
  if (!infoDialog) {
    initInfoDialog();
  }
  $("infodialogtitle").innerHTML = titleText;
  $("infodialogbody").innerHTML = bodyText;
  if( type == 'WARN' ) {
    infoDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_WARN);
  }
  else if( type == 'INFO' ) {
    infoDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_INFO);
  }
  infoDialog.show();
}


var csr911Dialog;

function initCSR911Dialog() {
	
  
	// Define various event handlers for Dialog
  var handleSubmit = function() {
    this.submit();
  };
  var handleCancel = function() {
    this.cancel();
  };
  var handleSuccess = function(o) {
    var response = o.responseText;
    if( response.length > 0 ) {
      showInfoDialogText( $('csr911failuretitle').innerHTML, response, 'WARN' ); 
    }
    else {
      showInfoDialog( 'csr911successtitle', 'csr911successbody', 'INFO' );
    }
  };
  var handleFailure = function(o) {
    showInfoDialog( 'csr911failuretitle', 'csr911failurebody', 'WARN' );
  };
  var closeCSR911Dialog = function() {
    currentRownumDialog = -1;
    resetCSR911Dialog();
  };

  csr911Dialog = new YAHOO.widget.Dialog("csr911dialog", 
    { width : "470px",
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3},
      buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
        { text:"Cancel", handler:handleCancel } ]
    } );
					
  // Wire up the success and failure handlers
  csr911Dialog.callback = { success: handleSuccess, failure: handleFailure };

  // Add validation
  csr911Dialog.validate = function() {
    var data = this.getData();
    resetCSR911Errors();

    return true;
  };
  // Render the Dialog
  csr911Dialog.render();
  csr911Dialog.beforeHideEvent.subscribe( closeCSR911Dialog, csr911Dialog, true );
	removeClassName( csr911Dialog.innerElement, 'displayNone' );
}


var currentRownumDialog = -1;

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

/**
 * Toggle display of the CSR911 dialog.
 * If the user switches to another CSR911 dialog, reset the error msgs.
 */
function toggleCSR911Dialog( objId, objType) {
  if( currentRownumDialog == objId ) {
    currentRownumDialog = -1;
    csr911Dialog.hide();
  }
  else {
	if (!csr911Dialog) {
	    initCSR911Dialog();
	}
    currentRownumDialog = objId;
    resetCSR911Errors();
    csr911Dialog.show();
    $('object_id').value = objId;
  }
}

/**
 * Reset the CSR911 dialog fields
 */
function resetCSR911Dialog() {
  resetCSR911Errors();
 $("object_id").value = '';
 $("login_name").value = '';
 $("subject").value = '';
 $("comments").value = '';
}

/**
 * Reset the error messages on the CSR911 dialog.
 */
function resetCSR911Errors() {
}

var addToListDialog;

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 != 'success' ) {
      showInfoDialogText( $('addToListfailuretitle').innerHTML, response, 'WARN' ); 
    }
    else {
      showInfoDialog( 'addToListsuccesstitle', 'addToListsuccessbody', 'INFO' );
    }
  };
  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:"Submit", handler:atlhandleSubmit, isDefault:true },
        { text:"Cancel", 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 = '';
}


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

/**
 * 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){
    
   var url = '/php/myelance/main/watchCenter.php?mode=check&addToListObjType='+$('addToListObjType').value+'&addToListObjId='+objId+'&addToListObjName='+objType;
   new Ajax.Request(url,
   {
     asynchronous:true,
     method:'get',
     onSuccess: function(t){ 
         var celldata = t.responseText.split('##');
         if(celldata[0]=='No'){
            toggleaddToListDialog(celldata[1], celldata[2]);
         }else{
             atlAlreadyAddedDialog(celldata[2]);
         }
     },
     onFailure: function(){ alert('Internal Error, Please check if you are currently logged in and try again.') }
   }
   );
}
var signInPanel;     // Panel for signin in
var regChooseDialog; // Dialog for choosing buyer/provider for reg
var forgotLDialog;   // Forgot Login Dialog
var forgotPDialog;   // Forgot Password Dialog

/* CSI = "Check Signed In"
 * CSI Modes:
 *  8: 'Contact Me' - Invite to Bid
 *  9: 'Contact Me' - Chat
 * 10: 'Contact Me' - Call
 * 11: View Provider Contact Info
 * 12: Post Project
 * 13: Invite To Bid [Search Page]
 * 20: Provider [generic]
 * 30: Global Sign In 
 * 31: Add To List
 * 32: Email To Friend
 * 33: Report Violation
 */
// csi Mode is what operation is being perfomed, 
// csiCmd is what command to proceed with, but for reg it might probably wont be used
var csiMode, csiCmd = "";

/**
 * Checks if user is signed in, executes 'cmd' if so. Otherwise it shows the signInPanel.
 * signInPanel will use the captured mode/cmd to determine its actions on success.
 */
function checkSignedIn( mode, cmd, cmdAlt ) {
	csiMode = mode;
	csiCmd = cmd;

	var csiSuccess = function(o) {
    var responseObj = eval("({" + o.responseText + "})");

    if( responseObj.code >= 0 ) {
			// Signed in: execute command!	
			execCsiCommand();
		} else if ( cmdAlt && cmdAlt !== "" ) {
			// Alternate command specified: run it
			eval(cmdAlt);
    } else {
			// Not Signed in, show sign in panel
			if (!signInPanel) { initSignInPanel(); }
			signInPanel.show();
    }
	};
	// Ajax failure: just try to do the command anyway
	var csiFailure = function(o) {
		execCsiCommand();
	};
	var csiCallback = { success: csiSuccess, failure: csiFailure };
  
	// Fire off JSON to detect signed-in status
	var url = '/php/reg/main/signInAHR.php?mode=checksignedin';
	var req = YAHOO.util.Connect.asyncRequest('POST', url, csiCallback, null);
}

/**
 * Execute the CSI comand, if one exists.
 */
function execCsiCommand() {
	if( csiCmd != "" ) {
		eval(csiCmd);
	}
}


/*** SIGN IN PANEL ***/

// Whether we have loaded the signInPanel guts or not
var signInPanelIframeLoaded = false;

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

function initSignInPanel() {
	var sihandleOpen = function() {
		// If the iframe is loaded already, we can skip out.
		if ( signInPanelIframeLoaded ) { return; }
		
		// Check for cookies enabled (only done during iframe load)
		setCookie('test', 'elance', '', '/', '', '');
		var test = getCookie('test');
		if( !test || test != 'elance'  ) {
			setErrorFromId('signInError', 'signInCookiesWarning');
		}

		/**** LOAD IFRAME ****/

		// Set onAvaible event to remove loading image
		YAHOO.util.Event.onAvailable('signInPanelIframe1', signInIframeLoaded);

		// create iFrame
		var iFrame;
		iFrame = document.createElement("iframe");
		iFrame.setAttribute("src", '\/signiniframe');
		iFrame.setAttribute("scrolling", "no");
		iFrame.setAttribute("frameBorder", "0"); 
		iFrame.setAttribute("id", 'signInPanelIframe1'); 
		iFrame.setAttribute("class", "signinpanelsecure"); // for firefox
		iFrame.setAttribute("className", "signinpanelsecure"); // For silly IE

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

		signInPanelIframeLoaded = true;
	};
	var sihandleClose = function() {
		// We need to do this on close for IE to cooperate!
		resetError("signInError");
	}

	signInPanel = new YAHOO.widget.Panel("signInPanelDiv", 
		{ 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
	signInPanel.render();
	signInPanel.beforeShowEvent.subscribe( sihandleOpen, signInPanel, true );
	signInPanel.beforeHideEvent.subscribe( sihandleClose, signInPanel, true );

	if (!regChooseDialog) { initRegChooseDialog(); }
	if (!forgotLDialog) { initForgotLDialog(); }
	if (!forgotPDialog) { initForgotPDialog(); }
	if (!infoDialog) { initInfoDialog(); }
	removeClassName( signInPanel.innerElement, 'displayNone' );
}


// Commands from the HTTPS side will be handled by this function
function signInCallback( cmd, arg, email ) {
	// If email is specified, set it in the email fields
	if ( email != '' ) {
		forgotLDialog.form.email.value = email;
		forgotPDialog.form.email.value = email;
	}

	// take action based on cmd
	switch (cmd) {
	case -1: // Dialog Error
		setErrorText("signInError", "   "); // give the appearance of refresh
		arg = arg.replace(/([\'\"])/g, "\\$1"); // escape quotes
		setTimeout("setErrorText('signInError', '"+ arg +"')", 100);
		break;
	case 0: // Cancel button
		signInPanel.hide();
		break;
	case 1: // Sign In Success
	case 2: // unVerfied Signin
		// Default behavior: close panel, update login link
		signInPanel.hide();
		getLoginLink(document.getElementById('loginlink'), 1);

		// Pause briefly to allow browser time to get settled [cookies]
		setTimeout('execCsiCommand()', 100 );
		break;
	case 5: // Register success
		resetError("signInError");

		// Set Email Signups ID from arg, csiMode from var
		regChooseDialog.form.emailSignupsId.value = arg;
		regChooseDialog.form.csiMode.value = csiMode;

		// setup url for updating signup information
		var url = '/php/reg/main/signInAHR.php?mode=savesignupdata';
		url += '&emailSignupsId=' + arg;
		url += '&csiMode=' + csiMode;

		// Choose based on CSI-Mode
		switch (csiMode) {
		case 8:  // Invite to bid
		case 12: // Post Project
			// Update signups entry
			url += '&regType=buyer';
			YAHOO.util.Connect.asyncRequest('POST', url, dummyCallback, null);

			if (csiMode == 8 && self.getInviteeList) {
				var invitedUsers = document.createElement('input');
				invitedUsers.setAttribute('name', 'inviteId');
				invitedUsers.setAttribute('value', getInviteeList().toString().replace(/,/g, '_'));
				regChooseDialog.form.appendChild(invitedUsers);
			} else if (csiMode == 8) {
				invitedUsers = document.createElement('input');
				invitedUsers.setAttribute('name', 'inviteId');
				invitedUsers.setAttribute('value', $('profileUserId').innerHTML);
				regChooseDialog.form.appendChild(invitedUsers);
			}

			// Goto post project [give time for asyn to fire]
			regChooseDialog.form.action = "/postjob";
			setTimeout('regChooseDialog.form.submit();', 100);
			break;

		/**** PROVIDER SIGNUP CASE ****/
		case 20: // Provider [generic]
			// Update signups entry	
			url += '&regType=provider';
			YAHOO.util.Connect.asyncRequest('POST', url, dummyCallback, null);		

			// Go To Provider Registration
			setRegChooseDialogProvider();
			setTimeout('regChooseDialog.form.submit();', 100);
			break;

		/**** UNKNOWN CASE ****/
		case 30: // Global Signin
		case 31: // AddToList
		case 32: // EmailAFriend
		case 33: // ReportViolation
			regChooseDialog.show();
			break;

		/**** BUYER SIGNUP CASE (DEFAULT) ****/
		default:
			// Update signups entry
			url += '&regType=buyer';
			YAHOO.util.Connect.asyncRequest('POST', url, dummyCallback, null);

			// Go To Buyer Registration
			setRegChooseDialogBuyer();
			setTimeout('regChooseDialog.form.submit();', 100);
			break;
		}
		break;
	case 10: // Forgot Login
		forgotLDialog.show();
		break;
	case 11: // Forgot Password
		forgotPDialog.show();
		break;
	default: // Should never see this
		setErrorText("signInError", "Error: invalid callback mode ["+cmd+"]");
		break;
	}
}


/*** REGISTRATION ***/

function setRegChooseDialogBuyer() {
	regChooseDialog.form.action = "/register";
}

function setRegChooseDialogProvider() {
	regChooseDialog.form.action = "/signup";
}

function initRegChooseDialog() {
	// Define various event handlers for Panel
	var rchandleSubmit = function() {
		var data = this.getData();
		getMoreData(this.form, data);
		
		// Update the signup entry
		var url = '/php/reg/main/signInAHR.php?mode=savesignupdata';
		url += '&emailSignupsId=' + data.emailSignupsId;
		url += '&csiMode=' + data.csiMode;
		url += '&regType=' + data.regType;
		YAHOO.util.Connect.asyncRequest('POST', url, dummyCallback, null);

		// Change action for provider type
		if ( data.regType == "provider" ) {
			setRegChooseDialogProvider();
		} else {
			setRegChooseDialogBuyer();
		}
	
		// Give some time for the async request to fire
		setTimeout('document.regChooseForm.submit()', 100);
	};
	var rchandleCancel = function() {
		this.cancel();
	};
	var rchandleOpen = function() {
		signInPanel.hide();
	};
	var rchandleClose = function() {
		signInPanel.show();
	};

	regChooseDialog = new YAHOO.widget.Dialog("regChooseDialogDiv", 
		{ fixedcenter : true,
			visible : false, 
			constraintoviewport : true,
			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3},
			draggable: true,
			buttons : [ 
				{ text:"", handler: rchandleSubmit, isDefault:true },
				{ text:"", handler: rchandleCancel } 
			],
			postmethod: "none"
		} 
	);

	// Render, add open/close event handlers
	regChooseDialog.render();
	regChooseDialog.beforeShowEvent.subscribe( rchandleOpen, regChooseDialog, true );
	regChooseDialog.beforeHideEvent.subscribe( rchandleClose, regChooseDialog, true );
	regChooseDialog.firstButton.className = "continue";
	regChooseDialog.lastButton.className = "cancel";
	removeClassName( regChooseDialog.innerElement, 'displayNone' );
}



/** FORGOT LOGIN DIALOG **/

function initForgotLDialog() {
	// Define various event handlers for Dialog
	var flhandleSubmit = function() {
		// We can't use "submit()" because it will hide if AJAX success... which we may not want
		if (this.validate()) { this.doSubmit(); }
	};
	var flhandleCancel = function() {
		this.cancel();
	};
	var flhandleSuccess = function(o) {
		// Convert our response [json] into object
		var responseObj = eval("({" + o.responseText + "})");

		if( responseObj.code != 1 ) {
			setErrorText("forgotLError", responseObj.error);
		}
		else {
			// success!
			forgotLDialog.hide();
			signInPanel.hide(); // cuz forgotLdialog.hide will open this
			showInfoDialog("forgotLSuccessTitle", "forgotLSuccessBody", "INFO");
		}
		return;
	};
	var flhandleFailure = function(o) {
		setErrorFromId("forgotLError", "signInAjaxFailure");
		return;
	};	
	var flhandleOpen = function() {
		signInPanel.hide();
	};
	var flhandleClose = function() {	  
		resetError("forgotLError");
		signInPanel.show();
	};

	forgotLDialog = new YAHOO.widget.Dialog("forgotLDialogDiv", 
		{ fixedcenter : true,
			visible : false, 
			constraintoviewport : true,
			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3},
			buttons : [ 
				{ text:"", handler:flhandleSubmit, isDefault:true },
				{ text:"", handler:flhandleCancel } 
			]
		} 
	);

	// Add validation
	forgotLDialog.validate = function() {
		var data = this.getData();
		if (data.email == "" || 
				data.email.search(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/) == -1	) {
			setErrorFromId("forgotLError", "forgotLInvalidEmail");
			return false;
		}
		return true;
	};

	// Wire up the success and failure handlers
	forgotLDialog.callback = { success: flhandleSuccess, failure: flhandleFailure };

	// Render, add open/close event handlers
	forgotLDialog.render();
	forgotLDialog.beforeShowEvent.subscribe( flhandleOpen, forgotLDialog, true );
	forgotLDialog.beforeHideEvent.subscribe( flhandleClose, forgotLDialog, true );
	forgotLDialog.firstButton.className = "submit";
	forgotLDialog.lastButton.className = "cancel";
	removeClassName( forgotLDialog.innerElement, 'displayNone' );
}



/** FORGOT PASSWORD DIALOG **/

function initForgotPDialog() {
	// Define various event handlers for Dialog
	var fphandleSubmit = function() {
		// We can't use "submit()" because it will hide if AJAX success... which we may not want
		if (this.validate()) { this.doSubmit(); }
	};
	var fphandleCancel = function() {
		this.cancel();
	};
	var fphandleSuccess = function(o) {
		// Convert our response [json] into object
		var responseObj = eval("({" + o.responseText + "})");

		if( responseObj.code != 1 ) {
			setErrorText("forgotPError", responseObj.error);
		}
		else {
			// success!
			forgotPDialog.hide();
			signInPanel.hide(); // cuz forgotPdialog.hide will open this
			showInfoDialog("forgotPSuccessTitle", "forgotPSuccessBody", "INFO");
		}
		return;
	};
	var fphandleFailure = function(o) {
		setErrorFromId("forgotPError", "forgotPAjaxFailure");
		return;
	};	
	var fphandleOpen = function() {
		signInPanel.hide();
	};
	var fphandleClose = function() {
		resetError("forgotPError");
		signInPanel.show();
	};

	forgotPDialog = new YAHOO.widget.Dialog("forgotPDialogDiv",
		{ fixedcenter : true,
			visible : false, 
			constraintoviewport : true,
			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3},
			buttons : [ 
				{ text:"", handler:fphandleSubmit, isDefault:true },
				{ text:"", handler:fphandleCancel } 
			]
		} 
	);

	// Add validation
	forgotPDialog.validate = function() {
		var data = this.getData();
		if (data.login_name == "" ) {
			setErrorFromId("forgotPError", "forgotPEnterLoginName");
			return false;
		} 
		else if ( !isValidEmailAddress(data.email) ) {
			setErrorFromId("forgotPError", "forgotPInvalidEmail");
			return false;
		}
		return true;
	};

	// Wire up the success and failure handlers
	forgotPDialog.callback = { success: fphandleSuccess, failure: fphandleFailure };

	// Render, add open/close event handlers
	forgotPDialog.render();
	forgotPDialog.beforeShowEvent.subscribe( fphandleOpen, forgotPDialog, true );
	forgotPDialog.beforeHideEvent.subscribe( fphandleClose, forgotPDialog, true );
	forgotPDialog.firstButton.className = "submit";
	forgotPDialog.lastButton.className = "cancel";

	username = getReturningUsername();
	if( username != '' ) {
		forgotPDialog.form.login_name.value = username;
	}	
	removeClassName( forgotPDialog.innerElement, 'displayNone' );
}


