// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

//Inbox Related Functions
function show_action_button_error(message){
  $('mailalert_message').innerHTML = message;
  $('mailalert').style.display = 'block';
}

function hide_action_button_error(){
  $('mailalert').style.display = 'none';
}

function toggleAllCheckBoxes(value){
  allRows = document.inbox_message_form.message_row;
  if(allRows){
    if(allRows.length == null){
      allRows.checked = value;
    }else{
      for(i=0; i< allRows.length; i++){
        allRows[i].checked = value;
      }
    }
  }
  return true;
}

function resetSelectMessagesCheckBox(){
  if(document.inbox_message_form.selectAllRows){
   document.inbox_message_form.selectAllRows.checked = 0;
   toggleAllCheckBoxes(0);
  }
}

function is_any_inbox_message_selected(){
  allRows = document.inbox_message_form.message_row;
  selected = false;
  if(allRows.length == null){
   return (allRows.checked == 1)
  }else{
    for(i=0; i< allRows.length; i++){
      if(allRows[i].checked == 1){
        selected = true;
        return true;
      }
    }
  }
  return selected;
}

function prepare_selected_messages(){
  allRows = document.inbox_message_form.message_row;
  selected_messages_ids = "";
  if(allRows.length == null){
    if(allRows.checked == 1){
      selected_messages_ids = allRows.value;
      return selected_messages_ids;
    }
  }else{
    first_value = true;
    for(i=0; i< allRows.length; i++){
      if(allRows[i].checked == 1){
        if(first_value){
          selected_messages_ids = allRows[i].value;
          first_value = false;
        }else{
          old_values = selected_messages_ids ;
          selected_messages_ids = old_values + "," + allRows[i].value;
        }
      }
    }
  }

  return selected_messages_ids;
}

function archive_messages(){
  return execute_selected_messages_action(archive_action_url);
  /*
  if(is_any_inbox_message_selected() == false){
    show_action_button_error("No messages selected.");
    return false;
  }
  hide_action_button_error();
  if(archive_action_url){
    selected_ids = prepare_selected_messages();
    if(selected_ids != ""){
      archive_action_url = archive_action_url + "&selected_messages=" + selected_ids ;
    }
    document.inbox_message_form.action = archive_action_url;
    document.inbox_message_form.submit();
  }
  return true;
  */
}

function delete_messages(){
  return execute_selected_messages_action(delete_action_url);
}

function execute_selected_messages_action(action_url){
  if(is_any_inbox_message_selected() == false){
    show_action_button_error("No messages selected.");
    return false;
  }
  hide_action_button_error();
  if(action_url){
    selected_ids = prepare_selected_messages();
    if(selected_ids != ""){
      action_url = action_url + "&selected_messages=" + selected_ids ;
    }
    document.inbox_message_form.action = action_url;
    document.inbox_message_form.submit();
  }
  return true;
}

function fetch_sorted_message(sort_on, is_descending){
  document.inbox_message_form.sort_on_column.value = sort_on ;
  document.inbox_message_form.descending.value = is_descending ;
  document.inbox_message_form.action = sort_action_url;
  document.inbox_message_form.submit();
}


function hide_all_QnA_Head(){
  temp_head1 = document.getElementById('ask_head');
  if (temp_head1 != null) {
    temp_head1.style.display = 'none';
  }
  temp_head2 = document.getElementById('answer_head');
  if (temp_head2 != null) {
    temp_head2.style.display = 'none';
  }
  temp_head3 = document.getElementById('vote_head');
  if (temp_head3 != null) {
    temp_head3.style.display = 'none';
  }
  temp_head4 = document.getElementById('reward_head');
  if (temp_head4 != null) {
    temp_head4.style.display = 'none';
  }
}

function display_QnA_Head(tab_head) {
 tabHead = document.getElementById(tab_head);
 if(tabHead != null) {
   hide_all_QnA_Head();
   tabHead.style.display = "block";
 }
}

function qa_activate_tab(tab){
	var hide_element=document.getElementById('RecentContent');
	if (hide_element) {
		hide_element.style.display = 'none';
        var recent = document.getElementById('Recent')
        if(recent != null){
        	recent.className = '';
        }
        
        var more_link = document.getElementById('more_open_question_link')
        if(more_link != null){
        	more_link.style.display = 'none';
        }
    }
	
	hide_element=document.getElementById('PopularContent');
	if (hide_element) {
		hide_element.style.display='none';
        popular = document.getElementById('Popular')
        if(popular){
        	popular.className='';
        }
	}
	
	hide_element=document.getElementById('RecentBestAnswer');
	if (hide_element) {
		hide_element.style.display='none';
        var answer = document.getElementById('Answer')
        if(answer){
        	answer.className='';
        }
	}
	
	if (tab == "Recent") {
		display_content = "RecentContent";
        var more_link = document.getElementById('more_open_question_link')
        if(more_link != null){
        	more_link.style.display = '';
        }
	}else if (tab == "Popular") {
		display_content = "PopularContent";
	}else if (tab == "Answer"){
		display_content = "RecentBestAnswer";
	}
	display_element=document.getElementById(display_content); 
	display_element.style.display='';
	document.getElementById(tab).className='selected';
		
}

//Function to limit the number of characters in text area
//All you need to do now is add the following line of code within the TextArea Tag;
//onKeyPress="limitText(this,254);"
function limitText(textArea, length) {
    if (textArea.value.length > length) {
        textArea.value = textArea.value.substr(0,length);
    }
}

function passwordStrength(password, password_length)
{
  var score = 0;
	if (password.length < password_length) {
  	if (password.length != 0) {
  		document.getElementById("password_strength_meter").innerHTML = "";
			document.getElementById("password_strength_meter").style.color = "";
			document.getElementById("password_strength_title").innerHTML = "";
  		return false;
  	}
		else {
			document.getElementById("password_strength_meter").innerHTML = "";
			document.getElementById("password_strength_title").innerHTML = "";
  		return false;			
		}
  }
  if (password.length >= password_length)
		score++;
  if ((password.match(/[a-z]/)) && (password.match(/[A-Z]/)))
		score++;
  if (password.match(/\d+/))
		score++;
  if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/))
		score++;
  if (password.length > 12)
		score++;
	if (score == 1) {
  	document.getElementById("password_strength_meter").innerHTML = "Weak&nbsp;";
		document.getElementById("password_strength_meter").style.color = "#FF6600";
		document.getElementById("password_strength_title").innerHTML = "Strength:";
  }
  else if (score > 1 && score <= 3) {
 		document.getElementById("password_strength_meter").innerHTML = "Medium&nbsp;";
		document.getElementById("password_strength_meter").style.color = "#3399FF";
		document.getElementById("password_strength_title").innerHTML = "Strength:";
  }
  else if (score > 3){
  	document.getElementById("password_strength_meter").innerHTML = "Strong&nbsp;";
		document.getElementById("password_strength_meter").style.color = "green";
		document.getElementById("password_strength_title").innerHTML = "Strength:";
  }
}


function moveDivtoBody(div_id){
 s = document.getElementById(div_id);
 if(s.parentNode.id!='floatingCalendar')
 document.getElementById('floatingCalendar').appendChild(s);
}


function ValidateElement(element, onblur, formid){
    if (!onblur)
        onblur = false;
    var elName=element.name;
    if ((!elName)||(elName.length == 0))
        return true;
    var validationType = element.getAttribute("validate");
    if ((!validationType)||(validationType.length == 0))
        return true;
    var strMessages=element.getAttribute("msg");
    if (!strMessages)
        strMessages = '';
    var arrMessages = strMessages.split("|");
    var arrValidationTypes = validationType.split("|");
    var blnValid=true;
    for (var j=0; j<arrValidationTypes.length; j++) {
        var curValidationType = arrValidationTypes[j];
        switch (curValidationType) {
            case "not_empty":
            if (onblur == false)
                blnValid = ValidateNotEmpty(element);
            break;
            case "integer":
            blnValid = ValidateInteger(element);
            break;
            case "number":
            blnValid = ValidateNumber(element);
            break;
            case "decimal":
            blnValid = ValidateDecimaluptoTwoPlaces(element);
            break;
            case "min_number":
            blnValid = ValidateMinNumber(element);
            break;
            case "max_number":
            blnValid = ValidateMaxNumber(element);
            break;
            case "min_length":
            blnValid = ValidateMinLength(element);
            break;
            case "max_length":
            blnValid = ValidateMaxLength(element);
            break;
            case "email":
            blnValid = ValidateEmail(element);
            break;
            case "phone":
            blnValid = ValidatePhone(element);
            break;
            case "phone_or_blank":
            blnValid = ValidatePhoneOrBlank(element);
            break;
            case "length":
            blnValid = ValidateLength(element);
            break;
            case "start_with_letter":
            blnValid = ValidateStartWithLetter(element);
            break;
            case "alpha_numeric":
            blnValid = ValidateAlphanumeric(element);
            break;
            case "alpha_numeric_with_whitespace":
            blnValid = ValidateAlphanumericWithWhiteSpace(element);
            break;
            case "url":
            blnValid = ValidateURL(element); //Not Working Correctly. Dont use.
            break;
            case "date":
            blnValid = ValidateDate(element);
            break;
            case "confirm":
            blnValid = ValidateConfirmation(element);
            break;
            case "not_special_chars_not_digits_between_spaces":
            blnValid = ValidateNotSpecialCharsNotDigitsBetweenSpaces(element);
            break;
            case "time":
            blnValid = ValidateTime(element);
            break;
            default:
            try {
                blnValid = eval(curValidationType+"(element)");
            }
            catch (ex) {
                blnValid = true;
            }
        }
        if (blnValid == false) {
            var message="invalid value for "+element.name;
            if ((j < arrMessages.length)&&(arrMessages[j].length > 0))
                message = arrMessages[j];
            InsertError(formid, element, message);
            //			if ((typeof element.focus == "function")||(element.focus)) {
            //			element.focus();
            //			}
            break;
        }
        else
            ClearError(element);
    }
    return blnValid;
}

function Validate(objForm, parentID) {
	var returnValue = true;
	var arrValidated=new Array();
  clearDefaultValues(objForm);
	for (var i=0; i<objForm.elements.length; i++) {
		var element=objForm.elements[i];
		if (arrValidated[element.name])
			continue;
		arrValidated[element.name] = true;
    returnValue = ValidateElement(element, null, (parentID == undefined ? objForm.getAttribute('id') : parentID)) && returnValue
	}
        return returnValue;
}

function clearDefaultValues(objForm){
	for (var i=0; i<objForm.elements.length; i++) {
		var element=objForm.elements[i];
    if((element.getAttribute("default_value")) != null && (GetElementValue(element) == element.getAttribute("default_value"))){
      element.value = "";
    }
  }
}

//Empty Validation
function ValidateNotEmpty(objElement) {
 	var strValue = GetElementValue(objElement);
	var blnResult = true;
	if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
 	if(strValue == "") //check for nothing
	{
 		blnResult = false;
	}
	if (objElement.getAttribute("prompt") != null)
	{
		var dummy_value = objElement.getAttribute("prompt");
		if (dummy_value ==  strValue) {
			blnResult = false;
		}
	}
	return blnResult;
}

//URL validation

function ValidateURL(objElement)
{
	var strString = GetElementValue(objElement);
	//Not working correctly. Please do not use.
  var regexp = /[ftp:\/\/|http:\/\/|https:\/\/]*(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(strString);
}

//Date Validation
function ValidateDate(objElement){
    strDate = GetElementValue(objElement);
    regex = /^\d\d\d\d-\d\d-\d\d$/
    if(!strDate.match(regex)){
        return false;
    }
    arr = strDate.split('-');
    year = parseInt(arr[0]);
    month = parseInt(arr[1]);
    day = parseInt(arr[2]);
    
    
    if(year<0 || month < 0 || month > 12 || day < 0 || day > 31)
        return false;
    if([4,6,9,11].include(month) && day > 30) //include requires prototype.js
        return false;
    if(month == 2){
        if(day > 29)
            return false;
        
        is_leap = false;
        if(year % 4 == 0 && ((year % 100 != 0) || (year % 400 == 0)))
            is_leap = true;
        
        if(!is_leap && day > 28)
            return false;
    }
    current_date = objElement.getAttribute("current_date");
	  if(current_date != null){
      curr_arr = current_date.split('-');
      curr_year = parseInt(curr_arr[0]);
      curr_month = parseInt(curr_arr[1]);
      curr_day = parseInt(curr_arr[2]);
      if(curr_year > year || (curr_year == year && curr_month > month) || (curr_year == year && curr_month == month && curr_day > day))
        return false;
    }
    return true;
}

//Password confirmation Validation
function ValidateConfirmation(objElement){
    parentElementId = objElement.getAttribute("confirm_with");
    if(parentElementId == null)
        return false;
    objValue = GetElementValue(objElement);
    parentValue = GetElementValue($(parentElementId));
    if(objValue==parentValue)
        return true;
    return false;
}

//Integer Validation
function ValidateInteger(objElement)
// check for valid numeric strings
{
	if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
 	integer_regex = /^[0-9]+$/;
	var strString = GetElementValue(objElement);
        if (strString == "")
		return true;
	if (strString.match(integer_regex))
		return true;
	else
		return false;
}

//Number Validation
function ValidateNumber(objElement)
// check for valid numeric strings
{
	if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
        var strString = GetElementValue(objElement);
	var strValidChars = ".0123456789"; //decimal ok
	var strChar;
	var blnResult = true;
        var decimal_count=0;
	// test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{	
		strChar = strString.charAt(i);
                if(strChar == '.' )decimal_count++;
		if (strValidChars.indexOf(strChar) == -1 || decimal_count>1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}
function ValidateDecimaluptoTwoPlaces(objElement)
{
	if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
        var strString = GetElementValue(objElement);
	var strValidChars = ".0123456789"; //decimal ok
	var strChar;
	var blnResult = true;
        var decimal_count=0;
        var places_count=0;
	// test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{	
		strChar = strString.charAt(i);
                if(decimal_count == 1)
                  places_count++;
                if(strChar == '.' )decimal_count++;
		if (strValidChars.indexOf(strChar) == -1 || decimal_count>1 || places_count > 2)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

function ValidateAlphanumeric(objElement)
{
	var strString = GetElementValue(objElement);
	var regex_alphanumeric = /^\w+$/i;
	if (strString.match(regex_alphanumeric))
		return true;
	else
		return false;
}

function ValidateAlphanumericWithWhiteSpace(objElement)
{
	var strString = GetElementValue(objElement);
	var regex_alphanumeric = /^[a-z0-9\s]+$/i;
	if (strString.match(regex_alphanumeric))
		return true;
	else
		return false;
}

function ValidateStartWithLetter(objElement)
{
	var regex = /^([a-z]|[A-Z])/;
	var strString = GetElementValue(objElement);
	if (strString.match(regex))
		return true;
	else
		return false;	
}

//Email Validation

function ValidateEmail(objElement) {
  var strValue = GetElementValue(objElement);
  if (objElement.getAttribute("blank_allowed") == 'true' && strValue == "" ){
    return true
  }

  email_regex = /^[^\.]([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;

  if (strValue.match(email_regex))
    return true;
  else
    return false;
}

function ValidateLength(objElement) {
	var minLength, maxLength;
	if (objElement.getAttribute("min_length"))
		minLength = objElement.getAttribute("min_length");
	else
		minLength = 1;
	if (objElement.getAttribute("max_length"))
		maxLength = objElement.getAttribute("max_length");
	else
		maxLength = 500;
	var currLength = GetElementValue(objElement).length;
	if (currLength >= minLength && currLength <= maxLength)
		return true;
	else
		return false;
}

function ValidateMinLength(objElement) {
  if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
	var currLength = GetElementValue(objElement).length;
	var limit = objElement.getAttribute("min_length");
	if (currLength >= limit)
		return true;
	return false;
}

function ValidateMinNumber(objElement) {
    if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
  if(GetElementValue(objElement) == ''){return true;}
	var currNumber = parseFloat(GetElementValue(objElement));
	var limit = parseFloat(objElement.getAttribute("min_number"));
	if (currNumber >= limit)
		return true;
	return false;
}

function ValidateMaxNumber(objElement) {
    if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
  if(GetElementValue(objElement) == ''){return true;}
	var currNumber = parseFloat(GetElementValue(objElement));
	var limit = parseFloat(objElement.getAttribute("max_number"));
  if (currNumber <= limit)
		return true;
	return false;
}

function ValidateMaxLength(objElement) {
  if ((objElement.getAttribute("constraint") != null) && (objElement.getAttribute("const_value") != null))
	{
		var res = GetElementValue(document.getElementsByName(objElement.getAttribute("constraint"))[0]);
    if(objElement.getAttribute("const_check_type") == null){
      if (res == objElement.getAttribute("const_value"))
        return true;
    }
    else{
      if (res != objElement.getAttribute("const_value"))
        return true;
    }
	}
	var currLength = GetElementValue(objElement).length;
	var limit = objElement.getAttribute("max_length");
	if (currLength <= limit)
		return true;
	return false;
}
 //Valid PhoneNumber

function ValidatePhone(objElement){

 	// non-digit characters which are allowed in phone numbers
 	var phoneNumberDelimiters = "()- ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
 	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	var minDigitsInIPhoneNumber = 10;
	var strValue = GetElementValue(objElement);
 	s=stripCharsInBag(strValue,validWorldPhoneChars);
        integer_regex = /^[0-9]+$/;
	
	if(s.length == 0){
            return false;
        }
        if (s.match(integer_regex)){
		return true;
	}else{
		return false;
       }
}

//Valid PhoneNumber or blank

function ValidatePhoneOrBlank(objElement){

 	// non-digit characters which are allowed in phone numbers
 	var phoneNumberDelimiters = "()- ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
 	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	var minDigitsInIPhoneNumber = 10;
	var strValue = GetElementValue(objElement);
 	s=stripCharsInBag(strValue,validWorldPhoneChars);
        integer_regex = /^[0-9]+$/;
	
	if(s.length == 0){
            return true;
        }
        if (s.match(integer_regex)){
		return true;
	}else{
		return false;
       }
}

// Valid: "  abc 45abc abc45 "
// Invalid: "#", " abc 45", "4", "adc#4", " 4 "
function ValidateNotSpecialCharsNotDigitsBetweenSpaces(objElement){
  obj_value = GetElementValue(objElement);
  if(obj_value.strip() == ""){
    return true;
  }
  if(ValidateAlphanumericWithWhiteSpace(objElement)){
    valid = true;    
    words = obj_value.match(/\w+/g);
    if(words){
      var i = 0;
      while(i < words.length && valid ){
        if(words[i].match(/^\d+$/)){
          valid = false;
        }
        i++;
      }  
    }
    return valid;
  }else{
    return false;
  }
  return true;
}

function ValidateTime(objElement) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.
obj_value = GetElementValue(objElement);
var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = obj_value.match(timePat);
if (matchArray == null) {
//alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
//alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}

if  (hour > 12 && ampm != null) {
//alert("You can't specify AM or PM for military time.");
return false;
}
if (minute<0 || minute > 59) {
//alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
//alert ("Second must be between 0 and 59.");
return false;
}
return true;
}

function GetElementValuebyName(objForm, name) {
	for (var i=0; i<objForm.elements.length; i++) {
		var element=objForm.elements[i];
		var val = element.value;
		if (element.type == "radio")
		{
			val = GetRadioElementValue(element);
		}
		if (element.name == name) {
			return val;
		}
	}	
	return "";
}

function GetRadioElementValue(element) {
	var radioLength = element.length;
	if(radioLength == undefined)
	{
		if(element.checked)
			return element.value;
		else
			return "";
	}
	for(var i = 0; i < radioLength; i++) {
		if(element[i].checked) {
			return element[i].value;
		}
	}
	return "";
	
}

function GetElementValue(objElement) {
 	var result="";
	switch (objElement.type) {
		case "text":
		case "hidden":
		case "textarea":
		case "password":
			result = allTrim(objElement.value);
		break;
		
		case "select-one":
		case "select":
			if (objElement.selectedIndex >= 0)
				result = objElement.options[objElement.selectedIndex].value;
		break;
		
		case "select-multiple":
			if (objElement.selectedIndex >= 0)
				result = objElement.options[objElement.selectedIndex].value;
		break;
		case "file":
			result = allTrim(objElement.value);
		break;
		case "radio":
		case "checkbox":
			for (var i=0; i<objElement.form.elements.length; i++) {
				if (objElement.form.elements[i].name == objElement.name) {
					if (objElement.form.elements[i].checked)
						result += objElement.form.elements[i].value+",";
				}
			}
			result = result.substr(0,result.length-1);
		break;
	}
	return result;
}

var br_before_error = true;

function InsertError(formid, element, strMessage) {
	if ((element.form != null) && (element.form.getAttribute("show_alert")) && (element.form.getAttribute("show_alert") != "0")) {
		alert(strMessage);
		return;
	}
	if (element.getAttribute("span_id"))
		var strSpanID = element.getAttribute("span_id");
	else
		var strSpanID = element.name+"_val_error";
 	  var objSpan = $$("#"+formid+" #"+strSpanID)[0];
    if (objSpan == undefined || objSpan==null){objSpan = $(strSpanID);}
         if(br_before_error){
            objSpan.innerHTML = "<br/>" + strMessage;
         }
         else{
            objSpan.innerHTML = "" + strMessage;
         }
         //Step: Change the color of the text field
         var strTextfieldID = element.name.replace('[','_');
         strTextfieldID = strTextfieldID.replace(']','');
         var objTextfield = $$("#" + formid + " " + element.tagName + "[name='" +strTextfieldID + "']")[0];
         if (objTextfield == null || objTextfield == undefined) {objTextfield = document.getElementById(strTextfieldID);}
         if (objTextfield != null && (objTextfield.type == 'textarea' || objTextfield.type == 'text' || objTextfield.type == 'password' || objTextfield.id == 'newuser_category[]' || objTextfield.type == 'select-one'))
            {
                //objTextfield.className = 'inptBoxError';
                objTextfield.removeClassName('inptBoxCorrect');
                objTextfield.addClassName('inptBoxError');
            }
         else{
           if((element.type == 'textarea' || element.type == 'text' || element.type == 'password')){
            element.className = 'inptBoxError';
           }
         }
}

function ClearError(element) {
	if (element.getAttribute("span_id"))
		var strSpanID = element.getAttribute("span_id");
	else
		var strSpanID = element.name+"_val_error";
	var objSpan = document.getElementById(strSpanID);
	if (objSpan) {
		objSpan.innerHTML = "";
	}
         //Step: Change the color of the text field
         var strTextfieldID = element.name.replace('[','_');
         strTextfieldID = strTextfieldID.replace(']','');
         var objTextfield = document.getElementById(strTextfieldID);
         if (objTextfield != null && (objTextfield.type == 'text' || objTextfield.type == 'password' || objTextfield.id == 'newuser_category[]'))
            {
                //objTextfield.className = 'inptBoxF1';
try{
objTextfield.removeClassName('inptBoxError');
objTextfield.addClassName('inptBoxF1');
} catch(e){}
            }
         
}

function allTrim(cValue){
	return cValue.strip();
}

 

function stripCharsInBag(s, bag) { 
	var i;
	var returnString = "";
	// Search through string’s characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++) {
		// Check that current character isn’t whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1)
			returnString += c;
	}
	return returnString;
}

function populate_time(time_message_id){
	var element = document.getElementById(time_message_id);
	var mytime = "";
	
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var ampm = "AM";
	if (hours > 11){
		ampm = "PM";
	}
	if (hours==0){
		hours = 12;
	}
	if (hours > 12){
		hours = hours - 12;
	}

	var minutes = currentTime.getMinutes();
	if (minutes < 10){
		minutes = "0" + minutes;
	}
	mytime = hours + ":" + minutes + " " + ampm;
	element.innerHTML = mytime;
}

function chat_class(public_message_id){
	var other_name_element = document.getElementById('other_user_name_id');
	var chat_message_row_element = document.getElementById(public_message_id);
	var other_name = "";
	var chat_sender_name = "";
	var pos = -1;
	if (other_name_element){
		other_name = other_name_element.innerHTML;
	}
	if (chat_message_row_element){
		chat_sender_name = chat_message_row_element.innerHTML;
	}
	pos=chat_sender_name.indexOf(other_name);
	if (pos>=0){
		chat_message_row_element.className = 'chatOtherMsg';
	}
	else{
		chat_message_row_element.className = 'chatSelfMsg';
	}
}

function scroll_bottom(id){
  var objDiv = document.getElementById(id);
  if (objDiv){
        objDiv.scrollTop = objDiv.scrollHeight;
  }
}


removeDivsAllowed = true;

var timer = 0;
agent = navigator.userAgent.toLowerCase();
var isIE = agent.indexOf("msie")>0;
var isIE7 = isIE && agent.indexOf("msie 7")>0;
var X = 0;
var Y = 0;
document.onmousemove = getMouseXY;

/* connection use ids*/
var conn_user_ids = new Array();

function getMouseXY(e){
	if(!e) e = window.event;
        
	X = (isIE ? (e.clientX + document.body.scrollLeft) : e.pageX);
	Y = isIE7 ? (e.clientY + document.documentElement.scrollTop) : (isIE ? (e.clientY + document.body.scrollTop) : e.pageY);
  Y1 = isIE ? (e.clientY + document.body.scrollTop) : e.pageY; //Fix for non-xhtml pages on IE7
}

function showPremiumDef(){
	clearTimeout(timer);

	$('popUpBox').style.left = X - 6;
	$('popUpBox').style.top = Y - 12;// + document.body.scrollTop;
	$('popUpBox').style.display="";

	timer = window.setTimeout("$('popUpBox').style.display='none'",3000);
}

function showProjectListing(){
	
	$('projectList').style.left = X - 250;
	$('projectList').style.top = Y + 5;// + document.body.scrollTop;
	$('projectList').style.display="";

}

function showConnActionMenu(conn_id){
  hideAllConnActionMenu();
  menu_div_id = "conn_action_menu_" + conn_id;
  if($(menu_div_id)){
    $(menu_div_id).style.display = "";
  }
  return true;
}
  
function hideConnActionMenu(conn_id){
    menu_div_id = "conn_action_menu_" + conn_id;
    if($(menu_div_id)){
      $(menu_div_id).style.display = "none";
    }
    return true;
  }

function hideAllConnActionMenu(){
  for(i=0; i<conn_user_ids.length; i++){
    hideConnActionMenu(conn_user_ids[i]);
  }
}

function toggleConnActionMenu(conn_id){
  menu_div_id = "conn_action_menu_" + conn_id;
  menu_obj = $(menu_div_id);
  if(menu_obj){
    if(menu_obj.style.display == "none"){
      showConnActionMenu(conn_id);
    }else{
      hideConnActionMenu(conn_id);
    }
  }
}

function showContactFlyOut(contact_id, is_known, is_added_contact, is_pure_buyer){
	
	$('conViewProfile').href 		   = "/search/provider/" + contact_id;
	//$('conSendMessage').href 		   = "/public_messages/compose/" + contact_id;
	
        if(is_pure_buyer == true){
            $('conInviteBid').parentNode.style.display = 'none';
        }
        else{
            $('conInviteBid').href  		   = "/bid_invitations/compose/" + contact_id;
            $('conInviteBid').parentNode.style.display = '';
        }
            
	$('conRequestRecommendation').href = "/recommendations/compose_recommendation_request/" + contact_id;
	
        if($('conRemove')){
            if(is_added_contact){
                $('conRemove').href 	   = "/network/remove_friend/" + contact_id;
                $('conRemove').parentNode.style.display = '';
            }
            else{
                $('conRemove').parentNode.style.display = 'none';
            }
	}
	if($('conSendFriendRequest')){
            if(is_known){
                $('conSendFriendRequest').parentNode.style.display = 'none';
            }
            else{
                $('conSendFriendRequest').href = "/connection_messages/compose/" + contact_id;
                $('conSendFriendRequest').parentNode.style.display = '';
            }
	}
  /**
   * Browser specific code. It can be improved by putting the action menu inline and playing only with show/hide.
   */
  if(navigator.appName == "Microsoft Internet Explorer"){
    //$('conFlyOutContainer').style.left = (X - 170) + "px";
    $('conFlyOutContainer').style.top = (Y - 98) + "px";
  }
  else{
    if(navigator.appName == "Netscape"){
      if(agent.indexOf("firefox") > 0){
        //$('conFlyOutContainer').style.left = (X - 380) + "px";
        $('conFlyOutContainer').style.top = (Y - 621) + "px";
      }else if(agent.indexOf("chrome") > 0){
        //$('conFlyOutContainer').style.left = (X - 170) + "px";
        $('conFlyOutContainer').style.top = (Y - 585) + "px";
      }else if(agent.indexOf("safari") > 0){
        //$('conFlyOutContainer').style.left = (X - 170) + "px";
        $('conFlyOutContainer').style.top = (Y - 700) + "px";
      }
    }
    else{
     // $('conFlyOutContainer').style.left = (X - 380) + "px";
      $('conFlyOutContainer').style.top = (Y - 625) + "px";
    }
  }
	$('conFlyOutContainer').style.display="";
	
}

function allowRemoveDivs(){
	removeDivsAllowed = true;
}

function disallowRemoveDivs(){
	removeDivsAllowed = false;
}

document.onmousedown = removeDivs;
function removeDivs(){
	if(removeDivsAllowed){
		divArray = new Array('popupBox', 'projectList', 'conFlyOutContainer');
		for(i=0; i<divArray.length; i++){
			div_id = divArray[i];
			div = document.getElementById(div_id);
			if(div){
				div.style.display = 'none';
			}
		}	
	}
}


function advSearch(obj){
	//document.getElementById(obj + 'Radio').checked = true;

	var advProject = document.getElementById('advProject');
	var advProvider = document.getElementById('advProvider');
	var advQa = document.getElementById('advQa');
        //var advCs  = document.getElementById('advCs');

	var linksProjects = document.getElementById('linksProjects');
	var linksProviders = document.getElementById('linksProviders');
	var linksQa = document.getElementById('linksQa');
        //var linksCs = document.getElementById('linksCs');
	
	if(obj == 'project')
	{	
		advProject.style.display='';
		advProvider.style.display='none';
		advQa.style.display='none';
          //      advCs.style.display='none';
                if(linksProjects){
                    linksProjects.style.display='';
                }
		if(linksProviders){
                    linksProviders.style.display='none';
                }
		if(linksQa){
                    linksQa.style.display='none';
                }
            /*    if(linksCs){
                    linksCs.style.display='none';
                }
                */

	}

	if(obj == 'provider')
	{
		advProject.style.display='none';
		advProvider.style.display='';
		advQa.style.display='none';
                //advCs.style.display='none';

                if(linksProjects){
                    linksProjects.style.display='none';
                }
		if(linksProviders){
                    linksProviders.style.display='';
                }
                if(linksQa){
                    linksQa.style.display='none';
                }
                 /*if(linksCs){
                    linksCs.style.display='none';
                }*/

	}

	if(obj == 'qa')
	{
		advProject.style.display='none';
		advProvider.style.display='none';
		advQa.style.display='';
                //advCs.style.display='none';

                if(linksProjects){
                    linksProjects.style.display='none';
                }
		if(linksProviders){
                    linksProviders.style.display='none';
                }
		if(linksQa){
                    linksQa.style.display='';
                }/*
                if(linksCs){
                    linksCs.style.display='none';
                }*/

	}/*
         if(obj == 'cs')
             {
                 advProject.style.display='none';
                 advProvider.style.display='none';
                 advQa.style.display='none';
                 advCs.style.display='';
                 
                 if(linksProjects){
                     linksProjects.style.display='none';
                 }
                 if(linksProviders){
                     linksProviders.style.display='none';
                 }
                 if(linksQa){
                     linksQa.style.display='none';
                 }
                 if(linksCs){
                     linksCs.style.display='';
                 }
                 
             }*/

}

function toggleClass(obj, class1, class2){
	tr = obj.parentNode.parentNode;
	original_class_name = tr.className;
	if(original_class_name == class1){
		tr.className = class2;
	}
	else{
		tr.className = class1;		
                if(document.getElementById('select_all_checkbox')){
		  selectAllCheckBox = document.getElementById('select_all_checkbox');
		  selectAllCheckBox.checked = false;
               }
	}
}

//Method to toggle the class name of an object
function toggleClass2(obj, class1, class2){
	tr = obj.parentNode.parentNode
	original_class_name = tr.className;
	if(original_class_name == class1){
		tr.className = class2;
	}
	else{
		tr.className = class1;				
	}
}

function checkAllBidProjects(){
	var allCheckBox = document.getElementsByName('project_ids[]')
	for(var i=0; i < allCheckBox.length;i++){
		allCheckBox[i].checked = true
	}
}

//Method to check the contacts of a particular type (all contacts, favorites, connections)
function checkAllContacts(contactType){
	var allCheckBox = document.getElementsByName('selected_'+contactType+'[]')
	var selectedContacts = document.getElementById('selectedContacts');
	for(var i=0; i < allCheckBox.length;i++){
		if(allCheckBox[i].checked == false){
			allCheckBox[i].checked = true
			var contactName = allCheckBox[i].parentNode.childNodes[2].innerHTML;
			toggleClassShow(allCheckBox[i],'','messageSelected',contactName,allCheckBox[i].id.split(contactType)[1]);
		}	
	}
}
//Method to un-check the contacts of a particular type (all contacts, favorites, connections)
function uncheckAllContacts(contactType){
	var allCheckBox = document.getElementsByName('selected_'+contactType+'[]')
	var selectedContacts = document.getElementById('selectedContacts');
	for(var i=0; i < allCheckBox.length;i++){
		allCheckBox[i].checked = false;
		contactName = allCheckBox[i].parentNode.childNodes[2].innerHTML;
		toggleClassShow(allCheckBox[i],'','messageSelected',contactName,allCheckBox[i].id.split(contactType)[1]);
		
	}	
}

//Method to show the tab and hide the active tab in the Contacts display
function showTab(showElement,noOfElements){
	
	if(noOfElements == 0){
		return;
	}
	
	var hideElement = $('active_tab').innerHTML;
		
	Element.hide(hideElement);
	Element.show(showElement);
	
	$(hideElement+'_tab').className = '';
	$(showElement+'_tab').className = 'selected';
	
	
	$('active_tab').innerHTML = showElement;	
}

function call_float1(pWidth)
{
	var winL = (screen.width - pWidth) / 2;
	var winH = "100";
	
	
	var floatingDiv = document.getElementById("floatingDiv");
	var floatContainer1 = document.getElementById("floatContainer1");
	var floatContent1 = document.getElementById("floatContent1");
	
	var bidForm1 = document.getElementById("bidForm1");
			
	floatingDiv.style.display="";
	floatingDiv.style.height = document.body.scrollHeight;
	
	floatContainer1.style.display="";
	floatContent1.style.display="";

	divHeight = floatContainer1.clientHeight;

	floatContainer1.style.height =  divHeight;
	floatContainer1.style.width = pWidth;

	floatContainer1.style.left=winL;
	floatContainer1.style.top=winH;

	bidForm1.style.display = ""
	
	troublesomeDivVisibility('hidden', null);
}

function callSendMessage()
{
	var obj = document.getElementById("sendMessage");
	var sendMessageDiv = document.getElementById("sendMessageDiv");
	var curtop = 0;
	
	if(obj.offsetParent)
	{
		while(1)
		{
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	}
	else if(obj.y)
	{
		curtop += obj.y;
	}

	if(sendMessageDiv.style.display == "none"){
		sendMessageDiv.style.display = "";
	}
	else{
		sendMessageDiv.style.display = "none";
	}
	
	sendMessageDiv.style.top = curtop + 40;
	
	
}

function callQuicklinks()
{
	var obj = document.getElementById("quickLink");
	var sendMessageDiv = document.getElementById("quickLinkDiv");
	var curtop = 0;
	
	if(obj.offsetParent)
	{
		while(1)
		{
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	}
	else if(obj.y)
	{
		curtop += obj.y;
	}

	if(sendMessageDiv.style.display == "none"){
		sendMessageDiv.style.display = "";
                  $('quickLink').hide();
                 document.getElementById("quickLinkDown").style.display = '';
	}
	else{
		sendMessageDiv.style.display = "none";
                $('quickLink').show();
                document.getElementById("quickLinkDown").style.display = "none";
	}
	
	sendMessageDiv.style.top = curtop + 40;
  
}


function submit_contact()
{
	var bidForm1 = document.getElementById("bidForm1");
	var floatContainer1 = document.getElementById("floatContainer1");
	var progressBig1 = document.getElementById("progressBig1");
	floatContainer1.style.display ="block";
	bidForm1.style.display="none";
	progressBig1.style.display="";
        troublesomeDivVisibility('visible');
}

function close_contacts()
{
	var floatingDiv = document.getElementById("floatingDiv");
	var floatingDivHead = document.getElementById("floatingDivHead");
	var floatingDivFooter = document.getElementById("floatingDivFooter");
	var floatContainer1 = document.getElementById("floatContainer1");
	var floatContent1 = document.getElementById("floatContent1");
	var progressBig1 = document.getElementById("progressBig1");
	var contactList = document.getElementById("contactList");
        var bidForm1 = document.getElementById("bidForm1");

	floatContainer1.style.display="none";
	floatContent1.style.display="none";
	floatingDiv.style.display="none";
        floatingDivHead.style.display="none";
        floatingDivFooter.style.display="none";
	progressBig1.style.display="none";
	contactList.style.display="";
        bidForm1.style.display="";
	
	troublesomeDivVisibility('visible');

}
function cancel_select_contacts()
{
	var floatingDiv = document.getElementById("floatingDiv");
	var floatContainer1 = document.getElementById("floatContainer1");
	var floatContent1 = document.getElementById("floatContent1");
	var progressBig1 = document.getElementById("progressBig1");

	floatContainer1.style.display="none";
	floatContent1.style.display="none";
	floatingDiv.style.display="none";
	progressBig1.style.display="none";
	
	troublesomeDivVisibility('visible');

}


//Toggle state of the contact object
//This method changes the state of all the rows(all contacts, favorites and connections) of that particular contacts
//Eg: If a user checks a contact in favorites, it is selected in all contacts as well
function toggleClassShow(obj,class1,class2, contactName, contactUserId){
	
	
	var obj_all = $('contacts'+contactUserId);
	var obj_fav = $('favorites'+contactUserId);
	var obj_con = $('connections'+contactUserId);	
	var allObjs = [obj_all,obj_fav,obj_con];
	
	//In case we have to remove a contact from the 'selectedContacts'list by clicking the image 'remove', we don't have the check box object
	if(obj=='remove'){
		obj = obj_all;
		obj.checked = false;
	}
	
	var selectedContacts = document.getElementById('selectedContacts');
	var divIdName = 'contact'+obj.value+'Div';
	var contactDiv = document.getElementById(divIdName);
	
	//Add the contact if it doesn't already exists
	if(obj.checked == true){		
		if(contactDiv==null){
			contactDiv = document.createElement('div');
			contactDiv.setAttribute('id',divIdName);
			var removeRef = '<a href="javascript:toggleClassShow(\'remove\',\'\',\'messageSelected\',\''+contactName+'\' , \''+contactUserId+'\');">&nbsp;<img src="/images/icn_error.gif"></a>';
			contactDiv.innerHTML = contactName+removeRef;
			selectedContacts.appendChild(contactDiv);
		}
	}
	else{		
	//Remove if not already existing
		if(contactDiv != null){
			selectedContacts.removeChild(contactDiv);
		}
	}
		
	//toggle the state only if the corresponding contact exists in the selected contact list
	if(contactDiv != null){
		for (var i=0; i < allObjs.length;i++){
			if(allObjs[i] != null){
				allObjs[i].checked = obj.checked;
				toggleClass2(allObjs[i],class1,class2);
			}
		}
	}
}


var divHeight
function callFloat(pWidth, pHeight, pid, avoid, other_details){
	var winL = (screen.width - pWidth) / 2;
	var winH = "100";
        moveDivtoBody("floatContainer"+pid);
	var floatingDiv = document.getElementById("floatingDiv");
	var floatingDivHead = document.getElementById("floatingDivHead");
	var floatingDivFooter = document.getElementById("floatingDivFooter");
	var floatSearch = document.getElementById("floatSearch");
	var floatContainer = document.getElementById("floatContainer" + pid);
	var floatContent = document.getElementById("floatContent" + pid);
	
	//var bidForm = document.getElementById("bidForm"+pid); // Not Needed
	
	floatingDiv.style.display = "";
	if (floatingDivHead != null) {
		floatingDivHead.style.display = "";
	}
	if (floatingDivFooter != null) {
		floatingDivFooter.style.display = "";
	}
	if (floatSearch != null) {
		floatSearch.style.display = "";
	}
	floatingDiv.style.height = document.body.scrollHeight;
	floatContainer.style.display="";
	floatContainer.style.position="absolute";
	floatContent.style.display="";

	//divHeight = floatContainer.clientHeight;
        //alert(divHeight);
	//floatContainer.style.height = pHeight+"px";
	floatContainer.style.width = pWidth+"px";
        
	floatContainer.style.left="50%";
        floatContainer.style.marginLeft=-pWidth/2+"px";
        floatContainer.style.top = (window.pageYOffset || document.documentElement.scrollTop) +70+ "px";
 //if(st < 70){
  // floatContainer.style.top= 70 + 20+"px";
 // }
//	else{
  //  floatContainer.style.top= st + 20+"px";
  //}

  if(other_details){
      detail_type = other_details[0];
      if(detail_type=="submit_bid"){
        project_id = other_details[1];
        project_title = other_details[2];
        project_budget_range = other_details[3];
				project_proposed_duration = other_details[4];
				buyer_proposed_end_date = other_details[5];
                                project_one099_requested = other_details[6];
        document.getElementById('bid_form').action = "/bids/submit_bid/" + project_id;
        document.getElementById('bid_popup_project_title').innerHTML = project_title;
        document.getElementById('bid_popup_project_amount').innerHTML = project_budget_range;
        if(project_one099_requested=='true')
        {
          document.getElementById('1099').style.display = '';
          document.getElementById('1099_text').style.display = '';
        }else{
          document.getElementById('1099').style.display = 'none';
          document.getElementById('1099_text').style.display = 'none';
        
        }

				if (project_proposed_duration > 365) {
					document.getElementById('bid_days').selectedIndex = 365;	
				}
				else {
					document.getElementById('bid_days').selectedIndex = project_proposed_duration;	
				}
				document.getElementById('bid_popup_buyer_proposed_end_date').innerHTML = buyer_proposed_end_date;
      }
  }
  troublesomeDivVisibility('hidden', avoid);
}


function closeFloat(pid)
{
	var floatingDiv = document.getElementById("floatingDiv");
        var floatingDivHead = document.getElementById("floatingDivHead");
        var floatingDivFooter = document.getElementById("floatingDivFooter");
	var floatContainer = document.getElementById("floatContainer"+pid);
	var floatContent = document.getElementById("floatContent"+pid);
	var floatSearch = document.getElementById("floatSearch");

	floatingDiv.style.display="none";
	if (floatingDivHead != null) {
		floatingDivHead.style.display = "none";
	}
	if (floatingDivFooter != null) {
		floatingDivFooter.style.display = "none";
	}
	if (floatSearch != null) {
		floatSearch.style.display = "none";
	}
	floatContainer.style.display="none";
	floatContent.style.display="none";
        
        troublesomeDivVisibility('visible');
}

function closeFloatFeedBack(pid)
{
	var floatingDiv = document.getElementById("floatingDiv");
	var floatContainer = document.getElementById("floatContainer"+pid);
	var floatContent = document.getElementById("floatContent"+pid);

	floatingDiv.style.display="none";
	floatContainer.style.display="none";
	floatContent.style.display="none";
        
        troublesomeDivVisibility('visible');
        document.getElementById("feedback_form").submit();        
}

function fileUpload(obj)
{
	if(obj == "1")
	{
		document.getElementById("fileUpload").style.display="";
	}
	if(obj == "0")
	{
		document.getElementById("fileUpload").style.display="none";
	}
}

function textbox_enter(id, msg){
	var element = document.getElementById(id);
  var msg = (element.getAttribute("default_value") != null) ? element.getAttribute("default_value") : ((msg == null) ? 'Type your message here...' : msg);
	if (element){
		if (element.value == msg){
			element.value = "";
      element.style.color = "";
		}
	}
}

function textbox_leave(id, msg){
	var element = document.getElementById(id);
  var msg = (element.getAttribute("default_value") != null) ? element.getAttribute("default_value") : ((msg == null) ? 'Type your message here...' : msg);
	if (element){
		if (element.value==""){
      element.style.color = "#acacac";
			element.value = msg;
		}
	}
}

function hide(id){
	var element = document.getElementById(id);
	element.style.display = 'none';
}

function find_time_zone(){
   i = new Date();
   tz = i.getTimezoneOffset();
   b = Math.abs(tz);
   l = Math.floor(b/60);
   m = b - l*60;
   if (m < 15) {m = 0;}
   else if (m >= 15 && m < 45) {m = 30;}
   else {m = 0;l = l + 1;}
   if (l<10) {l = '0'+l;}
   if (m<10) {m = '0'+m;}
   f = ''; 
   if (tz < 0) {f = 'GMT+'+ l +':'+m;}
   if (tz >= 0) {f = 'GMT-'+ l +':'+m;}
   for(i = 0; i< document.registration_form.newuser_time_zone.length -1; i++)
   {
    temp = document.registration_form.newuser_time_zone.options[i].text.substr(1,9);
  
     if (temp == f){
        document.registration_form.newuser_time_zone.selectedIndex = i;
        break;
     }
   }
}

function showAbuseReport(){
 document.getElementById("abuse_report").style.display=""
 document.getElementById("abuse_report_link").style.display="none"
}

function showMessageTextArea(bid_id){
	var message_text_area = document.getElementById('message_text_area'+bid_id)
	message_text_area.style.display=""
}

function hideMessageTextArea(bid_id){
	var message_text_area = document.getElementById('message_text_area'+bid_id);
	message_text_area.style.display="none";
	//return false;
}

/* Profile related functions */
function informationtable_form() {
	info = "<table>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"> <span class=\"textBold\">Name: </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"user_name\" name=\"user[name]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("infoname").innerHTML + "\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"> <span class=\"textBold\">Email: </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"user_email\" name=\"user[email]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("infoemail").innerHTML + "\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"> <span class=\"textBold\">Exchange Rating </span></td>";
	info += "<td id=\"infoexchangerating\" class=\"inptContainer\">" + document.getElementById("infoexchangerating").innerHTML + "</td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"> <span class=\"textBold\"> Limex Rating </span></td>";
	info += "<td id=\"infolimexrating\" class=\"inptContainer\">" + document.getElementById("infolimexrating").innerHTML + "</td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"> <span class=\"textBold\"> Sold Amount </span></td>";
	info += "<td id=\"infosoldamount\" class=\"inptContainer\">" + document.getElementById("infosoldamount").innerHTML + "</td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"> <span class=\"textBold\"> Bought Amount</span></td>";
	info += "<td id=\"infoboughtamount\" class=\"inptContainer\">" + document.getElementById("infoboughtamount").innerHTML + "</td> </tr>";
//	info += "<tr> <td class=\"textDescriptionFormGreen\"> <span class=\"textBold\"> Rogue</span></td>";
//	info += "<td id=\"inforogue\" class=\"inptContainer\">" + document.getElementById("inforogue").innerHTML + "</td> </tr>";
	info += "<tr> <td> <input type=\"submit\" class=\"btn\" value=\"update\" style=\"width:50\"> </td> </tr>"
	info += "</table>";
	document.getElementById("informationtable").innerHTML = info;
	document.getElementById('personal_info_edit_btn').disabled = true // Added by Dinesh
}


function detailtable_form(type) {
        // type = 1 doesn't work now
	if (type==1)
	{
	info = "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> First Name </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_firstname\" name=\"userdetail[firstname]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Last Name </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_lastname\" name=\"userdetail[lastname]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Street1 </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_firststreet\" name=\"userdetail[firststreet]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Street2 </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_secondstreet\" name=\"userdetail[secondstreet]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> City </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_city\" name=\"userdetail[city]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> State </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_state\" name=\"userdetail[state]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Country </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_country\" name=\"userdetail[country]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Landline </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_landline\" name=\"userdetail[landline]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Mobile </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_mobile\" name=\"userdetail[mobile]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Birth Date </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_birth_date\" name=\"userdetail[birth_date]\" size=\"30\" type=\"text\" value=\"\" /></td></tr>";
	info += "<tr> <td> <input type=\"submit\" class=\"btn\" value=\"Submit\" style=\"width:50\"> </td> </tr>";
	}
	else
	{
	info = "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> First Name </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_firstname\" name=\"userdetail[firstname]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailfirstname").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Last Name </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_lastname\" name=\"userdetail[lastname]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detaillastname").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Street1 </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_firststreet\" name=\"userdetail[firststreet]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailfirststreet").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Street2 </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_secondstreet\" name=\"userdetail[secondstreet]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailsecondstreet").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> City </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_city\" name=\"userdetail[city]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailcity").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> State </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_state\" name=\"userdetail[state]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailstate").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Country </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_country\" name=\"userdetail[country]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailcountry").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Landline </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_landline\" name=\"userdetail[landline]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detaillandline").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Mobile </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_mobile\" name=\"userdetail[mobile]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailmobile").innerHTML + "\" /></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Birth Date </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"userdetail_birth_date\" name=\"userdetail[birth_date]\" size=\"30\" type=\"text\" value=\"" + document.getElementById("detailbirth_date").innerHTML + "\" style=\"width:60%\"/>";
	info += "<a href=\"#\" onclick=\"cal.select(document.getElementsByName('userdetail[birth_date]')[0], 'userdetail[birth_date]_selector', 'yyyy-MM-dd'); return false;\" name=\"userdetail[birth_date]_selector\" id=\"userdetail[birth_date]_selector\"><img border=0 src=\"/images/calendar.gif\" alt=\"Select Date\"/></a></td></tr>"
	info += "<tr> <td> <input type=\"submit\" class=\"btn\" value=\"update\" style=\"width:50\"> </td> </tr>";
	}
	
	document.getElementById("detailtable").innerHTML=info;
}

function educationtable_form(type) {
  //request is to add 
  if (type ==0){
	info = "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Institute </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"education_institute\" name=\"education[institute]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Degree </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"education_degree\" name=\"education[degree]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Description </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"education_description\" name=\"education[description]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Start Date </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"education_start_date\" name=\"education[start_date]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> End Date </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"education_end_date\" name=\"education[end_date]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Grade </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"education_grade\" name=\"education[grade]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td> <input type=\"submit\" class=\"btn\" value=\"Submit\" style=\"width:50\"> </td> </tr>";
	document.getElementById("educationtable").innerHTML=info;
  }
}

function worktable_form(type) {
       //request is to add 
  if (type ==0){
	info = "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Designation </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"work_designation\" name=\"work[designation]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Organization </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"work_company\" name=\"work[company]\" size=\"30\" type=\"text\"/></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Description </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"work_description\" name=\"work[description]\" size=\"30\" type=\"text\"/></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Start Date </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"work_start_date\" name=\"work[start_date]\" size=\"30\" type=\"text\"/></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> End Date </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"work_end_date\" name=\"work[end_date]\" size=\"30\" type=\"text\"/></td></tr>";
	info += "<tr> <td> <input type=\"submit\" class=\"btn\" value=\"Submit\" style=\"width:50\"> </td> </tr>";
	document.getElementById("worktable").innerHTML=info;
  }
}
function external_recotable_form(type) {
       //request is to add 
  if (type ==1){
	info = "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Name  </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"external_reco_recommender_name\" name=\"external_reco[recommender_name]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Content </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"external_reco_recommendation_content\" name=\"external_reco[recommendation_content]\" size=\"30\" type=\"text\"/></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\"><span class=\"textBold\"> Link </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"external_reco_recommendation_link\" name=\"external_reco[recommendation_link]\" size=\"30\" type=\"text\"/></td></tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> E-mail  </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"external_reco_recommender_email\" name=\"external_reco[recommender_email]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Phone </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"external_reco_recommender_phone\" name=\"external_reco[recommender_phone]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td> <input type=\"submit\" class=\"btn\" value=\"Submit\" style=\"width:50\"> </td> </tr>";
	document.getElementById("external_recotable").innerHTML=info;
  }
}
function skilltable_form(type) {
       //request is to add 
  if (type ==1){
	info = "<tr> <td class=\"textDescriptionFormGreen\" width=\"30%\"><span class=\"textBold\"> Skill  </span></td>";
	info += "<td class=\"inptContainer\"><input class=\"inptBox\" id=\"skill_skill\" name=\"skill[skill]\" size=\"30\" type=\"text\"/></td> </tr>";
	info += "<tr> <td> <input type=\"submit\" class=\"btn\" value=\"Submit\" style=\"width:50\"> </td> </tr>";
	document.getElementById("skilltable").innerHTML=info;
  }
}

function referertable_form() {
	info = "<tr> <td class=\"listItemAlt\"><input class=\"inptBox\" id=\"user_name\" name=\"user[name]\" size=\"30\" type=\"text\"/></td>";
	info += "<td class=\"listItemAlt\"><input class=\"inptBox\" id=\"user_designation\" name=\"user[designation]\" size=\"30\" type=\"text\"/></td>";
	info += "<td class=\"listItemAlt\"><input class=\"inptBox\" id=\"user_organization\" name=\"user[organization]\" size=\"30\" type=\"text\"/></td>";
	info += "<td> <input type=\"submit\" class=\"btn\" value=\"Submit\" style=\"width:50\"> </td> </tr>";
	document.getElementById("referertable").innerHTML=info;
}


function information_form() {
	info = "<form action=\"/admin/addinformation\" method=\"post\"> <fieldset> <legend>Your Information</legend> <p><label for=\"Name\">Name:</label> <input id=\"user_name\" maxlength=\"20\" name=\"user[name]\" size=\"20\" type=\"text\" value=\""+ document.getElementById("infoname").innerHTML + "\"/></p> <p><label for=\"email\">email address:</label> <input id=\"user_email\" maxlength=\"50\" name=\"user[email]\" size=\"20\" type=\"text\" value=\"" + document.getElementById("infoemail").innerHTML + "\" /></p> <p><label for=\"aboutme\">aboutme:</label>   <input id=\"user_aboutme\" maxlength=\"80\" name=\"user[aboutme]\" size=\"20\" type=\"text\" value=\"" + document.getElementById("infoaboutme").innerHTML + "\"/></p> <p class=\"submit\"><input type=\"submit\" value=\"Update\" /></p> </fieldset> </form>"
	document.getElementById("information").innerHTML=info;
}

function address_form(type) {
	if (type==1)
	{
		info = "<form action=\"/admin/addaddress\" method=\"post\"> <fieldset> <legend>Your Address</legend> <p><label for=\"Street\">Street:</label> <input id=\"user_street\" maxlength=\"20\" name=\"user[street]\" size=\"20\" type=\"text\" value=\""+ document.getElementById("addstreet").innerHTML + "\"/></p>"; 
		info += "<p><label for=\"city\">City:</label> <input id=\"user_city\" maxlength=\"20\" name=\"user[city]\" size=\"20\" type=\"text\" value=\"" + document.getElementById("addcity").innerHTML + "\" /></p> ";
		info += "<p><label for=\"state\">State:</label> <input id=\"user_state\" maxlength=\"20\" name=\"user[state]\" size=\"20\" type=\"text\" value=\"" + document.getElementById("addstate").innerHTML + "\" /></p> ";	
		info += "<p><label for=\"country\">Country:</label> <input id=\"user_country\" maxlength=\"20\" name=\"user[country]\" size=\"20\" type=\"text\" value=\"" + document.getElementById("addcountry").innerHTML + "\" /></p> ";	
		info += "<p><label for=\"zip\">Zip:</label> <input id=\"user_zip\" maxlength=\"20\" name=\"user[zip]\" size=\"20\" type=\"text\" value=\"" + document.getElementById("addzip").innerHTML + "\" /></p> ";	
		info += "<p><label for=\"telephone\">Telephone:</label> <input id=\"user_telephone\" maxlength=\"20\" name=\"user[telephone]\" size=\"20\" type=\"text\" value=\"" + document.getElementById("addtelephone").innerHTML + "\" /></p> ";	
		info += "<p class=\"submit\"><input type=\"submit\" value=\"Submit\" /></p> </fieldset> </form>"
	}
	else
	{
		info = "<form action=\"/admin/addaddress\" method=\"post\"> <fieldset> <legend>Your Address</legend> <p><label for=\"Street\">Street:</label> <input id=\"user_street\" maxlength=\"20\" name=\"user[street]\" size=\"20\" type=\"text\" /></p>"; 
		info += "<p><label for=\"city\">City:</label> <input id=\"user_city\" maxlength=\"20\" name=\"user[city]\" size=\"20\" type=\"text\" /></p> ";
		info += "<p><label for=\"state\">State:</label> <input id=\"user_state\" maxlength=\"20\" name=\"user[state]\" size=\"20\" type=\"text\" /></p> ";	
		info += "<p><label for=\"country\">Country:</label> <input id=\"user_country\" maxlength=\"20\" name=\"user[country]\" size=\"20\" type=\"text\" /></p> ";	
		info += "<p><label for=\"zip\">Zip:</label> <input id=\"user_zip\" maxlength=\"20\" name=\"user[zip]\" size=\"20\" type=\"text\" /></p> ";	
		info += "<p><label for=\"telephone\">Telephone:</label> <input id=\"user_telephone\" maxlength=\"20\" name=\"user[telephone]\" size=\"20\" type=\"text\" /></p> ";	
		info += "<p class=\"submit\"><input type=\"submit\" value=\"Submit\" /></p> </fieldset> </form>"
	}
	document.getElementById("address").innerHTML=info;
}

function education_form() {
	info = "<br><form action=\"/admin/addeducation\" method=\"post\"> <fieldset> <legend>Add Education</legend> <p><label for=\"Course\">Course:</label> <input id=\"user_course\" maxlength=\"20\" name=\"user[course]\" size=\"20\" type=\"text\" /></p>";
	info += "<p><label for=\"department\">Department:</label> <input id=\"user_department\" maxlength=\"20\" name=\"user[department]\" size=\"20\" type=\"text\" /></p> ";
	info += "<p><label for=\"college\">College:</label> <input id=\"user_college\" maxlength=\"20\" name=\"user[college]\" size=\"20\" type=\"text\" /></p> ";	
	info += "<p><label for=\"year\">Year:</label> <input id=\"user_year\" maxlength=\"20\" name=\"user[year]\" size=\"20\" type=\"text\" /></p> ";	
	info += "<p><label for=\"location\">Location:</label> <input id=\"user_location\" maxlength=\"20\" name=\"user[location]\" size=\"20\" type=\"text\" /></p> ";	
	info += "<p class=\"submit\"><input type=\"submit\" value=\"Submit\" /></p> </fieldset> </form>"
	document.getElementById("educationform").innerHTML=info;
}

function work_form() {
	info = "<br><form action=\"/admin/addwork\" method=\"post\"> <fieldset> <legend>Add Work Experience</legend> <p><label for=\"Designation\">Designation:</label> <input id=\"user_designation\" maxlength=\"20\" name=\"user[designation]\" size=\"20\" type=\"text\" /></p>";
	info += "<p><label for=\"organization\">Organization:</label> <input id=\"user_organization\" maxlength=\"20\" name=\"user[organization]\" size=\"20\" type=\"text\" /></p> ";
	info += "<p><label for=\"description\">Description:</label> <input id=\"user_description\" maxlength=\"20\" name=\"user[description]\" size=\"20\" type=\"text\" /></p> ";	
	info += "<p><label for=\"location\">Location:</label> <input id=\"user_location\" maxlength=\"20\" name=\"user[location]\" size=\"20\" type=\"text\" /></p> ";	
	info += "<p class=\"submit\"><input type=\"submit\" value=\"Submit\" /></p> </fieldset> </form>"
	document.getElementById("workform").innerHTML=info;
}

function skill_form() {
	info = "Sorry You can't add them right now, since categories need to be selected for this"
	document.getElementById("skillform").innerHTML=info;
}

function referer_form() {
	info = "<br><form action=\"/admin/addreferer\" method=\"post\"> <fieldset> <legend>Add References</legend> <p><label for=\"name\">Name:</label> <input id=\"user_name\" maxlength=\"20\" name=\"user[name]\" size=\"20\" type=\"text\" /></p>";
	info += "<p><label for=\"designation\">Designation:</label> <input id=\"user_designation\" maxlength=\"20\" name=\"user[designation]\" size=\"20\" type=\"text\" /></p> ";
	info += "<p><label for=\"organization\">Organization:</label> <input id=\"user_organization\" maxlength=\"20\" name=\"user[organization]\" size=\"20\" type=\"text\" /></p> ";	
	info += "<p class=\"submit\"><input type=\"submit\" value=\"Submit\" /></p> </fieldset> </form>"
	document.getElementById("refererform").innerHTML=info;
}

function check_submit_form(form_id, field_id){
  if(document.getElementById(field_id).value != "")
   document[form_id].submit();
}

function editportfolio(status_to_set, file_id){
    
    display_data_div = $('editportfolio-' + file_id);
    edit_data_div    = $('editportfolioEdit-' + file_id);
    
    if (status_to_set == 'on'){
        edit_data_div.style.display = '';
        display_data_div.style.display = 'none';
    }
    else if(status_to_set == 'off'){
        edit_data_div.style.display = 'none';
        display_data_div.style.display = '';
    }
    else{
        alert('Unknown status to set.');
    }
}

function selectAllRows(checked){
	
	allCheckBoxes = document.getElementsByName('selected_messages[]');
	var class_name = '';
	if(checked == true){
		class_name = 'messageSelected';
	}
	for(var i = 0; i< allCheckBoxes.length; i++){
		if (allCheckBoxes[i].disabled == false) {
			allCheckBoxes[i].checked = checked;
			allCheckBoxes[i].parentNode.parentNode.className = class_name;
		}
	}
}

function troublesomeDivVisibility(status, avoid){
    tag=document.getElementsByTagName('select');
    for(i=tag.length-1;i>=0;i--){
        tag[i].style.visibility=status;
    }
    tag=document.getElementsByTagName('iframe');
    tl = tag.length
    for(i=tl-1;i>=0;i--){
        tag[i].style.visibility=status;
        calendar = $('calendarDiv')
        if(calendar && status=='visible'){
            calendar.style.visibility='hidden'
        }
    }
    tag=document.getElementsByTagName('object');
    for(i=tag.length-1;i>=0;i--){
        tag[i].style.visibility=status;
    }
    
    tag=document.getElementsByTagName('embed');
    for(i=tag.length-1;i>=0;i--){
        tag[i].style.visibility=status;
    }
    
    if(avoid){
        for(var i=0, len = avoid.length; i < len; ++i){
            element = document.getElementById(avoid[i]);
            if(element){
                if(status=='hidden')
                    status_prime = 'visible';
                else
                    status_prime = 'hidden';
                element.style.visibility=status_prime;
            }
        }    
    }
    
}

/*
 * Client side check to verify if the 'Email this project' form completely filled. And all the email addresses
 * are correct
 */
function validate_email_project(count,div_id){
	
	var is_valid = true;
	
	//check if the subject is not empty
	if(!checkNullAndSetError('mail[subject]','subject_error_msg','Please enter mail subject.','err'))
		is_valid = false;
		
	//check if the message text is not empty
	if(!checkNullAndSetError('invitation_message'+div_id,'text_error_msg','Please enter mail text.','err'))
		is_valid = false;
	
	
	//check if the email address(s) are valid
	emailRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/;
	
    var err_mail='Please enter a valid email address';
	var no_email_addr_flag = false;
	for(var i=1; i<=count; i++){
		var email_addr = document.getElementById('email_id_'+i).value;
		
		if(email_addr==null || trim(email_addr)=="")
			continue;
		no_email_addr_flag = true;
		var email_err_obj = document.getElementById('email_err_id_'+i);	
		if(!emailRegExp.test(email_addr)){				
      email_err_obj.innerHTML=err_mail;
			email_err_obj.className='err';   
			is_valid = false;   		      		
    	}else if(email_err_obj.innerHTML){
			email_err_obj.innerHTML='';
			email_err_obj.className='';  
		}	
		
	}
	//Check if any email addr was entered
	var error_msg_obj = document.getElementById('error_msg');
	if(no_email_addr_flag==false){		
		error_msg_obj.innerHTML='Please enter at least one valid email address.';	
		error_msg_obj.className='err';	
		is_valid = false;	
	}else if(error_msg_obj.innerHTML){
		error_msg_obj.innerHTML='';	
		error_msg_obj.className='';
	}
	
	return is_valid;
    
}

function validate_bid_invitation_compose(size){
	var is_valid = true;
	var has_selected_project = false;
	
	//check if the project list is not empty
	if(size==0){		
		var project = document.getElementById('selected_bid_projects').value;	
		if(project!=null && project!=''){		
			has_selected_project = true;
		}
		
	}else{		
		var all_project = document.getElementById('all_projects_id').checked;
		if(all_project==true){
			has_selected_project = true;
		}else{
			for(var i=1; i<=size;i++){
				var selected_project = document.getElementById('selected_bid_projects'+i).checked;
				if(selected_project==true){
					has_selected_project = true;
					break;
				}
			}
		}
	}
	
	var project_error_msg_obj = document.getElementById('project_err_msg');
	if(has_selected_project==false){
		project_error_msg_obj.innerHTML='Please select a project.';	
		project_error_msg_obj.className='err';	
		is_valid = false;
	}else if(project_error_msg_obj.innerHTML){
		project_error_msg_obj.innerHTML='';	
		project_error_msg_obj.className='';
	}
		
	//check if the seller list is not empty
	if(!checkNullAndSetError('seller_ids[]','seller_err_msg','Please select contact(s).','err'))
		is_valid = false;
	
	//check if the text is not empty
	if(!checkNullAndSetError('invitation_message','text_error_msg','Please enter message text.','err'))
		is_valid = false;
	
	return is_valid;
	
	
}

function validate_reco_request_compose(){
	var is_valid = true;
	
	
	//check if the seller list is not empty
	if(!checkNullAndSetError('seller_ids[]','seller_err_msg','Please select contact(s).','err'))
		is_valid = false;
		
	//check if the subject is not empty
	if(!checkNullAndSetError('subject','subject_error_msg','Please enter message subject.','err'))
	is_valid = false;
	
	//check if the text is not empty
	if(!checkNullAndSetError('request_recommendation_message','text_error_msg','Please enter message text.','err'))
		is_valid = false;
	
	return is_valid;
	
	
}

function validate_reco_compose(){
	var is_valid = true;
			
	//check if the subject is not empty
	if(!checkNullAndSetError('subject','subject_error_msg','Please enter message subject.','err'))
		is_valid=false;	
	
	//check if the text is not empty
	if(!checkNullAndSetError('reco_message_id','text_error_msg','Please enter message text.','err'))
		is_valid=false;	
	
	return is_valid;
	
	
}


function validate_project_discussion_compose(){
	var is_valid = true;
	
	//check if the project is not empty
	if(!checkNullAndSetError('pmb_projects','project_err_msg','Please select a project.','err'))
		is_valid=false;	
            
        //check if no contact is selected
        if(!checkNullAndSetError('bid_contacts','bid_contact_err_msg','Please select a contact.','err'))	
		is_valid=false;	
        
	
	//check if the subject is not empty
	if(!checkNullAndSetError('subject','subject_error_msg','Please enter message subject.','err'))	
		is_valid=false;	
	//check if the text is not empty
	if(!checkNullAndSetError('pmb_message_id','text_error_msg','Please enter message text.','err'))
		is_valid=false;	
            
         return is_valid;
	
	
}


function validate_project_clearification_compose(){
	var is_valid = true;
	//check if the text is not empty
	if(!checkNullAndSetError('message_id','text_error_msg','Please enter message text.','err'))
		is_valid=false;
  return is_valid;
}


function validate_conversation_compose(){
	var is_valid = true;
			
	//check if the seller list is not empty
	if(!checkNullAndSetError('seller_ids[]','seller_err_msg','Please select contact(s).','err'))
			is_valid = false;
		
	//check if the subject is not empty
	if(!checkNullAndSetError('subject','subject_error_msg','Please enter message subject.','err'))
	is_valid = false;
	
	
	//check if the text is not empty
	if(!checkNullAndSetError('general_message','text_error_msg','Please enter message text.','err'))
	is_valid = false;
		
	return is_valid;
	
	
}

function validate_friend_request_compose(){
	var is_valid = true;
			
	//check if the text is not empty
	if(!checkNullAndSetError('friend_request_message_id','text_error_msg','Please enter message text.','err'))
		is_valid = false;
		
	return is_valid;
	
	
}

function validate_reply(key){
	var is_valid = true;
			
	//check if the text is not empty
	
	if(!checkNullAndSetError('text_area_'+key,'text_err_msg_'+key,'Please enter message text.','err'))
		is_valid = false;
	
	//if(is_valid)
	//hideMessageTextArea(key);
	
	return is_valid;
	
	
}

function checkNullAndSetError(element_name,error_element_name,errorMsg,className){
	
	var element_obj = document.getElementById(element_name)
	if(element_obj==null)
		return true;
	element = element_obj.value;
	var element_error_msg_obj = document.getElementById(error_element_name);
	if(element==null || trim(element)==''){		
		element_error_msg_obj.innerHTML=errorMsg;	
		element_error_msg_obj.className=className;	
		return false;
	}else if(element_error_msg_obj.innerHTML){
		element_error_msg_obj.innerHTML='';	
		element_error_msg_obj.className='';
		
	}
	return true;
	
}

function trim(message){
	return message.replace(/^\s+|\s+$/g, ""); 
}
function isLessThanIE6(){
    result = false;
    if (navigator.appVersion.indexOf("MSIE")!=-1){
        temp=navigator.appVersion.split("MSIE");
        version=parseFloat(temp[1]);
        if(version <= 6){
            result = true;
        }
        else{
            result = false;
        }
    }
    else{
        result = false;
    }
    return result;
}
function starClicked(star_id_str, hidden_field_id){
	star_id = star_id_str * 1;
	actual_rating = $(hidden_field_id).value * 1
	clicked_star = $('star-'+star_id)
		
	if(actual_rating == star_id){
		for(i = 1; i <= star_id; i++){
			star = $('star-'+i)
			star.className = "star empty";
		}
		$(hidden_field_id).value = 0
	}
	else{
		for(i = 1; i <= star_id; i++){
			star = $('star-'+i)
			star.className = "star full";
		}
		$(hidden_field_id).value = star_id
	}
	for(i = star_id*1 + 1; i <= 5; i++){
		star = $('star-'+i)
		star.className = "star empty";
	}
	
	
}

function change_widget_preview(element_id,color,widget_element){
    
    switch(widget_element){
        case 'border_color':
            document.getElementById(element_id).style.borderColor = color;
            break;
        case 'background_color':
            document.getElementById(element_id).style.backgroundColor = color;
            document.getElementById(element_id).parentNode.style.borderColor = color;
            break;
        case 'title_color':
            document.getElementById(element_id).style.color = color;
            break;
        case 'text_color':
          if(document.getElementById(element_id) == null){
            var elems = document.getElementsByClassName(element_id)
            for(var i=0; i<elems.length; i++){
              elems[i].style.color = color;
            }
          } else {
            document.getElementById(element_id).style.color = color;
          }
            break;
        case 'url_color':
            document.getElementById(element_id).style.color = color;
            break;
        case 'color':
            break;
    }      
}

function set_picker_from_widget(){ 
    
    widget_preview = document.getElementById("widget_preview");
    border_color = widget_preview.style.borderColor;
    background_color = widget_preview.style.backgroundColor;
    
    title_color = document.getElementById("widget_preview_title").style.color;
    text_color = document.getElementById("widget_preview_text").style.color;
    url_color = document.getElementById("widget_preview_url").style.color;
    
    document.getElementById('widget_border_color').style.backgroundColor = border_color;
    document.getElementById('widget_border_color').value = border_color;
    
    document.getElementById('widget_background_color').style.backgroundColor = background_color;
    document.getElementById('widget_background_color').value = background_color;
    
    document.getElementById('widget_title_color').style.backgroundColor = title_color;
    document.getElementById('widget_title_color').value = title_color;
    
    document.getElementById('widget_text_color').style.backgroundColor = text_color;
    document.getElementById('widget_text_color').value = text_color;
    
    document.getElementById('widget_url_color').style.backgroundColor = url_color;
    document.getElementById('widget_url_color').value = url_color;
           
}

function checkArrow(obj, right_align)
{
        if(right_align){
	  var yahoo = document.getElementById('arrow_yahoo2');
	  var gmail = document.getElementById('arrow_gmail2');
	  var aol = document.getElementById('arrow_aol2');
	  var hotMail = document.getElementById('arrow_hotmail2');
	  var linkedIn = document.getElementById('arrow_linkedin2');

        } else {
	  var yahoo = document.getElementById('arrow_yahoo');
	  var gmail = document.getElementById('arrow_gmail');
	  var aol = document.getElementById('arrow_aol');
	  var hotMail = document.getElementById('arrow_hotmail');
	  var linkedIn = document.getElementById('arrow_linkedin');

        }
	
	if(obj == 'arrow_yahoo')
	{	
		yahoo.style.display='';
		
		gmail.style.display='none';
		aol.style.display='none';
		hotMail.style.display='none';
		linkedIn.style.display='none';
	}

	if(obj == 'arrow_gmail')
	{
		yahoo.style.display='none';		
		
		gmail.style.display='';
		
		aol.style.display='none';
		hotMail.style.display='none';
		linkedIn.style.display='none';
	}
	
	if(obj == 'arrow_aol')
	{
		yahoo.style.display='none';			
		gmail.style.display='none';
		
		aol.style.display='';
		hotMail.style.display='none';
		linkedIn.style.display='none';
	}
	
	if(obj == 'arrow_hotmail')
	{
		yahoo.style.display='none';			
		gmail.style.display='none';		
		aol.style.display='none';
		
		hotMail.style.display='';
		
		linkedIn.style.display='none';		
	}	
	
	if(obj == 'arrow_linkedin')
	{
		yahoo.style.display='none';			
		gmail.style.display='none';		
		aol.style.display='none';
		hotMail.style.display='none';
		
		linkedIn.style.display='';		
	}		
	
}

function getSelectedRadio(buttonGroup) {
  if (buttonGroup[0]) { 
    for (var i=0; i<buttonGroup.length; i++) {
      if (buttonGroup[i].checked) {
        return i
      }
    }
  } else {
      if (buttonGroup.checked) {return 0;}
  }
  return -1;
} 

function getSelectedRadioValue(buttonGroup) {
  var i = getSelectedRadio(buttonGroup);
  if (i == -1) {return "";} 
  else {
    if (buttonGroup[i]) {
      return buttonGroup[i].value;
    } else {
      return buttonGroup.value;
      }
  }
}

function getRadiowithValue(buttonGroup, sourceName) {
  if (buttonGroup[0]) { 
    for (var i=0; i<buttonGroup.length; i++) {
      if (buttonGroup[i].value == sourceName) {
        return buttonGroup[i]
      }
    }
  } else {
      if (buttonGroup.value == sourceName) {return buttonGroup;}
  }
 if (buttonGroup[0]){
  return buttonGroup[0];
 } else {
  return buttonGroup
 }
} 


function markDefaultImportSourceSelected(sourceName, right_align){
  sources = document.getElementsByName('import[source1]');
  selected_source = getRadiowithValue(sources, sourceName);
  selected_source.checked = true;
  checkArrow('arrow_'+ selected_source.value, right_align);
}

function getAbsolutePosition(element) {
  var r = {x: element.offsetLeft, y: element.offsetTop};
  if (element.offsetParent) {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
    }
  return r;
}

function moveToPos(element, contactsContainer) {
   containerPos = getAbsolutePosition(contactsContainer);
   grouppos = getAbsolutePosition(element)
   contactsContainer.scrollTop = grouppos.y - containerPos.y  ;
}

function getCheckBoxWithValue(buttonGroup, value) {
  if (buttonGroup[0]) {
    for (var i=0; i<buttonGroup.length; i++) {
      if (buttonGroup[i].value == value) {
        return i;
      }
    }
  } else {
    if(buttonGroup.value == value) {return 0;}
  }
      return -1;
}

function getWidgetParameters(text_link_type,banner_type){
    var qString;
    
    widget_type = document.getElementById('user_widget_widget_type').value;
    
    qString = '?widget_type='+widget_type;
    
    qString += '&size='+document.getElementById('user_widget_widget_dimensions').value;
    
    if(widget_type==text_link_type){
    
        qString += '&message='+document.getElementById('user_widget_landingcode_message').value;
        border = document.getElementById('user_widget_border_color').value.split('#')[1];
        qString += '&border='+border;
        background = document.getElementById('user_widget_background_color').value.split('#')[1];
        qString += '&background='+background;
        title = document.getElementById('user_widget_title_color').value.split('#')[1];
        qString += '&title='+title
        text = document.getElementById('user_widget_text_color').value.split('#')[1];
        qString += '&text='+text;
        url = document.getElementById('user_widget_url_color').value.split('#')[1];
        qString += '&url='+url;
        
    }
    
    return qString;
}

function showEarning(exchangeFeesPer100, avg_affiliate_comission){
  noOfReferrals = no_of_referrals.value;
  avgEarning = avg_earning.value;
  if (noOfReferrals && avgEarning) {
    error_message_div.style.display= 'none';
    totalEarning = noOfReferrals * avgEarning;
    totalExchangeFees = (totalEarning/100.0)* exchangeFeesPer100;
    affiliateEarning = totalExchangeFees * (avg_affiliate_comission/100.0) ;
    total_earning.innerHTML = "$" + affiliateEarning;
  }else {
    error_message_div.style.display= '';
    error_message_div.innerHTML = "<span class='validation_error'> Please select some numbers. </span>" ;
  }
}


function setTermsAgreed(objForm){
  closeFloat('_terms');
  objForm['terms_agreed'].value = "1";
  objForm.submit();
}

/* Profile Tabs Script Starts here */

function ShowHand(curobj)
{
	curobj.style.cursor="hand";
}

  /* Edited by Dinesh : Please do not over-write*/
  /* Begin */
function hideDivs(div_id_array){
  for(i=0; i<div_id_array.length; i++){
    div_id = div_id_array[i];
    div = $(div_id);
    if(div){
        div.style.display = 'none';
    }
  }
}

function showDivs(div_id_array){
  for(i=0; i<div_id_array.length; i++){
    div_id = div_id_array[i];
    div = $(div_id);
    if(div){
        div.style.display = '';
    }
  }
}

function ChangeTabs(tabnum)
{
  active_div_ids   = new Array('tabOverviewActive', 'tabCompanyActive', 'tabPortfolioActive', 'tabConnectionsActive', 'tabFeedbackActive', 'tabRecActive', 'tabResumeActive','tabCSActive');
	inactive_div_ids = new Array('tabOverviewInActive', 'tabCompanyInActive', 'tabPortfolioInActive', 'tabConnectionsInActive', 'tabFeedbackInActive', 'tabRecInActive', 'tabResumeInActive','tabCSInActive');
  content_div_ids  = new Array('contentOverview', 'contentCompany', 'contentPortfolio', 'contentConnections', 'contentFeedback', 'contentRec', 'contentResume','contentCS');
  
  hideDivs(active_div_ids);
  showDivs(inactive_div_ids);
  hideDivs(content_div_ids);

  switch(parseInt(tabnum)){
  case 1:
    document.getElementById('tabOverviewInActive').style.display="none";
    document.getElementById('tabOverviewActive').style.display="";
		document.getElementById('contentOverview').style.display="";
    break;
  case 2:
    document.getElementById('tabCompanyInActive').style.display="none";
		document.getElementById('tabCompanyActive').style.display="";
		document.getElementById('contentCompany').style.display="";
    break;
  case 3:
    document.getElementById('tabPortfolioInActive').style.display="none";
    document.getElementById('tabPortfolioActive').style.display="";
    document.getElementById('contentPortfolio').style.display="";
    break;
  case 4:
    document.getElementById('tabConnectionsInActive').style.display="none";
    document.getElementById('tabConnectionsActive').style.display="";
    document.getElementById('contentConnections').style.display="";
    break;
  case 5:
    document.getElementById('tabFeedbackInActive').style.display="none";
    document.getElementById('tabFeedbackActive').style.display="";
    document.getElementById('contentFeedback').style.display="";
    break;
  case 6:
    document.getElementById('tabRecInActive').style.display="none";
    document.getElementById('tabRecActive').style.display="";
    document.getElementById('contentRec').style.display="";
    break;
  case 7:
    document.getElementById('tabResumeInActive').style.display="none";
    document.getElementById('tabResumeActive').style.display="";
    document.getElementById('contentResume').style.display="";
    break;
   case 8:
    document.getElementById('tabCSInActive').style.display="none";
    document.getElementById('tabCSActive').style.display="";
    document.getElementById('contentCS').style.display="";
    break;

  default:
    break;
  }	
}

/* End */

/* Profile Tabs Script Ends here */

function ResetTabs2()
{
	
	document.getElementById('imageTabsActive').style.display="none";
	document.getElementById('videoTabsActive').style.display="none";
	

	
	
	document.getElementById('imageTabsInActive').style.display="none";
	document.getElementById('videoTabsInActive').style.display="none";
	

}
function ResetDivContents2()
{

	document.getElementById('imageHolder').style.display="none";
	document.getElementById('videoHolder').style.display="none";

}

function ChangeTabs2(tabnum)
{
	ResetTabs2();
	ResetDivContents2();
	
	if(tabnum == '1'){
		document.getElementById('imageTabsActive').style.display="";
		document.getElementById('videoTabsInActive').style.display="";
		
		document.getElementById('imageHolder').style.display="";
    /* Changes by Dinesh, do not edit*/
    ia = $('imageActions');
    if(ia){
        ia.style.display = "";
    }
    iv = $('videoActions');
    if(iv){
        iv.style.display = "none";
    }
    /* Changes end */
	}
	else if(tabnum == '2'){
		document.getElementById('videoTabsActive').style.display="";
		document.getElementById('imageTabsInActive').style.display="";
		document.getElementById('videoHolder').style.display="";
    /* Changes by Dinesh, do not edit*/
    ia = $('imageActions');
    if(ia){
        ia.style.display = "none";
    }
    iv = $('videoActions');
    if(iv){
        iv.style.display = "";
    }
    /* Changes end */
	}
}




function showContent(x)
{
		var moreInfo = document.getElementById("moreInfo" + x);
		if(document.getElementById(x).style.display=='none')
		document.getElementById(x).style.display='';
		else
		document.getElementById(x).style.display='none';
		moreInfo.style.display="none";
}

function hideContent(x)
{
		var moreInfo = document.getElementById("moreInfo" + x);
		if(document.getElementById(x).style.display=='none')
		document.getElementById(x).style.display='';
		else
		document.getElementById(x).style.display='none';
		moreInfo.style.display="";
}

/* Agreements Tabs Script starts here */

function ResetTabs3()
{
	
	document.getElementById('tabOngoingActive').style.display="none";
	document.getElementById('tabAcceptedActive').style.display="none";
	document.getElementById('tabRejectedActive').style.display="none";
	document.getElementById('tabDraftsActive').style.display="none";
	document.getElementById('tabWithdrawnActive').style.display="none";
	document.getElementById('tabInvalidActive').style.display="none";
	
	document.getElementById('tabOngoingInActive').style.display="none";
	document.getElementById('tabAcceptedInActive').style.display="none";
	document.getElementById('tabRejectedInActive').style.display="none";
	document.getElementById('tabDraftsInActive').style.display="none";
	document.getElementById('tabWithdrawnInActive').style.display="none";
	document.getElementById('tabInvalidInActive').style.display="none";

}
function ResetDivContents3()
{
	document.getElementById('agreementsOngoing').style.display="none";
	document.getElementById('agreementsAccepted').style.display="none";
	document.getElementById('agreementsRejected').style.display="none";
	document.getElementById('myDrafts').style.display="none";
	document.getElementById('agreementsWithdrawn').style.display="none";
	document.getElementById('agreementsInvalid').style.display="none";
}

function ChangeTabs3(tabnum)
{
	ResetTabs3();
	ResetDivContents3();
	
	if(tabnum == 1)
	{
		document.getElementById('tabOngoingActive').style.display="";
		document.getElementById('agreementsOngoing').style.display="";
		document.getElementById('tabAcceptedInActive').style.display="";
		document.getElementById('tabRejectedInActive').style.display="";
		document.getElementById('tabDraftsInActive').style.display="";
		document.getElementById('tabWithdrawnInActive').style.display="";
		document.getElementById('tabInvalidInActive').style.display="";
		document.getElementById('createDraft').style.display="none";
		document.getElementById('createDraft1').style.display="none";
	}
	else if(tabnum == 2)
	{
		document.getElementById('tabAcceptedActive').style.display="";
		document.getElementById('agreementsAccepted').style.display="";
		document.getElementById('tabOngoingInActive').style.display="";
		document.getElementById('tabRejectedInActive').style.display="";
		document.getElementById('tabDraftsInActive').style.display="";
		document.getElementById('tabWithdrawnInActive').style.display="";
		document.getElementById('tabInvalidInActive').style.display="";
		document.getElementById('createDraft').style.display="none";
		document.getElementById('createDraft1').style.display="none";
	}
	
	else if(tabnum == 3)
	{
		document.getElementById('tabRejectedActive').style.display="";
		document.getElementById('agreementsRejected').style.display="";
		document.getElementById('tabOngoingInActive').style.display="";
		document.getElementById('tabAcceptedInActive').style.display="";
		document.getElementById('tabDraftsInActive').style.display="";
		document.getElementById('tabWithdrawnInActive').style.display="";
		document.getElementById('tabInvalidInActive').style.display="";
		document.getElementById('createDraft').style.display="none";
		document.getElementById('createDraft1').style.display="none";
	}
	else if(tabnum == 4)
	{
		document.getElementById('tabDraftsActive').style.display="";
		document.getElementById('myDrafts').style.display="";
		document.getElementById('tabOngoingInActive').style.display="";
		document.getElementById('tabAcceptedInActive').style.display="";
		document.getElementById('tabRejectedInActive').style.display="";
		document.getElementById('tabWithdrawnInActive').style.display="";
		document.getElementById('tabInvalidInActive').style.display="";
		document.getElementById('createDraft').style.display="";
		document.getElementById('createDraft1').style.display="none";
	}
	else if(tabnum == 5)
	{
		document.getElementById('tabWithdrawnActive').style.display="";
		document.getElementById('agreementsWithdrawn').style.display="";
		document.getElementById('tabOngoingInActive').style.display="";
		document.getElementById('tabAcceptedInActive').style.display="";
		document.getElementById('tabRejectedInActive').style.display="";
		document.getElementById('tabDraftsInActive').style.display="";
		document.getElementById('tabInvalidInActive').style.display="";
		document.getElementById('createDraft').style.display="none";
		document.getElementById('createDraft1').style.display="none";
	}
	else if(tabnum == 6)
	{
		document.getElementById('tabInvalidActive').style.display="";
		document.getElementById('agreementsInvalid').style.display="";
		document.getElementById('tabOngoingInActive').style.display="";
		document.getElementById('tabAcceptedInActive').style.display="";
		document.getElementById('tabRejectedInActive').style.display="";
		document.getElementById('tabDraftsInActive').style.display="";
		document.getElementById('tabWithdrawnInActive').style.display="";
		document.getElementById('createDraft').style.display="none";
		document.getElementById('createDraft1').style.display="";
	}		
}

/* Agreements Tabs Script ends here */

/* Task Tabs Script starts here */

function ResetTaskTabs()
{
	document.getElementById('tabOpenTaskActive').style.display="none";
	document.getElementById('tabResolvedTaskActive').style.display="none";
	document.getElementById('tabClosedTaskActive').style.display="none";
	
	document.getElementById('tabOpenTaskInActive').style.display="none";
	document.getElementById('tabResolvedTaskInActive').style.display="none";
	document.getElementById('tabClosedTaskInActive').style.display="none";
}
function ResetTaskDivContents()
{
	document.getElementById('openTasks').style.display="none";
	document.getElementById('resolvedTasks').style.display="none";
	document.getElementById('closedTasks').style.display="none";
}

function ChangeTabsTasks(tabnum)
{
	ResetTaskTabs();
	ResetTaskDivContents();
	
	if(tabnum == 1)
	{
		document.getElementById('tabOpenTaskActive').style.display="";
		document.getElementById('openTasks').style.display="";
		document.getElementById('tabResolvedTaskInActive').style.display="";
		document.getElementById('tabClosedTaskInActive').style.display="";
	}
	else if(tabnum == 2)
	{
		document.getElementById('tabResolvedTaskActive').style.display="";
		document.getElementById('resolvedTasks').style.display="";
		document.getElementById('tabOpenTaskInActive').style.display="";
		document.getElementById('tabClosedTaskInActive').style.display="";
	}
	
	else if(tabnum == 3)
	{
		document.getElementById('tabClosedTaskActive').style.display="";
		document.getElementById('closedTasks').style.display="";
		document.getElementById('tabOpenTaskInActive').style.display="";
		document.getElementById('tabResolvedTaskInActive').style.display="";
	}
}

/* Task Tabs Script ends here */

function applyTaskFilter(length_tasks) {
	var milestone_id = document.getElementById('filter_milestone_id').value;
	var priority = document.getElementById('filter_priority').value;
	var assignee = document.getElementById('filter_assignee').value;
	for (var i=0; i < length_tasks; i++) {
		var temp = "issues_" + i;
		var element_i = document.getElementById(temp);
		var milestone_val = element_i.getAttribute('type').split("_")[0];
		var priority_val = element_i.getAttribute('type').split("_")[1];
		var assignee_val = element_i.getAttribute('type').split("_")[2];
		if ((milestone_id == "all" || milestone_id == milestone_val) && (priority=="all" || priority == priority_val) && (assignee=="all" || assignee==assignee_val))
			element_i.style.display = "";
		else
			element_i.style.display = "none";
	}
}

/* Attch more Script Starts here  */



function showAttachment(obj){
	
	var attachLink = document.getElementById('attachLink');
	var addMore = document.getElementById('addMore');
	var attachOne = document.getElementById('attachOne');
	var attachTwo = document.getElementById('attachTwo');
	
	attachLink.style.display='none';

	addMore.style.display='';
	attachOne.style.display='';
	
	}

function showMoreAttach(obj){
	
	var attachLink = document.getElementById('attachLink');
	var addMore = document.getElementById('addMore');
	var removeMore = document.getElementById('removeMore');
	var attachOne = document.getElementById('attachOne');
	var attachTwo = document.getElementById('attachTwo');
	
	attachLink.style.display='none';

	addMore.style.display='';
	removeMore.style.display='';
	attachTwo.style.display='';
	
	}
function removeMoreAttach(obj){
	
	var attachLink = document.getElementById('attachLink');
	var addMore = document.getElementById('addMore');
	var removeMore = document.getElementById('removeMore');
	var attachOne = document.getElementById('attachOne');
	var attachTwo = document.getElementById('attachTwo');
	
	attachLink.style.display='none';

	addMore.style.display='';
	removeMore.style.display='none';
	
	attachTwo.style.display='none';
	
	}
function removeAllAttach(obj){
	
	var attachLink = document.getElementById('attachLink');
	var addMore = document.getElementById('addMore');
	var removeMore = document.getElementById('removeMore');
	var attachOne = document.getElementById('attachOne');
	var attachTwo = document.getElementById('attachTwo');
	
	attachLink.style.display='';

	addMore.style.display='none';
	removeMore.style.display='none';
	
	attachOne.style.display='none';
	attachTwo.style.display='none';
	
	}	


/* functions for Carousel : Begin*/
function buttonStateHandler(button, enabled) {
 if (button == "prev-arrow") 
   $('prev-arrow').src = enabled ? "/images/left3-enabled.gif" : "/images/left3-disabled.gif"
 else 
   $('next-arrow').src = enabled ? "/images/right3-enabled.gif" : "/images/right3-disabled.gif"
}

function animHandler(carouselID, status, direction) {
//  var region = $(carouselID).down(".carousel-clip-region")
//  alert("carouselID : " + carouselID)
  var region = document.getElementById(carouselID).childrenWithClassName("carousel-clip-region")[0]
  if (status == "before") {
    Effect.Fade(region, {to: 0.3, queue: {position:'end', scope: "carousel"}, duration: 0.2})
  }
  if (status == "after") {
    Effect.Fade(region, {to: 1, queue: {position:'end', scope: "carousel"}, duration: 0.2})
  }
}

var firstTimeLoad = false;
// Show/hide "loading" overlay before and after ajax request
function ajaxHandler(carousel, status) {
  var overlay = $('overlay');
  if (status == "before") {
    if (overlay) {
      overlay.setOpacity(0);
      overlay.show();
      Effect.Fade(overlay, {from: 0, to: 0.8, duration: 0.2});
      firstTimeLoad = false;
    }
    else{
      new Insertion.Top("ajax-carousel", "<div id='overlay' ><img src='/images/processSmall.gif'> Loading...</div>");
      firstTimeLoad = true;
    }
    

  }
  else{ 
    Effect.Fade(overlay, {from: 0.8, to: 0.0, duration: 0.2});
    if(firstTimeLoad){
        img = $('carousel-list').select('img').first();
        if(img){
          img.onclick();
          $('portfolio_file_name_label').style.display = "";
          $('portfolio_file_description_label').style.display = "";
        }
        else{
            div = document.getElementById('portfolioBigThumb');
            div.innerHTML = "<br><br><br><br><br><br><br><br><br><br><br>No file in portfolio. Portfolio enables you to upload your best work samples. A good portfolio helps in attracting potential buyers and is critical in getting projects.<br> <a href='/guide/help/general/provider_profile_help' target='_blank'>Click here</a> to know more about portfolio.";
        }
    }
  }
}

function ajaxButtonStateHandler(button, enabled) {
 if (button == "ajax-prev-arrow") 
   $('ajax-prev-arrow').src = enabled ? "/images/thumbArrowLeft1.gif" : "/images/thumbArrowLeft.gif"
 else 
   $('ajax-next-arrow').src = enabled ? "/images/thumbArrowRight1.gif" : "/images/thumbArrowRight.gif"
}

function ajaxAnimHandler(carouselID, status, direction) {
//  var region = $(carouselID).down(".carousel-clip-region")
//  alert("carouselID : " + carouselID)
  var region = $("carousel-clip-region")
  if (status == "before") {
    Effect.Fade(region, {to: 0.3, queue: {position:'end', scope: "carousel"}, duration: 0.2})
  }
  if (status == "after") {
    Effect.Fade(region, {to: 1, queue: {position:'end', scope: "carousel"}, duration: 0.2})
  }
}

function editPortfolio(file_id, file_name, file_description){
    callFloat(600, 400, 'Portfolio', '');
    $('portfolio_name_input').value = file_name.replace(/<br>/g, '');
    $('portfolio_desc_input').value = file_description.replace(/<br>/g, '');
    $('portfolio_upload_form').action = "/portfolio/change_file/" + file_id;
}

function addPortfolio(){
    callFloat(600, 360, 'Portfolio', '');
    $('portfolio_name_input').value = "";
    $('portfolio_desc_input').value = "";
    $('portfolio_upload_form').action = "/portfolio/upload_file";
}

function showBiggerImage(display_url, actual_url, file_name, file_description, file_id){
  download_link = "/portfolio/get_file/" + actual_url;
  display_image  = "/portfolio/get_file/" + display_url;
  div = document.getElementById('portfolioBigThumb');
  div.innerHTML = "<a href='"+download_link+"' target='_blank' style='text-decoration:none'><img id='portfolioBigThumb1' src='"+display_image+"' /></a>";
  $('portfolio_file_name').innerHTML = file_name;
  $('portfolio_file_description').innerHTML = file_description;
  edit_link = $('portfolio_edit_link')
  if(edit_link){
      edit_link.href = "javascript:editPortfolio('"+file_id+"', '"+file_name+"', '"+file_description+"')";
      edit_link.style.display= "";
  }
  delete_link = $('portfolio_delete_link')
  if(delete_link){
      delete_link.href = "/portfolio/delete/" + file_id;
      delete_link.style.display= "";
  }
}

function showOtherBiggerImage(display_url, actual_url, file_name, file_description, file_id){
  download_link = "/portfolio/get_file/" + actual_url;
  div = document.getElementById('portfolioBigThumb');
  div.innerHTML = "<a href='"+download_link+"' target='_blank' style='text-decoration:none'><img id='portfolioBigThumb1' src='" +display_url+ "' /></a>";
  $('portfolio_file_name').innerHTML = file_name;
  $('portfolio_file_description').innerHTML = file_description;
  edit_link = $('portfolio_edit_link')
  if(edit_link){
      edit_link.href = "javascript:editPortfolio('"+file_id+"', '"+file_name+"', '"+file_description+"')";
      edit_link.style.display= "";
  }
  delete_link = $('portfolio_delete_link')
  if(delete_link){
      delete_link.href = "/portfolio/delete/" + file_id;
      delete_link.style.display= "";
  }
}
/* functions for Carousel end*/

function showMoreAttachments(index, nextIndex){
	var more_temp = 'more_' + index;
	var currMoreDiv = document.getElementById(more_temp);
	var temp1 = 'attachment_' + nextIndex;
	var nextDiv = document.getElementById(temp1);
	var temp1_more = 'more_' + nextIndex;
	var nextMoreDiv = document.getElementById(temp1_more);
	currMoreDiv.style.display = 'none';
	nextDiv.style.display = '';
	if (nextMoreDiv != null) {
  	nextMoreDiv.style.display = '';
  }
	else {
		document.getElementById('no_more').innerHTML = "No more attachments are allowed";
		document.getElementById('no_more').style.display="";
	}
}
function showMoreLinks(index, nextIndex){
	var more_temp = 'more_' + index;
	var currMoreDiv = document.getElementById(more_temp);
	var temp1 = 'link_' + nextIndex;
	var nextDiv = document.getElementById(temp1);
	var temp1_more = 'more_' + nextIndex;
	var nextMoreDiv = document.getElementById(temp1_more);
	currMoreDiv.style.display = 'none';
	nextDiv.style.display = '';
	if (nextMoreDiv != null) {
          nextMoreDiv.style.display = '';
        }
}

function showMoreReferences(index, nextIndex){
	var more_temp = 'more_reference_' + index;
	var currMoreDiv = document.getElementById(more_temp);
	var temp1 = 'reference_' + nextIndex;
	var nextDiv = document.getElementById(temp1);
	var temp1_more = 'more_reference_' + nextIndex;
	var nextMoreDiv = document.getElementById(temp1_more);
	currMoreDiv.style.display = 'none';
	nextDiv.style.display = '';
	if (nextMoreDiv != null) {
          nextMoreDiv.style.display = '';
        }
}

function showMoreContacts(index, nextIndex){
  var more_temp = 'more_span_' + index;
	var currMoreDiv = document.getElementById(more_temp);
	var temp1 = 'link_' + nextIndex;
	var nextDiv = document.getElementById(temp1);
	var temp1_more = 'more_' + nextIndex;
	var nextMoreDiv = document.getElementById(temp1_more);
	currMoreDiv.style.display = 'none';
	nextDiv.style.display = '';
	if (nextMoreDiv != null) {
          nextMoreDiv.style.display = '';
        }
}

function validate_and_submit_qa_credits(total_credits,update_div,credit_field,div_id){
    var credit_input_box = document.getElementById('credits').value;
    
    if (credit_input_box == ""){
	document.getElementById('credits_error').innerHTML = "Cannot be blank"
        return false;
     }
     var integer_regex = /^[0-9]+$/;
    if (!credit_input_box.match(integer_regex)){
        document.getElementById('credits_error').innerHTML = "Credits should be integer"
        return false;
     }    
    if(credit_input_box <= 0){
        document.getElementById('credits_error').innerHTML = "Credits should be greater than 0"
        return false;
    }
    
    if(credit_input_box > total_credits){
        document.getElementById('credits_error').innerHTML = "Cannot be more than "+total_credits +"."
        return false;
    }
    var up_div = document.getElementById(update_div);
    up_div.innerHTML = "  Credits:" + credit_input_box +'  <a href="javascript:callFloat(350,\'\',1,\'\');" >Edit</a>';
    up_div.style.display = '';
    document.getElementById(credit_field).value = credit_input_box;
    
    
    closeFloat(div_id);
    return true;
    
}

function showQuestionAddDetails(obj){
	
    var answerPanel = document.getElementById('optional');
	
    answerPanel.style.display='';

}

function hideQuestionAddDetails(obj){
	
   var answerPanel = document.getElementById('optional');
   var answerText = document.getElementById('qa_question_detail');
	
   answerPanel.style.display='none';
   answerText.value = '';
   
   show_decreasing_char_count(answerText, 5000,'question_detail_length_span');
	
}

function clearQuestionOptionalFields(){
    var tagList = document.getElementById('qa_question_tag_list');
    tagList.value = '';
    
}

function changeTabClass2(tabnum){
	
	var tabAnswersByUser = document.getElementById("tabAnswersByUser");
	var tabDoubtsByUser = document.getElementById("tabDoubtsByUser");

	
	
	var contentUserAnswer = document.getElementById("contentUserAnswer");
	var contentDoubts = document.getElementById("contentDoubts");

	
	
	if(tabnum == 1)
	{
            if(tabAnswersByUser)
                tabAnswersByUser.className="selected";
        
            if(tabDoubtsByUser)
                tabDoubtsByUser.className="";
        
            if(contentUserAnswer)
                contentUserAnswer.style.display="";
        
            if(contentDoubts)
                contentDoubts.style.display="none";
            
        }
	
	else if(tabnum == 2)
	{
	if(tabAnswersByUser)	
            tabAnswersByUser.className="";
	if(tabDoubtsByUser)	
            tabDoubtsByUser.className="selected";

	
	if(contentUserAnswer)
            contentUserAnswer.style.display="none";
        if(contentDoubts)
            contentDoubts.style.display="";
	
	}	
	

}

function showProvideClarification(obj){
	
	var buttonClarify = document.getElementById('buttonClarify');
	var clarificationPanel = document.getElementById('clarificationPanel');
	
	if(buttonClarify)
            buttonClarify.style.display='none';
	clarificationPanel.style.display='';
	
	
	
}

function showAnswers(obj){
	
	var buttonAnswer = document.getElementById('buttonAnswer');
	var answerPanel = document.getElementById('answerPanel');
	
	var buttonSeekClarification = document.getElementById('buttonSeekClarification');
	var seekClarificationPanel = document.getElementById('seekClarificationPanel');
	
	
	buttonAnswer.style.display='none';
	answerPanel.style.display='';
	
	buttonSeekClarification.style.display='none';
	seekClarificationPanel.style.display='none';
	
	
	
}

function hideAnswers(obj){
	
	var buttonAnswer = document.getElementById('buttonAnswer');
	var answerPanel = document.getElementById('answerPanel');
	
	var buttonSeekClarification = document.getElementById('buttonSeekClarification');
	var seekClarificationPanel = document.getElementById('seekClarificationPanel');
	
	
	buttonAnswer.style.display='';
	answerPanel.style.display='none';
	

	buttonSeekClarification.style.display='';
	seekClarificationPanel.style.display='none';

}

function showSeekClarification(obj){
	
	var buttonAnswer = document.getElementById('buttonAnswer');
	var answerPanel = document.getElementById('answerPanel');
	
	var buttonSeekClarification = document.getElementById('buttonSeekClarification');
	var seekClarificationPanel = document.getElementById('seekClarificationPanel');
	
	
	buttonAnswer.style.display='none';
	answerPanel.style.display='none';
	
	buttonSeekClarification.style.display='none';
	seekClarificationPanel.style.display='';
	
	}

function hideSeekClarification(obj){
	
	var buttonAnswer = document.getElementById('buttonAnswer');
	var answerPanel = document.getElementById('answerPanel');
	
	var buttonSeekClarification = document.getElementById('buttonSeekClarification');
	var seekClarificationPanel = document.getElementById('seekClarificationPanel');
	
	
	buttonAnswer.style.display='';
	answerPanel.style.display='none';
	
	buttonSeekClarification.style.display='';
	seekClarificationPanel.style.display='none';
	}
        
        
 function hideProvideClarification(div_id,button_id,outer_div_id){
	var clarificationPanel = document.getElementById(div_id);
	clarificationPanel.style.display='none';
        var button_div = document.getElementById(button_id);
        if(button_div)
            button_div.style.display='';
        var div_name = 'qa_clarification_content'+outer_div_id;
        var text_content_div = document.getElementById(div_name);
        if(text_content_div){
            text_content_div.value = '';
        }
        
}
function addSelectedContactsToBackGroundForm(){
  var selectedContactsDiv = document.getElementById('selectedContacts');
  var selectedContacts = selectedContactsDiv.childNodes;
  var contact_list_div    = document.getElementById('contactList');
  contact_list_div.style.display= '';
  contact_list_div.innerHTML = '';
  var submitButton = document.inviteContactsForm.elements[ document.inviteContactsForm.elements.length - 1 ]; 
  var unhideSubmitButton = 1;
  submitButton.onclick = function(){document.getElementById('no_contacts_selected_error').style.display = '';return false;};
  for(i=0; i<selectedContacts.length; ++i){
    if(selectedContacts[i].tagName == "DIV"){
      if(unhideSubmitButton == 1){
       contact_list_div.innerHTML = '<div class="blueHeads floatLeft">Selected Contact(s)</div><br/><div class="clear"></div>';
       var contact_list = document.createElement('ul');
       contact_list.setAttribute('id','contactUl');
       contact_list_div.appendChild(contact_list);
       unhideSubmitButton = 0;
      }
      var contact_id   = selectedContacts[i].id.split('contact')[1].split('Div')[0];
      var contact_name = selectedContacts[i].innerHTML.split(/<(a|A)/)[0];
      var li_elem = document.createElement('li');
      li_elem.innerHTML = contact_name + '<input type="hidden" name="contact_ids[]" value="'+contact_id+'" />';
      contact_list.appendChild(li_elem);
    }
  }
 
  if (unhideSubmitButton == 0) {
   submitButton.onclick = function(){document.inviteContactsForm.submit();return true};
   document.getElementById('no_contacts_selected_error').style.display = 'none';
  }
  close_contacts();
  return false;
}

function addSelectContactsToForm(){
    
    var optionsToContact = document.getElementById('qa_invitation_toContact').options;
    var selectedContactIds = '';
    if(optionsToContact.length == 0){
        document.getElementById('qa_invite_not_selected').innerHTML = 'Please select Contact(s) to invite.';
        return false;
    }
    for(var i=0; i<optionsToContact.length; ++i){    
        selectedContactIds +=optionsToContact[i].value+",";
    }
    document.getElementById('qa_invitation_to_contact').value = selectedContactIds;
    document.inviteContactsForm.submit(); 
    return true;
    
}


function clearCredits(){
    var paid_div = document.getElementById('qa_question_paid_true');
    if (paid_div.checked){
        var credits_div = document.getElementById('qa_credits');
        credits_div.style.display='';
    }
    else{
    var credits_div = document.getElementById('qa_credits');
    credits_div.style.display='none';
    var credit_text_field = document.getElementById('qa_question_credits');
    if(credit_text_field)
        credit_text_field.value = '';
    var credit_text_field_error = document.getElementById('qa_question[credits]_val_error');
    if(credit_text_field_error)
        credit_text_field_error.innerHTML = '';
    }

}

function showQuestionOptionalFields(){
    var optional_fields_div = document.getElementById('optional_question_fields');
    var displayStyle = optional_fields_div.style.display;
    if(displayStyle == 'none'){
        optional_fields_div.style.display = '';
    }else{
        optional_fields_div.style.display = 'none';
        document.getElementById('qa_question_tag_list').value = '';
        document.getElementById('qa_question_embed_code').value = '';
        document.getElementById('qa_question_upload1').value = '';
        document.getElementById('qa_question_upload2').value = '';
        document.getElementById('qa_question_upload3').value = '';
        
    }
}

function buyCredits(){
    $('buy_credits').value=1;
    var ask_form = document.getElementById('ask_form');
    ask_form.submit();
}

function showClarifications(show){
    if(show==true){
        document.getElementById('all_clarifications').style.display='';
    }else{
        document.getElementById('all_clarifications').style.display='none';
    }
}

function updateMainMediaDiv(div_id,main_div_id){
    f_div_id = 'main_media_div'+main_div_id
    var main_media_div = document.getElementById(f_div_id);
    if(main_media_div){
    if(div_id=='main_media_div')
       main_media_div.style.display='';
     else
       main_media_div.style.display='none';
    }
    f_div_id = 'main_image_div1'+main_div_id
    var main_image_div1 = document.getElementById(f_div_id);
    if(main_image_div1){
        if(div_id=='main_image_div1')
            main_image_div1.style.display='';
         else
            main_image_div1.style.display='none';
         
    }
    f_div_id = 'main_image_div2'+main_div_id
    var main_image_div2 = document.getElementById(f_div_id);
    if(main_image_div2){
        if(div_id=='main_image_div2')
            main_image_div2.style.display='';
         else
            main_image_div2.style.display='none';
         
    }
    f_div_id = 'main_image_div3'+main_div_id
    var main_image_div3 = document.getElementById(f_div_id);
    if(main_image_div3){
        if(div_id=='main_image_div3')
            main_image_div3.style.display='';
         else
            main_image_div3.style.display='none';
         
    }
}

function make_filter_url(original_url, milestone_id, priority, assignee, status) {
	var index = original_url.indexOf('?');
	if (index != -1)
		var act_url = original_url.substring(0,index);
	else
		var act_url = original_url;
	var url_string = '';
	if (milestone_id != null)
		url_string = "?milestone_id=" + milestone_id;
	if (priority != null) {
		if (url_string == '')
			url_string = "?priority=" + priority;
		else
			url_string += "&priority=" + priority;
	}
	if (assignee != null) {
		if (url_string == '')
			url_string = "?assignee=" + assignee;
		else
			url_string += "&assignee=" + assignee;
	}
	if (status != null) {
		if (url_string == '')
			url_string = "?status=" + status;
		else
			url_string += "&status=" + status;
	}
	return (act_url + url_string);
}

// Tooltip JS Starts here //


function HideTooltip(d) {
if(d.length < 1) {return;}
document.getElementById(d).style.display = "none";
}
function ShowTooltip(e, d, left, top_margin) {  
//if(d.length < 1) { return; }
left = (left == null)? 0 : left
top_margin = (top_margin == null)? 0 : top_margin
var dd = document.getElementById(d);
//AssignPosition(dd);
  evt = window.event || e;
  st = document.body.scrollTop || document.documentElement.scrollTop;
  dd.style.left = evt.clientX - document.getElementById('contentwrapper1').offsetLeft + 10 + left + "px";
  var x = evt.clientY + st - document.getElementById('contentwrapper1').offsetTop;
  if((x + 40 + 20) > document.getElementById('contentwrapper1').clientHeight)
   x = x - 40 - 20; 
  dd.style.top = x + top_margin + "px";
  dd.style.display ="block";
}
function ShowTooltipNew(e, d, x) {  
//if(d.length < 1) { return; }
var dd = document.getElementById(d);
//AssignPosition(dd);
  evt = window.event || e;
  st = document.body.scrollTop || document.documentElement.scrollTop;
  dd.style.left = evt.clientX - document.getElementById(x).offsetLeft + 10 + "px";
  var x = evt.clientY + st - document.getElementById(x).offsetTop;
  //if((x + 40 + 20) > document.getElementById(x).clientHeight)
   x = x - 40 - 20; 
  dd.style.top = x + "px";
  dd.style.display ="block";
}


function ShowTooltipInExpandedBlock(e, d) {
//if(d.length < 1) { return; }
var dd = document.getElementById(d);
//AssignPosition(dd);
  evt = e;
  st = document.body.scrollTop || document.documentElement.scrollTop;
  dd.style.left = evt.clientX - document.getElementById('contentwrapper1').offsetLeft - 10  +"px";
  var x = evt.clientY + st - document.getElementById('contentwrapper1').offsetTop;
  if((x + 40 + 20) > document.getElementById('contentwrapper1').clientHeight)
   x = x - 40 - 20;
  //dd.style.top = x + "px";
  dd.style.display ="block";
}

function ToggleNote(e, d, prefixes){
  var dd = document.getElementById(d);
  if(dd){
    if(dd.visible()){
      dd.hide();
    }
    else{
      HideAllNotes(prefixes);
      var evt = e;
      var st = document.body.scrollTop || document.documentElement.scrollTop;
      dd.style.left = evt.clientX - document.getElementById('contentwrapper1').offsetLeft - 10  +"px";
      var x = evt.clientY + st - document.getElementById('contentwrapper1').offsetTop;
      if((x + 40 + 20) > document.getElementById('contentwrapper1').clientHeight)
        x = x - 40 - 20;
      dd.style.top = x + "px";
      dd.style.display ="block";
    }
  }
}

function HideAllNotes(prefixes){
  prefixes.each(function(prefix){
    $$('div.tooltips1[id^='+prefix+']').each(function(note_div){
      note_div.hide();
    })
  });
}

function showNoteTextArea(textarea, div, bid_id){
  div.hide();
  textarea.show();
  textarea.focus();
  var suffix = "";
  if(bid_id){
    suffix = "_"+bid_id
  }
  $('note_actions'+suffix).hide();
  $('form_actions'+suffix).show();
}
function hideNoteTextArea(textarea, div, bid_id){
  textarea.hide();
  //textarea.blur();
  div.show();
  var suffix = "";
  if(bid_id){
    suffix = "_"+bid_id
  }
  $('note_actions'+suffix).show();
  $('form_actions'+suffix).hide();
}

function setNoteIcon(note_content, img){
  if(img){
    if(note_content == null || note_content.empty()){
      img.src="/images/add-notes-icon.gif";
      img.setAttribute("alt", "Add a Note");
      img.setAttribute("title", "Add a Note");
    }
    else{
      img.src="/images/notes-icon.gif";
      img.setAttribute("alt", "View Note");
      img.setAttribute("title", "View Note");
    }
  }
}

function showTT(e){
  evt = window.event || e;
  alert(evt.clientX + "-" + evt.clientY);
}

function xhtmlShowTooltip(d) {  
if(d.length < 1) {return;}
var dd = document.getElementById(d);
//AssignPosition(dd);
dd.style.left = (X - 200)  + 'px';
dd.style.top = (Y - 200)+  'px';
dd.style.display = "block";
}

function ReverseContentDisplay(d) {
if(d.length < 1) {return;}
var dd = document.getElementById(d);
AssignPosition(dd);
if(dd.style.display == "none") {dd.style.display = "block";}
else {dd.style.display = "none";}
}


// Tooltip JS Ends here //


function showHiddenCategories(){
    allElements = document.getElementsByName('category_name[]');
    for(var i=0; i < allElements.length;i++){
		allElements[i].style.display = '';
		
		
	}
        
    allSpacers = document.getElementsByName('category_spacer[]');
    for(var i=0; i < allSpacers.length;i++){
		allSpacers[i].style.display = '';
		
		
	}	
}



function show_char_count(element, char_count_span_id){
  var element_val = element.value;
  var length = element_val.length;
  char_count_span = document.getElementById(char_count_span_id);
  char_count_span.innerHTML = length  
}

function show_decreasing_char_count(element, total_count,char_count_span_id){
  var element_val = element.value;
  var length = element_val.length;
  char_count_span = document.getElementById(char_count_span_id);
  char_count_span.innerHTML = total_count - length   
}

function showProfileSummary(userId){
  summaryElementId = 'profile_summary_' + userId;
  summaryElement = document.getElementById(summaryElementId);
  if (summaryElement.innerHTML == ''){
    new Ajax.Updater(summaryElementId, '/user/profile_summary/'+userId, {asynchronous:true, evalScripts:true});return false;
  }else{
    summaryElement.style.display='';
  } 
}

function hideProfileSummary(userId){
  summaryElementId = 'profile_summary_' + userId;
  document.getElementById(summaryElementId).style.display='none';
}

/* Tooltip related scripts : Start*/
function showToolTip(tipElementId, tipUrl){
  var tipElement = document.getElementById(tipElementId);
  if (tipElement.innerHTML == ''){
    new Ajax.Updater(tipElementId, tipUrl, {asynchronous:true, evalScripts:true}); 
  }
  //clearTimeout(timer);
  //tipElement.style.left = X + 10;
  //tipElement.style.top = Y + 10;
  tipElement.style.display='';
  //timer = window.setTimeout("hideToolTip('" + tipElementId +"');",3000);
  return false;
}

function showBoxHover(tipElementId){
  var tipElement = document.getElementById(tipElementId);
  
  //clearTimeout(timer);
  if(navigator.appName == "Microsoft Internet Explorer"){
    tipElement.style.left = X-210;
    tipElement.style.top = (Y-180)+ "px";
  }
  else{
    tipElement.style.left = X-250;
    tipElement.style.top = Y+10;
  }
  tipElement.style.display='';
  //timer = window.setTimeout("hideToolTip('" + tipElementId +"');",3000);
  return false;
}

function showBoxSlideShare(tipElementId){
  var tipElement = document.getElementById(tipElementId);
  
  //clearTimeout(timer);
  tipElement.style.left = X-5;
  tipElement.style.top = Y+6;
  tipElement.style.display='';
  //timer = window.setTimeout("hideToolTip('" + tipElementId +"');",3000);
  return false;
}

function hideToolTip(tipElementId){
    if (mouse_over == "1"){
      clearTimeout(timer);
      timer = window.setTimeout("hideToolTip('" + tipElementId +"');",200);
      return;
    }
    tipElement = document.getElementById(tipElementId);
    tipElement.style.display='none';
}
function setToolTipMouseOver()
{
	clearTimeout(timer);
}

function resetToolTipMouseOver(tipElementId)
{document.getElementById(tipElementId).setAttribute("show","off");
       timer = window.setTimeout("hideToolTip('" + tipElementId +"');",2);
       
}


/* Tooltip related scripts : End*/
function resetShortlistedsort(td_id){
  td = $(td_id);
  table = td.parentNode.parentNode.parentNode;
  headrow = table.tHead.rows[0].cells;
  for (var i=0; i<headrow.length; i++){
    if(headrow[i].id == "shortlistedhead"){
      if(headrow[i].className.search(/\bsorttable_sorted_reverse\b/) != -1){
        headrow[i].className = headrow[i].className.replace('sorttable_sorted_reverse','');
        break;
      }
      if(headrow[i].className.search(/\bsorttable_sorted\b/) != -1){
        headrow[i].className = headrow[i].className.replace('sorttable_sorted','');
        break;
      }
    }
  }
  sorttable.init();
}

/********************************************** 
* Functions for Import Contacts Feature : Start
* By Jagadish Rath
***********************************************/
function selectDeselectAllContacts(select_all_checkbox, checkbox_name){
  var allCheckBoxes = document.getElementsByName(checkbox_name);
  for(var i = 0; i< allCheckBoxes.length; i++){
    selectDeselectContact(allCheckBoxes[i], select_all_checkbox.checked);
  }
}
function selectDeselectContact(checkbox, select){
  var td = checkbox.parentNode;
  var tr = td.parentNode;
  checkbox.checked = select;
  tr.className = (select)? 'messageSelected' : '';
}
/********************************************** 
* Functions for Import Contacts Feature : End
* By Jagadish Rath
***********************************************/


/********************************************** 
* Functions for Advanced Bids Search : Start
* By Jagadish Rath
***********************************************/

function evaluateCriterion(row, criterionAttribute, criterion){
  if (criterion == 'Any' || criterion == '' ){return true;}
  if (!row.attributes[criterionAttribute]){return false;}
  if (row.attributes[criterionAttribute].value == criterion){return true;}
  return false;
}
function evaluateCriterionRange(row, criterionAttribute, criterion, stringEvaluationFunction){
  if (criterion['lower_limit'] == '' && criterion['upper_limit'] == ''){return true;}
  if (!row.attributes[criterionAttribute]){return false;}
  var lower_limit_evaluation = false;
  var upper_limit_evaluation = false;
  if(criterion['lower_limit'] != ''){
    if (stringEvaluationFunction(row.attributes[criterionAttribute].value) >= stringEvaluationFunction(criterion['lower_limit'])){lower_limit_evaluation = true;}
  }else{
   lower_limit_evaluation =true; 
  }
  if(criterion['upper_limit'] != ''){
    if (stringEvaluationFunction(row.attributes[criterionAttribute].value) <= stringEvaluationFunction(criterion['upper_limit'])){upper_limit_evaluation = true;}
  }else{
    upper_limit_evaluation = true;
  }
  return (lower_limit_evaluation && upper_limit_evaluation);
}
function evaluateCriterionStringMatch(row, criterionAttribute, criterion){
  if (criterion == ''){return true;}
  if (!row.attributes[criterionAttribute]){return false;}
  if (row.attributes[criterionAttribute].value.toLowerCase().search(new RegExp(criterion.toLowerCase())) != -1){
     return true;
  }
  return false;
}

function showAdvancedSearchBids(apply_advanced_options){
  
  var bidsTable = document.getElementById('bids_table');
  var rows = bidsTable.rows;
  var bids_filter_type            = GetRadioElementValue(document.getElementsByName('bids_filter_type'));
  if (!Validate(document.advancedBidSearchForm)) return;
  if(apply_advanced_options){
    var TOE_criterion               = document.advancedBidSearchForm['advanced_bid_search_TOE_status'].value;
    var POC_criterion               = document.advancedBidSearchForm['advanced_bid_search_POC_status'].value;
    var amount_criterion            = 
    { 
   
      lower_limit: ValidateNumber(document.advancedBidSearchForm['advanced_bid_search_amount_lower_limit'])? document.advancedBidSearchForm['advanced_bid_search_amount_lower_limit'].value : '', 
      upper_limit: ValidateNumber(document.advancedBidSearchForm['advanced_bid_search_amount_upper_limit'])? document.advancedBidSearchForm['advanced_bid_search_amount_upper_limit'].value : ''
    };
    var delivery_duration_criterion = 
    {
      lower_limit: ValidateNumber(document.advancedBidSearchForm['advanced_bid_search_delivery_duration_lower_limit'])? document.advancedBidSearchForm['advanced_bid_search_delivery_duration_lower_limit'].value : '', 
      upper_limit: ValidateNumber(document.advancedBidSearchForm['advanced_bid_search_delivery_duration_upper_limit'])? document.advancedBidSearchForm['advanced_bid_search_delivery_duration_upper_limit'].value : ''
    };
    var received_date_criterion     = {lower_limit: document.advancedBidSearchForm['advanced_bid_search_received_date_lower_limit'].value, 
                                     upper_limit: document.advancedBidSearchForm['advanced_bid_search_received_date_upper_limit'].value};
  }
  
  var total_bids_elem = document.getElementById('bids_count');
  var total_bids = 0;
  for(var i=1; i<rows.length; i++){//i=1 to exclude the header
    var row = rows[i];
    
    if (row.attributes['searchable'] && row.attributes['searchable'].value == 'true'){
        var eligible = true;
        switch(bids_filter_type){
          case 'All':
            break;
          case 'New Bids':
            eligible = eligible && evaluateCriterion(row, 'bid_status', 'New');
            break;
          case 'Shortlisted Bids':
            eligible = eligible && evaluateCriterion(row, 'shortlisted', 'shortlisted');
            break;
          case 'TOE Agreed Bids':
            eligible = eligible && evaluateCriterion(row, 'TOE_status', 'Agreed');
            break;
          case 'Under POC Bids':
            eligible = eligible && !evaluateCriterion(row, 'POC_status', 'Not Started');
            break;
          case 'Vantage Bids' :
            eligible = eligible && evaluateCriterion(row, 'vantage', 'Vantage');
            break;
          case 'Credential Bids' :
            eligible = eligible && evaluateCriterion(row, 'credentials', 'true');
            break;
          default:
        }
       // Evaluate the Search criteria
       if (apply_advanced_options){
         eligible = (eligible && 
                     evaluateCriterion(row,'TOE_status', TOE_criterion) && 
                     evaluateCriterion(row, 'POC_status', POC_criterion) && 
                     evaluateCriterionRange(row, 'amount', amount_criterion, function(str){return parseFloat(str);}) && 
                     evaluateCriterionRange(row, 'delivery_duration', delivery_duration_criterion, function(str){return parseFloat(str);}) && 
                     evaluateCriterionRange(row, 'received_date', received_date_criterion, function(str){return str;}));
       }
       if(eligible){total_bids += 1;}
       showHideRowAndSpacer(i, rows, eligible);
    }
  }
  total_bids_elem.innerHTML = ''+total_bids;
  checkUncheckSelectAllCheckbox();
}

function checkUncheckSelectAllCheckbox(){
  var checkboxes = document.getElementsByName('selected_bid_ids[]');
  var check_value = "";
  for(var i=0; i < checkboxes.length; i++){
     var row = checkboxes[i].parentNode.parentNode;
     if(row.style.display != 'none'){
       if (check_value == ""){check_value = true;}
       check_value = check_value && checkboxes[i].checked;
       if (!check_value){break;}
     }
  }
  if (document.getElementsByName('select_deselect_all_visible_bids_checkbox')[0]){
    document.getElementsByName('select_deselect_all_visible_bids_checkbox')[0].checked = (check_value == "")? false : check_value;
  }
}


function showHideRowAndSpacer(i, rows, eligible){
  //alert('i= '+ i + ', eligible = '+ eligible);
  if(eligible){
    rows[i].style.display= '';//show the Element
    if((i+1) < rows.length){ //show the Spacer
      rows[i+1].style.display= '';
    }
  }else{
    rows[i].style.display= 'none';//show the Element
    if((i+1) < rows.length){ //show the Spacer
      rows[i+1].style.display= 'none';
    }
  }
}
function selectDeselectAllVisibleRows(mainCheckbox, checkboxName){
  var checkboxes = document.getElementsByName(checkboxName);
  for(var i=0; i < checkboxes.length; i++){
     var row = checkboxes[i].parentNode.parentNode;
     if(row.style.display != 'none'){
       checkboxes[i].checked = mainCheckbox.checked;
       row.className = (mainCheckbox.checked)? 'messageSelected' : '';
     }
  }
}

function atLeastOneSelected(checkboxName){
  var checkboxes = document.getElementsByName(checkboxName);
  checkboxes_length = checkboxes.length
  at_least_one_selected = false;
  for(var i=0; i < checkboxes_length; i++){
     var row = checkboxes[i].parentNode.parentNode;
     if(row.style.display != 'none' && checkboxes[i].checked == true){
       at_least_one_selected = true;
       break;
     }
  }
  return at_least_one_selected;
}

function selectDeselectAllVisibleRows1(mainCheckbox, checkboxName){
  var checkboxes = document.getElementsByName(checkboxName);
  for (var i = 0; i < checkboxes.length; i++) {
    var row = checkboxes[i].parentNode.parentNode;
    if (row.style.display != 'none') {
      checkboxes[i].checked = mainCheckbox.checked;
      if(mainCheckbox.checked) row.className = 'rowSelected' ;
      else row.className = (row.getAttribute('vantage') == 'Vantage') ? 'vantagebid' : '';
    }
  }
}

function update_total_poc_amount(checkboxName, poc_amount, span_id){
  var total_amount = 0.00
  if(poc_amount > 0){  
  var checkboxes = document.getElementsByName(checkboxName);
  for(var i=0; i < checkboxes.length; i++){
    if(checkboxes[i].checked == true){
      total_amount = total_amount + poc_amount;
    }
  }
  var total_amount_span = document.getElementById(span_id)
  if(total_amount_span!=null) 
  total_amount_span.innerHTML = total_amount + " USD"
  }  
}


/********************************************** 
* Functions for Advanced Bids Search : End
* By Jagadish Rath
***********************************************/

function hideAffiliationsAnchorLink(){
    var anchor_link_info = document.getElementById('anchor_link_info');
    anchor_link_info.style.display='none';
}


function showHideProjDesc(show_desc){
    if(show_desc == true){
        document.getElementById('proj_desc_hidden').style.display='';
        document.getElementById('proj_desc').style.display='none';
    }else{
        document.getElementById('proj_desc_hidden').style.display='none';
        document.getElementById('proj_desc').style.display='';
    }
}

function showHideQATags(show_tags){
    if(show_tags == true){
        document.getElementById('hidden_tag_list').style.display='';
        document.getElementById('default_tag_list').style.display='none';
    }else{
        document.getElementById('hidden_tag_list').style.display='none';
        document.getElementById('default_tag_list').style.display='';
    }
}

function changeURLHelp(obj,show_strong){
   if(obj.value=="1"){
    document.getElementById("slidedharehelp").style.display='none';
    document.getElementById("youtubehelp").style.display='';
    if(show_strong==true)
    document.getElementById("media_code").innerHTML = "<strong>YouTube URL</strong>:";
    else
     document.getElementById("media_code").innerHTML = "YouTube URL:";
   }else{
   document.getElementById("slidedharehelp").style.display='';
   document.getElementById("youtubehelp").style.display='none';
   if(show_strong==true)
   document.getElementById("media_code").innerHTML = "<strong>SlideShare Code</strong>:";
   else
   document.getElementById("media_code").innerHTML = "SlideShare Code:";
    }
    
}

function showTipEvent(){
    
}
function toggleHelpMenu(objID) {
    if (!document.getElementById) return;
    var ob = document.getElementById(objID).style;
    ob.display = (ob.display == 'block')?'none': 'block';
}

//Move Select From and To options
function addOption(theSel, theText, theValue){
	var newOpt = new Option(theText, theValue);
  	var selLength = theSel.length;
  	theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex){ 
  	var selLength = theSel.length;
  	if(selLength>0){
    	theSel.options[theIndex] = null;
  	}
}

function moveOptions(theSelFrom, theSelTo){  
  	var selLength = theSelFrom.length;
  	var selectedText = new Array();
  	var selectedValues = new Array();
  	var selectedCount = 0;  
  	var i; 
  
  	for(i=selLength-1; i>=0; i--){
    	if(theSelFrom.options[i].selected){    		
      		selectedText[selectedCount] = theSelFrom.options[i].text;
      		selectedValues[selectedCount] = theSelFrom.options[i].value;
      		deleteOption(theSelFrom, i);
      		selectedCount++;
    	}
  	}
	
  	for(i=selectedCount-1; i>=0; i--){
    	addOption(theSelTo, selectedText[i], selectedValues[i]);
  	}
  	
}

function moveAllOptions(theSelFrom, theSelTo){  
  	var selLength = theSelFrom.length;
  	var selectedText = new Array();
  	var selectedValues = new Array();
  	var selectedCount = 0;  
  	var i; 
  
  	for(i=selLength-1; i>=0; i--){
    	   		
      		selectedText[selectedCount] = theSelFrom.options[i].text;
      		selectedValues[selectedCount] = theSelFrom.options[i].value;
      		deleteOption(theSelFrom, i);
      		selectedCount++;
    	
  	}
	
  	for(i=selectedCount-1; i>=0; i--){
    	addOption(theSelTo, selectedText[i], selectedValues[i]);
  	}
  	
}
function getFormValues(id){
	var thisSel = document.getElementById(id);
	var selectedValues = new Array();
	var str = "";
	
	for(var i=0; i<thisSel.length-1; i++){
		str = str + thisSel.options[i].value + ",";
	}
	if(thisSel.length > 0){
		str = str + thisSel.options[thisSel.length-1].value;	
		document.getElementById("selectStr").value = str;
	}	
	return true;
}


/********************************************** 
* Functions Fetching PMB Messages : Start
* By Jagadish Rath
***********************************************/

function showPmbMessages(bid_id, fetchLinkId, compose){
  compose=compose||false;
  updateElementId    = 'messages_content_'+bid_id;
  displayParentElementId   =  'pmb_messages_'+bid_id+'_row';
  displayElementId   =  'messages_widget_'+bid_id;
  fetchLink = document.getElementById(fetchLinkId);
  if (!($('message_compose_'+bid_id).style.display=='' && $(displayParentElementId).style.display=="" && !(fetchLink.attributes['showingPmbMessages'] && fetchLink.attributes['showingPmbMessages'].value == "true")))
  toggleDisplay(displayParentElementId);
  toggleDisplay(displayElementId);
  if (!fetchLink.attributes['showingPmbMessages'])
  {
    indicatorElementId = 'messages_fetching_indicator_'+bid_id;
    indicatorElement = document.getElementById(indicatorElementId);
    indicatorElement.style.display = '';
    new Ajax.Updater(updateElementId, '/bids/show_communication/'+bid_id, {asynchronous:true, evalScripts:true, onComplete:(function(){indicatorElement.style.display='none';if(compose)$('message_compose_'+bid_id).show();})});
      fetchLink.setAttribute('showingPmbMessages', "true");
      fetchLink.innerHTML = '[-] Messages';
      fetchLink.style.backgroundColor = "#D5EDFB";
    return false;
  }
  if (fetchLink.attributes['showingPmbMessages'] && fetchLink.attributes['showingPmbMessages'].value == "true")
  {
    fetchLink.setAttribute('showingPmbMessages', "false");
    fetchLink.innerHTML = '[+] Messages';
    fetchLink.style.backgroundColor = "";
    return false;
  }
  if (fetchLink.attributes['showingPmbMessages'] && fetchLink.attributes['showingPmbMessages'].value == "false")
  {
    fetchLink.setAttribute('showingPmbMessages', "true");
    fetchLink.innerHTML = '[-] Messages';
    fetchLink.style.backgroundColor = "#D5EDFB";
    if(compose)$('message_compose_'+bid_id).show();
    return false;
  }
    return false;
}
function refreshPmbMessages(bid_id){
  updateElementId    = 'messages_content_'+bid_id;
  indicatorElementId = 'messages_fetching_indicator_'+bid_id;
  indicatorElement = document.getElementById(indicatorElementId);
  indicatorElement.style.display = '';
  new Ajax.Updater(updateElementId, '/bids/show_communication/'+bid_id, {asynchronous:true, evalScripts:true, onComplete:(function(){indicatorElement.style.display='none';})});
  return false;
}
function submitPmbMessage(url, formObj, messageSendingIndicatorId, containerId){
  if (Validate(formObj))
  {
    messageSendingIndicator = document.getElementById(messageSendingIndicatorId);
    container = document.getElementById(containerId);
    if(messageSendingIndicator != null){
      //Sometimes we do not keep any thing like "message indicator". So its painful.
     messageSendingIndicator.style.display = '';
    }
    //new Ajax.Request(formObj.action, {asynchronous:true, evalScripts:true, parameters:Form.serialize(formObj), onComplete:(function(){messageSendingIndicator.style.display='none';container.style.display='none'; formObj.reset();})}); return false;
    return true;
  }
  return false;
}

/********************************************** 
* Functions Fetching PMB Messages : End
* By Jagadish Rath
***********************************************/

//Function to search online tests. Author: Jay Prakash. Date:01/09/08

function search_online_tests(test_title, table_rows){
  var no_result = true;
  for(var i=0; i<table_rows.length; i++){
    var row = table_rows[i];
    if(!(evaluateCriterionStringMatchIndexOf(row, 'test_title', test_title))){
      showHideRowAndSpacer(i, table_rows, false);
    }
    else{
      showHideRowAndSpacer(i, table_rows, true);
      no_result = false;
    }
  }
  if(no_result){
      document.getElementById("no_results").innerHTML = "No Result";
  }
}

function evaluateCriterionStringMatchIndexOf(row, criterionAttribute, criterion){
  if (criterion == ''){return true;}
  if (!row.attributes[criterionAttribute]){return false;}
  if (row.attributes[criterionAttribute].value.toLowerCase().indexOf((criterion.toLowerCase())) != -1){
     return true;
  }
  return false;
}

function showBoxHoverEntry(tipElementId){
    var left = 0;
    var top = 0;
    var isBrowserIE = false;
    var scrollTop = 0;
    if(navigator.appName == "Microsoft Internet Explorer")
        isBrowserIE = true;
    var tipElement = document.getElementById(tipElementId);
    if (tipElement.getAttribute('show') == "on") return;
    
    tipElement.setAttribute("show","on");
    left = parseInt(X) + 40;
    if(left + 420 > window.screen.width)
        left = parseInt(X) - 460;
    
    top = parseInt(Y) - 250;
    if(isBrowserIE) 
        scrollTop = top + document.documentElement.scrollTop;
    else 
        scrollTop =  top;
    
    if((scrollTop + 250) > window.screen.height){
        top = parseInt(Y) - 450;
    }  
    else if(top < document.documentElement.scrollTop)
        top = parseInt(Y);
    if(isBrowserIE)
        top  += parseInt(document.documentElement.scrollTop);
    
    tipElement.style.left = left + 'px';
    tipElement.style.top =  top + 'px';
    tipElement.style.display='block';
    
    return false;
}

function sanitizeProfileKeywords(keyword, hidden_field_id, display_field_id, max_characters){
  if(max_characters == null){
    max_characters = 25
  }
  
  hidden_field  = document.getElementById(hidden_field_id);
  display_field = document.getElementById(display_field_id);
  
  sanitized_keyword = keyword.split(/\s/)[0];
  sanitized_keyword = sanitized_keyword.substring(0, max_characters);
  
  display_field.innerHTML = sanitized_keyword;
  hidden_field.value = sanitized_keyword;
}

function showExternalTranscriptForm(prefix, index, total_indices){
  for(i=0; i<total_indices; i++){
    document.getElementById(prefix + i).style.display = 'none';
  }
  document.getElementById(prefix + index).style.display = '';
}

function togglePanel(to_hide, to_show){
  for(i=0; i<to_hide.length; i++){
    document.getElementById(to_hide[i]).hide();
  }
  for(i=0; i<to_show.length; i++){
    document.getElementById(to_show[i]).show();
  }
//  var screenSharingPlans = document.getElementById('screenSharingPlans');
//  var captionScreenSharing = document.getElementById('captionScreenSharing');
//  var collapseScreenIcon = document.getElementById('collapseScreenIcon');
//  var uncollapseScreenIcon = document.getElementById('uncollapseScreenIcon');
//
//
//  screenSharingPlans.style.display='';
//
//  captionScreenSharing.style.display='none';
//  captionScreenSharing2.style.display='';
//
//  collapseScreenIcon.style.display='none';
//  uncollapseScreenIcon.style.display='';
}

function hideScreenSharing_panel(obj){
	
	var screenSharingPlans = document.getElementById('screenSharingPlans');
	var captionScreenSharing = document.getElementById('captionScreenSharing');
	var collapseScreenIcon = document.getElementById('collapseScreenIcon');
	var uncollapseScreenIcon = document.getElementById('uncollapseScreenIcon');
	
	
	screenSharingPlans.style.display='none';
	
	captionScreenSharing.style.display='';
	captionScreenSharing2.style.display='none';
	
	collapseScreenIcon.style.display='';
	uncollapseScreenIcon.style.display='none';


}


function xhtmlCallFloat(pWidth, pHeight, pid, avoid, other_details)
{
  callFloat(pWidth, pHeight, pid, avoid, other_details);
  /*var winL = (screen.width - pWidth) / 2;
  var winH = "100";

  var floatingDiv = document.getElementById("floatingDiv");
  var floatContainer = document.getElementById("floatContainer"+pid);
  var floatContent = document.getElementById("floatContent"+pid);
  var floatingDivHead = document.getElementById("floatingDivHead");
  var floatingDivFooter = document.getElementById("floatingDivFooter");
  var floatSearch = document.getElementById("floatSearch");

  floatingDiv.style.display="";
  floatingDiv.style.height = document.body.scrollHeight + 'px';
  if (floatingDivHead != null) {
    floatingDivHead.style.display = "";
  }
  if (floatingDivFooter != null) {
    floatingDivFooter.style.display = "";
  }
  if (floatSearch != null) {
    floatSearch.style.display = "";
  }
  floatContainer.style.display="";
  floatContent.style.display="";

  //floatContainer.style.height = pHeight+"px";
  floatContainer.style.width = pWidth+"px"
  floatContainer.style.left="50%";
  floatContainer.style.marginLeft=-pWidth/2+"px";

  //floatContainer.style.left=winL + 'px';
  st = document.body.scrollTop
  st = document.body.scrollTop
 if(st < 70){
   floatContainer.style.top= 70 + 20+"px";
  }
	else{
    floatContainer.style.top= st + 20+"px";
  }
  
  //var topPosFix = (typeof window.pageYOffset != 'undefined')? window.pageYOffset : ((document.documentElement && document.documentElement.scrollTop)? document.documentElement.scrollTop : ((document.body.scrollTop)? document.body.scrollTop : 0));
  //floatContainer.style.top= (topPosFix + 10 ) + 'px';
  if(other_details){
      detail_type = other_details[0];
      if(detail_type=="submit_bid"){
        project_id = other_details[1];
        project_title = other_details[2];
        project_budget_range = other_details[3];
				project_proposed_duration = other_details[4];
				buyer_proposed_end_date = other_details[5];
                                project_one099_requested = other_details[6];
        document.getElementById('bid_form').action = "/bids/submit_bid/" + project_id;
        document.getElementById('bid_popup_project_title').innerHTML = project_title;
        document.getElementById('bid_popup_project_amount').innerHTML = project_budget_range;
        if(project_one099_requested=='true')
        {
          document.getElementById('1099').style.display = '';
          document.getElementById('1099_text').style.display = '';
        }else{
          document.getElementById('1099').style.display = 'none';
          document.getElementById('1099_text').style.display = 'none';
        
        }

				if (project_proposed_duration > 365) {
					document.getElementById('bid_days').selectedIndex = 365;	
				}
				else {
					document.getElementById('bid_days').selectedIndex = project_proposed_duration;	
				}
				document.getElementById('bid_popup_buyer_proposed_end_date').innerHTML = buyer_proposed_end_date;
      }
  }

  troublesomeDivVisibility('hidden', avoid);*/
}

////////////////// CS Java Script Starts Here ///////////////////

function cs_callFloat(pWidth, pHeight, pid, avoid)
  {
    var winL = (screen.width - pWidth) / 2;
    var winH = "100";

    var floatingDiv = document.getElementById("cs_floatingDiv");
    var floatingDivHead = document.getElementById("cs_floatingDivHead")
    var floatingDivFooter = document.getElementById("cs_floatingDivFooter");
    var floatContainer = document.getElementById("cs_floatContainer"+pid);
    var floatContent = document.getElementById("cs_floatContent"+pid);
     //var floatPopUp = document.getElementById("cs_popDiv"+pid);

    
  
  st = document.body.scrollTop
  if(parseInt(st) < 70){
      
    if ( navigator.appName != "Microsoft Internet Explorer" )  {
        floatContainer.style.top= (window.pageYOffset + 80 ) + 'px';
    }else{    
        floatContainer.style.top= (document.documentElement.scrollTop + 80 ) + 'px';
    }
  }
  else{
     if (typeof window.pageYOffset != "undefined" )  {  
        floatContainer.style.top= (window.pageYOffset + 80 ) + 'px';
    }else{
        floatContainer.style.top= (90 + st + 80 ) + 'px';
    }
  }
  
  floatingDiv.style.display="";
  floatingDivHead.style.display="";
  floatingDivFooter.style.display="";
  floatingDiv.style.height = document.body.scrollHeight + 'px';

  floatContainer.style.display="";
  floatContent.style.display="";

  floatContainer.style.height = pHeight + 'px' ;
  floatContainer.style.width = pWidth + 'px';
  floatContainer.style.marginLeft = -pWidth/2 + 'px';
//  floatContainer.style.left=winL + 'px';

  troublesomeDivVisibility('hidden', avoid);
  }
	
function cs_callFloat2(pWidth, pHeight, pid, avoid){
  var winL =  -pWidth/2;
    st = window.pageYOffset;

    if (navigator.appName == "Microsoft Internet Explorer"){
            st = parseInt(document.body.scrollTop);
    }
  var winH = 100 + st;

  var floatingDiv = document.getElementById("cs_floatingDiv");
  var floatingDivHead = document.getElementById("cs_floatingDivHead")
  var floatingDivFooter = document.getElementById("cs_floatingDivFooter");
  var floatContainer = document.getElementById("cs_floatContainer"+pid);
  var floatContent = document.getElementById("cs_floatContent"+pid);  
	
  floatingDiv.style.display="";
  floatingDiv.style.height = document.body.scrollHeight + 'px';

  floatContainer.style.display="";
  floatingDivHead.style.display="";
  floatingDivFooter.style.display="";
  floatContent.style.display="";

  floatContainer.style.height = pHeight + 'px' ;
  floatContainer.style.width = pWidth + 'px';
	
  floatContainer.style.left = winL + 'px';
  if ( navigator.appName != "Microsoft Internet Explorer" )  {
    floatContainer.style.top= (window.pageYOffset - 100) + 'px';
  }
  else{    
    floatContainer.style.top= (document.documentElement.scrollTop) + 'px';
  }
	
  troublesomeDivVisibility('hidden', avoid);
}

  function cs_closeFloat(pid)
{
	var floatingDiv = document.getElementById("cs_floatingDiv");
        var floatingDivHead = document.getElementById("cs_floatingDivHead")
        var floatingDivFooter = document.getElementById("cs_floatingDivFooter");
	var floatContainer = document.getElementById("cs_floatContainer"+pid);
	var floatContent = document.getElementById("cs_floatContent"+pid);
        //var floatPopUp = document.getElementById("cs_popDiv"+pid);

	floatingDiv.style.display="none";
        floatingDivHead.style.display="none";
        floatingDivFooter.style.display="none";
	floatContainer.style.display="none";
	floatContent.style.display="none";
        //floatPopUp.style.display="none";
        troublesomeDivVisibility('visible');
}


////////////////// CS Java Script Ends Here ///////////////////////
function ResetDivContentsPricing()
{
	
	document.getElementById('serviceProviderContent').style.display="none";
	document.getElementById('buyerContent').style.display="none";


}

function changePricing(tabnum){
	
	ResetDivContentsPricing();
	
	var serviceProvider = document.getElementById('Providers');
	var buyer = document.getElementById('Buyers');
	
	var serviceProviderContent = document.getElementById('serviceProviderContent');
	var buyerContent = document.getElementById('buyerContent');
	
	
	if(tabnum == 1)
	{
	
	
	document.getElementById("Providers").className="selected";		
	document.getElementById("Buyers").className="";

	
	document.getElementById('serviceProviderContent').style.display="";
	}
	
	else if(tabnum == 2)
	{
		
	
	document.getElementById("Providers").className="";		
	document.getElementById("Buyers").className="selected";

	
	document.getElementById('buyerContent').style.display="";
	}	

}

function HideTooltipCS(d) {
if(d.length < 1) {return;}
document.getElementById(d).style.display = "none";
}
function ShowTooltipCS(d) {  
if(d.length < 1) {return;}
var dd = document.getElementById(d);
//AssignPosition(dd);
dd.style.left = (X -350)+'px';
dd.style.top = (Y-180) + 'px';
dd.style.display = "block";


}

function selectAllWatchListProjectRows(checked){
	
	allCheckBoxes = document.getElementsByName('selected_messages[]');
	var class_name = '';
	if(checked == true){
		class_name = 'messageSelected';
	}
	for(var i = 0; i< allCheckBoxes.length; i++){
		allCheckBoxes[i].checked = checked;
		allCheckBoxes[i].parentNode.parentNode.className = class_name;
	}
        
        allCheckBoxes = document.getElementsByName('selected_cs_messages[]');
	var class_name = '';
	if(checked == true){
		class_name = 'messageSelected';
	}
	for(var i = 0; i< allCheckBoxes.length; i++){
		allCheckBoxes[i].checked = checked;
		allCheckBoxes[i].parentNode.parentNode.className = class_name;
	}
}

function generate_new_captcha(img_src) {
	var src_arr = img_src.split('/');
	src_arr[5] = src_arr[5] + 1;
	var new_url = src_arr.join('/');
	return new_url;
}

function changeVantageItem(direction, item_name, current_item_num, total_items){
  var new_item_num;
  if(direction=="<-"){
    new_item_num = current_item_num-1;
  }
  else if(direction=="->"){
    new_item_num = current_item_num+1;
  }
  // Change the item
  $('vantage_'+item_name+'_'+current_item_num).hide();
  $('vantage_'+item_name+'_'+new_item_num).show();
  
  // Change the arrows
  
    // Previous Arrow
    var previous_enabled = $('img_vantage_'+item_name+'_previous_enabled')
    var previous_disabled = $('img_vantage_'+item_name+'_previous_disabled')
    if(new_item_num == 0){
      previous_disabled.show();
      previous_enabled.hide();
    }
    else{
      previous_enabled.onclick = function(){changeVantageItem('<-', item_name, new_item_num, total_items)};
      previous_disabled.hide();
      previous_enabled.show();
    }
  
    // Next Arrow
    var next_enabled = $('img_vantage_'+item_name+'_next_enabled')
    var next_disabled = $('img_vantage_'+item_name+'_next_disabled')
    if(new_item_num == total_items-1){
      next_disabled.show();
      next_enabled.hide();
    }
    else{
      next_enabled.onclick = function(){changeVantageItem('->', item_name, new_item_num, total_items)};
      next_disabled.hide();
      next_enabled.show();
    }
}

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function add_to_url(name, value, regex_name){
  url = window.location.href;
  if(regex_name == null){
    search_str = '(\\?|&)' + name + '=[^&]*'
  }
  else{
    search_str = '(\\?|&)' + regex_name + '=[^&]*'
  }
  search_reg = new RegExp(search_str);
  url = url.replace(search_reg, '');
  replace_str = name + '=' + value;
  if(url.include('?')){
    url += '&' + replace_str;
  }
  else{
    if(url.include('&')){
      url = url.replace('&', '?');
      url += '&' + replace_str
    }
    else{
      url += '?' + replace_str;
    }
  }
  window.location.href = url;   
}

function ValidatePhoneStr(phone_str){
  // non-digit characters which are allowed in phone numbers
 	//var phoneNumberDelimiters = "()- ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
 	//var validWorldPhoneChars = phoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	//var minDigitsInIPhoneNumber = 10;
	var strValue = phone_str;
 	//s=stripCharsInBag(strValue,validWorldPhoneChars);
  s=strValue
  integer_regex = /^[0-9]+$/;

	if(s.length == 0){
    return false;
  }
  if (s.match(integer_regex)){
    return true;
  }else{
    return false;
  }
}

function setPhoneNumber(phone_number, country_code_box, number_part1_box, number_part2_box, number_part3_box){
  tmp_phone_number = parseInt(phone_number).toString();
  if(country_code_box && number_part1_box && number_part2_box && number_part3_box){
    drop_down_set = false;
    options_length = country_code_box.options.length;
    for(i=0; i<options_length; i++){
      option = country_code_box.options[i]
      if(tmp_phone_number.startsWith(option.value)){
        country_code_box.selectedIndex = option.index;
        country_code_box.onchange();
        tmp_phone_number = tmp_phone_number.sub(option.value, '');
        drop_down_set = true;
        break;
      }
    }
    if(drop_down_set){
      part1 = tmp_phone_number.truncate(3,'');
      tmp_phone_number = tmp_phone_number.sub(part1, '');
      part2 = tmp_phone_number.truncate(3,'');
      tmp_phone_number = tmp_phone_number.sub(part2, '');

      part3 = tmp_phone_number
      number_part1_box.value = part1
      number_part2_box.value = part2
      number_part3_box.value = part3
    }
    else{
      country_code_box.selectedIndex = 0;
      country_code_box.onchange();
      number_part1_box.value = ""
      number_part2_box.value = ""
      number_part3_box.value = ""
    }
  }
}

function setCountryCode(country_name, country_code_box, number_part1_box, number_part2_box, number_part3_box){
  if(country_code_box && !country_name.empty()){
    options_length = country_code_box.options.length;
    for(i=0; i<options_length; i++){
      option = country_code_box.options[i];
      if(option.innerHTML.indexOf(country_name) >=0){
        phone_number = option.value;
        setPhoneNumber(phone_number, country_code_box, number_part1_box, number_part2_box, number_part3_box);
        break;
      }
    }

  }

}
//Start: Function to be used on project posting page for Project Type specific fields
function updateRate(elementId, value){
    document.getElementById(elementId).innerHTML = "Rate "+ value;
}
function updateEstimatedBudget(budget_id, load_id, duration_id){
    load_sel = document.getElementById(load_id);
    duration_sel = document.getElementById(duration_id);
    if(load_sel.selectedIndex > 0 && duration_sel.selectedIndex > 0){
        document.getElementById(budget_id).innerHTML = load_sel.options[load_sel.selectedIndex].value * duration_sel.options[duration_sel.selectedIndex].value;
    }
}
function isInteger(value){
  integer_regex = /^[0-9]+$/;
  value = value + "";
  value = value.trim();
  if (value.trim() == "")
    return false;
  if (value.match(integer_regex))
    return true;
  else
    return false;
}

function isFloat(value){
  float_regex = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
  value = value + "";
  value = value.trim();
  if (value.trim() == "")
    return false;
  if (value.match(float_regex))
    return true;
  else
    return false;
}
String.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
}
function checkLinks(ev){
  var targ;
  if(!ev) ev = window.event;
  if (ev.target) targ = ev.target;
	else if (ev.srcElement) targ = ev.srcElement;
  if(targ.getAttribute("show_div_id") == "quick_links"){
    return;
  }
  if(document.getElementById('quick_links') != null && document.getElementById('quick_links').style.display != "none")
    document.getElementById('quick_links').style.display = "none";
}
document.onclick = checkLinks;
function setDefaultText(obj, default_span_id){
  if(obj.value.trim() == ""){
    obj.value = document.getElementById(default_span_id).innerHTML;
    obj.style.color = "c1c1c1";
  }
}

function toggleShowHideText(elementId, text1, text2){
  if(document.getElementById(elementId).innerHTML == text1){
    document.getElementById(elementId).innerHTML = text2;
  } else {
    document.getElementById(elementId).innerHTML = text1;
  }

}
//End: Function to be used on project posting page for Project Type specific fields

function toggle_comment(element){
  var truncated_comment_span = element.select('span.truncated_comment')[0];
  var expanded_comment_span = element.select('span.expanded_comment')[0];
  if(truncated_comment_span && truncated_comment_span.visible()){
    truncated_comment_span.hide();
    expanded_comment_span.show();
  }
  else{
    truncated_comment_span.show();
    expanded_comment_span.hide();
  }
}

// Method to uncheck the selected categories and select the clicked category with count in search
function checkUncheckCategoryOption(cat_id){
  var categorySelectBoxes = document.getElementsByName('search_category[]');
  for(var i=0; i < categorySelectBoxes.length; i++){
    if(categorySelectBoxes[i].id == ('search_category_id_' + cat_id)){
      categorySelectBoxes[i].checked = true;
    }
    else{
      categorySelectBoxes[i].checked = false;
    }
  }
}
