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


// Reference: http://javascript.crockford.com/remedial.html

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};



// UFO Interaction:

function loadFile(swf,obj) { 
  thisMovie(swf).loadFile(obj); 
};

function check_is_current(to_present_div, end_date_select_div) {
	
	if (end_date_select_div.visible()) {
		end_date_select_div.hide();
		to_present_div.show();
		
		var select_boxes = end_date_select_div.getElementsByTagName('select');
		for(var i = 0; i < select_boxes.length; i++ ) {
			select_boxes[i].selectedIndex = null;
		}
		
	} else {
		end_date_select_div.show();
		to_present_div.hide();
	}
}

function mirror_contact_fields() {
	contact_fields = new Array('contact_address_1', 'contact_address_2', 'contact_country_id', 'contact_state_id', 'contact_city_id', 'contact_city_name', 'contact_zip_code', 'contact_mobile', 'contact_land_phone', 'contact_ims', 'contact_websites');

	contact_fields.each(function(field) {
		$(field).value = $('user_' + field).value
	});
}

function clean_contact_fields() {
	contact_fields = new Array('contact_address_1', 'contact_address_2', 'contact_country_id', 'contact_state_id', 'contact_city_id', 'contact_city_name', 'contact_zip_code', 'contact_mobile', 'contact_land_phone', 'contact_ims', 'contact_websites');
	
	contact_fields.each(function(field) {
		$(field).value = ""
	});
}

// dynamic select box function for multiple dependant select boxes inside a single view.
function dynamicSelectSelected(choisesCollection, parentFieldId, childFieldId, selectedChild) {
  parent_field_id = (parentFieldId == null ? 'dynamic_select_parent_id' : parentFieldId);
  child_field_id = (childFieldId == null ? 'dynamic_select_city_id' : childFieldId);
  parent_field = $(parent_field_id);
  child_field = $(child_field_id);
  choises = choisesCollection.sort();
  //console.info('parent_field: '+parent_field.id);
  //console.info('child_field: '+child_field.id);
  
  
  current_parent_id = parseInt(parent_field.getValue());
  console.info('current_parent_selected_id: '+current_parent_id);
  options = child_field.options;
  
  if('undefined' == typeof selectedChild) {
		selected_child = parseInt(child_field.getValue());
  	//console.info('selected_child: '+selected_child+', '+typeof(selected_child));
  } else {
  	selected_child = parseInt(selectedChild);
  }
  
  if (options[0] != null && options[0].value == "") { 								// If the first option is the prompt option then...
  	options.length = 1; 
  } else { 																														// else it is a preselected value.
  	options.length = 0; 
  }
  
  choises.each(function(choise) {
    if (choise[0] == current_parent_id) {
      options[options.length] = new Option(choise[1], choise[2]);
    }
  });
  
  for(i = 0; i < options.length; i++) { 
  	//console.info('option value: '+parseInt(options[i].value)+' - '+typeof(parseInt(options[i].value))+' :: selected_child: '+selected_child+' - '+typeof(selected_child));
  	if (parseInt(options[i].value) == selected_child) { 
  		//console.info('Selected Option: '+i+', '+parseInt(options[i].value));
  		options[i].selected = true; 
  		//console.info('Selected Option: '+options[i].selected);
  	} 
  } 
  
  if (options.length == 1) {
    child_field.disabled = true;
  } else {
    child_field.disabled = false;
    new Effect.Highlight(child_field_id,{duration:0.5, startcolor: '#f3eab7', endcolor: '#ffffff'});
  }
	// dynamicSelectSelected(); to chain several subsequent dynamic selects.
}


// Automate the spinner display on and off uon an ajax request.
Ajax.Responders.register({ 
 onCreate: function() { 
   if (Ajax.activeRequestCount > 0) 
     if ($('spinner') != null) { Element.show('spinner') };
     if ($('taxonomy_search_spinner') != null) { Element.show('taxonomy_search_spinner') }; 
     startShadowedSpinner(); 
 }, 
 onComplete: function() { 
   if (Ajax.activeRequestCount == 0) 
     if ($('spinner') != null) { Element.hide('spinner') };
     if ($('taxonomy_search_spinner') != null) { Element.hide('taxonomy_search_spinner') }; 
     endShadowedSpinner(); 
 } 
});

// Client-side image resizing function.
function resize(which, max) {
  var elem = document.getElementById(which);
  if (elem == undefined || elem == null) return false;
  if (max == undefined) max = 100;
  if (elem.width > elem.height) {
    if (elem.width > max) elem.width = max;
  } else {
    if (elem.height > max) elem.height = max;
  }
}


// ----------------------------------------------------------
// Text field / Select swapping methods
// ----------------------------------------------------------

// Swap a select_box for a textfield input
//
// Options
//
// 		=> triggerOption: the option on the select that triggers the swap.
//

function swap_select_for_text_field(element, options) {
	element = (typeof(element) == "string" ? $(element) : element);
	options = ( options == undefined ? {triggerOption: 'Other'} : options );
	
	var swappedField = element.next('span');
	
	//console.info('element =>'); console.info(element);
	//console.info('triggerOption =>'); console.info(options.triggerOption);
	console.info('swappedField 1 =>'); console.info(swappedField);
	
	
	if (element.value == options.triggerOption) {
		if (swappedField == undefined || swappedField == null) {
			// Create span wrapper and set its properties.
			span = document.createElement("span");
			span.style.position = "relative";
			
			// Create text_field and set its properties.
			field = select_to_text_mirror(element);
			
			// Create cancel link and set its properties.
			cancel = document.createElement("a");
			cancel.innerHTML = "<b>&laquo;</b>";
			onclickFunction = "return_select_for_text_field($(this)); return false;";
			cancel.setAttribute('onclick', onclickFunction);
			cancel.href = "#";
			cancel.style.position = "absolute";
			cancel.style.top = "-3px";
			cancel.style.right = "5px";
			cancel.style.fontSize = "14px";
			
			// Append text_field and cancel link to span.
			span.appendChild(field);
			span.appendChild(cancel);
			
			// Insert span after element.
			element.insert({ 'after': span });
			
			swappedField = span;
		}
		//console.info('swappedField 2 =>'); console.info(swappedField);
		
		// Clear, disable and hide the original select element.
		element.value = "";
		element.disable();
		element.hide();
		
		// Enable and show the text field element.
		// ATTENTION: Only assign one class name to the select element or if multiple, 
		// place the class related to this mechanism first.
		class_name = 'input.' + element.classNames().toArray().first();
		text_field_elem = swappedField.down(class_name);
		if (text_field_elem.disabled) { text_field_elem.enable(); }
		if (!swappedField.visible()) { swappedField.show(); }
		text_field_elem.focus();
	}
}


function return_select_for_text_field(element, options) {
	element = (typeof(element) == "string" ? $(element) : element);
	options = ( options == undefined ? {} : options );
	
	// Clear and disable the text field element and hide its span wrapper.
	text_field_elem = element.previous('input');
	
	//console.info('element =>'); console.info(element);
	//console.info('text_field_elem =>'); console.info(text_field_elem);
	
	text_field_elem.clear();
	text_field_elem.disable();
	text_field_span_wrapper = text_field_elem.up('span');
	text_field_span_wrapper.hide();
	
	// Enable and show the select field element.
	// ATTENTION: Only assign one class name to the text element or if multiple, 
	// place the class related to this mechanism first.
	class_name = 'select.' + text_field_elem.classNames().toArray().first();
	select_elem = element.up().previous(class_name);
	if (select_elem.disabled) { select_elem.enable(); }
	if (!select_elem.visible()) { select_elem.show(); }
}

// Create a text field that mirrors a select's attributes.
function select_to_text_mirror(element, options) {
	element = (typeof(element) == "string" ? $(element) : element);
	options = ( options == undefined ? {} : options );
	
	//console.info('select_to_text_mirror options =>');
	//console.info(options);
	//console.info('element =>');
	//console.info(element);
	//console.info('------------------------------------');
	
	// Create text_field and set its properties.
	field = document.createElement("input");
	// ATTENTION: Only assign one class name to the passed element or if multiple, 
	// place the class related to this mechanism first.
	class_name = element.classNames().toArray().first();
	field.addClassName(class_name);
	field.name = element.name;
	field.type = "text";
	// Default options
	field.size = "15";
	field.setAttribute('maxlength', "100");
	/*
	options.each(function(pair) {
		field.setAttribute(pair.key, pair.value);
	}*/
	return field;
}

/*
// Swap a textfield for a select_box input
function swap_text_field_for_select(element, trigger_optn) {
	var elem = element;
	var parent = elem.parentNode;
	trigger_optn = (trigger_optn == null ? 'Other' : trigger_optn);
	
	// Create select and set its properties.
	select = document.createElement("select");
	select.id = elem.previous().id;
	select.name = elem.previous().name;
	select.setAttribute('onchange', "swap_select_for_text_field($(this)); return false;");
	// Add the select options.
	options = ["- Payment base -", "Per Song/Piece", "Per Performance", "Per Hour", "Per Day", "Per Week", "Per Month", "Per Season", "Other"]
	options.each(function(option) { 
		if (option == "- Payment base -") {
			select.options[select.options.length] = new Option(option, option, true, true);
		} else {
			select.options[select.options.length] = new Option(option, option, false, false);
		}
	});
	
	// Replace elem with select.
	parent.parentNode.replaceChild(select, parent);
}
*/

// ----------------------------------------------------------


// Disable an anchor element.
function disableAnchor(objId, disable) { 
	var obj = document.getElementById(objId); 
	if(obj != null) { 
		if(disable) { 
			var href = obj.getAttribute("href"); 
			var onclick = obj.getAttribute("onclick"); 
			//First we store previous value in a new attribute 
			if(href && href != "" && href != null) { 
				obj.setAttribute('href_bak', href); 
			} 
			if(onclick != null) { 
				obj.setAttribute('onclick_back', onclick); 
				obj.setAttribute('onclick', "void(0);"); 
			} 
			obj.removeAttribute('href'); 
			//obj.style.color="gray"; 
	} else { 
		var hrefBack = obj.getAttribute("href_bak"); 
		var onclickBack = obj.getAttribute("onclick_back"); 
		if(onclickBack !=null ) { 
			obj.setAttribute('onclick', onclickBack); 
			obj.removeAttribute('onclick_back'); 
		} 
		if(hrefBack !=null ) { 
			obj.setAttribute('href', hrefBack); 
			obj.removeAttribute('href_bak'); 
			//obj.style.color="blue"; 
		} 
	}
 } 
} 


// Example from http://www.aldenta.com/examples/script.aculo.us/slider-scrollbar.html			

function createSlider() {
	// vertical slider control
	var slider1 = new Control.Slider('scroller_handle', 'scroller_track', {
		axis: 'vertical',
		onSlide: function(v) { scrollVertical(v, $('album_items_list'), slider1);  },
		onChange: function(v) { scrollVertical(v, $('album_items_list'), slider1); }
	});
	
	// disable vertical scrolling if text doesn't overflow the div
	//if ($('album_items_list').scrollHeight <= $('album_items_list').offsetHeight) {
	//	slider1.setDisabled();
	//	$('scroller_handle').hide();
	//}
}
// scroll the element vertically based on its width and the slider maximum value
function scrollVertical(value, element, slider) {
	element.scrollTop = Math.round(value/slider.maximum*(element.scrollHeight-element.offsetHeight));
}

// changes de url action of the new job post form
function update_form_action(form_element, newURL){
  var domainRegExp = /(http:\/\/[A-Za-z0-9_:\.]+)/; 
  var matchesArray = domainRegExp.exec(form_element.action);
 
  if (typeof(newURL) == 'string') {
  	// var newAction = matchesArray[0] + newURL; // Includes domain
  	var newAction = newURL; // Path only
  }
  
  form_element.action = newAction;
  return true;
}


// WARNING USES PROTOTYPE
// Measures the 'box_row' fields inside the container element defined by 'id' and sets the width 
// for all their box_row_contents elements. Uses Prototype
function measureBoxRow(container_id){
	var rowObj = $(container_id).down('.box_row label').up('.box_row');
	var rowWidth = rowObj.getWidth();
	var label = rowObj.down('label');
	
	var labelWidth = label.getWidth();
	var labelLeftMargin = parseInt(label.getStyle('margin-left'));
	var labelRightMargin = parseInt(label.getStyle('margin-right'));
	var rowContentWidth = rowWidth - (labelLeftMargin + labelWidth + labelRightMargin);
	
	//console.info('rowWidth: '+rowWidth);
	//console.info('rowContentWidth: '+rowContentWidth);
	//alert('rowWidth: '+rowWidth);";		
	//alert('rowContentWidth: '+rowContentWidth);
	
	var box_row_content_locator = '#' + container_id + ' .box_row .box_row_content';
	$$(box_row_content_locator).each(function(value, index) {
		value.setStyle({'width': (rowContentWidth.toString() + 'px')});
	});
}
// WARNING USES MOOTOOLS
// Measures the 'box_row' fields inside the container element defined by 'id' and sets the width 
// for all their box_row_contents elements. Uses Mootools
function measureBoxRowMootools(container_id){
	var rowObj = $(container_id).getElement('.box_row label').getParent('.box_row');
	var rowWidth = parseInt(rowObj.getStyle('width'));
	var label = rowObj.getElement('label');
	
	var labelWidth = parseInt(label.getStyle('width'));
	var labelLeftMargin = parseInt(label.getStyle('margin-left'));
	var labelRightMargin = parseInt(label.getStyle('margin-right'));
	var rowContentWidth = rowWidth - (labelLeftMargin + labelWidth + labelRightMargin);
	
	//console.info('rowWidth: '+rowWidth);
	//console.info('rowContentWidth: '+rowContentWidth);
	//alert('rowWidth: '+rowWidth);";		
	//alert('rowContentWidth: '+rowContentWidth);
	
	var box_row_content_locator = '#' + container_id + ' .box_row .box_row_content';
	$$(box_row_content_locator).each(function(value) {
		value.setStyle('width', (rowContentWidth.toString() + 'px'));
	});
} 

// Find the real height of an element with margins and paddings
function getRealHeight(element_id) {
	var el = $(element_id)
	
	var h = el.getHeight();
	var tm = parseInt(el.getStyle('margin-top'));
	var bm = parseInt(el.getStyle('margin-bottom'));
	// getHeight already takes into account the paddings
	//var tp = parseInt(el.getStyle('padding-top'));
	//var bp = parseInt(el.getStyle('padding-bottom'));
	
	var realHeight = h + tm + bm;
	//console.info('realHeigh: '+realHeight);
	return realHeight;
}

// Checks the currently selected value for a group of radio buttons and returns it
function getRadioGroupValue(radio_grp_name) {
	var radioGrp = $$("input[type=radio][name='" + radio_grp_name + "']");
	for(i=0; i < radioGrp.length; i++){
		if (radioGrp[i].checked == true) {
			var radioValue = radioGrp[i].value;
			
			//console.info(radioValue);
			return radioValue;
		}
	}
}

// Resizes an object based on the max-value provided
function resizeCanvas(element, maxValue) {
	var canvas = element;
	var canvasDimensions = element.getDimensions();
	var oldStyle = element.getAttribute('style');
	var heightRegex = /height: \d+px/;
	var widthRegex = /width: \d+px/;
	if (canvasDimensions.width > canvasDimensions.height) {
		var newWidth = maxValue;
		var newHeight = (canvasDimensions.height / canvasDimensions.width) * maxValue;
	} else {
		var newHeight = maxValue;
		var newWidth = (canvasDimensions.width / canvasDimensions.height) * maxValue;
	}
	
	var newStyle = oldStyle.replace(heightRegex, 'height: '+ newHeight + 'px').replace(widthRegex, 'width: '+ newWidth + 'px');
	canvas.setAttribute('style', newStyle);
}

/*
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
 
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}





// Enables/Disables the child input fields for the referenced element.
function toggle_desired_wage_fields(form_id, radio_grp_name, desired_wages_container_id, main_container, button){
	//console.info($RF(form_id, radio_grp_name));
	if ($RF(form_id, radio_grp_name) == '1') {
		
		$(desired_wages_container_id).select('input', 'select', 'textarea').each(function (elem) { 
			elem.disabled=false; elem.style.backgroundColor = ''; 
		}); 
		new Effect.Appear(button, {duration:0.5}); 
		new Effect.Appear(main_container, {duration:0.5});
	
	} else {
	
		$(desired_wages_container_id).select('input', 'select', 'textarea').each(function (elem) { 
			elem.disabled=true; elem.style.backgroundColor = '#d5d5d5'; 
		}); 
		new Effect.Fade(button, {duration:0.5}); 
		new Effect.Fade(main_container, {duration:0.5});
	
	}
}

// Recalculates the number of items in a list and assigns classes (odd, even) to handle different backgrounds.
//
// class_names: {header: 'header_class', item: 'item_class'}
// containerHeightAdjustment: a number to take off of the container's height
//
//
function recalculateListItems(list_id, counter_class, container_id, raw_class_names, options) {
	var list = $(list_id);
	var container = $(container_id);
	if (raw_class_names != null) { var class_names = $H(raw_class_names).values(); }
	//console.info(class_names);
	
	if (class_names != null && class_names.length > 0) {
		var unfiltered_list_items = list.descendants();
		var curr_list_items = unfiltered_list_items.findAll(function(el) { 
			return class_names.any(function(class_name) { 
				return el.hasClassName(class_name);
			});
		}); 
	} else {
		var curr_list_items = list.childElements();
	}
	
	var items_index = 0;
	curr_list_items.flatten().each(function (item, index) { 
		//console.info(item);
		item.hasClassName('odd_bkgd') ? item.removeClassName('odd_bkgd') : null;
		item.hasClassName('even_bkgd') ? item.removeClassName('even_bkgd') : null;
		
		// if there is a counter is an item
		if (item.down('.'+counter_class) != null) {
			items_index += 1;
			item.down('.'+counter_class).innerHTML = (items_index.toString() + '.');  // reassign list numbers
			// assign new bkgd class name to rows with a counter only
			if (isOdd(items_index)) { item.addClassName('odd_bkgd'); } else if (isEven(items_index)) { item.addClassName('even_bkgd'); }
		}
		
		// If it's the last item and the height of the container is around the same as the list
		if (options != null && options.containerHeightAdjustment != null) { 
			//console.info('options.containerHeightAdjustment: '+options.containerHeightAdjustment);
			var listToContainerDiff = Math.abs(list.offsetHeight - container.offsetHeight) - options.containerHeightAdjustment;
		} else {
			var listToContainerDiff = Math.abs(list.offsetHeight - container.offsetHeight);
		}
		
		//console.info("index == (curr_list_items.length - 1): "+(index == (curr_list_items.length - 1)));
		if (index == (curr_list_items.length - 1)) { 
			if (listToContainerDiff < 6) { item.style.borderBottomStyle = 'none'; } else { item.style.borderBottomStyle = 'solid'; } 
		} else {
			item.style.borderBottomStyle = 'solid';
		}
		
		// if it's the first item and is a header (NOTE: this loop must come after the previous one at all times)
		if ((raw_class_names != null) && (index == 0) && (item.hasClassName(raw_class_names.header)) ) { 
			item.style.borderTopStyle = 'solid'; 
		}
	});
	
	//console.info('curr_list_items: '+curr_list_items.length);
}

// Check if number is even.
// reference: http://tobielangel.com/2006/8/10/javascript-quick-tips-odd-or-even 
function isEven(num) {
  return !(num % 2);
}
// Check if number is odd. 
function isOdd(num) {
  return !isEven(num);
}

// Looks up for the largest column directly descending from the object specified through the id and assign this object the largest child's background color;
function assignDominantHeightColumnForList(container_id, column_ids, options) {
	if (!options) { /* Die silently if no options are supplied.*/ } 
	
	var container = $(container_id);
	var ids_array = column_ids.map(function(id) { return "#" + id });
	var curr_columns = container.select(ids_array);	
	//console.info(curr_columns);
	
	heightsArray = curr_columns.map(function(el, index) { return el.getHeight(); });	
	//console.info('heightsArray: '+heightsArray);
	
	if (!options) {
		var highestElement = 0;
		var highestIndex = 0;
		
		heightsArray.each(function(height_a, index_a) { 
			heightsArray.each(function(height_b, index_b) { 
				//console.info('height_a: '+height_a+' - '+'index: '+index+', '+'height_b: '+height_b);
				if (height_a > height_b) {
					//console.info('A is higher');
					//console.info('A higher than highest?: '+(height_a > highest));
					if (height_a > highestElement) { 
						highestElement = height_a;
						highestIndex = index_a;
						//console.info('highestIndex: '+highestIndex);
					}
					
				} else {
					//console.info('B is higher');
					//console.info('B higher than highest?: '+(height_b > highest));
					if (height_b > highestElement) { 
						highestElement = height_b;
						highestIndex = index_b;
						//console.info('highestIndex: '+highestIndex);
					}
				}
			});	  
		});
		
		var newHeight = curr_columns[highestIndex].offsetHeight.toString() + 'px';
		
	} else if (options.newHeight) {
		var newHeight = options.newHeight;
	}	
	
	
	curr_columns.each(function(el) { el.style.minHeight = newHeight; });
	//console.info('highestElement: '+highestElement);
	//console.info('newHeight: '+newHeight);
}

// Rescales the height of a div based on the height of another div
function rescaleHeight(element_to_rescale, reference_element) {
	if ($(element_to_rescale) != null && $(reference_element) != null) {
		currentHeight = $(element_to_rescale).offsetHeight;
		newHeight = $(reference_element).offsetHeight;
		currentInnerHeight = $(element_to_rescale).down().offsetHeight;
		
		//console.info('currentHeight: '+currentHeight);
		//console.info('newHeight: '+newHeight);
		
		// If the reference element is larger than the element to rescale, then rescale (enlarge).
		ref_larger_than_el = (newHeight > currentHeight);
		// If the element to rescale is already larger than the reference element AND 
		// the reference element is larger than the inner height of the element to rescale, then rescale (reduce).
		el_larger_than_ref = ( (currentHeight > newHeight) && (newHeight > currentInnerHeight) );
		
		//console.info('ref_larger_than_el: '+ref_larger_than_el);
		//console.info('el_larger_than_ref: '+el_larger_than_ref);
		if ( ref_larger_than_el || el_larger_than_ref ) {
			//console.info('Conditions passed');
			$(element_to_rescale).setStyle({minHeight: newHeight.toString()+'px'});
		}
	}
}


// Switched the field's background color to red when its content exceeds the max-limit.
function watchTextareaContentLength(element, limit, counter_class){
	//console.info(element.value.split(/./).length);
	var curr_length = (element.value.split(/./).length - 1); // -1 is a quick fix to adjust the counter properly
	var chars_left = limit;
	if (curr_length > limit) {
		element.style.backgroundColor = '#ffadad';
		chars_left = 0;
	} else {
		element.style.backgroundColor = '';
		chars_left = (limit - curr_length);
	}
	element.next('.'+counter_class).innerHTML = chars_left.toString() + ' Characters left';
}



// Creates a spinner with a shadow overlay behind
function createShadowedSpinner() {
	var objBody = $$('body')[0];
	objBody.appendChild(Builder.node('div',{id:'overlay'}));
	
	$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
	
	// stretch overlay to fill page and fade in
	var arrayPageSize = this.getPageSize();
	$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

	new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity });
}

// Activate the shadow overlay
function startShadowedSpinner() {
	// NOTE: scriptaculous and lightbox must be loaded first
	var objBody = $$('body')[0];
	
	if ($('shadowed_loading') == null) {
		objBody.appendChild(Builder.node('div',{id:'shadowed_overlay'}));
		objBody.appendChild(Builder.node('div',{id:'shadowed_loading', style:'padding:15px;'}, 
			Builder.node('a',{id:'shadowed_loadingLink', href: '#' }, 
				Builder.node('img', {src: LightboxOptions.fileLoadingImage})
			)
		));
		
		$('shadowed_overlay').setStyle({ position: 'absolute', top: '35%', left: '45%', zIndex: '990', width: '82px', height: '82px', backgroundColor: '#000' });
		$('shadowed_loading').setStyle({ position: 'absolute', top: '35%', left: '45%', zIndex: '1000', width: '32px', height: '32px', textAlign: 'center', lineHeight: '0', backgroundColor: 'rgb(255, 255, 255)' });
	}
	
	$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
	
	// stretch overlay to fill page and fade in
	//var arrayPageSize = Lightbox.prototype.getPageSize();
	//$('shadowed_overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

	// calculate top and left offset for the lightbox 
	var arrayPageScroll = document.viewport.getScrollOffsets();
	var spinnerTop = arrayPageScroll[1] + (document.viewport.getHeight() /2);
	var spinnerLeft = arrayPageScroll[0] + (document.viewport.getWidth() /2) - 50;
	//console.info('spinnerTop: '+spinnerTop);
	//console.info('spinnerLeft: '+spinnerLeft);
	$('shadowed_overlay').setStyle({ top: spinnerTop + 'px', left: spinnerLeft + 'px' });
	new Effect.Appear($('shadowed_overlay'), { duration: 0.2, from: 0.0, to: 0.4 });
	$('shadowed_loading').setStyle({ top: (spinnerTop+10) + 'px', left: (spinnerLeft+10) + 'px' }).show();
}
// Deactivate the shadow overlay
function endShadowedSpinner() {
	$('shadowed_loading').hide();
	new Effect.Fade($('shadowed_overlay'), { duration: 0.2 });
	$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
}


// Decide weather of not to change the portfolio's background color
function definePortfolioBkgd(buttons_container) {
	if ($(buttons_container)) {
		var buttons = $(buttons_container).select('a');
		//console.info(buttons);
		
		if (buttons.detect(function(butt) { return butt.id == 'stage_button' }) && buttons.detect(function(butt) { return butt.id == 'stage_button' }).hasClassName('active')) {
			fadeOutPortfolioBkgd($('portfolio_background_container'), $('portfolio_background_wrapper'));
		} else {
			fadeInPortfolioBkgd($('portfolio_background_container'), $('portfolio_background_wrapper'));
		}	
	}
}


// -----------------------------------------------------------
// TOGGLE Effects
// -----------------------------------------------------------

function slide_toggle(element_a_id, element_b_id, options){
	options == null ? options = {} : null;
	if (options.afterFinish) { 
		last_eff_opts = { queue: 'end', afterFinish: options.afterFinish }
	} else { 
		last_eff_opts = { queue: 'end' }
	}
	var duration = 0.75;
	
	if ($(element_a_id).visible()) {
		//console.info(element_a_id + ' is visible');
		// Element A
		new Effect.SlideUp(element_a_id, { duration: duration, scaleFrom: 100, scaleTo: 0 });
		
		// Element B
		if (element_b_id != null && typeof(element_b_id) == 'object') { // Elem. B is an array
			new Effect.SlideDown($(element_b_id[0]), { duration: duration, scaleFrom: 0, scaleTo: 100 });
			
	  } else if (element_b_id != null && typeof(element_b_id) == 'string') {
			/*if (options.scrollTo != undefined) {
				new Effect.Parallel(
		      [ 
		      	new Effect.SlideDown(element_b_id, { sync: true, duration: duration, scaleFrom: 0, scaleTo: 100 }),
						new Effect.ScrollTo(options.scrollTo, { sync: true, duration: duration })
		      ], last_eff_opts
		    );
		    
	    } else {
	    	new Effect.SlideDown(element_b_id, { duration: duration, scaleFrom: 0, scaleTo: 100, queue: 'end' });
	    }*/
	    new Effect.SlideDown(element_b_id, { duration: duration, scaleFrom: 0, scaleTo: 100 });
    }
    
    if (options.scrollTo != undefined) { new Effect.ScrollTo(options.scrollTo[1], { duration: duration, queue: 'end' }); }
    
	} else if (!$(element_a_id).visible()) {
		if (element_b_id != null && typeof(element_b_id) == 'object') { // Elem. B is an array
			// Element B
			var effects = new Array();
			var eff_options = { sync: true,scaleFrom: 100,scaleTo: 0,scaleContent: false,scaleX: false,scaleY: true }; 
			for(var i=0; i<element_b_id.length; i++) { 
        effects.push(new Effect.SlideUp($(element_b_id[i]), eff_options));
      }
      
      new Effect.Parallel(effects, { duration: duration });
			
			// Element A
			new Effect.SlideDown(element_a_id, { duration: duration, scaleFrom: 0, scaleTo: 100 });
			
		} else if (element_b_id != null && typeof(element_b_id) == 'string') {				
			//console.info(element_a_id + ' is not visible');
			new Effect.SlideUp(element_b_id, { duration: duration, scaleFrom: 100, scaleTo: 0 }); 
		
	    /*if (options.scrollTo != undefined) {
				new Effect.Parallel(
		      [ 
		      	new Effect.SlideDown(element_a_id, { sync: true, duration: duration, scaleFrom: 0, scaleTo: 100 }),
						new Effect.ScrollTo(options.scrollTo, { sync: true, duration: duration })
		      ], last_eff_opts
		    );
	    } else {
	    	new Effect.SlideDown(element_a_id, { duration: duration, scaleFrom: 0, scaleTo: 100, queue: 'end' });
	    }*/
	    new Effect.SlideDown(element_a_id, { duration: duration, scaleFrom: 0, scaleTo: 100 });
	    
    } else {
    	new Effect.SlideDown(element_a_id, { duration: duration, scaleFrom: 0, scaleTo: 100 }); 
    }
    
    if (options.scrollTo != undefined) { new Effect.ScrollTo(options.scrollTo[0], { duration: duration, queue: 'end' }); }
	}
}

function appear_toggle(element_a_id, element_b_id){
	if ($(element_a_id).visible()) {
		//console.info(element_a_id + ' is visible');
		new Effect.Fade(element_a_id, { duration: 0.5 }); 
		new Effect.Appear(element_b_id, { duration: 0.5, queue: 'end' });
		
	} else if (!$(element_a_id).visible()) {
		//console.info(element_a_id + ' is not visible');
		new Effect.Fade(element_b_id, { duration: 0.5 }); 
		new Effect.Appear(element_a_id, { duration: 0.5, queue: 'end' });
	}
}

// End of TOGGLE Effects
// -----------------------------------------------------------





// UNDER_CONSTRUCTION Fades with mootools
function fade_with_mootools(element_id){
	var elm = $(element_id).setStyles({
		display:'block',
		opacity: 1
	});
	var transition = new Fx.Transition(Fx.Transitions.Elastic, 3);
	div.effect('opacity', {transition: transition.easeOut});
}



// SHASTIC CALENDAR FUNCTIONS
// -----------------------------------------------------------


Date.prototype.getWeek = function() {
	var determinedate = new Date();
	determinedate.setFullYear(this.getFullYear(), this.getMonth(), this.getDate());
	var D = determinedate.getDay();
	if(D == 0) D = 7;
	determinedate.setDate(determinedate.getDate() + (4 - D));
	var YN = determinedate.getFullYear();
	var ZBDoCY = Math.floor((determinedate.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
	var WN = 1 + Math.floor(ZBDoCY / 7);
	return WN;
}

// End of SHASTIC CALENDAR FUNCTIONS
// -----------------------------------------------------------


function percent(x) { return Math.round((x-0)*100) + '%'; }



// ACCEPT TERMS & CONDITIONS AND PRIVACY POLICY
// -----------------------------------------------------------

function validateAcceptedTerms(terms_id) {
	if (!$(terms_id).checked) { 
		alert("You must first accept the Terms & Conditions and Privacy Policy in order to continue."); 
		return false; 
	} else { 
		return true; 
	}
}




