Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
};

var oldLink = null;
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}
function trimNumber(s) {
  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
  return s;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {

	
	if (typeof minSelDate != 'undefined' && typeof maxSelDate != 'undefined') {
		var minArray = minSelDate.split('-'); 
		
		var maxArray = maxSelDate.split('-'); 
		var curArray = date.split('-'); 
		var minNew=new Date(minArray[2],minArray[1],minArray[0]);
		var maxNew=new Date(maxArray[2],maxArray[1],maxArray[0]);
		var curNew=new Date(curArray[2],parseInt(trimNumber(curArray[0]))-1,curArray[1]);	
		
		
		if(maxSelDate!=""){
		if(!(curNew <= maxNew && curNew >= minNew)) {
			alert("You can select your timinings in between "+(minNew.getMonth()+1)+"-"+minNew.getDate()+"-"+minNew.getFullYear()+" and "+(maxNew.getMonth()+1)+"-"+maxNew.getDate()+"-"+maxNew.getFullYear()+".");	 
			return false;
		}
		}
		else{
			
			if(minNew.getDate() != curNew.getDate()){
			alert("You can not select your event start date other than "+(minNew.getMonth()+1)+"-"+minNew.getDate()+"-"+minNew.getFullYear()+".");	 
			return false;
		}
		}

	}
	/* Start of Advance photo, video & audio search */
	/*if(cal.sel.id == "PhotoAfterdate") {
		document.getElementById('PhotoBeforedate').value = "";
	}
	if(cal.sel.id == "PhotoBeforedate") {
		document.getElementById('PhotoAfterdate').value = "";
	}
	
	if(cal.sel.id == "VideoAfterdate") {
		document.getElementById('VideoBeforedate').value = "";
	}
	if(cal.sel.id == "VideoBeforedate") {
		document.getElementById('VideoAfterdate').value = "";
	}
	
	if(cal.sel.id == "AudioAfterdate") {
		document.getElementById('AudioBeforedate').value = "";
	}
	if(cal.sel.id == "AudioBeforedate") {
		document.getElementById('AudioAfterdate').value = "";
	}*/
	
	/* End of Advance photo, video & audio search */
	
  cal.sel.value = date; // just update the date in the input field.
 // if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
	if (cal.dateClicked && (cal.sel.id == "ConsumerProfileBirthdate" || cal.sel.id == "ConsumerProfileBirthdate" ||cal.sel.id =="ClassifiedStartdate"||cal.sel.id =="ClassifiedEnddate"||cal.sel.id=="AnnouncementStartdate"||cal.sel.id=="AnnouncementEnddate"||cal.sel.id=="EventStartdate"||cal.sel.id=="EventEnddate"||cal.sel.id=="PromotionalValidUpto"||cal.sel.id=="announcement_offer_startdate"||cal.sel.id=="announcement_offer_enddate"||cal.sel.id=="announcement_offer_enddate"||cal.sel.id=="make_offer_startdate"||cal.sel.id=="make_offer_enddate"))
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function showFlatCalendar(id, holder, format, selectedHandler) {
  var prnt = document.getElementById(holder);
  var element = document.getElementById(id);
  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(0, null, selectedHandler);
  // hide week numbers
  cal.setDateFormat(format);
  cal.weekNumbers = false;
  cal.create(prnt);
  cal.parseDate(element.value);
  cal.show();
}

function showlist(id) {
	if(id == "0" || id == "-2") {
		document.getElementById('list').style.display = 'none';
	} else {				
		document.getElementById('list').innerHTML = document.getElementById(id).innerHTML;		
		document.getElementById('list').style.display = 'block';
	}
}

function chkAccessOption(obj,formName,section,section_name) {
	if(obj.id == "chkPublic") {
		if(obj.checked) {
			if(document.getElementById('chkAllCon')) {	
				document.getElementById('chkAllCon').checked = false;
			}
			document.getElementById('chkMe').checked = false;
			if(section != 1 && section != 13 && section != 8) {
				setAllEveryoneConnectionsAccessRights(formName,section,section_name);
				document.getElementById('custom_connections').style.display = "block";	
			} else {
				document.getElementById('custom_connections').style.display = "none";
			}
			setAllConnectionsAccessRights(formName,section,section_name,0);
		} else {
			document.getElementById('everyone').innerHTML = "";
			if(document.getElementById('chkAllCon')) {
				document.getElementById('chkAllCon').checked = true;
			}
			setAllConnectionsAccessRights(formName,section,section_name,1);
			document.getElementById('custom_connections').style.display = "block";	
		}
		if(section != 1 && section != 13 && section != 8) {
			document.getElementById('showPersonalMsg').style.display = 'block';
		}
	}
	
	if(obj.id == "chkAllCon") {
		
		if(obj.checked) {
			document.getElementById('everyone').innerHTML = "";
			document.getElementById('chkPublic').checked = false;
			document.getElementById('chkMe').checked = false;				
			setAllConnectionsAccessRights(formName,section,section_name,1);			
			document.getElementById('custom_connections').style.display = "block";					
			if(section != 1 && section != 13 && section != 8) {
				document.getElementById('showPersonalMsg').style.display = 'block';
			}
		} else {
			document.getElementById('chkMe').checked = true;	
			setAllConnectionsAccessRights(formName,section,section_name,0);
			document.getElementById('custom_connections').style.display = "none";	
			if(section != 1 && section != 13 && section != 8) {
				document.getElementById('showPersonalMsg').style.display = 'none';
			}
		}	
	}
	
	if(obj.id == "chkMe")
	{
		if(obj.checked) {
			document.getElementById('everyone').innerHTML = "";
			document.getElementById('chkPublic').checked = false;
			if(document.getElementById('chkAllCon')) {
				document.getElementById('chkAllCon').checked = false;
			}
			setAllConnectionsAccessRights(formName,section,section_name,0);
			document.getElementById('custom_connections').style.display = "none";
			if(section != 1 && section != 13 && section != 8) {
				document.getElementById('showPersonalMsg').style.display = 'none';
			}
		} else {
			if(document.getElementById('chkAllCon')) {
				document.getElementById('chkAllCon').checked = false;
			}
			document.getElementById('chkPublic').checked = true;
			if(section != 1 && section != 13 && section != 8) {
				setAllEveryoneConnectionsAccessRights(formName,section,section_name);
				document.getElementById('custom_connections').style.display = "block";	
				document.getElementById('showPersonalMsg').style.display = 'block';
			} else {
				document.getElementById('custom_connections').style.display = "none";
			}				
		}
	}	
	
	hideCustomMessageBox(section_name,obj.id,obj.checked);
}

function chkAccessOptionForEdit(obj,formName,section,section_name,access_id,access_module) {
	
	if(obj.id == "chkPublic") {
		if(obj.checked) {
			if(document.getElementById('chkAllCon')) {	
				document.getElementById('chkAllCon').checked = false;
			}
			document.getElementById('chkMe').checked = false;			
			if(section != 1 && section != 13 && section != 8) {
				getAllEveryoneConnectionsAccessRights(section,access_id,section_name,access_module,formName);	
				document.getElementById('custom_connections').style.display = "block";	
			} else {
				document.getElementById('custom_connections').style.display = "none";
			}
			getAllConnectionsAccessRights(section,access_id,section_name,access_module,formName,0);
		} else {
			document.getElementById('everyone').innerHTML = "";
			if(document.getElementById('chkAllCon')) {
				document.getElementById('chkAllCon').checked = true;	
			}
			getAllConnectionsAccessRights(section,access_id,section_name,access_module,formName,1);
			document.getElementById('custom_connections').style.display = "block";
		}	
		if(section != 1 && section != 13 && section != 8) {
			document.getElementById('showPersonalMsg').style.display = 'block';
		}
	}
	
	if(obj.id == "chkAllCon") {		
		if(obj.checked) {
			document.getElementById('everyone').innerHTML = "";
			document.getElementById('chkPublic').checked = false;
			document.getElementById('chkMe').checked = false;			
			getAllConnectionsAccessRights(section,access_id,section_name,access_module,formName,1);
			document.getElementById('custom_connections').style.display = "block";
			if(section != 1 && section != 13 && section != 8) {
				document.getElementById('showPersonalMsg').style.display = 'block';
			}
		} else {
			getAllConnectionsAccessRights(section,access_id,section_name,access_module,formName,0);
			document.getElementById('chkMe').checked = true;				
			document.getElementById('custom_connections').style.display = "none";
			if(section != 1 && section != 13 && section != 8) {
				document.getElementById('showPersonalMsg').style.display = 'none';
			}
		}				
	}
	if(obj.id == "chkMe")
	{
		if(obj.checked) {
			document.getElementById('everyone').innerHTML = "";
			document.getElementById('chkPublic').checked = false;
			if(document.getElementById('chkAllCon')) {
				document.getElementById('chkAllCon').checked = false;
			}
			getAllConnectionsAccessRights(section,access_id,section_name,access_module,formName,0);
			document.getElementById('custom_connections').style.display = "none";	
			if(section != 1 && section != 13 && section != 8) {
				document.getElementById('showPersonalMsg').style.display = 'none';
			}
		} else {
			if(document.getElementById('chkAllCon')) {
				document.getElementById('chkAllCon').checked = false;
			}
			//getAllConnectionsAccessRights(section,access_id,section_name,access_module,formName,1);
			document.getElementById('chkPublic').checked = true;
			if(section != 1 && section != 13 && section != 8) {
				getAllEveryoneConnectionsAccessRights(section,access_id,section_name,access_module,formName);	
				document.getElementById('custom_connections').style.display = "block";	
				document.getElementById('showPersonalMsg').style.display = 'block';
			} else {
				document.getElementById('custom_connections').style.display = "none";
			}							
		}
	}
	
	hideCustomMessageBox(section_name,obj.id,obj.checked);
}

function hideCustomMessageBox(section,accessOption,isChecked)
{
	if(section != "status_updates" && section != "recommendations" && section != "questions_answers")
	{
		if(accessOption == "chkPublic" && isChecked)
		{
			document.getElementById('custom_message').style.display = "table-row";
		}
		
		if(accessOption == "chkAllCon" && isChecked) {
			document.getElementById('custom_message').style.display = "table-row";
		}
		if(accessOption == "chkAllCon" && !isChecked){
			document.getElementById('custom_message').style.display = "none";
		}
		
		if(accessOption == "chkMe" && isChecked) {
			document.getElementById('custom_message').style.display = "none";
		}
		if(accessOption == "chkMe" && !isChecked) {
			document.getElementById('custom_message').style.display = "table-row";
		}
	}
}

function checkUncheckAllConnection(bool,formName,disableCheckbox)
{
	var formElements = document.getElementById('listAllCon').getElementsByTagName('input');	
	var followerFormElements = document.getElementById('conAllFollowersList').getElementsByTagName('input');
	
	var disabledChk;
	
	if(bool) {
		disabledChk = false;
	} else {
		if(disableCheckbox) {
			disabledChk = true;				
		}
	}
	
	for (var i =0; i < formElements.length; i++) {
		
		if(formElements[i].type == "checkbox")
		{
			if(formElements[i].id != "chkPublic" && formElements[i].id != "chkAllCon" && formElements[i].id != "chkMe")
			{
				if(formElements[i].id.search('chkAllCon') >= 0 || formElements[i].id.search('allow') >= 0 || formElements[i].id.search('notify') >= 0)
				{
					formElements[i].checked = bool;
					
					formElements[i].disabled = disabledChk;
				}
			}
			
			if(formElements[i].id == "chkAllUnsortedPersonalMessage") {
				document.getElementById("chkAllUnsortedPersonalMessage").checked = bool;
				document.getElementById("chkAllUnsortedPersonalMessage").disabled = disabledChk;				
			}
		}
	}	
	
	for (var i =0; i < followerFormElements.length; i++) {		
		if(followerFormElements[i].type == "checkbox")
		{
			followerFormElements[i].checked = bool;					
			followerFormElements[i].disabled = disabledChk;
			
			if(followerFormElements[i].id == "chkFollowerPersonalMessage") {
				document.getElementById("chkFollowerPersonalMessage").checked = bool;
				document.getElementById("chkFollowerPersonalMessage").disabled = disabledChk;				
			}
		}
	}
	
	if(document.getElementById('chkAllConnectionPersonalMessage')) {
		document.getElementById("chkAllConnectionPersonalMessage").checked = bool;
		document.getElementById("chkAllConnectionPersonalMessage").disabled = disabledChk;				
	}
}

function chkList(obj,name,formName)
{
	if(obj.checked == true)
	{
		checkUncheckContacts(true,name+"_",formName);
	}
	else
	{
		checkUncheckContacts(false,name+"_",formName);
	}
}

function checkUncheckContacts(bool,name,formName)
{
	var formElements = document.getElementById('listAllCon').getElementsByTagName('input');	
	if (document.getElementById('connection_followers_list'))
		var followerFormElements = document.getElementById('connection_followers_list').getElementsByTagName('input');	
	
	for (var i =0; i < formElements.length; i++) {
		
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;		
			
			if(eleId.search(name) >= 0)
			{
				formElements[i].checked = bool;
			
				var idArr = new Array(); 
				idArr = eleId.split("-");
				
				if(idArr.length == 3) 
				{
					var multipleEleId;
					
					multipleEleId = idArr[1] + "-" + idArr[2];
					
					for (var j =0; j < formElements.length; j++)
					{
						if(formElements[j].type == "checkbox")
						{
							var contactId = formElements[j].id;	
							
							if(contactId.search(multipleEleId) >= 0)
							{
								if(formElements[j].id.search("_notify") >=0)
								{	
									if(bool)
										formElements[j].disabled = false;
									else
										formElements[j].disabled = true;
								}
								else
								{	
									formElements[j].disabled = false;
								}
									
								formElements[j].checked = bool;
							}
						}
						
						for (var k = 0; k < followerFormElements.length; k++)
						{
							if(followerFormElements[k].type == "checkbox")
							{
								var eleId = followerFormElements[k].id;
								var idArr = new Array(); 
								idArr = eleId.split("_");			
								if(idArr.length == 3)
								{
									var followerMultipleEleId;
									
									followerMultipleEleId = idArr[1] + "_" + idArr[2];
								
									if(followerMultipleEleId.search(multipleEleId) >= 0)
									{
										followerFormElements[k].checked = bool;
										
										if(!bool && followerMultipleEleId.search("notify") >= 0) {
											followerFormElements[k].disabled = true;
										} else {
											followerFormElements[k].disabled = false;
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	
	if(document.getElementById('unsorted_list')) {
		var unsortedformElements = document.getElementById('unsorted_list').getElementsByTagName('input');
		
		for (var i = 0; i < unsortedformElements.length; i++) {
			
			if(unsortedformElements[i].type == "checkbox")
			{
				var unsortedEleId = unsortedformElements[i].id;		
				
				var idArr = new Array(); 
					idArr = unsortedEleId.split("-");
					
				if(idArr.length == 3 ) {
					
					var tempArr = idArr[2].split("_");
					
					var multipleEleId = idArr[1]+"-"+tempArr[0];
					
					if(multipleEleId.search(name) >= 0) {
						unsortedformElements[i].checked = bool;	
						if(!bool && unsortedformElements.search("notify") >= 0) {
							unsortedformElements[i].disabled = true;
						} else {
							unsortedformElements[i].disabled = false;
						}
					}			
				}
			}
		}
	}
	enableDisableMessagebox();
}

function checkMultipleList(obj,name,formName)
{
	if(obj.checked == true)
	{
		checkUncheckMultipleLists(true,name,formName);
	}
	else
	{
		checkUncheckMultipleLists(false,name,formName);
	}
	enableDisableMessagebox();
}

function checkUncheckMultipleLists(bool,name,formName)
{
	var formElements = document.getElementById('listAllCon').getElementsByTagName('input');		
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;
			
			var idArr = new Array(); 
			idArr = eleId.split("-");
			
			if(idArr.length == 3)
			{
				var multipleEleId;
				
				multipleEleId = idArr[1] + "-" + idArr[2];
				
				if(multipleEleId.search(name) >= 0)
				{
					formElements[i].checked = bool;
					
					if(multipleEleId.search('allow') >= 0) {
						
						var notifyIdArr = new Array();
						
						notifyIdArr = idArr[2].split("_");
						
						var notifyId = idArr[1] + "-" + notifyIdArr[0] + "_notify";
						
						checkUncheckNotify(bool,notifyId,formName);
					}
				}
			}
		}
	}
	
	var formElements = document.getElementById('connection_followers_list').getElementsByTagName('input');		
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;
			var idArr = new Array(); 
			idArr = eleId.split("_");			
			if(idArr.length == 3)
			{
				var multipleEleId;
				
				multipleEleId = idArr[1] + "_" + idArr[2];
			
				if(multipleEleId.search(name) >= 0)
				{
					formElements[i].checked = bool;
					
					if(multipleEleId.search('allow') >= 0) {						
						var notifyId = idArr[1] + "_notify";				
						checkUncheckNotify(bool,notifyId,formName);
					}
				}
			}
		}
	}
	
	var unsortedformElements = document.getElementById('unsorted_list').getElementsByTagName('input');		
	for (var i = 0; i < unsortedformElements.length; i++)
	{
		if(unsortedformElements[i].type == "checkbox")
		{
			var eleId = unsortedformElements[i].id;
			var idArr = new Array(); 
			
			idArr = eleId.split("-");			
			
			if(idArr.length == 3)
			{
				var multipleEleId;
				
				multipleEleId = idArr[1] + "-" + idArr[2];
				
				if(multipleEleId.search(name) >= 0)
				{
					unsortedformElements[i].checked = bool;
					
					if(multipleEleId.search('allow') >= 0) {	
					
						var idArr = new Array(); 
						idArr = eleId.split("_");
						
						var multipleEleId;				
						
						multipleEleId = idArr[1] + "-" + idArr[2];
						
						var notifyId = idArr[1] + "_notify";				
						
						checkUncheckNotify(bool,notifyId,formName);
					}
				}
			}
		}
	}
}

function checkSingleUnsortedList(obj,name,formName)
{
	var idArr = new Array();
	idArr = obj.id.split("_");	
	var notifyId = idArr[0]+"_"+idArr[1]+"_notify";
	
	if(obj.checked == true)
	{
		if(document.getElementById(notifyId)) {
			document.getElementById(notifyId).checked = true;
			document.getElementById(notifyId).disabled = false;
		}
		checkUncheckSingleUnsortedLists(true,name,formName);
	}
	else
	{
		if(document.getElementById(notifyId)){
			document.getElementById(notifyId).checked = false;
			document.getElementById(notifyId).disabled = true;
		}
		checkUncheckSingleUnsortedLists(false,name,formName);
	}
	enableDisableMessagebox();
}

function checkUncheckSingleUnsortedLists(bool,name,formName)
{
	var formElements = document.getElementById('connection_followers_list').getElementsByTagName('input');		
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;
			var idArr = new Array(); 
			idArr = eleId.split("_");			
			if(idArr.length == 3)
			{
				var multipleEleId;
				
				multipleEleId = idArr[1] + "_" + idArr[2];
			
				if(multipleEleId.search(name) >= 0)
				{
					formElements[i].checked = bool;
					
					if(multipleEleId.search('allow') >= 0) {						
						var notifyId = idArr[1] + "_notify";				
						checkUncheckNotify(bool,notifyId,formName);
					}
				}
			}
		}
	}	
}

function checkMultipleFollowerList(obj)
{
	if(obj.checked == true)
	{
		checkUncheckMultipleFollowerLists(true);
	}
	else
	{
		checkUncheckMultipleFollowerLists(false);
	}
	enableDisableMessagebox();
}

function checkUncheckMultipleFollowerLists(bool)
{
	var followersFormElements = document.getElementById('conAllFollowersList').getElementsByTagName('input');	
	var connectionFormElements = document.getElementById('listAllCon').getElementsByTagName('input');
	var unsortedFormElements = document.getElementById('unsorted_list').getElementsByTagName('input');
	
	for (var i = 0; i < followersFormElements.length; i++)
	{
		if(followersFormElements[i].type == "checkbox")
		{
			var followerEleId = followersFormElements[i].id;
			followersFormElements[i].checked = bool;
			
			if(!bool && followerEleId.search("notify") >= 0) {
				followersFormElements[i].disabled = true;
			} else {
				followersFormElements[i].disabled = false;
			}							
			
			var followersIdArr = new Array(); 
			followersIdArr = followerEleId.split("_");
			
			var followerMultipleEleId = followersIdArr[1] + "_" + followersIdArr[2];
		
			for (var j = 0; j < connectionFormElements.length; j++)
			{
				if(connectionFormElements[j].type == "checkbox")
				{
					var connecionEleId = connectionFormElements[j].id;
					
					var idArr = new Array(); 
					idArr = connecionEleId.split("-");
					
					if(idArr.length == 3)
					{
						var multipleEleId;
						
						multipleEleId = idArr[1] + "-" + idArr[2];
						
						if(multipleEleId.search(followerMultipleEleId) >= 0)
						{
							connectionFormElements[j].checked = bool;
							
							if(!bool && connecionEleId.search("notify") >= 0) {
								connectionFormElements[j].disabled = true;
							} else {
								connectionFormElements[j].disabled = false;
							}
						}
					}
				}
			}
			
			for (var k = 0; k < unsortedFormElements.length; k++)
			{
				if(unsortedFormElements[k].type == "checkbox")
				{
					var unsortedEleId = unsortedFormElements[k].id;
					
					var idArr = new Array(); 
					idArr = unsortedEleId.split("-");
					
					if(idArr.length == 3)
					{
						var multipleEleId;
						
						multipleEleId = idArr[1] + "-" + idArr[2];
						
						if(multipleEleId.search(followerMultipleEleId) >= 0)
						{
							unsortedFormElements[k].checked = bool;
							
							if(!bool && unsortedEleId.search("notify") >= 0) {
								unsortedFormElements[k].disabled = true;
							} else {
								unsortedFormElements[k].disabled = false;
							}
						}
					}
				}
			}
		}
	}	
}

function checkMultipleUnsortedList(obj)
{
	if(obj.checked == true)
	{
		checkUncheckMultipleUnsortedLists(true);
	}
	else
	{
		checkUncheckMultipleUnsortedLists(false);
	}
	enableDisableMessagebox();
}

function checkUncheckMultipleUnsortedLists(bool)
{
	var unsortedFormElements = document.getElementById('unsorted_list').getElementsByTagName('input');
	var followersFormElements = document.getElementById('connection_followers_list').getElementsByTagName('input');	
	
	for (var i = 0; i < unsortedFormElements.length; i++)
	{
		if(unsortedFormElements[i].type == "checkbox")
		{
			var unsortedEleId = unsortedFormElements[i].id;
			unsortedFormElements[i].checked = bool;
			
			if(!bool && unsortedEleId.search("notify") >= 0) {
				unsortedFormElements[i].disabled = true;
			} else {
				unsortedFormElements[i].disabled = false;
			}
			
			var unsortedIdArr = new Array(); 
			unsortedIdArr = unsortedEleId.split("-");
			
			var unsortedMultipleEleId = unsortedIdArr[1] + "-" + unsortedIdArr[2];
			
			for (var j = 0; j < followersFormElements.length; j++)
			{
				if(followersFormElements[j].type == "checkbox")
				{
					var followerEleId = followersFormElements[j].id;
					
					var idArr = new Array(); 
					idArr = followerEleId.split("_");
					
					if(idArr.length == 3)
					{
						var multipleEleId;
						
						multipleEleId = idArr[1] + "_" + idArr[2];
						
						if(multipleEleId.search(unsortedMultipleEleId) >= 0)
						{
							followersFormElements[j].checked = bool;
							if(!bool && followerEleId.search("notify") >= 0) {
								followersFormElements[j].disabled = true;
							} else {
								followersFormElements[j].disabled = false;
							}
						}
					}
				}
			}
		}
	}	
}

function checkUncheckNotify(bool,notifyId,formName) {
	
	var formElements = document.getElementById('listAllCon').getElementsByTagName('input');			
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;
			
			var idArr = new Array(); 
			idArr = eleId.split("-");
			
			if(idArr.length == 3)
			{
				var multipleEleId;
				
				multipleEleId = idArr[1] + "-" + idArr[2];
				
				if(multipleEleId.search(notifyId) >= 0)
				{
					formElements[i].checked = bool;
					
					if(bool)
						formElements[i].disabled = false;
					else
						formElements[i].disabled = true;
				}
			}
		}
	}
	
	var formElements = document.getElementById('connection_followers_list').getElementsByTagName('input');			
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;
			
			var idArr = new Array(); 
			idArr = eleId.split("_");
			
			if(idArr.length == 3)
			{
				var multipleEleId;
				
				multipleEleId = idArr[1] + "_" + idArr[2];
				
				if(multipleEleId.search(notifyId) >= 0)
				{
					formElements[i].checked = bool;
					
					if(bool)
						formElements[i].disabled = false;
					else
						formElements[i].disabled = true;
				}
			}
		}
	}
	
	var unsortedformElements = document.getElementById('unsorted_list').getElementsByTagName('input');		
	for (var i = 0; i < unsortedformElements.length; i++)
	{
		if(unsortedformElements[i].type == "checkbox")
		{
			var eleId = unsortedformElements[i].id;
			var idArr = new Array(); 
			
			idArr = eleId.split("-");			
			
			if(idArr.length == 3)
			{
				var multipleEleId;
				
				multipleEleId = idArr[1] + "-" + idArr[2];
				
				if(multipleEleId.search(notifyId) >= 0)
				{
					unsortedformElements[i].checked = bool;
					
					if(bool)
						unsortedformElements[i].disabled = false;
					else
						unsortedformElements[i].disabled = true;
				}
			}
		}
	}
}

function getFollowers(section) {
		
		var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById('followers').innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/albums/getFollowersList/'+section,
			data: "ajax=true",
			success: function(msg) {
			
				if(msg != "")
				{				
					document.getElementById('followers').innerHTML = "";
					document.getElementById('followers').innerHTML = msg;
				}						
			}
		});
		return false;
}

function getNotifiedFollowers(section,access_id,access_module) {
		
		var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById('followers').innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/albums/getNotifiedFollowers/'+section+'/'+access_id+'/'+access_module,
			data: "ajax=true",
			success: function(msg) {
			
				if(msg != "")
				{				
					document.getElementById('followers').innerHTML = "";
					document.getElementById('followers').innerHTML = msg;
				}						
			}
		});
		return false;
}

function getAllConnectionsAccessRights(section,access_id,section_name,model_name,form_name,boolean) {
	
		var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById('all_connection').innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/albums/getAllConnectionsAccessRights/'+section+'/'+access_id+'/'+section_name+'/'+model_name+'/'+form_name+'/'+boolean,
			data: "ajax=true",
			success: function(msg) {			
				if(msg != "")
				{			
					$j('#all_connection').attr('style','padding-left:0px');	
					document.getElementById('all_connection').innerHTML = msg;
					if(document.getElementById("list_all")) {
						document.getElementById("chkAllCon").checked = true;
					}
				}						
			}
		});
		return false;
}

function getAllEveryoneConnectionsAccessRights(section,access_id,section_name,model_name,form_name) {
		var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById('everyone').innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/albums/getEveryoneAccessRights/'+section+'/'+access_id+'/'+section_name+'/'+model_name+'/'+form_name,
			data: "ajax=true",
			success: function(msg) {
			
				if(msg != "")
				{				
					document.getElementById('everyone').innerHTML = "";
					document.getElementById('everyone').innerHTML = msg;
				}						
			}
		});
		return false;
}

function setAllEveryoneConnectionsAccessRights(form_name,section,section_name) {
		var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById('everyone').innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/albums/setEveryoneAccessRights/'+form_name+'/'+section+'/'+section_name,
			data: "ajax=true",
			success: function(msg) {
			
				if(msg != "")
				{				
					document.getElementById('everyone').innerHTML = "";
					document.getElementById('everyone').innerHTML = msg;
				}						
			}
		});
		return false;
}

function setAllConnectionsAccessRights(form_name,section,section_name,boolean) {
		var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById('all_connection').innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/albums/setAllConnectionsAccessRights/'+form_name+'/'+section+'/'+section_name+'/'+boolean,
			data: "ajax=true",
			success: function(msg) {
				if(msg != "")
				{	
					$j('#all_connection').attr('style','padding-left:0px');	
					document.getElementById('all_connection').innerHTML = msg;
				}						
			}
		});
		return false;
}

function checkUncheckAllConnections(obj) {
	formName = obj.form.id;
	
	if(obj.checked) {
		checkUncheckConnections(true,formName);
	}	
	else
	{
		checkUncheckConnections(false,formName);
	}
	
}

function checkUncheckConnections(bool,formName) {
	
	//var formElements = document.getElementById(formName);	 	
	var formElements = document.getElementById('followers').getElementsByTagName('input');	
	
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;
			
			if(eleId.search("ControlNotifyConnection") >= 0)
			{
				formElements[i].checked = bool;
				
				checkUncheckMultipleFollowers(formElements,eleId,'ControlNotification',bool);
			}
		}
	}
}

function checkUncheckAll(obj,checkbox_id) {
	formName = obj.form.id;
	
	if(obj.checked) {
		checkUncheckConnectionFollower(true,formName,checkbox_id);
	}	
	else
	{
		checkUncheckConnectionFollower(false,formName,checkbox_id);
	}	
}

function checkUncheckConnectionFollower(bool,formName,checkbox_id) {
	
	//var formElements = document.getElementById(formName);	 	
	var formElements = document.getElementById('followers').getElementsByTagName('input');	
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;
			
			if(eleId.search(checkbox_id) >= 0)
			{
				formElements[i].checked = bool;
			}
		}
	}	
}

function chkUnCheckAllPersonalMessage(bool)
{
	var formElements = document.getElementById('list_all').getElementsByTagName('input');	
	var followerFormElements = document.getElementById('connection_followers_list').getElementsByTagName('input');	
		
	for (var i =0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox" && (formElements[i].id.search('notify') >= 0 || formElements[i].id.search('groupPersonalMessage') >= 0) && !formElements[i].disabled)
		{
			formElements[i].checked = bool;	
			
			var connectionEleId = formElements[i].id;
			var connectionIdArr = new Array(); 
			
			connectionIdArr = connectionEleId.split("-");
			if(connectionIdArr.length == 3)
			{
				var multipleEleId;
				multipleEleId = connectionIdArr[1] + "-" + connectionIdArr[2];
				
				for (var j = 0; j < followerFormElements.length; j++)
				{
					if(followerFormElements[j].type == "checkbox" && !followerFormElements[j].disabled)
					{
						var eleId = followerFormElements[j].id;
						if(eleId.search(multipleEleId) >= 0)
						{
							followerFormElements[j].checked = bool;
						}						
					}
				}				
			}
		}
	}	
	
		
	for (var i = 0; i < followerFormElements.length; i++)
	{	
		var eleId = followerFormElements[i].id;		
		if(followerFormElements[i].type == "checkbox" && eleId.search('notify') >= 0 && !followerFormElements[i].disabled)
		{
			var idArr = new Array(); 
			idArr = eleId.split("_");
			var multipleEleId = idArr[1] + "_" + idArr[2];
		
			followerFormElements[i].checked = bool;						
			checkUncheckMultipleConnectionFollowers(multipleEleId,bool);					
		}
	}
		
	enableDisableMessagebox();
}

function chkUnCheckUnsortedPersonalMessage(bool)
{
	var formElements = document.getElementById('unsorted_list').getElementsByTagName('input');	
	var followerFormElements = document.getElementById('connection_followers_list').getElementsByTagName('input');		
	
	for(var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox" && formElements[i].id.search('notify') >= 0 && !formElements[i].disabled)
		{
			formElements[i].checked = bool;	
			
			var unsortedEleId = formElements[i].id;
			var unsortedIdArr = new Array(); 
			unsortedIdArr = unsortedEleId.split("-");
			if(unsortedIdArr.length == 3)
			{
				var multipleEleId;
				multipleEleId = unsortedIdArr[1] + "-" + unsortedIdArr[2];
				
				for (var j = 0; j < followerFormElements.length; j++)
				{
					if(followerFormElements[j].type == "checkbox" && !followerFormElements[j].disabled)
					{
						var eleId = followerFormElements[j].id;
						if(eleId.search(multipleEleId) >= 0)
						{
							followerFormElements[j].checked = bool;
						}						
					}
				}				
			}
		}	
	}
	
	enableDisableMessagebox();
}

function chkUnCheckGroupPersonalMessage(bool,span_id)
{
	var formElements = document.getElementById(span_id).getElementsByTagName('input');	
	var allConnectionsFormElements = document.getElementById('listAllCon').getElementsByTagName('input');	
	var followersFormElements = document.getElementById('connection_followers_list').getElementsByTagName('input');
	
	for(var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox" && formElements[i].id.search('notify') >= 0 && !formElements[i].disabled)
		{
			formElements[i].checked = bool;	
			
			var connectionEleId = formElements[i].id;
			var conArr = new Array(); 
			conArr = connectionEleId.split("-");
			if(conArr.length == 3)
			{
				var multipleEleId;
				multipleEleId = conArr[1] + "-" + conArr[2];
				
				for (var j = 0; j < allConnectionsFormElements.length; j++)
				{
					if(allConnectionsFormElements[j].type == "checkbox" && allConnectionsFormElements[j].id.search('notify') >= 0 && !allConnectionsFormElements[j].disabled)
					{
						var connectionId = allConnectionsFormElements[j].id;
						if(connectionId.search(multipleEleId) >= 0) {
							allConnectionsFormElements[j].checked = bool;
						}						
					}
				}
				
				for (var k = 0; k < followersFormElements.length; k++)
				{
					if(followersFormElements[k].type == "checkbox" && followersFormElements[k].id.search('notify') >= 0 && !followersFormElements[k].disabled)
					{
						var followerId = followersFormElements[k].id;
						if(followerId.search(multipleEleId) >= 0) {
							followersFormElements[k].checked = bool;
						}						
					}
				}
			}
		}	
	}	
	enableDisableMessagebox();
}

function setAccessOptionUpdateItem(accessLevel,section,access_module,section_name,access_id,formName) {
	if(accessLevel == 0)
	{
		document.getElementById("chkPublic").checked = true;
		if(section != 1 && section != 13 && section != 8) {
			document.getElementById('showPersonalMsg').style.display = 'block';
			getAllEveryoneConnectionsAccessRights(section,access_id,section_name,access_module,formName);		
		}				
	}
	else if(accessLevel == '-1')
	{	
		if(section != 1 && section != 13 && section != 8) {
			document.getElementById('showPersonalMsg').style.display = 'block';
		}
		getAllConnectionsAccessRights(section,access_id,section_name,access_module,formName,1);
		//document.getElementById("chkAllCon").checked = true;
	}
	else 
	{	
		document.getElementById('showPersonalMsg').style.display = 'none';
		document.getElementById("chkMe").checked = true;
		hideCustomMessageBox(section_name,"chkMe",true);
	}	
}

/* BTS ITEM 172 - Access Rights amendments */
/*Temporary not used below function */
function checkUncheckEveryoneAllConnection(bool,formName) {
	
	if(bool.checked) {
		var checked = true;	
		document.getElementById('chkAllEveryonePersonalMessage').checked = true;
	} else {
		var checked = false;	
		document.getElementById('chkAllEveryonePersonalMessage').checked = false;
	}
	
	var formElements = document.getElementById('everyone_all_con').getElementsByTagName('input');	
	
	var followersElements = document.getElementById('followers_list').getElementsByTagName('input');
		
	for (var i = 0; i < formElements.length; i++) {
		
		if(formElements[i].type == "checkbox")
		{
			formElements[i].checked = checked;	
			
			var idArr = formElements[i].id.split("_");
			
			var followerId = "follower_"+idArr[1]+"_"+idArr[2];
			
			for (var j = 0; j < followersElements.length; j++)
			{
				var  searchFollowerId = followersElements[j].id;
			
				if(followersElements[j].type == "checkbox") {
					if(searchFollowerId.search(followerId) >= 0) {	
						followersElements[j].checked = checked;
					}
				}
			}		
		}
	}	
}

function checkUncheckEveryone(checked,formName) {
	var formElements = document.getElementById('everyone').getElementsByTagName('input');	
		
	for (var i = 0; i < formElements.length; i++) {
		
		if(formElements[i].type == "checkbox") {
			formElements[i].checked = checked;
			if(checked) {
				formElements[i].disabled = false;
				document.getElementById('chkEveryoneUnsortedPersonalMessage').checked = checked;
				document.getElementById('chkEveryoneUnsortedPersonalMessage').disabled = false;
			} else {
				formElements[i].disabled = true;
				document.getElementById('chkEveryoneUnsortedPersonalMessage').checked = checked;
				document.getElementById('chkEveryoneUnsortedPersonalMessage').disabled = true;
			}
		}
	}	
}

function checkUncheckAllFollowers(checked) {
	if(checked) {
		checkUncheckFollowers(true);
	} else {
		checkUncheckFollowers(false);
	}	
	enableDisableMessagebox();
}

function checkUncheckFollowers(bool) {
	
	var formElements = document.getElementById('followers_list').getElementsByTagName('input');		
		for (var i = 0; i < formElements.length; i++)
		{	
			var eleId = formElements[i].id;
			
			if(formElements[i].type == "checkbox")
			{
				formElements[i].checked = bool;						
				checkUncheckMultipleFollowers(eleId,'notify',bool);					
			}
		}
}

function checkUncheckMultipleFollowers(checkbox_id,match_string, bool) {
	
	var formElements = document.getElementById('everyone').getElementsByTagName('input');		

	var idArr = new Array(); 
	idArr = checkbox_id.split("_");

	var multipleEleId = idArr[1];
	
	for (var j = 0; j < formElements.length; j++)
	{
		if(formElements[j].type == "checkbox")
		{
			var followerId = formElements[j].id;	
			
			if(followerId.search(multipleEleId) >= 0 && followerId.search(match_string) >=0)
			{
				if(bool) {
					formElements[j].checked = true;
				} else {
					formElements[j].checked = false;
				}
			}
		}
	}	
}

function checkUncheckAllConnectionFollowers(checked) {
	if(checked) {
		checkUncheckConnectionFollowers(true);
	} else {
		checkUncheckConnectionFollowers(false);
	}	
	enableDisableMessagebox();
}

function checkUncheckConnectionFollowers(bool) {
	
	var followerFormElements = document.getElementById('connection_followers_list').getElementsByTagName('input');		
		for (var i = 0; i < followerFormElements.length; i++)
		{	
			var eleId = followerFormElements[i].id;		
			if(followerFormElements[i].type == "checkbox" && eleId.search('notify') >= 0 && !followerFormElements[i].disabled)
			{
				var idArr = new Array(); 
				idArr = eleId.split("_");
				var multipleEleId = idArr[1] + "_" + idArr[2];
			
				followerFormElements[i].checked = bool;						
				checkUncheckMultipleConnectionFollowers(multipleEleId,bool);					
			}
		}
}

function checkUncheckMultipleConnectionFollowers(multipleEleId,bool) {
	
	var formElements = document.getElementById('list_all').getElementsByTagName('input');		

	for (var j = 0; j < formElements.length; j++)
	{
		if(formElements[j].type == "checkbox" && !formElements[j].disabled)
		{
			var connectionId = formElements[j].id;	
			
			if(connectionId.search(multipleEleId) >= 0 && connectionId.search("notify") >= 0 && !formElements[j].disabled)
			{
				if(bool) {
					formElements[j].checked = true;
				} else {
					formElements[j].checked = false;
				}
			}
		}
	}	
	
	var unsortedFormElements = document.getElementById('unsorted_list').getElementsByTagName('input');		

	for (var k = 0; k < unsortedFormElements.length; k++)
	{
		if(unsortedFormElements[k].type == "checkbox" && !unsortedFormElements[k].disabled)
		{
			var unsortedId = unsortedFormElements[k].id;	
			
			if(unsortedId.search(multipleEleId) >= 0 && unsortedId.search("notify") >= 0 && !unsortedFormElements[k].disabled)
			{
				if(bool) {
					unsortedFormElements[k].checked = true;
				} else {
					unsortedFormElements[k].checked = false;
				}
			}
		}
	}
}

function checkMultipleFollowers(obj,match_string)
{
	var checkbox_id = obj.id;
	if(obj.checked) {
		checkUncheckMultipleFollowers(checkbox_id,match_string,true);
	} else {
		checkUncheckMultipleFollowers(checkbox_id,match_string,false);
	}
	enableDisableMessagebox();
}

function checkUncheckContactList(obj,name,formName)
{
	if(obj.checked == true)
	{
		checkUncheckMultipleFollowersConnections(true,name,formName);
	}
	else
	{
		checkUncheckMultipleFollowersConnections(false,name,formName);
	}
}

function checkUncheckMultipleFollowersConnections(bool,name,formName)
{
	var formElements = document.getElementById('everyone').getElementsByTagName('input');	
	
	for (var i =0; i < formElements.length; i++) {
		
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;		
			
			if(eleId.search(name) >= 0)
			{
				formElements[i].checked = bool;
			
				var idArr = new Array(); 
				idArr = eleId.split("_");
				
				var multipleEleId;
				
				multipleEleId = idArr[1] + "_" + idArr[2];
				
				for (var j =0; j < formElements.length; j++)
				{
					if(formElements[j].type == "checkbox")
					{
						var contactId = formElements[j].id;	
						
						if(contactId.search(multipleEleId) >= 0)
						{
							formElements[j].checked = bool;
						}
					}
				}				
			}
		}
	}
}

function checkUncheckUnsortedContactList(obj,name,spanId,formName)
{
	if(obj.checked == true) {
		checkUncheckUnsortedFollowerList(true,name,spanId,formName);
	} else {
		checkUncheckUnsortedFollowerList(false,name,spanId,formName);
	}
	enableDisableMessagebox();
}

function checkUncheckUnsortedFollowerList(bool,name,spanId,formName)
{
	var unsortedElements = document.getElementById(spanId).getElementsByTagName('input');	
	
	var followerElements = document.getElementById('followers_list').getElementsByTagName('input');		

	for (var i = 0; i < unsortedElements.length; i++)
	{
		if(unsortedElements[i].type == "checkbox")
		{	
			unsortedElements[i].checked = bool;
			
			var idArr = unsortedElements[i].id.split("_");
			
			var followerId = "follower_"+idArr[2];
			
			for (var j = 0; j < followerElements.length; j++)
			{
				var  searchFollowerId = followerElements[j].id;
			
				if(followerElements[j].type == "checkbox")
				{
					if(searchFollowerId.search(followerId) >= 0)
					{	
						followerElements[j].checked = bool;
					}
				}
			}
		}
	}	
}

function checkUncheckUnsortedEachContact(obj,user_id, profile_id,formName)
{
	if(obj.checked == true) {
		checkUncheckUnsortedFollowerContactsList(true,user_id,profile_id,formName);
	} else {
		checkUncheckUnsortedFollowerContactsList(false,user_id,profile_id,formName);
	}
	
	enableDisableMessagebox();
}

function checkUncheckUnsortedFollowerContactsList(bool,user_id,profile_id,formName)
{
	var followerElements = document.getElementById('followers_list').getElementsByTagName('input');		
			
	var followerId = "follower_"+user_id+"-"+profile_id;
	
	for (var j = 0; j < followerElements.length; j++)
	{
		var  searchFollowerId = followerElements[j].id;
	
		if(followerElements[j].type == "checkbox")
		{
			if(searchFollowerId.search(followerId) >= 0)
			{	
				followerElements[j].checked = bool;
			}
		}
	}	
}


function checkUncheckAllEveryonePersonalMessage(bool)
{
	var formElements = document.getElementById('everyone_all_con').getElementsByTagName('input');	
		
	for (var i = 0; i < formElements.length; i++)
	{
		if(formElements[i].type == "checkbox")
		{
			formElements[i].checked = bool;	
		}
	}	
	enableDisableMessagebox();
}

function collapsExpandsEveryone(option,checked,section) {
	if(option == "Everyone") {		
		if(checked) {
			/*if(section != 1 && section != 8 && section != 13) {
				if(document.getElementById('everyone_minusImage').style.display == "none") {
					SwitchMenu_2('everyone');
				}
			}*/
			if(document.getElementById('list_all_minusImage').style.display == "block") {
				SwitchMenu_2('list_all');
			} 
		} else {
			/*if(section != 1 && section != 8 && section != 13) {
				if(document.getElementById('everyone_minusImage').style.display == "block") {
					SwitchMenu_2('everyone');
				}
			}*/
			if(document.getElementById('list_all_minusImage').style.display == "none") {
				SwitchMenu_2('list_all');
			} 
		}
	} else if(option == "All Connection") {
		if(checked) {
			if(document.getElementById('list_all_plusImage').style.display == "block") {
				SwitchMenu_2('list_all');
			}
			/*if(section != 1 && section != 8 && section != 13) {
				if(document.getElementById('everyone_minusImage').style.display == "block") {
					SwitchMenu_2('everyone');
				}
			}*/
		} else {
			if(document.getElementById('list_all_minusImage').style.display == "block") {
				SwitchMenu_2('list_all');
			}	
			/*if(section != 1 && section != 8 && section != 13) {
				if(document.getElementById('everyone_minusImage').style.display == "block") {
					SwitchMenu_2('everyone');
				}
			}*/
		}
	} else if(option == "Only Me") {
		if(checked) {
			if(document.getElementById('list_all_minusImage').style.display == "block") {
				SwitchMenu_2('list_all');
			}			
		} else {
			if(document.getElementById('list_all_plusImage').style.display == "none") {
				SwitchMenu_2('list_all');
			}
		}
	}
}

function checkUncheckEveryoneAllContacts(bool,name,formName)
{

	var formElements = document.getElementById('everyone').getElementsByTagName('input');	
	for (var i =0; i < formElements.length; i++) {
		
		if(formElements[i].type == "checkbox")
		{
			var eleId = formElements[i].id;		
			
			if(eleId.search(name) >= 0 && eleId.search("_notify") >= 0)
			{
				formElements[i].checked = bool;
			
				var idArr = new Array(); 
				idArr = eleId.split("_");
				
				if(idArr.length == 3) 
				{
					var multipleEleId;
					
					multipleEleId = idArr[1] + "-" + idArr[2];
					
					for (var j =0; j < formElements.length; j++)
					{
						if(formElements[j].type == "checkbox")
						{
							var contactId = formElements[j].id;	
							
							if(contactId.search(multipleEleId) >= 0)
							{
								formElements[j].checked = bool;
							}
						}
					}
				}
			}
		}
	}
	
	enableDisableMessagebox();
}

/* BTS ITEM 172 - Access Rights amendments */

function showhideMessagebox() {
	if($j('#msgbox').is(':visible')) {
		$j('#msgbox').hide();
	} else	{
		$j('#msgbox').show();
	}		
}

function enableDisableMessagebox() {
	
	var contactSelected = false;
	var formElements = new Array();
	var	unsortedformElements = new Array();
	
	if(document.getElementById("chkPublic") && document.getElementById("chkPublic").checked) {
		if(document.getElementById("everyone")) {
			formElements = document.getElementById('everyone').getElementsByTagName('input');	
		}
	}
	
	if(document.getElementById("chkAllCon") && document.getElementById("chkAllCon").checked) {
		if(document.getElementById("listAllCon")) {
			formElements = document.getElementById('listAllCon').getElementsByTagName('input');
		}
	}
	
	if(document.getElementById("unsorted_list")) {
		unsortedformElements = document.getElementById('unsorted_list').getElementsByTagName('input');	
	}
	
	for (var i = 0; i < unsortedformElements.length; i++) {	
		if(unsortedformElements[i].type == "checkbox" && unsortedformElements[i].checked && unsortedformElements[i].id.search("_notify") >= 0 ) {
			contactSelected = true;
			break;			
		}
	}
	
	if(document.getElementById("connection_followers_list") && document.getElementById("connection_followers_list").checked) {
		formElements = document.getElementById('connection_followers_list').getElementsByTagName('input');	
	}
	
	for (var i = 0; i < formElements.length; i++) {	
		if(formElements[i].type == "checkbox" && formElements[i].checked && formElements[i].id.search("_notify") >= 0 ) {
			contactSelected = true;
			break;			
		}
	}	
	
	if (contactSelected) {
		$j("#perMsg").css("color", "#0000FF");	
		document.getElementById('msgbox').style.display = "table-row";
	} else {
		$j("#perMsg").css("color", "#999999");
		
		if(document.getElementById('msgbox') && document.getElementById('msgbox').style.display == "table-row") {
			document.getElementById('msgbox').style.display = "none";
			$j("#msgbox").children().children().val("Include a personal message to your contacts letting them know about what you have to share:\n\nEx: Come check out my new videos");
		}
	}		
}

function removeDefaultMessage(section_name,default_message,action) {
	if(document.getElementById(section_name + 'CustomNotifyMsg').value.length > 0 && action == "add") {
		if(document.getElementById(section_name + 'CustomNotifyMsg').value == default_message) {
			document.getElementById(section_name + 'CustomNotifyMsg').value = "";
		}
	}
}

function setDefaultMessage(section_name,default_message,action) {
	if(document.getElementById(section_name + 'CustomNotifyMsg').value.length < 1 && action == "add") {
		document.getElementById(section_name + 'CustomNotifyMsg').value = default_message;		
	}
}

function removeDefaultText(obj) {
	var textareaId = obj.id;
	if($j("#"+textareaId).val() == "Include a personal message to your contacts letting them know about what you have to share:\n\nEx: Come check out my new videos") {
		$j("#"+textareaId).val("");
		$j("#"+textareaId).attr("style","width:345px;height:90px;color:#000000");
	}
}

function setDefaultText(obj) {
	var textareaId = obj.id;	
	if($j("#"+textareaId).val().length < 1) {
		$j("#"+textareaId).val("Include a personal message to your contacts letting them know about what you have to share:\n\nEx: Come check out my new videos");		
		$j("#"+textareaId).attr("style","width:345px;height:90px;color:#999999");
	}
}

function removeDefaultPersonalNote(obj) {
	var textareaId = obj.id;
	if($j("#"+textareaId).val() == "e.g. Register your email address to receive updates, or to be entered for a monthly draw...") {
		$j("#"+textareaId).val("");
		$j("#"+textareaId).attr("style","width:450px;height:100px;color:#000000");
	}
}

function setDefaultPersonalNote(obj) {
	var textareaId = obj.id;	
	if($j("#"+textareaId).val().length < 1) {
		$j("#"+textareaId).val("e.g. Register your email address to receive updates, or to be entered for a monthly draw...");		
		$j("#"+textareaId).attr("style","width:450px;height:100px;color:#999999;");
	}
}

function deleteDefaultPersonalNote(personalNoteId) {
	
	if($j("#"+personalNoteId).val() == "e.g. Register your email address to receive updates, or to be entered for a monthly draw...") {
		$j("#"+personalNoteId).val("");		
	}
}

function duplicateProductName(formObj,productId){
   var productName = $j.trim(document.getElementById('ProductName').value);
	var product_category_id = $j.trim(document.getElementById('product_category_id').value);
	var description = CKEDITOR.instances.description.getData();
	var ProductActualPrice = $j.trim(document.getElementById('ProductActualPrice').value);
	if(productId==""){
		var frmName="ProductAddForm";
	}
	else{
		var frmName="ProductEditForm";
	}
	
	if(productName!="" && product_category_id!="" && description!="" && ProductActualPrice!="") {
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/products/checkDuplicate/'+productName+'/'+productId,
			data: "ajax=true",
			success: function(response) {
			
				if(response == "1")
				{		
					Modalbox.show(HOST_URL+site_root+'/products/productMessage/'+frmName, {title: 'Duplicate Product Name', height: 200,width:500, method: 'post', params: '', overlayClose: true }); 
		return false;	
				} else {
				  $j("#"+formObj.id).submit();
				  return true;	
				  //$j("#"+formObj.id).submit();
				}
			}
			
		});
	} else {
		$j("#"+formObj.id).submit();
		
	}
	return false;		
	
	
}
function removeDefaultPersonalMsg(formObj,sectionName) {
	if($j("#custom_notify_msg") && $j("#custom_notify_msg").val() == "Include a personal message to your contacts letting them know about what you have to share:\n\nEx: Come check out my new videos") {
		$j("#custom_notify_msg").val("");	
	}	
}





function fadetext(section_name){ 
	var hex=180;
	if(hex>0){ //If color is not black yet
		//hex-=11; // increase color darkness
		document.getElementById(section_name + 'CustomNotifyMsg').style.color="rgb("+hex+","+hex+","+hex+")";
	}
	else {
		hex=180 //reset hex value
	}
}

function saveNewPrivacy(field_name,model_name,privacy,title_text) {
		
		if(privacy == 0) 
			show_text = 'Everyone';
		if(privacy == 1) 
			show_text = 'All Connections';
		if(privacy == 2) 
			show_text = 'Only Me';		
		
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/business_profiles/savePrivacy/'+field_name + '/'+ model_name + '/' + privacy + '/' + title_text,
			data: "ajax=true",
			success: function(response) {//alert(response);
			
				if(response != "")
				{		
					var responseStringArray = response.split("||");
				//	document.getElementById('privacy_link_'+field_name).innerHTML = responseStringArray[0];
					document.getElementById('ulglobal_'+field_name).innerHTML = responseStringArray[1];	
					document.getElementById('linkglobal_'+field_name).innerHTML = "<small>"+show_text+"</small>";										
				}						
			}
		});
		return false;
}
/* START - Smart type search to generate custom connections list from all connections of an User - CR - ZV*/
/*$j(document).ready(function() {        
	$("#tokenize2").tokenInput(HOST_URL+site_root+"/albums/getCustomConnection", {
		prePopulate: [],
		classes: {
			tokenList: "token-input-list-facebook",
			token: "token-input-token-facebook",
			tokenDelete: "token-input-delete-token-facebook",
			selectedToken: "token-input-selected-token-facebook",
			highlightedToken: "token-input-highlighted-token-facebook",
			dropdown: "token-input-dropdown-facebook",
			dropdownItem: "token-input-dropdown-item-facebook",
			dropdownItem2: "token-input-dropdown-item2-facebook",
			selectedDropdownItem: "token-input-selected-dropdown-item-facebook",
			inputToken: "token-input-input-token-facebook"
		}
	});
});*/
/* END - Smarty type search to generate custom connections list from all connections of an User - CR - ZV*/

// Added By : AG On 6/1/2009
// Copyright (C) 2005-2008 Ilya S. Lyubinskiy. All rights reserved.
// Technical support: http://www.php-development.ru/
//
// YOU MAY NOT
// (1) Remove or modify this copyright notice.
// (2) Re-distribute this code or any part of it.
//     Instead, you may link to the homepage of this code:
//     http://www.php-development.ru/javascripts/dropdown.php
//
// YOU MAY
// (1) Use this code on your website.
// (2) Use this code as part of another product.
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind.
// You expressly acknowledge and agree that use of this code is at your own risk.


// ***** Popup Control *********************************************************

// ***** at_show_aux *****

function at_show_aux(parent, child)
{
  var p = document.getElementById(parent);
  var c = document.getElementById(child );

  var top  = (c["at_position"] == "y") ? p.offsetHeight+2 : 0;
  var left = (c["at_position"] == "x") ? p.offsetWidth +2 : 0;

  for (; p; p = p.offsetParent)
  {
    top  += p.offsetTop;
    left += p.offsetLeft;
  }

  c.style.position   = "absolute";
  c.style.top        = top +'px';
  c.style.left       = left+'px';
  c.style.visibility = "visible";
}

// ***** at_show *****

function at_show()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  at_show_aux(p.id, c.id);
  clearTimeout(c["at_timeout"]);
}

// ***** at_hide *****

function at_hide()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  c["at_timeout"] = setTimeout("document.getElementById('"+c.id+"').style.visibility = 'hidden'", 333);
}

// ***** at_click *****

function at_click()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  if (c.style.visibility != "visible") at_show_aux(p.id, c.id); else c.style.visibility = "hidden";
  return false;
}

// ***** at_attach *****

// PARAMETERS:
// parent   - id of the parent html element
// child    - id of the child  html element that should be droped down
// showtype - "click" = drop down child html element on mouse click
//            "hover" = drop down child html element on mouse over
// position - "x" = display the child html element to the right
//            "y" = display the child html element below
// cursor   - omit to use default cursor or specify CSS cursor name

function at_attach(parent, child, showtype, position, cursor)
{
  var p = document.getElementById(parent);
  var c = document.getElementById(child);
  
  if(p == null) return false;
  if(c == null) return false;
  
  p["at_parent"]     = p.id;
  c["at_parent"]     = p.id;
  p["at_child"]      = c.id;
  c["at_child"]      = c.id;
  p["at_position"]   = position;
  c["at_position"]   = position;

  c.style.position   = "absolute";
  c.style.visibility = "hidden";

  if (cursor != undefined) p.style.cursor = cursor;

  switch (showtype)
  {
    case "click":
      p.onclick     = at_click;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
    case "hover":
      p.onmouseover = at_show;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
  }
}
/* Start - Version 2.0 Follow Me - Email/SMS Notifications - AG */

// To follow up entity on different section
function followUp(userId,profileId,section,sectionId)
{
	
	//alert(document.getElementById('FollowupFollowup'));
	idVal="FollowupFollowup"	
	if(section==3){
		idVal="Followup"+sectionId;	
	}
	if(section==4){
		idVal="Followup"+sectionId;	
	}
	
	
	if(document.getElementById(idVal).checked)
		var newStatus = "1";
	else
		var newStatus = "0";
	
	//alert(userId+" "+profileId+" "+sectionId+" "+newStatus);
	//if(newStatus=="1"){
	$j.ajax({
		type: "POST",
		url: HOST_URL+site_root+'/Users/followup/'+userId+'/'+profileId+'/'+section+'/'+sectionId+'/'+newStatus,
		data: "",
		success: function(msg)
		{				
			//alert("res "+msg);
		}
	});
	//}
}
function acceptComment(section,sectionId)
{
	
	//alert(section);
	idVal=section+'AcceptComment';
	if(section=="Audio"){
		idVal=section+sectionId+'AcceptComment';
	}
	if(section=="Video"){
		idVal=section+sectionId+'AcceptComment';
	}
	
	
	if(document.getElementById(idVal).checked)
		var newStatus = "1";
	else
		var newStatus = "0";
	
	//alert(section+" "+sectionId+" "+newStatus);

	$j.ajax({
		type: "POST",
		url: HOST_URL+site_root+'/Users/acceptCommentFollowup/'+section+'/'+sectionId+'/'+newStatus,
		data: "",
		success: function(msg)
		{				
			//alert("res "+msg);
		}
	});

}
/* End - Version 2.0 Follow Me - Email/SMS Notifications  - AG */	


/*Start - version 2.1 Product module - JS */
function in_array (needle, haystack, argStrict) {

    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {         
				return true;
            }
        }
    }
     return false;
}

function isEmail(str){
	var nstr = trim(str);
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	return re.test(nstr);
}
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function loadEditor(id)
{
    var instance = CKEDITOR.instances[id];
    if(instance)
    {
        CKEDITOR.remove(instance);
    }
    CKEDITOR.replace(id);
}
function str_pad (input, pad_length, pad_string, pad_type) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://getsprink.com)
    // +      input by: Marco van Oort
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'

    var half = '', pad_to_go;

    var str_pad_repeater = function (s, len) {
        var collect = '', i;

        while (collect.length < len) {collect += s;}
        collect = collect.substr(0,len);

        return collect;
    };

    input += '';
    pad_string = pad_string !== undefined ? pad_string : ' ';
    
    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }
        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    }

    return input;
}
/*End- version 2.1 Product module - JS */

// Events calendar version 2.2 //

// The purpose of these functions is to find the absolute X and Y co-ordinates 
// of an HTML element. 
function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
		while(1) 
		{
		  curleft += obj.offsetLeft;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	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;
	return curtop;
}
// End of version 2.2 //
function chkPrice(obj,events)
{

	var unicodes=events.charCode? events.charCode :events.keyCode;	
	//alert(unicodes);
	var getdot =0;
	if (unicodes!=8)
	{ //backspace
	        if((unicodes>47 && unicodes<58 || unicodes == 46 || unicodes == 9)){
				var dd= obj.value;
				for(i=0;i<dd.length+1;i++){
					if(dd.charAt(i) == "."){
						getdot = getdot+1;
					}					
				}
				
				if(getdot > 0 && unicodes == 46){
					if(events.charCode == 0){
						
						return true;
					}else{	
						return false;
					}
				}else{					
					return true;
				}	            
			}else{			
				if(events.charCode == 0){					
					return true;
				}else{	
					return false; 
				}
			}	
	}
}

function checkUncheckNonSohoContacts(bool,name) {	
	var collection = document.getElementById('contacts').getElementsByTagName('input');					
	for(i=0; i< collection.length; i++) {		 
		if(collection[i].type == "checkbox") {
 			if(collection[i].id == name && collection[i].value != -1)  { 		
				collection[i].checked = bool;					
			}
		}
	}		
}

function accessRightsPreMsg(appType,appId,appAccess,detail_id) {
	if(appAccess == 0) {
		window.location = HOST_URL+site_root+'/messages/compose?premsg='+appType+'&val='+appId+'&appAccess=0&detailId='+detail_id;		
	} else {
		if(confirm("By sharing this with your Email contacts,the Privacy setting " +
				   	"of this album will change to 'Everyone' meaning connection or not will "+
					" be able to view this album. Do you wish to Continue?"))	
			window.location = HOST_URL+site_root+'/messages/compose?premsg='+appType+'&val='+appId+'&appAccess=1&detailId='+detail_id;	
	}	
}

/* Open video/audio in pop up window */
function watchPopOut(URL,windowName,width,height)
{
	var width=width;
	var height=height;
	var from_top=350;
	var from_left=500;
	var toolbar='no';
	var location='no';
	var directories='no';
	var status='no';
	var menubar='no';
	var scrollbars='yes';
	var resizable='yes';
	var atts='width='+width+',height='+height+',top='+from_top+',screenY=';
	atts+= from_top+',left='+from_left+',screenX='+from_left+',toolbar='+toolbar;
	atts+=',location='+location+',directories='+directories+',status='+status;
	atts+=',menubar='+menubar+',scrollbars='+scrollbars+',resizable='+resizable;
	var newPopupWindow;
	var newPopupWindow = window.open(URL,windowName,atts);
	if (window.focus) {newPopupWindow.focus()}
}

function showAlbumList(id,album_id,photo_id,separatedBy)
{
	var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById(id).innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/albums/generateAlbumLists/'+album_id+'/'+photo_id+'/'+separatedBy,
			data: "ajax=true",
			success: function(msg) {
				if(msg != "")
				{			
					$j('#'+id).show();
					$j('#'+id).html(msg);					
					return true;
				}						
			}
		});
		return false;
}

function showAudioAlbumList(id,album_id,audio_id,separatedBy)
{
	var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById(id).innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/audios/generateAlbumLists/'+album_id+'/'+audio_id+'/'+separatedBy,
			data: "ajax=true",
			success: function(msg) {
				if(msg != "")
				{			
					$j('#'+id).show();
					$j('#'+id).html(msg);					
					return true;
				}						
			}
		});
		return false;
}

function showVideoAlbumList(id,album_id,video_id,separatedBy)
{
	var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById(id).innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/videos/generateAlbumLists/'+album_id+'/'+video_id+'/'+separatedBy,
			data: "ajax=true",
			success: function(msg) {
				if(msg != "")
				{			
					$j('#'+id).show();
					$j('#'+id).html(msg);					
					return true;
				}						
			}
		});
		return false;
}

function showFileFolderList(id,folder_id,file_id,separatedBy)
{
	var ajaxLoader = "Loading data Please wait... <img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Loading data Please wait...' title='Loading data Please wait...' border='0'>";
		document.getElementById(id).innerHTML = ajaxLoader;
		
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/FileFolders/generateFolderLists/'+folder_id+'/'+file_id+'/'+separatedBy,
			data: "ajax=true",
			success: function(msg) {
				if(msg != "")
				{			
					$j('#'+id).show();
					$j('#'+id).html(msg);					
					return true;
				}						
			}
		});
		return false;
}

function hideAlbumList(id)
{
	$j('#'+id).hide();
	return true;	
}

function removeAlbumDefaultMessage(id,default_message) {
	if(document.getElementById(id).value.length > 0)
	{
		if(document.getElementById(id).value == default_message)
		{
			document.getElementById(id).value = "";
		}
	}
}

function setAlbumDefaultMessage(id,default_message) {
	if(document.getElementById(id).value.length < 1)
	{
		document.getElementById(id).value = default_message;		
	}
}

function callMembershipQuotaExpiredModalBox() {

		Modalbox.show(HOST_URL+site_root+'/albums/membershipQuotaAlert', {title: 'Membership Quota Limit', height: 150,width:500, method: 'post', params: '', overlayClose: true }); 
		return false;		
}

function getChronologicalOrderUpdate(startLimit, endLimit, totalUpdates){
		var ajaxLoader = "Loading updates Please wait... <img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' alt='Loading updates Please wait...' title='Loading updates Please wait...' border='0'>";
		
		if(startLimit == 0) {
			$j('#whatsup').html(ajaxLoader);
		} else {
			$j('#statusTable'+startLimit).html(ajaxLoader);
		}
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Users/getChronologicalUpdate/'+startLimit+'/'+endLimit+'/'+totalUpdates,					
					data: "ajax=true",
					success: function(msg)
					{//alert(msg);
						if(startLimit == 0) {
							$j('#whatsup').html(msg);
						} else {
							$j('#statusTable'+startLimit).html(msg);						
						}
					}
		});	
}
function cancelModalBox() {
	Modalbox.hide();
}
function SubmitForm(frmName) {
	//alert(frmName);
	Modalbox.hide();
	window.parent.document.getElementById(frmName).submit();
}

function getCityProvince(obj) {
		//alert(obj.value);
		document.getElementById('tr_id').style.display = "";
		var ajaxLoader = "<img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Processing please wait...' title='Processing please wait...' border='0'>";
		document.getElementById('ajax_loader').innerHTML = ajaxLoader;
		
		if(type == 'personal') {
			var countryCode = document.getElementById('ConsumerProfileCountry').value;			
			var profile = 'ConsumerProfiles';
		} else {			
			var profile = 'BusinessProfiles';
			var countryCode = document.getElementById('BusinessProfileCountry').value;
		}
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/'+profile+'/getCityProvince/'+countryCode+'/'+obj.value,
			data: "ajax=true",
			success: function(msg) {
				//alert(msg);
				if(msg != "") {				
					document.getElementById('ajax_loader').innerHTML = "";
					document.getElementById('tr_id').style.display = "none";						
					var city_province = msg.split("||");					
					if(city_province[0] != "") {
						//document.getElementById('city_td').innerHTML = city_province[0];
					}
					if(city_province[1] != "") {
						//document.getElementById('province_td').innerHTML = city_province[1];
					}					
				}		
				
			}
		});
		return false;
}
	
function getProvince(obj) {
		
		
		document.getElementById('tr_id').style.display = "";
		var ajaxLoader = "<img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Processing please wait...' title='Processing please wait...' border='0'>";
		document.getElementById('ajax_loader').innerHTML = ajaxLoader;
		
		if(type == 'personal') {
			var countryCode = document.getElementById('ConsumerProfileCountry').value;			
			//var profile = 'ConsumerProfiles';
			var provinceObj = document.getElementById('ConsumerProfileProvince');
		} else {			
			//var profile = 'BusinessProfiles';
			var countryCode = document.getElementById('BusinessProfileCountry').value;
			var provinceObj = document.getElementById('BusinessProfileProvince');
		}
		
		var profile = 'ConsumerProfiles';
		//alert(countryCode);
		//alert(obj.value);
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/Users/getProvince/'+countryCode+'/'+obj.value+'/'+type,
			data: "ajax=true",
			success: function(msg) {
			//alert(msg);
				if(msg != "") {				
					
					document.getElementById('ajax_loader').innerHTML = "";
					document.getElementById('tr_id').style.display = "none";										
					document.getElementById('province_td').innerHTML = msg;
					 //alert(provinceObj);
					 //provinceObj.focus();
				}		
				
			}
		});
		return false;
}
	
function getCity() {
		
		//alert("city");
		document.getElementById('tr_id').style.display = "";
		var ajaxLoader = "<img src='"+HOST_URL+site_root+"/img/ajax-loader.gif' alt='Processing please wait...' title='Processing please wait...' border='0'>";
		document.getElementById('ajax_loader').innerHTML = ajaxLoader;
		
		if(type == 'personal') {
			var countryCode = document.getElementById('ConsumerProfileProvince').value;			
			//var profile = 'ConsumerProfiles';
		} else {			
			//var profile = 'BusinessProfiles';
			var countryCode = document.getElementById('BusinessProfileProvince').value;
		}
		
		var profile = 'ConsumerProfiles';
		//alert(countryCode);
		//alert(obj.value);
		$j.ajax({
			type: "POST",
			url: HOST_URL+site_root+'/Users/getCity/'+countryCode+'/'+type,
			data: "ajax=true",
			success: function(msg) {
			//alert(msg);
				if(msg != "") {				
					
					document.getElementById('ajax_loader').innerHTML = "";
					document.getElementById('tr_id').style.display = "none";										
					//if(city_province[1] != "") {
						document.getElementById('city_td').innerHTML = msg;
					//}
									
				}		
				
			}
		});
		return false;
}

function showLeftMenu(arg) {
	if(arg) {
		$j("#masterdiv tr").each(function() {
			if($j(this).hasClass('leftMenuHide')) {							   
				$j(this).removeClass('leftMenuHide').addClass('leftMenuShow');		
			}
		});
		
		$j("#lessLeftMenu").show();
		$j("#moreLeftMenu").hide();				
	}else {
		$j("#masterdiv tr").each(function() {
			if($j(this).hasClass('leftMenuShow')) {				
				$j(this).removeClass('leftMenuShow').addClass('leftMenuHide');		
			}
		});
		$j("#moreLeftMenu").show();
		$j("#lessLeftMenu").hide();		
	}
}

function createUserInfo(data) {	
	user_id = data['U']['id'];
	role_id = data['U']['role_id'];
	if(role_id == 1) {
		profile_id = data['C']['id'];
		name = data['U']['firstname']+' '+data['U']['lastname'];
		city = data['C']['city'];
		profileType = 'ConsumerProfiles';
	}
	else {	
		profile_id = data['B']['id'];
		name = data['U']['profile_name'];		
		city = data['B']['city'];	
		profileType = 'BusinessProfiles';
	}

	coutnryName = data[0]['coutnryName'];
	friend = data[0]['friend'];
		
	html = '';
	html = '<div style="width:200px">';
	html += '<span style="float:left;width:45px;padding-left:5px;">';	
	html += '<img src='+HOST_URL+site_root+'/users/memberphoto/'+profile_id+'/'+role_id+'>';		
	html += '</span>';
	html += '<span style="width:110px;vertical-align:top;padding-left;5px;float:left;">';	
	html += '<a href="'+HOST_URL+site_root+'/'+profileType+'/profile/'+profile_id+'" target="_blank">'+name+'</a><Br>'+city+'-'+coutnryName;	
	html += '</span>';
	html += '<span style="width:30px;vertical-align:top;padding-left;5px;">';	
	/*if(friend == 1) {
		html += '<img src='+HOST_URL+site_root+'/img/icon1st.png>';			
	}*/
	html += '</span>';	
	html += '</div>';	
	return html;
}
//--------------------------------------AppointmentPersonHistory-----------------------------//
function viewSOHOAppointmentHistory(userid,profileid,startdata,starthr,startmin,stsrtampm,placeid) {
	
	$j.ajax({
		type: "POST",
		url: HOST_URL+site_root+'/events/viewAppointmentHistory',
		data:"userid="+userid+"&profileid="+profileid+"&startdata='"+startdata+"'&starthr="+starthr+"&startmin="+startmin+"&stsrtampm="+stsrtampm+"&placeid="+placeid,
		success: function(responseText) {
			if(responseText != 0) {
				$j("#historyDivappointment_"+placeid).html(responseText);
			} else {
				$j("#historyDivappointment_"+placeid).html('');
			}
		}
	});	
}
//----------------------------------------------------------------------------------------//
function createAppointmentUserInfo(data) {	
	user_id = data['U']['id'];
	role_id = data['U']['role_id'];
	var city ='';
	
	if(role_id == 1) {
		profile_id = data['C']['id'];
		toprofileid = profile_id;
		name = data['U']['firstname']+' '+data['U']['lastname'];
		if(data['C']['city']!=null) {
			city = data['C']['city'];
		} else {
			city = '';
		}
		profileType = 'ConsumerProfiles';
	}
	else {	
		profile_id = data['B']['id'];
		toprofileid = profile_id;
		name = data['U']['profile_name'];		
		if(data['B']['city']!=null) {
			city = data['B']['city'];
		} else {
			city ='';
		}
		profileType = 'BusinessProfiles';
	}
	coutnryName = data[0]['coutnryName'];
	friend = data[0]['friend'];
	html = '';
	html = '<div style="width:200px">';
	html += '<span style="float:left;width:45px;padding-left:5px;">';	
	html += '<img src='+HOST_URL+site_root+'/users/memberphoto/'+profile_id+'/'+role_id+'>';		
	html += '</span>';
	html += '<span style="width:110px;vertical-align:top;padding-left;5px;float:left;">';	
	html += '<a href="'+HOST_URL+site_root+'/'+profileType+'/profile/'+profile_id+'" target="_blank">'+name+'</a><Br>'+city+'-'+coutnryName;		
	html += '</span>';
	html += '<span style="width:30px;vertical-align:top;padding-left;5px;">';	
	html += '</span>';	
	html += '</div>';	
	
	return html;
}


function createRebateUserInfo(data) {	
	user_id = data['U']['id'];
	role_id = data['U']['role_id'];
	if(role_id == 1) {
		profile_id = data['C']['id'];
		name = data['U']['firstname']+' '+data['U']['lastname'];
		city = data['C']['city'];
	}
	else {	
		profile_id = data['B']['id'];
		name = data['U']['profile_name'];		
		city = data['B']['city'];		
	}

	coutnryName = data[0]['coutnryName'];
	friend = data[0]['friend'];
	
	var membertype = data['RC']['is_member'];	 
	label	= '';
	html = '';
	html = '<div style="width:200px;height:60px;">';
	html += '<span style="float:left;width:45px;height:60px;padding-left:5px;">';	
	html += '<img src='+HOST_URL+site_root+'/users/memberphoto/'+profile_id+'/'+role_id+'>';
	html += '</span>';
	html += '<span style="width:110px;vertical-align:top;padding-left;5px;float:left;">';	
	html += name+'<Br>'+city+'-'+coutnryName;	
	html += '</span>';
	
	html += '</div>';	
	return html;
}

function getAllThumbsUpMember(user_id,profile_id,section_id,startLimit, endLimit, totalThumbsup, item_id,is_employee,employer_id){
		var ajaxLoader = "Loading updates Please wait... <img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' alt='Loading updates Please wait...' title='Loading updates Please wait...' border='0'>";
		
		if(startLimit == 0) {
			$j('#thumbs_up').html(ajaxLoader);
		} else {
			$j('#showMoreThumbsUp'+startLimit).html(ajaxLoader);
		}
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/getAllThumbsUpMember/'+user_id+'/'+profile_id+'/'+section_id+'/'+startLimit+'/'+endLimit+'/'+totalThumbsup+'/'+item_id+'?emp='+is_employee+'&eid='+employer_id,				
					data: "ajax=true",
					success: function(msg)
					{
						if(startLimit == 0) {
							$j('#thumbs_up').html(msg);
						} else {
							$j('#showMoreThumbsUp'+startLimit).html(msg);						
						}
					}
		});	
}

function getOtherConnections(user_id,profile_id,startLimit, endLimit){
		var ajaxLoader = "Loading updates Please wait... <img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' alt='Loading updates Please wait...' title='Loading updates Please wait...' border='0'>";
		
		
			$j('#showMoreConnection'+startLimit).html(ajaxLoader);
		
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Users/showOtherConnections/'+user_id+'/'+profile_id+'/'+startLimit+'/'+endLimit,				
					data: "ajax=true",
					success: function(msg)
					{
						
							$j('#showMoreConnection'+startLimit).html(msg);						
						
					}
		});	
}

function giveThumbsUpDown(user_id,profile_id,section_id,action,is_employee,employer_id){
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/giveThumbsUp/'+user_id+'/'+profile_id+'/'+section_id+'/'+action+'?emp='+is_employee+'&eid='+employer_id,				
					data: "ajax=true",
					success: function(msg)
					{
						if(msg == AJAX_RESPONSE_NO_ACCESS_MSG) {
							alert(AJAX_RESPONSE_NO_ACCESS_MSG);
							return false;
						}
						
						var msgArr = msg.split("##");
						$j('#tot_thumbsup').html(msgArr[0]);
						$j('#thumbsUpDown').html(msgArr[1]);						
					}
		});	
}


function deleteStatus(id,feed_limit,displayUpdate,user_id,profile_id){
	
	if(confirm('Are you sure, you want to delete?')) {
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Users/deleteStatus/'+id,				
					data: "ajax=true",
					success: function(msg)
					{
						//var msgArr = msg.split("##");
						if(displayUpdate==1){
							
							getChronologicalOrderUpdate(0,feed_limit,0);
						}
						else if(displayUpdate==2){
							
						status_static_string = 	$j("#sample_attach_menu_parent_status_count").html();
						status_start_pos = status_static_string.indexOf("(") + 1;
						status_last_pos = status_static_string.indexOf(")");
						status_len  = status_last_pos - status_start_pos;
						finded_string = status_static_string.substr(status_start_pos,status_len);						
						//alert(finded_string);
						if(parseInt(finded_string) != 0){	
							finded_string=finded_string-1;
							//alert(finded_string);
							$j("#sample_attach_menu_parent_status_count").html("Status Updates("+finded_string+")");		
							//alert($j("#sample_attach_menu_parent_status_count").html);
						}
		 
							getStatusUpdates(0,'all',0);	
						}
						else if(displayUpdate==4){
								window.location = HOST_URL+site_root+'/BusinessProfiles/profile';	
						}
						else if(displayUpdate==5){
							window.location = HOST_URL+site_root+'/ConsumerProfiles/profile';	
						}
						else{
							window.location = HOST_URL+site_root+'/Users/previousStatus/'+user_id+'/'+profile_id;			
						}
					}
		});	
		 
		

	}
}

function deleteComment(comment_id,to_user_id,to_profile_id,section_id,limit,is_employee,employer_id){

	if(confirm('Are you sure, you want to delete?')) {
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/deleteComment/'+comment_id+'/'+to_user_id+'/'+to_profile_id+'/'+section_id+'/'+is_employee+'/'+employer_id,				
					data: "ajax=true",
					success: function(msg)
					{
						var msgArr = msg.split("##");						
						if(msgArr[0] == 1) {
							$j('#com_'+comment_id).remove();
							showAllComments(to_user_id,to_profile_id,section_id,is_employee,employer_id,limit);		
							$j("#viewAllComments").html(msgArr[1]);							
						}
					}
		});	
	}
}


function deleteCommentStatus(comment_id,to_user_id,to_profile_id,section_id,totComments,itemId){
	//alert(totComments);
	
	if(confirm('Are you sure, you want to delete?')) {
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/deleteCommentStatus/'+comment_id+'/'+to_user_id+'/'+to_profile_id+'/'+section_id+'/'+totComments+'/'+itemId,				
					data: "ajax=true",
					success: function(msg)
					{
											
						var msgArr = msg.split("##");

						if(msgArr[0] == 1) {
							$j('#com_'+comment_id).remove();								
							$j('#viewAllComments'+itemId).html(msgArr[1]);		
						}
					}
		});	
	}
}

function ajaxSaveComment(to_user_id,to_profile_id,section_id,is_employee,employer_id,startLimit){
	
		var comment = encodeURIComponent($j('#CommentComment').attr('value'));
		
		 $j.ajax({
				type: "POST",
				url: HOST_URL+site_root+'/Comments/ajaxSaveComment',				
				data: "to_user_id="+to_user_id+"&to_profile_id="+to_profile_id+"&section_id="+section_id+"&comment="+comment+"&emp="+is_employee+"&eid="+employer_id+"&ajax=true",
				success: function(msg)
				{
					if(msg == AJAX_RESPONSE_NO_ACCESS_MSG) {
						//alert(AJAX_RESPONSE_NO_ACCESS_MSG);
						callEmployeeNoAccessModalBox();
						return false;
					}
					
					if(msg!='N')
					{
						var msgArr = msg.split("##");
						if(msgArr[0] != '') {
							$j("#commentList").prepend(msgArr[0]);	
						}
						$j("#CommentComment").attr('value','Write a comment...');	
						$j("#btnSubmitComment").attr('style','display:none');						
					}
				}
		});	
}
 
function ajaxEnterSaveComment(to_user_id,to_profile_id,section_id,item_id,startLimit,totalComment){
		
		var commentOriginal = encodeURIComponent($j('#comment'+item_id).attr('value'));
		var comment=$j.trim(commentOriginal);
		if(comment == '' || comment == 'Write a comment...'){
			return false;
		}
		else{
		 $j.ajax({
				type: "POST",
				url: HOST_URL+site_root+'/Comments/ajaxSaveComment',				
				data: "to_user_id="+to_user_id+"&to_profile_id="+to_profile_id+"&section_id="+section_id+"&comment="+comment+"&item_id="+item_id+"&totalComment="+totalComment+"&ajax=true",
				success: function(msg)
				{
					if(msg == AJAX_RESPONSE_NO_ACCESS_MSG) {
						//alert(AJAX_RESPONSE_NO_ACCESS_MSG);
						callEmployeeNoAccessModalBox();
						return false;
					}

					if(msg!='N')
					{
					var msgArr = msg.split("##");
					if(msgArr[0] != '') {
						$j("#commentList"+item_id).append(msgArr[0]);	
					}
					$j('#comment'+item_id).attr('value','Write a comment...');							
					$j("#btnSubmitComment"+item_id).attr('style','display:none');
					$j('#comment'+item_id).attr('style','color:#777777;height:18px;');
					$j("#viewAllComments"+item_id).html(msgArr[1]);	
					//$j("#hdnPageNo"+item_id).val(msgArr[2]);
					$j('#commentGrowId'+item_id).attr('style','height:18px;');
					
					if(msgArr[3] > msgArr[4] ) {
						$j("#viewAllComments"+item_id).show();
					}
					
				}
				}
		});	
		}
		
		
}


function allComments(to_user_id,to_profile_id,section_id,limit,is_employee,employer_id){
		var ajaxLoader = "Please wait while comments are being loaded... <img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' alt='Loading updates Please wait...' title='Loading updates Please wait...' border='0'>";
		$j('#commentList').html(ajaxLoader);
		 $j.ajax({
				type: "POST",
				url: HOST_URL+site_root+'/Comments/getAllComments/'+to_user_id+'/'+to_profile_id+'/'+section_id+'/'+limit+'?emp='+is_employee+'&eid='+employer_id,				
				data: "ajax=true",
				success: function(msg)
				{
					$j("#commentList").html(msg);												
				}
			});	
}

function showAllCommentsStatus(user_id,profile_id,section_id,item_id){
	
		var ajaxLoader = "Loading updates Please wait... <img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' alt='Loading updates Please wait...' title='Loading updates Please wait...' border='0'>";
		
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/showAllCommentsStatus/'+user_id+'/'+profile_id+'/'+section_id+'?itemId='+item_id,				
					data: "ajax=true",
					success: function(msg)
					{
						//alert(msg);
						var msgArr = msg.split("##");
						$j('#commentList'+item_id).html(msgArr[0]);
						$j('#viewAllComments'+item_id).html(msgArr[1]);															
					}
		});	
}

function showPreviousCommentsStatus(user_id,profile_id,section_id,itemId){
	
		var ajaxLoader = "Loading updates Please wait... <img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' alt='Loading updates Please wait...' title='Loading updates Please wait...' border='0'>";
		
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/showPreviousCommentsStaus/'+user_id+'/'+profile_id+'/'+section_id+'/'+itemId,				
					data: "ajax=true",
					success: function(msg)
					{
						var msgArr = msg.split("##");						
						$j("#commentList"+itemId).html(msgArr[0]);	
						$j('#viewAllComments'+itemId).html(msgArr[1]);								
					}
		});	
}



function showAllComments(user_id,profile_id,section_id,is_employee,employer_id,limit){
		var ajaxLoader = "Loading updates Please wait... <img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' alt='Loading updates Please wait...' title='Loading updates Please wait...' border='0'>";
		if (typeof limit == 'undefined') {
			var limit = 'all';
		}
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/showAllComments/'+user_id+'/'+profile_id+'/'+section_id+'/'+limit+'?emp='+is_employee+'&eid='+employer_id,				
					data: "ajax=true",
					success: function(msg)
					{
						var msgArr = msg.split("##");
						$j('#commentList').html(msgArr[0]);
						$j('#viewAllComments').html(msgArr[1]);															
					}
		});	
}

function limitText(limitField, limitCount,id) {
	var limitNum = 2000;
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		document.getElementById('ReferralCountdown').value = limitNum - limitField.value.length;
	}
}

function addNewEmailContactField() {
	for(i=1; i <= 5 ; i++) {
		first_tr = 'newEmailContact'+i;
		second_tr = 'newEmailContactError'+i;
		if(document.getElementById(first_tr).style.display == 'none') {
			document.getElementById(first_tr).style.display = '';
			document.getElementById(second_tr).style.display = '';		
			break;
		}
	}	
}

function removeNewEmailContactField(id) {
	first_tr = 'newEmailContact'+id;
	second_tr = 'newEmailContactError'+id;
	document.getElementById(first_tr).style.display = 'none';
	document.getElementById(second_tr).style.display = 'none';	
	document.getElementById('Message'+id+'Fname').value = '';
	document.getElementById('Message'+id+'Lname').value = '';
	document.getElementById('Message'+id+'Email').value = '';
}

function openRecipientsDiv()
{
	$j('#div_emailrecipient').show('slow');
	clearallemails();
	for(var i =2; i <= 5 ;i++) { 
		temp_name = 'newEmailContact'+i;
		temp_error = 'newEmailContactError'+i;
		$j("#"+temp_name).hide();
		$j("#"+temp_error).hide();
	}
}

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){		   
		return false
	 }
	 return true					
}
function closeRecipientsDiv(close_type)
{
	var false_flag = false;
	var value = '';
	if(close_type == 0)  {
		$j('#div_emailrecipient').hide('slow');
		clearallemails();
	}
	else{
		
		for(var i =1; i <= 5 ;i++) { 
			contact_name = '';
			temp_fname = "Message"+i+"Fname";
			temp_lname = "Message"+i+"Lname";
			temp_email = "Message"+i+"Email";
			temp_error = "MessageError"+i;

			if(!$j("#"+temp_email).val()) 
					continue;

			if(!echeck($j("#"+temp_email).val())) 
			{
				$j("#"+temp_error).html("Enter Proper Email Address");
				false_flag = true;
				continue;			
			}
			
			contact_name = $j("#"+temp_fname).val()+" "+$j("#"+temp_lname).val();
			
			if(i == 1)
				value = contact_name+":"+$j("#"+temp_email).val();	
			else 
				value = value +";"+contact_name+":"+$j("#"+temp_email).val();	
		}
		
		if(value != '' && !false_flag) {
			$j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/messages/addEmail?value='+value,
					data: "",
					success: function(transport)
					{	
						getAllEmailContacts();
					}
				});	
		}
		if(!false_flag) {
			$j('#div_emailrecipient').hide('slow');	
			clearallemails();
		}
	}
	
}

function clearallemails() {
	for(var i =1; i <= 5 ;i++) { 
		temp_fname = "Message"+i+"Fname";
		temp_lname = "Message"+i+"Lname";
		temp_email = "Message"+i+"Email";
		error_msg = "MessageError"+i;
		
		$j("#"+temp_fname).val('');
		$j("#"+temp_lname).val('');
		$j("#"+temp_email).val('');
		$j("#"+error_msg).html('');
		
	}				
}

function getAllConnections() {
	$j('#listAllCon').html("<img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' align='center' alt='Loading email contacts' title='Loading email contacts' border='0'>");
		 
	$j.ajax({
		type: "POST",
		url: HOST_URL+site_root+'/messages/sohoContactTool/0',
		data: "",
		success: function(transport)
		{	
			$j('#listAllCon').html(transport);			
		}
	});	
}

function getAllEmailContacts() {
	if(document.getElementById('listAllCon')) {
		$j('#listAllCon').html("<img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' align='center' alt='Loading email contacts' title='Loading email contacts' border='0'>");
	} else {
			$j('#contacts').html("<img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' align='center' alt='Loading email contacts' title='Loading email contacts' border='0'>");
	}
		 
	$j.ajax({
		type: "POST", 
		url: HOST_URL+site_root+'/deal_invited_emails/nonSohoContact/0',
		data: "",
		success: function(transport)
		{	
			if(document.getElementById('listAllCon')) {
				$j('#listAllCon').html(transport);			
			} else {
				$j('#contacts').html(transport);
			}
		}
	});	
}

function giveThumbsUpDownStatus(user_id,profile_id,section_id,action,item_id){
		
		 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/giveThumbsUpStat/'+user_id+'/'+profile_id+'/'+section_id+'/'+action+'/'+item_id,				
					data: "ajax=true",
					success: function(msg)
					{	
						if(msg == AJAX_RESPONSE_NO_ACCESS_MSG) {
							//alert(AJAX_RESPONSE_NO_ACCESS_MSG);
							callEmployeeNoAccessModalBox();
							return false;
						}
						var msgArr = msg.split("##");
						
						$j('#tot_thumbsup'+item_id).html(msgArr[0]);
						$j('#thumbsUpDown'+item_id).html(msgArr[1]);						
					}
		});	
}


function addElement(parentId, html) {
	// Append an html to the parentId	
	$j('#inputText').append(html);
}

function removeElement(elementId) {
	--textBoxId;
	$j('#'+elementId).remove();	
}

function addTextBox() {
	if(textBoxId == 10) { 
		alert('You can only refer recommendation to only 10 email contacts at a time.'); 
		return false;
	}
	textBoxId++; // increment textBoxId to get a unique ID for the new element
	var html = '<tr id="text_' + textBoxId+'"><td width="29%" align="left"><input type="text" style="width: 120px;" class="txtbox" value="" size="50" name="data[Referral][to_first_name][]" id="ReferralToFirstName'+ textBoxId+'"></td><td width="30%" align="left"><input type="text" style="width: 120px;" class="txtbox" value="" size="50" name="data[Referral][to_last_name][]" id="ReferralToLastName'+ textBoxId+'"></td><td align="left"><input type="text" style="width: 120px;" class="txtbox" value="" size="50" name="data[Referral][to_email][]" id="ReferralToEmail'+ textBoxId+'">' + '&nbsp;<a href="javascript:void(0);" onclick="javascript:removeElement(\'text_' + textBoxId + '\'); return false;">Remove</a></td></tr>';	
	addElement('inputText',html);		
}

function validateReferToEmailContactsForm() {
	 $j(".error").hide();
        var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		
		var fromFirstname = $j("#ReferralFirstName").val();
        if(fromFirstname == '') {
            $j("#ReferralFirstName").after('<span class="error"><br />Please enter first name.</span>');
            hasError = true;
        }
		
		var fromlastname = $j("#ReferralLastName").val();
		if(fromlastname == '') {
            $j("#ReferralLastName").after('<span class="error"><br />Please enter last name.</span>');
            hasError = true;
        }
 
        var emailaddressVal = $j("#ReferralEmail").val();
        if(emailaddressVal == '') {
            $j("#ReferralEmail").after('<span class="error"><br />Please enter your email address.</span>');
            hasError = true;
        }
 
        else if(!emailReg.test(emailaddressVal)) {
            $j("#ReferralEmail").after('<span class="error"><br />Enter a valid email address.</span>');
            hasError = true;
        }
		
		for(var i = 0; i<=11; i++) {			
			var toFirstname = $j("#ReferralToFirstName"+i).val();			
			if(toFirstname == '') {
				$j("#ReferralToFirstName"+i).after('<span class="error"><br />Please enter first name.</span>');
				hasError = true;
			}	
			var toLastname = $j("#ReferralToLastName"+i).val();
			if(toLastname == '') {
				$j("#ReferralToLastName"+i).after('<span class="error"><br />Please enter last name.</span>');
				hasError = true;
			}	
			
			var to_email = $j("#ReferralToEmail"+i).val();
			if(to_email == '') {
				$j("#ReferralToEmail"+i).after('<span class="error"><br />Please enter email address.</span>');
				hasError = true;
			}
			else if(typeof to_email != 'undefined' && !emailReg.test(to_email)) {
				$j("#ReferralToEmail"+i).after('<span class="error"><br />Enter a valid email address.</span>');
				hasError = true;
			}			
		}
		
		var referralMsg = $j("#ReferralMessage").val();
		if(referralMsg == '') {
			$j("#ReferralMessage").after('<span class="error"><br />Please enter recommendation message.</span>');
			hasError = true;
		}
 		
        if(hasError == true) { return false; } 		
}

function validateReferConnectionsForm() {
	 $j(".error").hide();
        var hasError = false;
       
		var referralMsg = $j("#ReferralMessage").val();
		if(referralMsg == '') {
			$j("#ReferralMessage").after('<span class="error"><br />Please enter referral message.</span>');
			hasError = true;
		}
 		
		var total_connections = parseInt($j("#countOfSelectedConnection").text());
		var total_email_contacts = parseInt($j("#countOfSelectedContacts").text());
		var total_recipients = parseInt(total_connections) + parseInt(total_email_contacts);
		
		if(total_recipients == 0) {
			$j("#recipient_error").after('<span class="error"><br />Please select referral recipients</span>');
			hasError = true;
		}
		
        if(hasError == true) { return false; } 		
		clearFormFieldValue();
}

function getEmailContacts() {	     
	$j('#contacts').html("<img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' align='center' alt='Loading connections' title='Loading connections' border='0'>");
	$j.ajax({
		type: "POST",
		url: HOST_URL+site_root+'/messages/nonSohoContact/0',
		data: "",
		success: function(transport)
		{	
			$j('#contacts').html(transport);			
		}
	});	
}

function getSOHOConnections () {	     
	$j('#listAllCon').html("<img src='"+HOST_URL+site_root+"/img/facebook_loader.gif' align='center' alt='Loading email contacts' title='Loading email contacts' border='0'>");
	     
	$j.ajax({
		type: "POST",
		url: HOST_URL+site_root+'/announcements/sohoContact/0',
		data: "",
		success: function(transport)
		{	
			$j('#listAllCon').html(transport);			
		}
	});	
}

function showDeleteIcon(commentOwnerId,loggedInUserId,profileOwnerId,commentDivId,employerProfileId,loggedInProfileId) {
	if((parseInt(commentOwnerId) == parseInt(loggedInUserId)) || (parseInt(profileOwnerId) == parseInt(loggedInUserId)) || (parseInt(employerProfileId) == parseInt(loggedInProfileId)) ) {
		$j('#'+commentDivId).show();
	}
}

function hideDeleteIcon(commentDivId) {
	$j('#'+commentDivId).hide();
}


function showDeleteIconStatus(commentOwnerId,loggedInUserId,commentDivId) {
	if((parseInt(commentOwnerId) == parseInt(loggedInUserId)) ) {
		$j('#del'+commentDivId).show();
	}
}

function hideDeleteIconStatus(commentDivId) {
	$j('#del'+commentDivId).hide();
}


function activeComment(commentId){
 $j.ajax({
					type: "POST",
					url: HOST_URL+site_root+'/Comments/activeComment/'+commentId,				
					data: "ajax=true",
					success: function(msg)
					{							
						$j('#postId'+commentId).hide();						
						$j('#pend'+commentId).hide();	
						$j('#conRequest'+commentId).hide();							
					}
		});		
}

function hideSingleName(itemId){
	$j('#singleUser'+itemId).hide();
}

function displaySingleName(totalPeople,itemId){
	if(totalPeople==1){	
	$j('#singleUser'+itemId).show();
	}
}

function radioEffect() {
	var d = document;
    var safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1) ? true : false;
    var gebtn = function(parEl,child) {  return parEl.getElementsByTagName(child); };
    onload = function() {
        
        var body = gebtn(d,'body')[0];
        body.className = body.className && body.className != '' ? body.className + ' has-js' : 'has-js';
        
        if (!d.getElementById || !d.createTextNode) return;
        var ls = gebtn(d,'label');
        for (var i = 0; i < ls.length; i++) {
            var l = ls[i];
            if (l.className.indexOf('label_') == -1) continue;
            var inp = gebtn(l,'input')[0];
			   
            if (l.className == 'label_radio') {
                l.className = (safari && inp.checked == true || inp.checked) ? 'label_radio r_on' : 'label_radio r_off';
             //   l.onclick = turn_radio;
            };
        };
    };
   
    var turn_radio = function() { 		
        var inp = gebtn(this,'input')[0];
        if (this.className == 'label_radio r_off' || inp.checked) {
            var ls = gebtn(this.parentNode,'label');
            for (var i = 0; i < ls.length; i++) {
                var l = ls[i];
                if (l.className.indexOf('label_radio') == -1)  continue;
                l.className = 'label_radio r_off';
            };			
            this.className = 'label_radio r_on';
            if (safari) inp.click();
        } else {
            this.className = 'label_radio r_off';
            if (safari) inp.click();
        };
    };	
}

function getRemainingEmailLimit(user_id,profile_id,section_id) {	
	var total_email_limit = 0;
	$j.ajax({
		type: "POST",
		url: HOST_URL+site_root+'/messages/getEmailLimit/'+user_id+'/'+profile_id+'/'+section_id,
		data: "",
		async: false,
		success: function(email_limit) {	
			total_email_limit = email_limit;
		}
	});	
	return total_email_limit;
}

function showEmailLimitModalBox(option,section_name,totalEmail) {
	Modalbox.show(HOST_URL+site_root+'/messages/emailLimitModalBox/'+option+'/'+section_name+'/'+totalEmail, {title: 'Daily email limit', height: 150,width:500, method: 'post', params: '', overlayClose: true }); 
	return false;			
}

function setOptions(fromWhere){
//alert(fromWhere);
if(fromWhere=='user'){
	$j('#user').attr('checked', true);
	$j('#emp').attr('checked', false);
	$j('#userDiv').show();
	$j('#empDiv').hide();
}
else{
	$j('#emp').attr('checked', true);
	$j('#user').attr('checked', false);
	$j('#empDiv').show();
	$j('#userDiv').hide();
	
}
}

function callEmployeeNoAccessModalBox() {
	Modalbox.show(HOST_URL+site_root+'/empRights/noAccessMessage', {title: 'No access', height: 60,width:400, method: 'get', params: '', overlayClose: true }); 	
}

/* SOHO connections and Email Contacts start */

function activeConnections(section,showTree) {	
	$j("#email-contacts-block").hide();	
		
	if(showTree) {
		$j("#connections-div-block").show();	
	}
}
function deactivateConnections() {	
	if(!$j('#chkAllCon').is(':checked')) {
		$j("#countOfSelectedConnection").text('0');	
	}
}
function closeConnections() {	
	$j('#ulglobal_fieldname_connections').hide();
	$j("#connections-div-block").hide();
}
function removeSearchMessage(id,default_message) {
	if(document.getElementById(id).value.length > 0)
	{
		if(document.getElementById(id).value == default_message)
		{
			document.getElementById(id).value = "";
		}
	}
}

function setSearchMessage(id,default_message) {
	if(document.getElementById(id).value.length < 1)
	{
		document.getElementById(id).value = default_message;		
	}
}
	
function filterSohoConnections(obj) {
	var oUL = document.getElementById("fcbklist");	
	
	totalConnection = $j("#contactList .fcbklist_item").length;

	
	if(document.getElementById('GroupContactName').value == "Search all connections"){
		var	searchkeyword = "";
	} else {
		var	searchkeyword = document.getElementById('GroupContactName').value;
	}
	searchkeyword = searchkeyword.toLowerCase();
	var searchkeywordlength = searchkeyword.length;
	 // get an array of the SPAN elements within the list
	 var aSpans = oUL.getElementsByTagName("span");							
	 // walk the list  iSpan < aSpans.length
	 for(var iSpan = 0; iSpan < totalConnection; iSpan++) {
		var currentnamedata = aSpans[iSpan].title;
		currentnamedata = currentnamedata.toLowerCase();
		var datacomapra = currentnamedata.substring(0,searchkeywordlength);
		temp = currentnamedata.split(" ");
		temp[temp.length] = currentnamedata;
		
		flag = 0;
		for(i = 0; i < temp.length; i++) {
			if(temp[i].indexOf(searchkeyword) == '0')	{
				flag = 1;
				break;
			}
		}
		
		if(flag) {
			aSpans[iSpan].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display = '';
		} else {
			aSpans[iSpan].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display = 'none';
		}
	}
}

function filterEmailContacts(obj) {
	var oUL = document.getElementById("emailcontactsfcbklist");	
	
	totalConnection = $j("#emailContactFcbkList .fcbklistemail_item").length;
	//alert(totalConnection);
	if($j("#GroupEmailContactName").attr("value") == 'Search all contacts'){
		var	searchkeyword = "";
	} else {
		var	searchkeyword = $j("#GroupEmailContactName").val();
	}
	
	searchkeyword = searchkeyword.toLowerCase();
	var searchkeywordlength = searchkeyword.length;
	 // get an array of the SPAN elements within the list
	 var aSpans = oUL.getElementsByTagName("span");		
	
	 // walk the list  iSpan < aSpans.length
	 for(var iSpan = 0; iSpan < totalConnection; iSpan++) {
		var currentnamedata = aSpans[iSpan].title;
		currentnamedata = currentnamedata.toLowerCase();
		var datacomapra = currentnamedata.substring(0,searchkeywordlength);
		temp = currentnamedata.split(" ");
		temp[temp.length] = currentnamedata;
		
		flag = 0;
		for(i = 0; i < temp.length; i++) {
			if(temp[i].indexOf(searchkeyword) == '0')	{
				flag = 1;
				break;
			}
		}
		
		if(flag) {
			aSpans[iSpan].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display = '';
		} else {
			aSpans[iSpan].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display = 'none';
		}
	}
}

function redirectUser(URL) {
	window.location.href = URL;
}

function generateJsonConnectionTree(user_id,profile_id,section_id,item_id,follower) {
 $j.ajax({
	type: "GET",
	dataType: "json",
	url: HOST_URL+site_root+'/Contacts/fetchJsonConnection/?user_id='+user_id+'&profile_id='+profile_id+'&section_id='+section_id+'&item_id='+item_id+'&follower='+follower,
	success: function(response)
	{
		$j("#fcbklist").html(' ');
		$j("#all_connection_count").text(response.friends.length);
		
		 var groups = response.groups;
		 
		 var groupPrivacy = '-'+response.groupsPrivacy+'-';
		 
			$j.each(groups,function(key,value){
				var groupObj = new Object; 
					groupObj.list_minus_image = '<img width="11" height="11" border="0" src="'+HOST_URL+site_root+'/img/menu_open_blue.gif" id="list_'+key+'_minusImage" style="display: none; padding-left: 10px;" onClick="SwitchMenu_2(\'list_'+key+'\');" alt="">';
						groupObj.list_plus_image = '<img width="11" height="11" border="0" src="'+HOST_URL+site_root+'/img/menu_close.gif" id="list_'+key+'_plusImage" style="display: block; padding-left: 10px;" onClick="SwitchMenu_2(\'list_'+key+'\');" alt="">';	
						
						var groupChecked = '';
						if(groupPrivacy.indexOf('-'+key+'-') != -1) {
							groupChecked = 'checked="checked"';
						}
						
						groupObj.list_checkbox  = '<input type="checkbox" '+groupChecked +' name="data[AccessRight][Group]['+key+']" id="chkAllCon-'+key+'" class="checkboxgray" onClick="javascript:void(0);" value="'+key+'">';
						groupObj.title_with_count = value;
						groupObj.list_id = "list_"+key;
						groupObj.group_count_id = "list_count_"+key;
				var eventEl = $j("#connection_tree_template").tmpl(groupObj);			
				eventEl.appendTo("#allConnectionList");					
			});
		
		var connectionPrivacy = '-'+response.groupContactsPrivacy+'-';
		
		for(i=0; i < response.friends.length; i++) {
				var userObj = response.friends[i]; 
				
				if(connectionPrivacy.indexOf('-'+userObj.user_id+'-') != -1) {
					userObj.li_user_class = userObj.user_profile_id+'-userclass liselected';
				} else {
					userObj.li_user_class = userObj.user_profile_id+'-userclass';									
				}
				
				user_pic = '<img border="0" class="imgThumbnail"  src='+HOST_URL+site_root+userObj.profile_pic+'>';
				
				if($j.trim(userObj.profile_name).length > 20 ) {
					userObj.short_profile_name = userObj.profile_name.substring(0,20)+'...';
				} else {
					userObj.short_profile_name =  userObj.profile_name;
				}
				
				userObj.edit_contact = '<a href='+HOST_URL+site_root+'/Contacts/connection/'+userObj.user_id+'/deal alt="View & Edit connection information" title="View & Edit connection information" onclick="viewcolorbox(this.id);return false;" id="connection_'+userObj.user_id+'" class="editLinkClass"><img border="0" src="'+HOST_URL+site_root+'/img/icon_edit.gif"></a>';
				
				userObj.userlink = '<a href='+HOST_URL+site_root+userObj.public_url+' alt="'+userObj.profile_name+'" title="'+userObj.profile_name+'" target="_blank">'+user_pic+'</a>';
				
				var eventEl = $j("#user_contact_template").tmpl(userObj);
				eventEl.appendTo("#fcbklist");
	
				for(j=0; j < userObj.groups.length ; j++) {
					var treeobj = new Object;	
					checkboxId = userObj.groups[j].Group.id+'-'+userObj.user_id+'-'+userObj.profile_id;
					checkboxClass = userObj.user_id+'-'+userObj.profile_id+'-userclass';
					
					var connectionChecked = '';
					if(connectionPrivacy.indexOf('-'+userObj.user_id+'-') != -1) {
						connectionChecked = 'checked="checked"';
					}			
				
					treeobj.contact_checkbox = '<input type="checkbox" '+connectionChecked+' name="data[AccessRight][Connection]['+checkboxId+']" class="checkboxgray '+checkboxClass+'" id="'+checkboxId+'" onClick="javascript:void(0);" title="'+userObj.profile_name+'" value="'+userObj.user_id+'-'+userObj.profile_id+'">';
					
					treeobj.profile_link = "<a href='"+HOST_URL+site_root+userObj.public_url+"'>"+userObj.profile_name+"</a>";
					$j("#list_count_"+userObj.groups[j].Group.id).text(parseInt($j("#list_count_"+userObj.groups[j].Group.id).text()) + 1);			
					var eventEl = $j("#detail_tree_template").tmpl(treeobj);
					eventEl.appendTo("#list_"+userObj.groups[j].Group.id);
				}
		}
		
		$j.fcbkListSelectionConnectionList($j("#fcbklist"),"630","70","3","190");
				var followersPrivacy = '-'+response.followersPrivacy+'-';
				followerCnt = 0;
				for(i = 0;  i < response.followers.length; i++) {
					followerObj = 	response.followers[i];
					if(followerObj.User.role_id) {
						++followerCnt;	
						if(followerObj.User.role_id == 1)  {
							checkboxId =  followerObj.User.id+'-'+followerObj.ConsumerProfile.id;	
							profile_url = HOST_URL+site_root+'/ConsumerProfiles/profile/'+followerObj.ConsumerProfile.id;
						} else {
							checkboxId =  followerObj.User.id+'-'+followerObj.BusinessProfile.id;	
							profile_url = HOST_URL+site_root+'/BusinessProfiles/profile/'+followerObj.BusinessProfile.id;
						}
						
						var followerChecked = '';
						if(followersPrivacy.indexOf('-'+followerObj.User.id+'-') != -1) {
							followerChecked = 'checked="checked"';
						}
					
						checkboxClass = checkboxId+'-userclass';						
						followerObj.contact_checkbox = '<input type="checkbox" '+followerChecked+' name="data[followers]['+checkboxId+']" class="checkboxgray '+checkboxClass+'" id="follower-'+checkboxId+'"  onClick="javascript:void(0);" title="'+followerObj.profile_name+'"  value="'+checkboxId+'">';						
						
						followerObj.profile_link = "<a href='"+profile_url+"'>"+followerObj.User.profile_name+"</a>";
						var eventEl = $j("#follower_tree_template").tmpl(followerObj);
						eventEl.appendTo("#list_0000");
					}
					$j("#list_count_0000").text(followerCnt);
				}
		
			$j('body').click(function(e) {	
				var clicked = $j(e.target);
				 if (e.target.id != 'linkglobal_fieldname_connections'){ 
				//	$j('#ulglobal_fieldname_connections').hide();
					$j(".dropdown_connections dt a").removeClass("selected");
				}    
			});
			
			$j('#linkglobal_fieldname_connections').click(function(e) {									
				var clicked = $j(e.target);	
				if($j("#ulglobal_fieldname_connections").is(':visible')){												
					$j('#ulglobal_fieldname_connections').hide();
					$j(".dropdown_connections dt a").removeClass("selected");
				} else {
					$j("#ulglobal_fieldname_connections").show();															 				 
				}							
			});
			$j("#connection-link").html('<a onclick="activeConnections('+response.sections.section_id+',true);" id="connections-link" href="javascript:void(0);">Connection(s)</a>');
			$j("#connections-loading").html('');
			
			var customNotifyMsg = response.modelData.custom_notify_msg;
			$j("#custom_notify_msg").html(customNotifyMsg);
			$j("#custom_notify_msg").css('color','#000000');
			
			if(section_id==11) {
				var everyOneObj = new Object; 
				everyOneObj.id = 'chkPublic';
				everyOneObj.checked = true;
				checkUncheckBoxes(everyOneObj,section_id);
				$j('#chkPublic').attr('checked', true);						
			}
			
			
		}
	});					
}

function checkUncheckBoxes(obj,section) {
	if(obj.id == "chkPublic") {
		if(obj.checked) {			
			$j('#chkMe').attr('checked', false);
				$j('#chkAllConnection').attr('checked', true);
				activeConnections(section,false);
				$j('#chkAllCon').attr('checked', true);
				$j('#chkAllCon').trigger('click');
				$j('#chkAllCon').attr('checked', true);			
		} 
	} else if(obj.id == "chkAllConnection") {
		if(obj.checked) {
			$j('#chkMe').attr('checked', false);
			$j('#chkAllCon').attr('checked', true);
			$j('#chkAllCon').trigger('click');
			$j('#chkAllCon').attr('checked', true);
		} else {
			
			$j('#chkMe').attr('checked', false);	
			$j('#chkAllCon').attr('checked', false);
			$j('#chkAllCon').trigger('click');
			$j('#chkAllCon').attr('checked', false);
		}	
	} else if(obj.id == "chkMe") {
		if(obj.checked) {
			$j('#chkPublic').attr('checked', false);
			$j('#chkAllConnection').attr('checked', false);
			//if($j('#chkAllCon').is(':checked')) {
				$j('#chkAllCon').attr('checked', false);
				$j('#chkAllCon').trigger('click');
				$j('#chkAllCon').attr('checked', false);
			//}			
		} 
	}	
//--------------Check Me Checkbox----------BTS Iteam 1069------//
  if(obj.id == "chkMe") {
			if(section == 7) {
				if(obj.checked) {	
					$j('#personal-msg').hide();
					$j('#event_rsvp').hide();
				} else {
					$j('#personal-msg').show();
					$j('#event_rsvp').show();
				}
			} else {
				$j('#personal-msg').show();
			}
	} 
	if(section == 7 && obj.id != "chkMe") {
		$j('#personal-msg').show();
		$j('#event_rsvp').show();
	}
//--------------------------------------------------------------//	
}

function selectAllConnections(obj) {
	if(obj.id == "chkAllConnection") {
		if(obj.checked) {
			$j('#chkAllCon').attr('checked', true);
			$j('#chkAllCon').trigger('click');
			$j('#chkAllCon').attr('checked', true);
		} else {
			$j('#chkAllCon').attr('checked', false);
			$j('#chkAllCon').trigger('click');
			$j('#chkAllCon').attr('checked', false);
		}	
	} 	
}

function activeEmailContacts(user_id,profile_id,showTree) {
	$j("#connections-div-block").hide();
	
	var contactsCount = parseInt($j("#countOfSelectedContacts").text());
		if(contactsCount == 0) {
			if($j('#emailTreeDiv').html() == '') {
				$j("#email-contacts-loading").html('<img src="'+HOST_URL+site_root+'/img/facebook_loader.gif" alt="loading email contacts" title="loading email contacts">');
				getEmailTemplate(user_id,profile_id);					
			} else {
				totalText = $j("#hidden_email_contacts").text();						
				if(totalText != '') {
					totalTextArray = totalText.split(",");
				} else {
					totalTextArray = new Array();
				}
				$j("#countOfSelectedContacts").text(totalTextArray.length);
			}
		}	
	if(showTree) {
		$j("#email-contacts-block").show();	
	}
	
}

function closeEmailContacts() {	
	var total_selected_contacts = parseInt(countNewEmailContacts()) + parseInt($j("#view_selected_count1").text());	
	$j("#countOfSelectedContacts").text(total_selected_contacts);
	$j("#email-contacts-block").hide();
}

function generateJsonEmailContactsTree(user_id,profile_id) {
 $j.ajax({
	type: "GET",
	dataType: "json",
	url: HOST_URL+site_root+'/Contacts/getJsonEmailContacts/'+user_id+'/'+profile_id,
	success: function(response)
	{
		var totContact = response.contacts.length;
		for(i=0; i < totContact; i++) {
				
				var userObj = response.contacts[i].Contact; 
				
				userObj.li_user_class = userObj.id+'-userclass';
				
				var user_pic = ''
				if(userObj.soho_profile_id != 0 ){
					user_pic = '<img border="0" class="imgThumbnail" src='+HOST_URL+site_root+'/users/memberphoto/'+userObj.soho_profile_id+'/'+userObj.soho_role_id+' title='+userObj.email+' alt='+userObj.email+'>';
				}
				
				if(userObj.name != '' && userObj.name != userObj.email ) {
					userObj.short_profile_name = userObj.name+'<br />';			
				}
				if($j.trim(userObj.email).length > 20 ) {
					userObj.short_email_name =  userObj.email.substring(0,20)+'...';
				} else {
					userObj.short_email_name =  userObj.email;
				}
				userObj.profile_name = userObj.email;
				
				userObj.edit_contact = '<a href='+HOST_URL+site_root+'/Contacts/edit/'+userObj.id+' alt="View & Edit Contact Information" title="View & Edit Contact Information" onclick="viewcolorbox(this.id);return false;" id="edit_email_contact_'+userObj.id+'" class="editLinkClass"><img border="0" src="'+HOST_URL+site_root+'/img/icon_edit.gif"></a>';
				
				
				
				if(userObj.soho_profile_id != 0 ) {
					if(userObj.soho_role_id == 1) {
						var profileType = "ConsumerProfiles";
					} else {
						var profileType = "BusinessProfiles";
					}
					userObj.userlink = '<a href='+HOST_URL+site_root+'/'+profileType+'/profile/'+userObj.soho_profile_id+' target="_blank" alt="'+userObj.profile_name+'" title="'+userObj.profile_name+'">'+user_pic+'</a>';
				} else {
					userObj.userlink = user_pic;
				}
				
				userObj.user_profile_id = userObj.id;
				var eventEl = $j("#user_email_contact_template").tmpl(userObj);
				$j("#email_contacts_loading_div").html("");
				eventEl.appendTo("#emailcontactsfcbklist");
		}
		$j.fcbkListSelectionEmailContacts($j("#emailcontactsfcbklist"),"630","55","3","190",1);
		
		$j('#loading-data').empty();
		$j('#loading-data').hide();
		
		$j("#email-contacts-link").html('<a onclick="activeEmailContacts('+response.userIds.user_id+','+response.userIds.profile_id+',true);" id="contacts-link" href="javascript:void(0);">Email contact(s)</a>');
		$j("#email-contacts-loading").html('');
	}
	});					
}

function getConnectionTemplate(user_id,profile_id,section_id,item_id,follower) {
	$j.ajax({
		type: "GET",
		url: HOST_URL+site_root+'/Contacts/connectionTree/'+section_id,
		success: function(response)
		{
			$j("#connectionTreeDiv").html(response);
			setTimeout('generateJsonConnectionTree('+user_id+','+profile_id+','+section_id+','+item_id+','+follower+')',1500);					
		}
	});	
}

function getEmailTemplate(user_id,profile_id) {
	$j.ajax({
		type: "GET",
		url: HOST_URL+site_root+'/Contacts/getEmailContacts',
		success: function(response)
		{
			$j("#emailTreeDiv").html(response);
			checkAllContacts();
			setTimeout('generateJsonEmailContactsTree('+user_id+','+profile_id+')',1500);			
		}
	});	
}


function checkAllContacts() {
var totalSelectedContacts = 0;
$j("#emailTreeDiv input:checkbox").live("click",function(i){	
		  temp_id = $j(this).attr('id');				 
		  checked_value = $j(this).attr('checked');
				if(!checked_value)
					checked_value = false;
			if(temp_id == 'chkAllEmailContacts'){ // select all subchild 
				selectedAllCheckbox(checked_value,'all_email_list','mainDiv');
			} else {
				if(temp_id.substr(0,temp_id.indexOf('-')) == 'chkAllEmailContacts') {
					div_name = "email_list_"+temp_id.substr(temp_id.indexOf('-')+1);
					selectedAllCheckbox(checked_value,div_name,'subDiv');						
				}else {
					setCheckboxFckboxSelected(checked_value,temp_id);
				}
			}
	}); 	
}

var selectedAllCheckbox = function(check_value,div_name,div_type) {
	if(div_type == 'mainDiv') {		
		$j("#"+div_name+" input:checkbox").each(function(){ 
			$j(this).attr('checked',check_value);
			if($j(this).attr('id').indexOf('-') == '-1')
				countTotalEmailContacts(check_value,$j(this).attr('id'));
		});	
	}
	
	if(div_type == 'subDiv')  {
		$j("#"+div_name+" input:checkbox").each(function(){ 
			$j(this).attr('checked',check_value);
			setCheckboxFckboxSelected(check_value,$j(this).attr('id'));
		});
	}		
}
	
var setCheckboxFckboxSelected = function (check_value,item_id) {
		item_id = item_id.substr(item_id.indexOf('-')+1);
		$j("#all_email_list ."+item_id+"-emailuserclass").each(function(){
			$j(this).attr('checked',check_value);																		  	
		});	
		countTotalEmailContacts(check_value,item_id);
}

function countTotalEmailContacts(check_value,item_id) {	
	totalText = $j("#hidden_email_contacts").text();
	
	if(totalText != '') {
		totalTextArray = totalText.split(",");
	} else {
		totalTextArray = new Array();
	}

	arrayIndex = $j.inArray(item_id,totalTextArray);
	if(check_value) { 
		totalTextArray.push(item_id);
	}else {		
		totalTextArray.splice(arrayIndex,1);			
	}

	if(totalTextArray.length != 0) {	
		$j("#hidden_email_contacts").text(totalTextArray.join(','));		
	} else {
		$j("#hidden_email_contacts").text('');
	}
	
	$j("#countOfSelectedContacts").text(totalTextArray.length);		

}
function viewcolorbox(id,givenWidth,givenHeight) {	
	if(Modalbox.initialized) {
		Modalbox.hide();
	}		
	
	if(!givenWidth)
		givenWidth = '40%';
		
	if(!givenHeight)
		givenHeight = '65%';

	 $j("#"+id).colorbox({width:givenWidth, height:givenHeight, iframe:true});
	 return true;
} 

function setDefaultFadedText() {
$j('input[type="text"]').each(function(){
 	if($j(this).attr('title')) {
		this.value = $j(this).attr('title');
		if(this.value != '') {
			$j(this).addClass('text-default-label');
		}
	}
    $j(this).focus(function(){
        if(this.value == $j(this).attr('title')) {
            this.value = '';
            $j(this).removeClass('text-default-label');
        }
    });
 
    $j(this).blur(function(){
        if(this.value == '' && $j(this).attr('title')) {
            this.value = $j(this).attr('title');
			if(this.value != '') {
            	$j(this).addClass('text-default-label');
			}
        }
    });
});	
}

function addEmailContacts(obj) {
	tableLength = $j('#addEmailCotnactsTable > tbody > tr').length;
	new_id = parseInt($j("#addEmailCotnactsTable > tbody > tr:nth-child("+(tableLength - 1)+")").attr('id')) + 1;
	
	mainTableLength = $j('#addEmailCotnactsTable > tbody > tr.noCssClass').length;
	
	if(mainTableLength < 20) {
		new_row = $j("#addEmailCotnactsTable").append($j("#addEmailCotnactsTable > tbody> tr:nth-child("+(tableLength - 1)+").noCssClass").clone(true,true));
		$j("#addEmailCotnactsTable tbody> tr:last.noCssClass").attr('id',new_id);	
		$j("#addEmailCotnactsTable tbody> tr:last.noCssClass > td:first input[type=text]").attr('id','email_'+new_id).val('');
		$j("#addEmailCotnactsTable tbody> tr:last.noCssClass > td:nth-child(2) input[type=text]").attr('id','firstname_'+new_id).val('');	
		$j("#addEmailCotnactsTable tbody> tr:last.noCssClass > td:nth-child(3) input[type=text]").attr('id','lastname_'+new_id).val('');	
		$j("#addEmailCotnactsTable tbody> tr:last.noCssClass > td:nth-child(4) input[type=text]").attr('id','phone_'+new_id).val('');
						
		$j("#email_"+new_id).val($j("#email_"+new_id).attr('title'));
		$j("#firstname_"+new_id).val($j("#firstname_"+new_id).attr('title'));
		$j("#lastname_"+new_id).val($j("#lastname_"+new_id).attr('title'));
		$j("#phone_"+new_id).val($j("#phone_"+new_id).attr('title'));
		
		bindEmailContactSmartSearch('email',new_id);
		bindEmailContactSmartSearch('phone',new_id);
		bindEmailContactSmartSearch('firstname',new_id);
		bindEmailContactSmartSearch('lastname',new_id);
		
		NewTableLength = $j('#addEmailCotnactsTable > tbody > tr.noCssClass').length;
		if(NewTableLength == 19) {
			$j("#addEmailCotnactsTable tbody> tr:last >td:last ").find("#add").css('display','none');
		}
		
		new_row1 = $j("#addEmailCotnactsTable tbody> tr:nth-child(2).noCssClass").clone(false,false);					
		new_row1.find("#msgDiv_0").html('');
		new_row1.find("#historyDiv_0").html('');	
		$j("#addEmailCotnactsTable").append(new_row1);
		$j("#addEmailCotnactsTable tbody> tr:last.noCssClass").attr('id',"msgRow_"+new_id);			
		$j("#addEmailCotnactsTable tbody> tr:last.noCssClass > td:first >div:first").attr('id','msgDiv_'+new_id);				
		$j("#msgDiv_"+new_id).html('');
		$j("#historyDiv_"+new_id).html('');	
		obj.style.display = 'none';
	}
}
function removeEmailContacts(obj) {
	tableLength = $j('#addEmailCotnactsTable > tbody > tr').length;
	deleteId = $j(obj).parent().parent().attr('id');	
	if(tableLength != 2) {
		$j("#msgRow_"+deleteId).remove();
		$j(obj).parent().parent().remove();
		tableLength = parseInt($j('#addEmailCotnactsTable > tbody > tr').length) - 1;		
		$j("#addEmailCotnactsTable tbody> tr:nth-child("+tableLength+").noCssClass > td:last").find("#add").show();
	}else {
		$j("#email_"+deleteId).val('');				
		$j("#firstname_"+deleteId).val('');							
		$j("#lastname_"+deleteId).val('');	
		$j("#phone_"+deleteId).val('');
		$j("#msgDiv_"+deleteId).html('');	
		$j("#historyDiv_"+deleteId).html('');			
	}
}
// Check for Appointment Email Contacts //
function addAppointmentEmailContacts(obj) {
	tableLength = $j('#addAppointmentEmailCotnactsTable > tbody > tr').length;
	new_id = parseInt($j("#addAppointmentEmailCotnactsTable > tbody > tr:nth-child("+(tableLength - 1)+")").attr('id')) + 1;
	mainTableLength = $j('#addAppointmentEmailCotnactsTable > tbody > tr.noCssClass').length;
	if(mainTableLength < 20) {
		new_row = $j("#addAppointmentEmailCotnactsTable").append($j("#addAppointmentEmailCotnactsTable > tbody> tr:nth-child("+(tableLength - 1)+").noCssClass").clone(true,true));
		$j("#addAppointmentEmailCotnactsTable tbody> tr:last.noCssClass").attr('id',new_id);	
		$j("#addAppointmentEmailCotnactsTable tbody> tr:last.noCssClass > td:first input[type=text]").attr('id','emailappointment_'+new_id).val('');
		$j("#addAppointmentEmailCotnactsTable tbody> tr:last.noCssClass > td:nth-child(2) input[type=text]").attr('id','firstnameappointment_'+new_id).val('');	
		$j("#addAppointmentEmailCotnactsTable tbody> tr:last.noCssClass > td:nth-child(3) input[type=text]").attr('id','lastnameappointment_'+new_id).val('');	
		$j("#addAppointmentEmailCotnactsTable tbody> tr:last.noCssClass > td:nth-child(4) input[type=text]").attr('id','phoneappointment_'+new_id).val('');
						
		$j("#emailappointment_"+new_id).val($j("#emailappointment_"+new_id).attr('title'));
		$j("#firstnameappointment_"+new_id).val($j("#firstnameappointment_"+new_id).attr('title'));
		$j("#lastnameappointment_"+new_id).val($j("#lastnameappointment_"+new_id).attr('title'));
		$j("#phoneappointment_"+new_id).val($j("#phoneappointment_"+new_id).attr('title'));
		
		/*bindEmailContactSmartSearch('emailappointment',new_id);
		bindEmailContactSmartSearch('phone',new_id);
		bindEmailContactSmartSearch('firstname',new_id);
		bindEmailContactSmartSearch('lastname',new_id);*/
		
		NewTableLength = $j('#addAppointmentEmailCotnactsTable > tbody > tr.noCssClass').length;
		if(NewTableLength == 19) {
			$j("#addAppointmentEmailCotnactsTable tbody> tr:last >td:last ").find("#add").css('display','none');
		}
		
		new_row1 = $j("#addAppointmentEmailCotnactsTable tbody> tr:nth-child(2).noCssClass").clone(false,false);					
		new_row1.find("#msgDivappointment_0").html('');
		new_row1.find("#historyDivappointment_0").html('');	
		$j("#addAppointmentEmailCotnactsTable").append(new_row1);
		$j("#addAppointmentEmailCotnactsTable tbody> tr:last.noCssClass").attr('id',"msgRow_"+new_id);			
		$j("#addAppointmentEmailCotnactsTable tbody> tr:last.noCssClass > td:first >div:first").attr('id','msgDiv_'+new_id);				
		$j("#msgDivappointment_"+new_id).html('');
		$j("#historyDivappointment_"+new_id).html('');	
		obj.style.display = 'none';
	}
}
function removeAppointmentEmailContacts(obj) {
	tableLength = $j('#addAppointmentEmailCotnactsTable > tbody > tr').length;
	deleteId = $j(obj).parent().parent().attr('id');	
	if(tableLength != 2) {
		$j("#msgRow_"+deleteId).remove();
		$j(obj).parent().parent().remove();
		tableLength = parseInt($j('#addAppointmentEmailCotnactsTable > tbody > tr').length) - 1;		
		$j("#addAppointmentEmailCotnactsTable tbody> tr:nth-child("+tableLength+").noCssClass > td:last").find("#add").show();
	}else {
		$j("#email_"+deleteId).val('');				
		$j("#firstname_"+deleteId).val('');							
		$j("#lastname_"+deleteId).val('');	
		$j("#phone_"+deleteId).val('');
		$j("#msgDiv_"+deleteId).html('');	
		$j("#historyDiv_"+deleteId).html('');			
	}
}
//-------------------------------------------------------------------------------------------------//
function ajaxCheckAppointmentEmailExist(obj,userid,profileid) {
	var startdate = document.getElementById('q_event_date').value;
	var starthr = document.getElementById('q_event_hour').value;
	var startmin = document.getElementById('q_event_minute').value;
	var startampm = document.getElementById('q_eventampm').value;

	email = $j(obj).val();	
	placeId = $j(obj).parent().parent().attr('id');		
	$j("#msgDivappointment_"+placeId).html('');	
	$j("#historyDivappointment_"+placeId).html('');
	if(email != '') {	
		if(!echeck(email)) {
			$j("#msgDivappointment_"+placeId).show();		
			$j("#msgDivappointment_"+placeId).html('<font color=red>Enter Proper Email Address</font>');
		} else {
			$j.ajax({
				type: "GET",
				url: HOST_URL+site_root+'/dealCustomerCoupons/dealEmailCouponCheck/'+email,
				data: "",
				dataType: "json",
				success: function(data)
				{
					if(data.length != 0) {
						role_id = 2;
						if(data.length == 1) {
							userHtml = createUserInfo(data[0]);	
							if(data[0]['U']['role_id'] == 1) 						
								radios = createAppointmentRadioElement('InvitedAppointmentSohoMember','profile'+placeId,'couponRadio',1,data[0]['U']['role_id'],'','');	
							else 
							 radios = createAppointmentRadioElement('InvitedAppointmentSohoMember','profile'+placeId,'couponRadio',1,data[0]['U']['role_id'],'','');	
							 
							userContent = '<div style="width:210px;height:50px;background-color:#F9F2E8;">'; 
							userContent += '<span style="width:10px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += radios;							
							userContent += '</span>';							
							userContent += '<span style="width:190px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += userHtml;														
							userContent += '</span>';														
							userContent += '</div>';							
							$j("#msgDivappointment_"+placeId).html(userContent);
							
							role_id = data[0]['U']['role_id'];	
						}
						if(data.length == 2) {
							radios = createAppointmentRadioElement('InvitedAppointmentSohoMember','profile'+placeId,'couponRadio-'+data[0]['U']['id']+'-'+data[0]['C']['id'],0,data[0]['U']['role_id'],'','',data[0]['U']['id'],data[0]['C']['id']);
							radios1 = createAppointmentRadioElement('InvitedAppointmentSohoMember','profile'+placeId,'couponRadio-'+data[1]['U']['id']+'-'+data[1]['B']['id'],1,data[1]['U']['role_id'],'','',data[1]['U']['id'],data[1]['B']['id']);
							userContent = '<div style="width:460px;height:50px;background-color:#F9F2E8;" >'; 
							userContent += '<span style="width:10px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += radios;							
							userContent += '</span>';							
							userContent += '<span style="width:200px;vertical-align:top;float:left;margin-left:5px;border-right:2px solid;">';																					
							userContent += createAppointmentUserInfo(data[0]);															
							userContent += '</span>';	
							userContent += '<span style="width:10px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += radios1;							
							userContent += '</span>';							
userContent += '<span style="width:200px;vertical-align:top;float:left;margin-left:5px;">';																					
							userContent += createAppointmentUserInfo(data[1]);															
							userContent += '</span>';	
							userContent += '</div>';	
							$j("#msgDivappointment_"+placeId).html(userContent);
							
						if(data[1]['U']['role_id'] == 2) {
							profileiddata = data[1]['B']['id']; 
						}
						if(data[1]['U']['role_id'] == 1) {
							profileiddata = data[1]['C']['id']; 
						}
						
						var idforClick = data[1]['U']['id']+"-"+profileiddata;
						
						//------------------------------------//
						$j("#"+idforClick).children(".fcbklist_item").trigger('click');
						}
						

						//--------------------------------------//
						$j("#firstnameappointment_"+placeId).val(data[0]['U']['firstname']);
						$j("#lastnameappointment_"+placeId).val(data[0]['U']['lastname']);	
						viewSOHOAppointmentHistory(userid,profileid,startdate,starthr,startmin,startampm,placeId)
					}else {
						$j.ajax({
							type: "GET",
							url: HOST_URL+site_root+'/dealInvitedEmails/getEmailContactAppointmentDetail/'+email,
							data: "",
							success: function(responseText)
							{	
								
								if(responseText != '') {	
									var name = 	responseText.split("#");
									if(name.length == 3) {
										$j("#firstnameappointment_"+placeId).val(name[0]);						
										$j("#lastnameappointment_"+placeId).val(name[1]);												
										if(!$j("#"+name[1]).hasClass('liselected')){
											$j("#"+name[2]).children(".fcbklistemail_item").trigger('click');
											closeEmailContacts();
										}
									}
									if(name.length == 2) {
										$j("#firstnameappointment_"+placeId).val(name[0]);						
										$j("#lastnameappointment_"+placeId).val('');												
										if(!$j("#"+name[1]).hasClass('liselected')){
											$j("#"+name[1]).children(".fcbklistemail_item").trigger('click');
											closeEmailContacts();
										}
									}
								} else {
									$j("#msgDivappointment_"+placeId).html('');	
									$j("#historyDivappointment_"+placeId).html('');	
								}
							}
						});
						//
							
						viewSOHOAppointmentHistory(userid,profileid,startdate,starthr,startmin,startampm,placeId)							
					}
				}
			});	
		}
	}	
}


function ajaxCheckAppointmentPhoneExist(obj,userid,profileid) { 
	var startdate = document.getElementById('q_event_date').value;
	var starthr = document.getElementById('q_event_hour').value;
	var startmin = document.getElementById('q_event_minute').value;
	var startampm = document.getElementById('q_eventampm').value;
	
	if(document.getElementById('emailappointment_0').value == "" || document.getElementById('emailappointment_0').value == "Enter email address") {
		phone = $j(obj).val();	
		placeId = $j(obj).parent().parent().attr('id');	
		$j("#msgDivappointment_"+placeId).html('');	
		$j("#historyDivappointment_"+placeId).html('');	
		if(phone != '') {
				$j.ajax({
							type: "GET",
							url: HOST_URL+site_root+'/events/getPhoneEventAppointmentDetail/'+phone,
							data: "",
							success: function(responseText) {
								if(responseText != '') {	
									if(responseText!="0") {
										var name = 	responseText.split("#");
										$j("#firstnameappointment_"+placeId).val(name[0]);						
										$j("#lastnameappointment_"+placeId).val(name[1]);	
									}
								}
							}
						});
						viewSOHOAppointmentHistory(userid,profileid,startdate,starthr,startmin,startampm,placeId)
		}
	}
}

function ajaxCheckEmailExist(obj) {
	
	email = $j(obj).val();	
	
	placeId = $j(obj).parent().parent().attr('id');		

	$j("#msgDiv_"+placeId).html('');	
	$j("#historyDiv_"+placeId).html('');
	
	if(email != '') {	
		if(!echeck(email)) {
			$j("#msgDiv_"+placeId).show();		
			$j("#msgDiv_"+placeId).html('<font color=red>Enter Proper Email Address</font>');
		} else {
			$j.ajax({
				type: "GET",
				url: HOST_URL+site_root+'/dealCustomerCoupons/dealEmailCouponCheck/'+email,
				data: "",
				dataType: "json",
				success: function(data)
				{
					if(data.length != 0) {
						role_id = 2;
						if(data.length == 1) {
							userHtml = createUserInfo(data[0]);	
							if(data[0]['U']['role_id'] == 1) 						
								radios = createRadioElement('InvitedSohoMember','profile'+placeId,'couponRadio',1,data[0]['U']['role_id'],'','');	
							else 
							 radios = createRadioElement('InvitedSohoMember','profile'+placeId,'couponRadio',1,data[0]['U']['role_id'],'','');	
							 
							userContent = '<div style="width:210px;height:50px;background-color:#F9F2E8;">'; 
							userContent += '<span style="width:10px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += radios;							
							userContent += '</span>';							
							userContent += '<span style="width:190px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += userHtml;														
							userContent += '</span>';														
							userContent += '</div>';							
							$j("#msgDiv_"+placeId).html(userContent);
							
							role_id = data[0]['U']['role_id'];	
						}
						if(data.length == 2) {
							radios = createRadioElement('InvitedSohoMember','profile'+placeId,'couponRadio',0,data[0]['U']['role_id'],'','');
							radios1 = createRadioElement('InvitedSohoMember','profile'+placeId,'couponRadio',1,data[1]['U']['role_id'],'','');
							
							userContent = '<div style="width:460px;height:50px;background-color:#F9F2E8;" >'; 
							userContent += '<span style="width:10px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += radios;							
							userContent += '</span>';							
							userContent += '<span style="width:200px;vertical-align:top;float:left;margin-left:5px;border-right:2px solid;">';																					
							userContent += createUserInfo(data[0]);															
							userContent += '</span>';	
							userContent += '<span style="width:10px;vertical-align:top;margin-left:5px;float:left;" >';														
							userContent += radios1;							
							userContent += '</span>';							
userContent += '<span style="width:200px;vertical-align:top;float:left;margin-left:5px;">';																					
							userContent += createUserInfo(data[1]);															
							userContent += '</span>';	
							userContent += '</div>';	
							
							$j("#msgDiv_"+placeId).html(userContent);
							
						}
						$j("#firstname_"+placeId).val(data[0]['U']['firstname']);
						$j("#lastname_"+placeId).val(data[0]['U']['lastname']);	
						$j("#historyDiv_"+placeId).html('');					
					}else {
						$j.ajax({
							type: "GET",
							url: HOST_URL+site_root+'/dealInvitedEmails/getEmailName/'+email,
							data: "",
							success: function(responseText)
							{	
								if(responseText != '') {	
									var name = 	responseText.split("#");
									$j("#firstname_"+placeId).val(name[0]);						
									$j("#lastname_"+placeId).val(name[1]);												
								} else {
									/*$j("#firstname_"+placeId).val('');
									$j("#lastname_"+placeId).val('');	*/
									$j("#msgDiv_"+placeId).html('');	
									$j("#historyDiv_"+placeId).html('');	
								}
							}
						});								
					}
				}
			});	
		}
	}	
}

function createRadioElement(formName,fieldName,id, checked,value,eventType,eventCall) {	
    var radioHtml = '<input type="radio" id='+id+' name="data['+formName+']['+fieldName+']" value="'+value+'" ';
    if ( checked ) {
        radioHtml += ' checked="checked"';
    }
	
	if(eventType) {
        radioHtml += eventType+'='+eventCall;
	}
    radioHtml += '>';
   
    return radioHtml;
}

function bindEmailContactSmartSearch(searchType,id_no) {
$j("#"+searchType+"_"+id_no).autocomplete(HOST_URL+site_root+"/contacts/autoCompleteEmailContacts",
	{
		minChars: 1,
		cacheLength: 10,
		cache:true,
		onItemSelect: selectItem,
		onFindValue: findValue,
		formatItem: formatItem,
		autoFill: false,
		maxItemsToShow:10
	});
}

function viewColorboxHref(href,title) {		
	 $j.colorbox({href:href,title:title,width:"40%", height:"65%", iframe:true});
	 return true;
} 

function countNewEmailContacts() {
	var newContacts = 0;
	$j("#email-contacts-block input[type=text]").each(function(){   
		if($j(this).hasClass('emailTextBox')) {
			if(echeck($j(this).val())) {
			  newContacts++;
			}
		}
	});
	return newContacts;
}
function clearFormFieldValue() {
	$j('#addEmailCotnactsTable input[type="text"]').each(function(){
		if($j(this).hasClass('text-default-label')) {
			this.value = '';		
		} 	
	});	
}

function currency(val){
 window.open (HOST_URL+site_root+"/products/currency/"+val, "","width=260px,height=260px,resizable=yes,scrollbars=0"); 
}

function openShoppingCartNote(id,hrefLink) {
	$j("#addNoteArea").val('');	
	$j("#"+id).colorbox({inline:true, href:"#"+hrefLink,opacity:0.2});	
}

function validateEmailDailyLimit(user_id,profile_id,section_id,maxEmailOneTime) {
		var tot_contacts = 0 ;
		if($j('#countOfSelectedContacts')) {
			tot_contacts = parseInt($j('#countOfSelectedContacts').text());
		}
		
		var left_email_limit = getRemainingEmailLimit(user_id,profile_id,section_id);
		
		switch(parseInt(section_id)) {
			case 1:
				 var section_name = 'status update';		
				break;
			case 2:
				var section_name = 'blog';	
				break;
			case 3:
				var section_name = 'audio';	
				break;
			case 4:
				var section_name = 'video';	
				break;
			case 5:
				var section_name = 'photo';	
				break;
			case 6:
				var section_name = 'poll';	
				break;
			case 7:
				var section_name = 'event';	
				break;
			case 8:
				var section_name = 'question';	
				break;
			case 10:
				var section_name = 'announcement';	
				break;
			case 11:
				var section_name = 'product';	
				break;
			case 12:
				var section_name = 'file & folder';	
				break;
			case 13:
				var section_name = 'recommendation';	
				break;
			default:
				var section_name = 'email contacts';	
		}
	
		if(left_email_limit == 0) {
			showEmailLimitModalBox(1,section_name,0);				
			return false;
		} else if(left_email_limit > tot_contacts) {
			if(tot_contacts > maxEmailOneTime) {
				showEmailLimitModalBox(2,section_name,0);					
				return false;				
			}
		} else {
			if(tot_contacts > maxEmailOneTime && left_email_limit > maxEmailOneTime) {
				showEmailLimitModalBox(2,section_name,0);
				return false;				
			} else if(tot_contacts == left_email_limit) {
				return true;				
			} else {
				showEmailLimitModalBox(3,section_name,left_email_limit);
				return false;
			}
		}
}

function createAppointmentRadioElement(formName,fieldName,id, checked,value,eventType,eventCall,userid,profileid) {	
    var radioHtml = '<input type="radio" onclick="return selectprivacysetting('+userid+','+profileid+')"  id='+id+' name="data['+formName+']['+fieldName+']" value="'+value+'" ';
    if ( checked ) {
        radioHtml += ' checked="checked"';
    }
	
	if(eventType) {
        radioHtml += eventType+'='+eventCall;
	}
    radioHtml += '>';
   
    return radioHtml;
}

//-----------------------------------------------------//
function selectprivacysetting(userid,profileid) {
	if($j("#couponRadio-"+userid+"-"+profileid).is(':checked')) {
		if(!$j("#"+userid+"-"+profileid).hasClass('liselected'))
			$j("#"+userid+"-"+profileid).children(".fcbklist_item").trigger('click');
	} else {
			
	}
}
//------------------------------------------------------//


function chkCriteria(flag,id)
{
	
	if(flag == 'shipping') {		
		if (id == 'all_shipping' && $j('#all_shipping').is(':checked')) {
			$j('#offer_shipping').attr('checked',true);
			$j('#allow_pickup').attr('checked',true);
		} else if(id == 'all_shipping' && $j('#all_shipping').is(':checked') == false) {
			$j('#offer_shipping').attr('checked',false);
			$j('#allow_pickup').attr('checked',false);
		} else if($j('#allow_pickup').is(':checked') && $j('#offer_shipping').is(':checked')) {
			$j('#all_shipping').attr('checked',true); 
		} else {
			$j('#all_shipping').attr('checked',false); 
		}
	} else if (flag == 'payment') {
		if (id == 'all_payment' && $j('#all_payment').is(':checked')) {
			$j('#is_online_payment').attr('checked',true);
			$j('#is_onsite_payment').attr('checked',true);
		} else if(id == 'all_payment' && $j('#all_payment').is(':checked') == false) {
			$j('#is_online_payment').attr('checked',false);
			$j('#is_onsite_payment').attr('checked',false);
		} else if($j('#is_online_payment').is(':checked') && $j('#is_onsite_payment').is(':checked')) {
			$j('#all_payment').attr('checked',true); 
		} else {
			$j('#all_payment').attr('checked',false); 
		}
	}
	
}
