// JavaScript Document

function Help( thisLink ) {
    var comwin = window.open(thisLink,'','width=560,height=450,scrollbars=1,resizable=1');
    comwin.focus();
}

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

function Help640( thisLink) {
    var comwin = window.open(thisLink,'','width=640,height=480,scrollbars=1,resizable=1');
    comwin.focus();
}

function HelpTall( thisLink) {
    var comwin = window.open(thisLink,'','width=640,height=700,scrollbars=1,resizable=1');
    comwin.focus();
}

// --------------- EXTERNAL URL ----------------------------- //
// used in corporate top navigation
// used in both corp and enterprise footer includes

function setExternalURL( url, args ) {
    var host   = location.host;
    var port   = location.port;
    var proto  = location.protocol;
    var marker = host.indexOf('.elance.com');
    var first  = host.substring( 0, marker ); 
    first      = first.toLowerCase();
    var second = host.substring( marker, host.length );
    var prod   = "true";
    var urllc  = url.toLowerCase();
    var returl = proto + "//" + host;	
    if ( first == "www" || first == "secure" || first == "ws" ||
         first == "agency" || first == "csr" || first == "corporate" ||
	 first == "enterprise" || first == "corp" ) {
        prod = "true";
    } else {
        prod = "false";
    }
    if ( urllc == "corp" || urllc == "corporate" || urllc == "enterprise" || 
         urllc == "www" || urllc == "secure" || urllc == "ws" || 
         urllc == "agency" ) {
        if ( urllc == "secure" && proto == "http:" ) {
            proto = "https:";
            if ( port > 0 ) {
                port++;
                second = second.substring( 0, second.indexOf(':'));
                second = second + ":" + port;
            }
        }
	if ( urllc != "secure" && proto == "https:" ) {
	    proto = "http:";
            if ( port > 0 ) {
                port--;
                second = second.substring( 0, second.indexOf(':'));
                second = second + ":" + port;
            }
	}
        if ( prod == "true" ) {
            if ( args.length > 0 ) {
                returl = proto + "//" + urllc + second + "/" + args;
            } else {
                returl = proto + "//" + urllc + second;
            }
        } else {
            if ( first.indexOf('.') > 0 ) {
                first = first.substring( 0, first.indexOf('.'));
            }
            if ( args.length > 0 ) {
                returl = proto + "//" + first + "." + urllc + second + "/" + args;
            } else {
                returl = proto + "//" + first + "." + urllc + second;
            }
        }
    } else {
        if ( args.length > 0 ) {
            returl = proto + "//" + host + "/" + args;
        } else {
            returl = proto + "//" + host;
        }
    }
    // Specific case for www.elanceonline.com
    if( host == 'www.elanceonline.com' && url == 'www' && args == 'eolhome') {
      returl = proto + "//www.elance.com/eolhome";
    }
    // alert( returl );
    document.location.href = returl;
}


/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */

function setCookie(name, value, expirendays, path, domain, secure) {
    var today   = new Date();
    var expires = new Date();
    if ( expirendays == null || expirendays == 0 ) expirendays = 1;
    expires.setTime(today.getTime() + 86400000*expirendays);
    var cookiestr = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = cookiestr;
}
 
/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
 

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */

function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
 

function getURLParam(strParamName) {
    var strRet = "";
    var params = window.location.search;
    if ( params.length > 0 ) {
        params = params.substr( 1, params.length );
        var aQueryString = params.split("&");
        for ( var i = 0; i < aQueryString.length; i++ ){
            var aQueryStringLC = aQueryString[i].toLowerCase();
            if (aQueryStringLC.indexOf(strParamName + "=") > -1 ){
              // alert( "Doing param " + aQueryString[i] + " index = " + aQueryString[i].indexOf(strParamName) );
                var aParam = aQueryString[i].split("=");
                if ( aParam[1].length > 0 ) {
                    strRet = aParam[1];
                }
            }
        }
    }
    return strRet;
}

 

function setRIDCookie () {
    var ridval = getURLParam( "rid" );
    if ( ridval != "" && ridval.length <= 6 ) {
        // alert( "Setting RID to " + ridval );
        setCookie( "rid", ridval, "730", "/", ".elance.com" );
    }
}


setRIDCookie();

function simpleTextCount(field) {
  var textCount = field.value.length;
  if( field.value.match(/\r\n/) ) {
    // Some browsers count newline as two characters
    var numNewlines = field.value.match(/\r\n/g).length;
    textCount = field.value.length;
  }
  else if( field.value.match(/\n/) ) {
    // Some browsers count newline as one character
    var numNewlines = field.value.match(/\n/g).length;
    textCount = field.value.length + (numNewlines);
  }
  return textCount;
}


function simpleTextCounter(field, countfield, maxlimit)
{
  var plural = "s";
  var textCount = simpleTextCount(field);
  if((textCount == maxlimit-1) || (textCount == maxlimit+1)) {
    plural = "";
  }

  if( textCount > maxlimit ) {
    countfield.innerHTML = '<b>Your message is ' + (textCount - maxlimit) + ' character' + plural + ' too long.  Please make it shorter.</b>';
  }
  else {
    countfield.innerHTML = (maxlimit - textCount) + ' character' + plural + ' left';
  }
}


/** 
 * Used by the Project Description Assistant 
 **/
function dumpForm() {
    var count   = 0;
    var msg     = "";
    var len     = document.ASSISTANT.elements.length;
    var elemlen = 0;
    for ( i = 0; i < len; i++ ) {
        if ( document.ASSISTANT.elements[i].type == 'radio' ) {
	    if( document.ASSISTANT.elements[i].checked ) {
	        msg = msg + document.ASSISTANT.elements[i].name + ": " + document.ASSISTANT.elements[i].value + "\n";
	    }
        } else if ( document.ASSISTANT.elements[i].type == 'select-multiple' ) {
	    var optLen = document.ASSISTANT.elements[i].length;
	    var val = null;
   	    for ( j = 0; j < optLen; j++ ) {

		if( document.ASSISTANT.elements[i].options[j].selected ) {

		    var value = document.ASSISTANT.elements[i].options[j].value;

		    if( val != null && value != '' ) {
		    	val = val+", "+value;
		    } else if ( value != '' ) {
		    	val = value;
		    }
		} 

	    }
	    
	    if( val != null && val != '' ) {
	    	msg = msg + document.ASSISTANT.elements[i].name + ": " + val + "\n";
	    }
	    
        } else if ( document.ASSISTANT.elements[i].value != null ) {
	    var value = document.ASSISTANT.elements[i].value;
	    if( value != '' ) {
	        msg = msg + document.ASSISTANT.elements[i].name + ": " + value + "\n";
	    }
	}
    }
    parent.opener.document.forms[0].description.value = msg;
    parent.opener.simpleTextCounter(parent.opener.document.getElementById('description'),parent.opener.document.getElementById('charLimit'),3700);

    window.close();
}

/** 
 * Used by the Project Description Assistant 
 * script by http://www.hypergurl.com 
 **/

	
	function addToFavorites(urlAddress,pageName) { 
			if (window.external) { 
				window.external.AddFavorite(urlAddress,pageName);
			} 
			else { 
				alert("Press 'Ctrl+D'to bookmark this page or 'Apple+D' for Mac users")
			}
	}


// useCSI flag tells login link to use new SignIn Code [with YUI dialogs]
function getLoginLink(logindiv, useCSI) {
  var username = getCookie("uname");
  var sessionKey = getCookie("session_key");
  if((sessionKey != null) && (sessionKey != "void") && (username != null)) {
    logindiv.innerHTML = "Welcome,&nbsp;" + username + "!&nbsp;&nbsp;<span id='chatStat'></span>" +
                         "<a href=\"/c/home/main/logout.pl\">Sign out</a>";
    updateChatStatus(username);
  }
  else {
    var html = "<a href=\"";

    if( useCSI == 2 ) {
       // For search version, set action = refresh search results
       html += "javascript:checkSignedIn(30, 'projSearchJs.doProjSearch(true)');";
    } else if( useCSI ) {
      // normal PHP signin
      html += "javascript:checkSignedIn(30, '');";
    } else {
      // Old signin
      html += "/myelance";
    }

    html += "\">Sign in</a>";
    logindiv.innerHTML = html;
  }
}


function updateChatStatus(username){
    var d = new Date();
    YAHOO.util.Connect.asyncRequest('get', 
'/php/myelance/main/chat.php?ctx=profile&mode=check&format=mini&view_person='+username+"&t="+d.getTime(),
{success: updChatStat});
}
function updChatStat(tspt){
    document.getElementById('chatStat').innerHTML = tspt.responseText;
}

// Returns username if we have one from the cookie.
function getReturningUsername() {
  var username = getCookie("uname");
  if ( username != null ) {
    return username;
  } else {
    return '';
  }
}


function OnSubmitForm(formName) {
    var port   = location.port;
    var sport  = 0;
    var host   = location.hostname;
    var shost  = host.substring( 0, host.indexOf('.elance.com')).toLowerCase();
    var action = "";
    if ( port.length > 0 ) {
        sport = parseInt(port);
        if( location.protocol == 'http:' ) {
          sport++;
        }
        if ( shost == 'agency' || shost == 'corporate' ||
             shost == 'enterprise' ) {
             host = 'secure.elance.com';
        }
        action = "https://" + host + ":" + sport + "/c/rfp/main/buy.pl";
    } else {
        action = "https://secure.elance.com/c/rfp/main/buy.pl";

    }
    document.forms[formName].action = action;
    document.forms[formName].submit();
    return true;
}
