var AjaxLoadingOverlay = {
    overlay_cache: [],
    show: function(element_id, message) {
        if ( !message) message = 'Loading&hellip;';
        
        if ( this.overlay_cache[element_id] ) return;
        
        var overlay_id = element_id + '_ajax_loading_overlay';
        
        var fTop = $(element_id).positionedOffset().top;
        var fLeft = $(element_id).positionedOffset().left;
        var fWidth = $(element_id).getWidth();
        var fHeight = $(element_id).getHeight();
        
        var centerWidth = 200;
        var centerHeight = 50;
        var centerLeft = fLeft + ((fWidth - centerWidth) / 2);
        var centerTop = fTop + ((fHeight - centerHeight) / 2);
        
        if (!message)
            message = 'Submitting form&hellip;';
        
        var overlay
            = '<div id="'+overlay_id+'" style="'
            + ' position: absolute;'
            + ' top: '+fTop+'px;'
            + ' left: '+fLeft+'px;'
            + ' width: '+fWidth+'px;'
            + ' height: '+fHeight+'px;'
            + ' background: #ffffff;'
            + ' filter:alpha(opacity=70);'
            + ' moz-opacity: 0.7;'
            + ' -khtml-opacity: 0.7;'
            + ' opacity: 0.7;'
            + '">&nbsp;'
            + '</div>'
            + '<div style="'
            + ' position: absolute;'
            + ' top: '+centerTop+'px;'
            + ' left: '+centerLeft+'px;'
            + ' width: '+centerWidth+'px;'
            + ' height: '+centerHeight+'px;'
            + ' padding: 1em;'
            + ' background: rgb(255,255,255);'
            + ' border: 1px solid gray;'
            + '">'
            + ' <img src="/images/ajax-loader.gif" alt="" /> ' + message
            + '</div>'
            ;
        
        $(element_id).insert(overlay);
        
        this.overlay_cache[element_id] = overlay_id;
    },
    hide: function(element_id) {
        if ( ! this.overlay_cache[element_id] ) return;
        this.overlay_cache[element_id] = null;
        
        var overlay_id = this.overlay_cache[element_id];
        $(overlay_id).remove();
    }
}

function autoSubmitForm(formName, message)
{
    var form = $(document.forms[formName]);
    
    var fTop = $(form).positionedOffset().top;
    var fLeft = $(form).positionedOffset().left;
    var fWidth = $(form).getWidth();
    var fHeight = $(form).getHeight();
    
    var centerWidth = 200;
    var centerHeight = 50;
    var centerLeft = fLeft + ((fWidth - centerWidth) / 2);
    var centerTop = fTop + ((fHeight - centerHeight) / 2);
    
    if (!message)
        message = 'Submitting form&hellip;';
    
    var overlay
        = '<div style="'
        + ' position: absolute;'
        + ' top: '+fTop+'px;'
        + ' left: '+fLeft+'px;'
        + ' width: '+fWidth+'px;'
        + ' height: '+fHeight+'px;'
        + ' background: #ffffff;'
        + ' filter:alpha(opacity=70);'
        + ' moz-opacity: 0.7;'
        + ' -khtml-opacity: 0.7;'
        + ' opacity: 0.7;'
        + '">&nbsp;'
        + '</div>'
        + '<div style="'
        + ' position: absolute;'
        + ' top: '+centerTop+'px;'
        + ' left: '+centerLeft+'px;'
        + ' width: '+centerWidth+'px;'
        + ' height: '+centerHeight+'px;'
        + ' padding: 1em;'
        + ' background: rgb(255,255,255);'
        + ' border: 1px solid gray;'
        + '">'
        + ' <img src="/images/ajax-loader.gif" alt="" /> ' + message
        + '</div>'
        ;
    
    $(form).insert(overlay);
    setTimeout("document.forms['"+formName+"'].submit()", 250);
}

function addOneListItem(listID, inputName, value) {
    value = value.strip();
    if (value == '') return;
    var children = $(listID).childElements();
    var terminate = false;
    children.each(function(item) {
        if (item.title == value) {
            terminate = true;
            return;
        }
    });
    if (terminate) return;
    var newItem = '<li title="'+value+'">'
                + '<input type="hidden" name="'+inputName+'[]" value="'+value+'" />'
                + '<a title="remove keyword \''+value+'\'" href="javascript:void(0)" onclick="removeListItem(\''+listID+'\', Element.ancestors(this)[0])">X</a> '
                + '<span>' + value + '</span>'
                + '</li>';
    Element.insert($(listID), newItem );
}

function addListItems(mainID, inputName) {
    addOneListItem(mainID+'_list', inputName, $(mainID+'_input').value);
    $(mainID+'_input').value = '';
    $(mainID+'_input').focus();
}

function removeListItem(listID, element) {
    Element.remove(element);
}
        
function addListItemKeydown(event) {
    if (event.keyCode != Event.KEY_RETURN)
        return;

    event.stop();
    var element = event.element();
    var parent = $(element.ancestors()[0]);
    var inputName = getKeywordsFieldName(parent.id);
    addListItems(parent.id, inputName);
}


function disableSubmits(form)
{
    if (form.disabled)
        return false;
    else
    {
        buttons = form.getInputs("submit");
        buttons.invoke("disable");
        return true;
    }
}

function minimize(divid)
{
    var data = '';
    s = new String(divid);
    if (($(divid).style.display == '') || ($(divid).style.display == 'block'))
    {
        $(divid).hide();
        if ($('divchanged'))
        {
        	$('divchanged').value = s.replace("div","");
        	$('currentval').value = 0;
        }
    }
    else
    {
        $(divid).show();
        if ($('divchanged'))
        {
			$('divchanged').value = s.replace("div","");
			$('currentval').value = 1;
		}
    }
}

function showHide(fieldsetID)
{
	if (!$(fieldsetID)) return false;
	if ($(fieldsetID).style.display == 'none') Effect.BlindDown(fieldsetID, {duration:0.5});
	else Effect.BlindUp(fieldsetID, {duration:0.5});
}

function showHideDivAndLinks(div_id, expand_link_id, close_link_id)
{
	if (!$(div_id)) return false;
	if (!$(expand_link_id) || !$(close_link_id))
	{
        showHide(div_id);
        return;
    }
    
	if ($(div_id).style.display == 'none')
    {
        $(expand_link_id).hide();
        Effect.BlindDown(div_id, {duration:0.5});
        $(close_link_id).show();
    }
	else
    {
        $(close_link_id).hide();
        Effect.BlindUp(div_id, {duration:0.5});
        $(expand_link_id).show();
    }
}

function showHideSmart(fieldsetID,fieldValue)
{
	if (!$(fieldsetID))
        return false;
	if ($(fieldsetID).style.display == 'none') {  
        Effect.BlindDown(fieldsetID, {duration:0.5});
	}
	else {
	      if (fieldValue == "") {
              Effect.BlindUp(fieldsetID, {duration:0.5});
	      }
	}
}

function showHideConditional(fieldsetID, option_selected)
{
	if (!$(fieldsetID)) return false;
	if (option_selected == 1) //show
	{
		Effect.BlindDown(fieldsetID, {duration:0.5});
	}
	else //hide
	{
		Effect.BlindUp(fieldsetID, {duration:0.5});
	}	
}

function openList(x)
{
  b=$('list' + x);
  showHide(b);  
}

function openList2(x)
{
  b=$(x);
  showHide(b);  
}

function changeIndustriesInColumnCommon(catId, formName)
{
    $(formName).industry.options.length=0;
    $(formName).industry.options[0]=new Option('-- please select an industry --', 0);

    if ((catId != '') && (catId != 0))
    {
        longitud = eval('category_'+catId+'_ids.length');
        for(var q=0;q<longitud;q++)
        {
            $(formName).industry.options[q+1] = new Option(eval('category_'+catId+'_values['+q+']'), eval('category_'+catId+'_ids['+q+']'));
        }

    }
    else
    {
        $(formName).industry.options[0]=new Option('-- please select a category --', 0);
    }
}

function submitSortForm(form_name,sort_value)
{
    $(form_name).sort_by.value = sort_value;
    $(form_name).submit();
}
function submitSortFormAndTags(form_name,sort_value)
{
    $(form_name).sort_by.value = sort_value;
    $(form_name).tags.value = $('sort').tags.value;
    $(form_name).submit();
}

function reloadIndustries(category_id, formName, function_to_count, additional_params)
{
    showHideSmart('labelindustry', category_id)
    
    var AR = new Ajax.Request('/index.php/utilities/reloadIndustries.html',
		{
			asynchronous: false,
			onComplete:   function(request, json)
            {
                var tempArray = json.new_options;
                var counter = 0;
                $(formName).industry.options.length=0;
                for (var unid in tempArray)
                {
                    $(formName).industry.options[counter++] = new Option( tempArray[unid], unid);
                }
            },
			parameters: 'category_id='+category_id+'&function_to_count='+function_to_count+
                        '&additional_params='+additional_params
		});

	return false;
}
function reloadGroupedIndustries(type, formName)
{
    //showHideSmart('labelindustry', category_id)
    
    var AR = new Ajax.Request('/index.php/utilities/reloadGroupedIndustries.html',
		{
			asynchronous: false,
			onComplete:   function(request, json)
            {
                var tempArray = json.new_options;
                var counter = 0;
                
                for(i = $(formName).industry.options.length - 1 ; i >= 0 ; i--)
				{
					$(formName).industry.options[i] = null;
				}

				var optgroups = $(formName).industry.childNodes;
				for(i = optgroups.length - 1 ; i >= 0 ; i--)
				{
					$(formName).industry.removeChild(optgroups[i]);
				}

				$(formName).industry.options.length = 0;
				$(formName).industry.options[0] = new Option('-- Select --', '');
    			$(formName).industry.selectedIndex = 0;
    
                for (var group in tempArray)
                {
                	optGroup = document.createElement('optgroup');
					optGroup.label = group;
					$(formName).industry.appendChild(optGroup);
					
                    var inds = tempArray[group];
                	for (var unid in tempArray[group])
                	{
                		objOption=document.createElement("option");
						objOption.innerHTML = tempArray[group][unid];
						objOption.value = unid;

						optGroup.appendChild(objOption);                    	
                    }
                }                
            },
			parameters: 'type='+type
		});

	return false;
}

function generalSearch(cat_code)
{
    $('SearchGeneralForm').general_search_search_category.value = cat_code;
    $('SearchGeneralForm').submit();
}

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}


function _Common() {
	
	this.Recommendation = new _Recommendation();
	this.Ajax = new _skipsoAjax();
	
	this.onLoad = function() {
	}
	
	this.checkPwdStrength = function(inputField) {
		var PwdStrengthInfo = $('PwdStrengthInfo');
		if (PwdStrengthInfo == null) return;
		var inputStr = inputField.value;
		var strength = 0;
		var numberRe = new RegExp("[0-9]");
		if(numberRe.test(inputStr)){
			strength++;
		}
		var nonAlphaRe = new RegExp("[^A-Za-z0-9]");
		if(nonAlphaRe.test(inputStr)){
			strength++;
		}
		var upperAlphaRe = new RegExp("[A-Z]");
		if(upperAlphaRe.test(inputStr)){
			strength++;
		}
		if(inputStr.length >= 10){
			strength++;
		}
		var strengthStr = 'Password strength: ';
		if(inputStr.length < 6) {
			strengthStr += '<strong style="color:red">too short</strong>';
		} else if (strength <= 1) {
			strengthStr += '<strong style="color:grey">weak</strong>';
		} else if(strength <= 2) {
			strengthStr += '<strong style="color:blue">medium</strong>';
		} else {
			strengthStr += '<strong style="color:green">strong</strong>';
		}
		PwdStrengthInfo.innerHTML = strengthStr;
	}
	
	
	this.changeNameIDs4Node = function(element,oldValue,newValue) {
		var ndList = element.childNodes;
		for (var i=0; i<ndList.length; i++) this.changeNameIDs4Node(ndList[i],oldValue,newValue);
		if (element.name) element.name = element.name.replace(oldValue,newValue);
		if (element.id) element.id = element.id.replace(oldValue,newValue);
		if (element.type && (element.type == 'text' || element.type == 'hidden')) element.value = '';
		if (element.className) element.className = element.className.replace('error','');
	}
	
}

function _Recommendation() {
	
	this.go2Step2 = function() {
		for (var i = 0; i < document.recommendForm.recommendation_type.length; ++i) {
		  if (document.recommendForm.recommendation_type[i].checked) {
			var recommendation_type = document.recommendForm.recommendation_type[i].value;
			break;
		  }
		}
		var newtitle = 'Recommend '+document.recommendForm.name.value+', ';
		
		switch (recommendation_type) {
			case '1':
				newtitle += 'Colleague';
				break;
			case '2':
				newtitle += 'Service Provider';
				break;
			case '3':
				newtitle += 'Business Partner';
				break;
		}
		Modalbox.show(
			document.recommendForm.action,
			{
				title: newtitle,
				height: 600,
				method: 'post',
				params: Form.serialize('recommendForm')
			}
		);
	}
	
	this.finish = function() {
		Modalbox.show(
			document.recommendForm.action,
			{
				title: document.recommendForm.title.value,
				height: 600,
				method: 'post',
				params: Form.serialize('recommendForm')
			}
		);
	}
	
}

function _skipsoAjax() {
	
	
	this.loading = function(msg) {
			var ajax_indicator = $('ajax_indicator');
			var par = ajax_indicator.getElementsByTagName('P')[0];
			var parSpan = par.getElementsByTagName('SPAN')[0];
			par.className = 'loading';
			parSpan.innerHTML = msg;
			Element.show('ajax_indicator');
		}
	
	
	this.complete = function(msg) {
			setTimeout('Element.fade(\'ajax_indicator\')',3000);
		}
	
	this.showMessage = function(success, msg)
	{
        var ajax_indicator = $('ajax_indicator');
		var par = ajax_indicator.getElementsByTagName('P')[0];
		var parSpan = par.getElementsByTagName('SPAN')[0];
		if (success) {
			par.className = 'success';
		} else {
			par.className = 'error';
		}
		parSpan.innerHTML = msg;
    }

    this.updateJSON = function(request, json) {
			var ajax_indicator = $('ajax_indicator');
			if (ajax_indicator != null) {
				var par = ajax_indicator.getElementsByTagName('P')[0];
				var parSpan = par.getElementsByTagName('SPAN')[0];
				if (json.success) {
					par.className = 'success';
				} else {
					par.className = 'error';
				}
				parSpan.innerHTML = json.feedback;
				setTimeout('Element.fade(\'ajax_indicator\')',3000);
			}
			setTimeout(json.onComplete,0);
		}
	
	
	this.link2ajax = function(url,updateID) {
			$('link2ajax_loader').style.display = '';
			var AR = new Ajax.Request(
				url,
				{
					asynchronous:true,
					evalScripts:false,
					onSuccess:function(request){$(updateID).innerHTML = request.responseText;}
				}
			);
		}
		
	this.onCompleteLink2ajax = function(request,updateID) {
			
		}
	
}

function checkAgreed(field_name, message)
{
    if ($(field_name).checked)
        return true;
    alert(message);
    return false;
}

function generalMarkAll(category,formName)
{
   var checkboxes = $(formName).getElementsByClassName('checkbox_'+category);
   for (var i in checkboxes)
   {
     checkboxes[i].checked = true;
   }
}

function generalUnmarkAll(category,formName)
{
   var checkboxes = $(formName).getElementsByClassName('checkbox_'+category);
   for (var i in checkboxes)
   {
     checkboxes[i].checked = false;
   }
}


var Common = new _Common();

window.onload = function() {
	Common.onLoad();
	if (typeof Account != 'undefined') {
		Account.onLoad();
	}
	if (typeof Register != 'undefined') {
		Register.onLoad();
	}
	if (typeof Contacts != 'undefined') {
		Contacts.onLoad();
	}
	if (typeof Messages != 'undefined') {
		Messages.onLoad();
	}
	if (typeof ActivityStream != 'undefined') {
		ActivityStream.onLoad();
	}
	if (typeof Privacy != 'undefined') {
		Privacy.onLoad();
	}
	if (typeof OrganicGroup != 'undefined') {
		OrganicGroup.onLoad();
	}
	if (typeof Locations != 'undefined') {
		Locations.onLoad();
	}
	if (typeof AutocompleterDefaultText != 'undefined') {
		AutocompleterDefaultText.onLoad();
	}
	if (typeof MFU != 'undefined') {
		MFU.onLoad();
	}
}
