/**
 * Javascript Library for squirrel framework
 */

// This is variable for storing callback function 
var ae_cb = null;
 
// this is a simple function-shortcut 
// to avoid using lengthy document.getElementById 
function ae$(a) { return document.getElementById(a); } 
 
// This is a main ae_prompt function 
// it saves function callback  
// and sets up dialog 
function ae_prompt(cb, q, a) { 
	ae_cb = cb;
	ae$('aep_t').innerHTML = document.domain + ' question:';
	ae$('aep_prompt').innerHTML = q;
	ae$('aep_text').value = a;
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = '';
	ae$('aep_text').focus();
	ae$('aep_text').select();
} 
 
// This function is called when user presses OK(m=0) or Cancel(m=1) button 
// in the dialog. You should not call this function directly. 
function ae_clk(m) { 
	// hide dialog layers  
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = 'none';
	if (!m)  
		ae_cb(null);  // user pressed cancel, call callback with null 
	else 
		ae_cb(ae$('aep_text').value); // user pressed OK  
} 



function showParentInExpandableTree(obj) {

	var parentId = obj.parent().find('input').val();
	obj.parent().parent().find('.plusminus.id_' + parentId).each(function() {
		if ($(this).html() == '+') {
			$(this).click();
			showParentInExpandableTree($(this));
		}
	});

}

$(function() {

	/** Expandable tree component * */
	$(".expandable_tree .option span.label").click(function() {
		var id = $(this).parent().find('span input').val();

		// updating selection
		$(this).parent().parent().find('span').removeClass('selected');
		$(this).addClass("selected");
		$(this).parent().parent().find('input.hidden').val(id);
	});

	$(".expandable_tree div.plusminus").click(function() {

		if ($(this).html() == '-') {
			$(this).html('+');
			// hiding subelements
			var id = $(this).parent().find('span input').val();
			$(this).parent().parent().find('div.option.parent_' + id).each(function() {
				$(this).hide();
				$(this).find('div.plusminus').each(function() {

					if ($(this).html() == '-')
						$(this).click();
				});
			});
		} else {
			$(this).html('-');
			// showing subelements
			var id = $(this).parent().find('span input').val();
			$(this).parent().parent().find('div.option.parent_' + id).each(function() {
				$(this).show();

			});
		}

	});

	$('div.checkbox_tree ul').each(function() {
		var container = $(this);
		$(this).children('li').each(function() {
			if ($(this).children('ul').length > 0) {
				$(this).prepend($('<a>', {
				    'class' : 'tree-control',
				    href : 'javascript:',
				    click : function() {
					    var parent = $(this).parent();
					    if (parent.hasClass('collapsed')) {
						    parent.removeClass('collapsed').addClass('expanded');
					    } else {
						    parent.removeClass('expanded').addClass('collapsed');
					    }
				    }
				}));
				$(this).addClass('collapsed').addClass('has-children');
				// now find checked and open the tree to display them
				$(this).find('input:checked').each(function() {
					$(this).parents().each(function() {
						if ($(this) == container) {
							return false;
						} else {
							if ($(this).hasClass('collapsed')) {
								$(this).removeClass('collapsed').addClass('expanded');
							}
						}
					});
				});
			}
		});
	});

	showParentInExpandableTree($(".expandable_tree .selected"));

	$(".addLinks").click(function() {

		var total = $(this).parent().find('.sqContainer .sqItem').length;
		if (total >= $(this).parent().find('.max_number').val() - 1) {
			$(this).hide();
		}
		var $obj = $(this).parent().find('.sqContainer .sqItem:first').clone();
		var temp;

		// clearing values and processing id and for attributes
		$obj.find('input[type=text]').val('');
		$obj.find('input[type=checkbox]').attr('checked', false);
		$obj.find('label').each(function() {
			temp = $(this).attr('for').replace('_url_0', '_url_' + total);
			$(this).attr('for', temp);
			temp = $(this).attr('for').replace('_title_0', '_title_' + total);
			$(this).attr('for', temp);
			temp = $(this).attr('for').replace('_new_window_0', 'new_window_' + total);
			$(this).attr('for', temp);
		});
		$obj.find('input').each(function() {

			temp = $(this).attr('id').replace('_url_0', '_url_' + total);
			$(this).attr('id', temp);
			temp = $(this).attr('id').replace('_title_0', '_title_' + total);
			$(this).attr('id', temp);
			temp = $(this).attr('id').replace('_new_window_0', 'new_window_' + total);
			$(this).attr('id', temp);

			temp = $(this).attr('name').replace('_url[0]', '_url[' + total + ']');
			$(this).attr('name', temp);
			temp = $(this).attr('name').replace('_title[0]', '_title[' + total + ']');
			$(this).attr('name', temp);
			temp = $(this).attr('name').replace('_new_window[0]', 'new_window[' + total + ']');
			$(this).attr('name', temp);

		});

		$(this).parent().find('.sqContainer').append($obj);
	});

	// implement placeholder for older browsers
	if ( typeof Modernizr != 'undefined' && !Modernizr.input.placeholder) {

		$('input[placeholder]').each(function(n) {
			if ($(this).val().length == 0) {
				$(this).val($(this).attr('placeholder'));
				$(this).addClass('ghostInput');
			}
			$(this).bind('focus', function() {
				if ($(this).val() == $(this).attr('placeholder')) {
					$(this).val('');
					$(this).removeClass('ghostInput');
				} else {
					$(this).select();
					$(this).removeClass('ghostInput');
				}
			});
			$(this).bind('blur', function() {
				if ($(this).val().length == 0) {
					$(this).val($(this).attr('placeholder'));
					$(this).addClass('ghostInput');
				} else {
					$(this).removeClass('ghostInput');
				}
			});
		});

		$('form').bind('submit', function() {
			$('input[placeholder]').each(function() {
				if ($(this).val() == $(this).attr('placeholder')) {
					$(this).val('');
				}
			});
		});

	}
	
});

function isPopulated(obj) {
	if (obj && obj.value != '' && obj.value != 'Search')
		return true;
	return false;
}

function mouseX(evt) {
	if (evt.pageX)
		return evt.pageX;
	else if (evt.clientX)
		return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	else
		return null;
}
function mouseY(evt) {
	if (evt.pageY)
		return evt.pageY;
	else if (evt.clientY)
		return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	else
		return null;
}

/**
 * Shows submenu in Navigation
 */
function sqShowSubmenu(obj, display) {
	if (obj) {
		var ul = obj.getElementsByTagName('ul');
		if (ul.length == 1) {
			ul = ul.item(0);
			ul.style.display = display;
		}
	}
}

function trim(sString) {
	while (sString.substring(0, 1) == ' ')
		sString = sString.substring(1, sString.length);
	while (sString.substring(sString.length - 1, sString.length) == ' ')
		sString = sString.substring(0, sString.length - 1);
	return sString;
}

function convertToUrlCompatible(text) {
	text = text + '';
	text = trim(text);

	// text = text.replace( /[ ]+/g , ' ' );
	text = text.replace('_', '-');
	text = text.replace(/[^\-a-zA-Z0-9. ]*/g, '');
	text = text.replace(/ /g, '-');
	text = text.replace(/-{2,}/g, '-');

	return text.toLowerCase();
}

/**
 * Function select/unselect given checkboxes id = html id of checkboxes chilren
 * string of indexes of checkboxes to select/unselect select boolean - if true
 * then children will be selected, otherwise unselected )
 */

function selectCheckboxes(id, sChildren, checked, formId) {

	if (document.getElementById('autoselect_' + formId)) {

		if (document.getElementById('autoselect_' + formId).checked) {
			var children = sChildren.split(",");
			var obj;
			for ( var i = 0; i < children.length; i++) {
				obj = document.getElementById(id + '[' + children[i] + ']');
				if (obj) {
					obj.checked = checked;
				}
			}
		}
	}
}

function hideCheckboxes(id, children, directChildren, source) {

	var hide;
	if (source) {
		hide = source.innerHTML == '-';
	} else {
		hide = true;
	}

	var children = children.split(",");
	var obj;

	if (source && source.innerHTML == '+' && directChildren) {
		children = directChildren.split(",");
	}

	for ( var i = 0; i < children.length; i++) {
		obj = document.getElementById('div_' + id + '[' + children[i] + ']');
		if (obj) {
			if (hide) {
				obj.style.display = 'none';
				if (source)
					source.innerHTML = '+';

			} else {
				obj.style.display = 'block';
				if (source)
					source.innerHTML = '-';
			}
		}
		obj = document.getElementById('plusminus_' + id + '_' + children[i]);
		if (obj) {
			if (hide) {
				obj.style.display = 'none';
				var a = obj.getElementsByTagName('a').item(0);
				if (a)
					a.innerHTML = '+';
			} else {
				obj.style.display = 'block';
			}
		}
	}
}

function selectParent(id, parents, checked, formId) {
	if (document.getElementById('autoselect_' + formId) && document.getElementById('autoselect_' + formId).checked == 1) {
		var parents = parents.split(",");
		if (checked == false) {
			var obj;
			for ( var i = 0; i < parents.length; i++) {
				obj = document.getElementById(id + '[' + parents[i] + ']');
				if (obj) {
					obj.checked = false;
				}
			}
		}
	}
}

function addHTextField(name, itemName, itemLabel, displayLabel, text, removeLabel) {

	var ni = document.getElementById(name + '_div');
	var num = document.getElementById(name + '_counter').value * 1;
	var length = document.getElementById(name + '_length').value * 1;
	var min = document.getElementById(name + '_min').value * 1;
	var max = document.getElementById(name + '_max').value * 1;

	var newdiv = document.createElement('div');
	var divIdName = name + itemName + '_div_' + length;
	var inputIdName = name + itemName + '_text[' + length + ']';
	var inputName = name + itemName + '_text[' + length + ']';

	if (text == null)
		text = '';
	var p_string = text;
	p_string = p_string.replace(/&/g, '&amp;');
	p_string = p_string.replace(/</g, '&lt;');
	p_string = p_string.replace(/>/g, '&gt;');
	p_string = p_string.replace(/"/g, '&quot;');

	newdiv.setAttribute('id', divIdName);

	if (displayLabel)
		newdiv.innerHtml = '<label for=\"' + inputIdName + '\">' + itemLabel + ' :</label>';

	newdiv.innerHTML += '<input type="text" name="' + inputIdName + '" id="' + inputIdName + '" style="margin:5px; width:80% ;display:inline" value="' + p_string + '">';
	newdiv.innerHTML += ' <a href="javascript: " onclick="removeHTextField(\'' + name + '\',\'' + divIdName + '\');">' + removeLabel + '</a>';

	ni.appendChild(newdiv);

	num++;
	length++;
	document.getElementById(name + '_counter').value = num;
	document.getElementById(name + '_length').value = length;

	// hidding add
	if (max > 0 && num >= max && document.getElementById(name + '_add')) {
		document.getElementById(name + '_add').style.display = 'none';
	}
}

function createXmlHttpRequestObject() {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	return xmlHttp;
}

var xmlHttp = createXmlHttpRequestObject();
var url;
var feedFile;

function dropdownmenu_filter_onkeyup(feed, src, destId, data_source, field_names) {

	var dest = document.getElementById(destId);

	var keywords = src.value;
	feedFile = feed;
	if (dest) {

		keywords = encodeURIComponent(keywords);
		field_names = encodeURIComponent(field_names);
		data_source = encodeURIComponent(data_source);
		url = 'ds=' + data_source + '&fn=' + field_names + '&k=' + keywords;

		// ///////////////////////////////////////////////////////////////////
		// function to deal with data
		xmlHttp.onreadystatechange = function() {
			var elOptNew;
			var vals;
			var texts;
			var root;
			dest.options.length = 0;
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {

					var xmlResponse = xmlHttp.responseXML;
					var root = xmlResponse.documentElement;

					var vals = root.getElementsByTagName("primary_key");
					var texts = root.getElementsByTagName("field");

					for ( var i = 0; i < texts.length; i++) {

						var elOptNew = document.createElement('option');
						elOptNew.text = texts.item(i).firstChild.data;
						elOptNew.value = vals.item(i).firstChild.data;

						try {
							dest.add(elOptNew, null); // standards compliant;
							// doesn't work in IE
						} catch (ex) {
							dest.add(elOptNew); // IE only
						}

					}
				}
			}
		};
		ajaxSend();

	}
}

function hasClass(ele, cls) {
	return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(ele, cls) {
	if (!this.hasClass(ele, cls))
		ele.className += " " + cls;
}

function removeClass(ele, cls) {
	if (hasClass(ele, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		ele.className = ele.className.replace(reg, ' ');
	}
}

/**
 * 
 * @param feed
 *            the Path to feed.php file
 * @param input
 *            object representing input field
 * @param data_source
 *            Datasource name
 * @param template
 *            template to use
 * @param dst
 *            destination object ( should be div or any other block container
 * @return
 */
function ajaxDataSource(feed, input, data_source, template, dst, filter) {
	var keywords = input.value;
	addClass(input, 'progress');
	keywords = encodeURIComponent(keywords);
	template = encodeURIComponent(template);
	data_source = encodeURIComponent(data_source);
	filter = encodeURIComponent(filter);
	feedFile = feed;
	url = 'ds=' + data_source + '&t=' + template + '&k=' + keywords + '&f=' + filter;
	dst = document.getElementById(dst);

	xmlHttp.onreadystatechange = function() {
		var elOptNew;
		var vals;
		var texts;
		var html = '';

		if (xmlHttp.readyState == 4) {
			if (xmlHttp.status == 200) {

				var htmlResponse = xmlHttp.responseText;
				dst.innerHTML = htmlResponse;
				removeClass(input, 'progress');
			}
		}
	};

	ajaxSend();

}

function checkboxgroup_filter_onkeyup(feed, src, name, data_source, field_names) {
	var destId = name + "_div";
	var dest = document.getElementById(destId);
	feedFile = feed;
	var keywords = src.value;

	if (dest) {
		addClass(src, 'progress');
		keywords = encodeURIComponent(keywords);
		field_names = encodeURIComponent(field_names);
		data_source = encodeURIComponent(data_source);
		url = 'ds=' + data_source + '&fn=' + field_names + '&k=' + keywords;

		// ///////////////////////////////////////////////////////////////////
		// function to deal with data
		xmlHttp.onreadystatechange = function() {
			var elOptNew;
			var vals;
			var texts;
			var html = '';

			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {

					var xmlResponse = xmlHttp.responseXML;

					var root = xmlResponse.documentElement;

					var vals = root.getElementsByTagName("primary_key");
					var texts = root.getElementsByTagName("field");

					for ( var i = 0; i < texts.length; i++) {
						var checked = '';

						var text = texts.item(i).firstChild.data;
						var val = vals.item(i).firstChild.data;
						if (document.getElementById(name + '_item[' + val + ']')) {
							checked = 'checked="checked" ';
						}
						html += "<div>";
						html += "<input style=\"margin-top: 0;\" " + checked + " style=\"margin-top: 10px; width: auto;\" class=\"checkbox\" name=\"" + name + "[" + val + "]\" id=\"" + name + "[" + val + "]\" value=\"" + val + "\" type=\"checkbox\" onclick=\"checkboxgroup_update_item( this, '" + name + "', '" + text + "' )\"> ";
						html += "<label for=\"" + name + "[" + val + "]\" style=\"display: inline;\">" + text + "</label>";
						html += "</div>";
					}
					dest.innerHTML = html;
					removeClass(src, 'progress');
				}
			}
		};

		ajaxSend();

	}
}

function checkboxgroup_update_item(obj, name, label) {

	if (!obj)
		return;

	var val = obj.value;

	if (obj.checked) {
		var dest = document.getElementById(name + '_dest');
		if (dest) {

			var item = name + '_item[' + val + ']';
			var elm = document.getElementById(item);
			if (!elm) {
				var nname = name + '_selected[' + val + ']';
				var item = name + '_item[' + val + ']';
				dest.innerHTML += '<li id="' + item + '" >' + label;
				dest.innerHTML += "<input type=\"hidden\" name=\"" + nname + "\" value=\"" + val + "\"></li>";
			}
		}
	} else {
		var item = name + '_item[' + val + ']';
		var elm = document.getElementById(item);
		if (elm) {
			elm.parentNode.removeChild(elm);
		}
	}
}

function extendedcheckboxgroup_filter_onkeyup(feed, src, name, data_source, field_names, ex_options) {
	var destId = name + "_div";
	var dest = document.getElementById(destId);
	feedFile = feed;
	var keywords = src.value;

	if (dest) {

		keywords = encodeURIComponent(keywords);
		field_names = encodeURIComponent(field_names);
		data_source = encodeURIComponent(data_source);
		url = 'ds=' + data_source + '&fn=' + field_names + '&k=' + keywords;

		// ///////////////////////////////////////////////////////////////////
		// function to deal with data
		xmlHttp.onreadystatechange = function() {
			var elOptNew;
			var vals;
			var texts;

			// dest.innerHTML = '';
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {

					var xmlResponse = xmlHttp.responseXML;
					var root = xmlResponse.documentElement;

					var vals = root.getElementsByTagName("primary_key");
					var texts = root.getElementsByTagName("field");

					for ( var i = 0; i < texts.length; i++) {
						var checked = '';

						var text = texts.item(i).firstChild.data;
						var val = vals.item(i).firstChild.data;
						if (document.getElementById(name + '_item[' + val + ']')) {
							checked = 'checked="checked" ';
						}
						dest.innerHTML += "<div>";
						dest.innerHTML += "<input " + checked + " style=\"margin-top: 10px; width: auto;\" class=\"checkbox\" name=\"" + name + "[" + val + "]\" id=\"" + name + "[" + val + "]\" value=\"" + val + "\" type=\"checkbox\" onclick=\"extendedcheckboxgroup_update_item( this, '" + name + "', '" + text + "' , '" + ex_options + "' )\"> ";
						dest.innerHTML += "<label for=\"" + name + "[" + val + "]\" style=\"display: inline;\">" + text + "</label>";
						dest.innerHTML += "</div>";
					}
				}
			}
		};

		ajaxSend();

	}
}

function extendedcheckboxgroup_update_item(obj, name, label, ex_options) {

	if (!obj)
		return;
	var options = ex_options.split(';');
	var values = new Array();
	var labels = new Array();

	var j = 0;
	for ( var i = 0; i < options.length; i += 2) {
		if (options[i + 1]) {
			values[j] = options[i];
			labels[j] = options[i + 1];
			j++;
		}
	}

	var val = obj.value;

	if (obj.checked) {
		var dest = document.getElementById(name + '_dest');
		if (dest) {

			var item = name + '_item[' + val + ']';
			var elm = document.getElementById(item);
			if (!elm) {
				var select = '';
				var nname = name + '_selected[' + val + ']';
				var item = name + '_item[' + val + ']';
				var select_name = name + '_select[' + val + ']';

				// select += '<li id="'+item+'" > ";

				select += '<div style="float:left;width:100px;height:25px">' + label + '</div>';

				// adding extended options

				if (values.length > 0) {
					select += '<select name="' + select_name + '" style="height:25px;font-size:80%">';
					for ( var i = 0; i < values.length; i++) {
						select += "<option value=\"" + values[i] + "\">" + labels[i] + "</option>";
					}
					select += '</select>';
				}

				select += "<input type=\"hidden\" name=\"" + nname + "\" value=\"" + val + "\"><div style=\"clear:both\"></div>";
				// select += "</li>";
				// dest.innerHTML += select;

				// DOM version
				var li = document.createElement('li');
				li.setAttribute('id', item);
				li.innerHTML = select;
				dest.appendChild(li);
			}

		}
	} else {
		// deleting li element
		var item = name + '_item[' + val + ']';
		var elm = document.getElementById(item);
		if (elm) {
			elm.parentNode.removeChild(elm);
		}
	}
}

function ajaxSend(obj) {
	if (obj) {
		xmlHttp = obj;
	}
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {

		xmlHttp.open('POST', feedFile + '?' + url, true);
		xmlHttp.send(url);

	} else {
		setTimeout('ajaxSend()', 80);
	}
}

function removeHTextField(name, divNum) {

	var d = document.getElementById(name + '_div');
	var min = document.getElementById(name + '_min').value * 1;
	var max = document.getElementById(name + '_max').value * 1;
	var num = document.getElementById(name + '_counter').value * 1;

	if (num <= min)
		return false;

	var olddiv = document.getElementById(divNum);
	d.removeChild(olddiv);

	num--;
	document.getElementById(name + '_counter').value = num;
	// showing add
	if (num < max && document.getElementById(name + '_add')) {
		document.getElementById(name + '_add').style.display = 'block';
	}
}

function addHImageField(name, itemName, itemLabel, removeLabel, displayLabel, imageUrl) {

	if (name == null)
		return;
	var ni = document.getElementById(name + '_div');
	var num = 0;
	try {
		num = document.getElementById(name + '_counter').value * 1;

		var length = document.getElementById(name + '_length').value * 1;
		var min = document.getElementById(name + '_min').value * 1;
		var max = document.getElementById(name + '_max').value * 1;
		var aAttributes = document.getElementById(name + '_attributes').value;
		var aAttributesLabels = document.getElementById(name + '_attributes_labels').value;

		var attributes = aAttributes.split(",");
		var attributesLabels = aAttributesLabels.split(",");

		var newdiv = document.createElement('div');
		var divIdName = name + itemName + '_div_' + length;
		var inputIdName = name + itemName + '_file_' + length;
		var delIdName = name + itemName + '_del[' + length + ']';
		var inputName = name + itemName + '_file[' + length + ']';

		var tempHtml = '';
		newdiv.setAttribute('id', divIdName);

		if (displayLabel) {

			tempHtml = '<label for=\"' + inputIdName + '\">' + itemLabel + ' :</label>';
		}

		if (imageUrl != null) {

			tempHtml += "<img style=\"margin: 5px\" src=\"" + imageUrl + "\">";

			tempHtml += "<br/>";

			tempHtml += "<input class=\"checkbox\" style=\"display:inline;float: left\" type=\"checkbox\" name=\"" + delIdName + "\" id=\"" + delIdName + "\" value=\"true\">";

			tempHtml += "<label  for=\"" + delIdName + "\" title=\"Delete\">Delete</label> <br/>";

		}

		tempHtml += '<input type="file" name="' + inputIdName + '" id="' + inputIdName + '" style="width:80%">';

		if (aAttributes) {
			for ( var i = 0; i < attributes.length; i++) {
				tempHtml += '<br><label>' + attributesLabels[i] + '</label>';
				tempHtml += '<input type="text" name="' + inputIdName + '_' + attributes[i] + '" id="' + inputIdName + '_' + attributes[i] + '"><br><br>';
			}
		}

		tempHtml += '<a href="javascript:" onclick="removeHImageField(\'' + name + '\',\'' + divIdName + '\');">' + removeLabel + '</a>';

		newdiv.innerHTML = tempHtml;
		ni.appendChild(newdiv);

		num++;

		length++;

		document.getElementById(name + '_counter').value = num;

		document.getElementById(name + '_length').value = length;

		// hidding add

		if (max > 0 && num >= max && document.getElementById(name + '_add')) {

			document.getElementById(name + '_add').style.display = 'none';

		}
	} catch (err) {
	}
}

function removeHImageField(name, divNum) {

	var d = document.getElementById(name + '_div');

	var min = document.getElementById(name + '_min').value * 1;

	var max = document.getElementById(name + '_max').value * 1;

	var num = document.getElementById(name + '_counter').value * 1;

	if (num <= min)
		return false;

	var olddiv = document.getElementById(divNum);

	d.removeChild(olddiv);

	num--;

	document.getElementById(name + '_counter').value = num;

	// showing add

	if (num < max && document.getElementById(name + '_add')) {

		document.getElementById(name + '_add').style.display = 'block';

	}

}

function addHFileField(name, itemName, itemLabel, removeLabel, displayLabel, fileUrl, fileName) {

	var ni = document.getElementById(name + '_div');
	var num = document.getElementById(name + '_counter').value * 1;
	var length = document.getElementById(name + '_length').value * 1;
	var min = document.getElementById(name + '_min').value * 1;
	var max = document.getElementById(name + '_max').value * 1;

	var attributes = document.getElementById(name + '_attributes').value;
	var attributesLabels = document.getElementById(name + '_attributes_labels').value;

	attributes = attributes.split(",");
	attributesLabels = attributesLabels.split(",");

	var newdiv = document.createElement('div');
	var divIdName = name + itemName + '_div_' + length;
	var delIdName = name + itemName + '_del[' + length + ']';
	var inputIdName = name + itemName + '_file_' + length;
	var inputName = name + itemName + '_file[' + length + ']';
	newdiv.setAttribute('id', divIdName);

	if (displayLabel)
		newdiv.innerHtml = '<label for=\"' + inputIdName + '\">' + itemLabel + ' :</label>';

	if (fileUrl != null) {
		newdiv.innerHTML += "<a href=\"" + fileUrl + "\" style=\"display: inline;float:left\">" + fileName + "</a> ";
		newdiv.innerHTML += "<input class=\"checkbox\" style=\"display:inline;float: left\" type=\"checkbox\" name=\"" + delIdName + "\" id=\"" + delIdName + "\" value=\"true\">";
		newdiv.innerHTML += "<label  for=\"" + delIdName + "\" title=\"Delete\">Delete</label>";
	}

	newdiv.innerHTML += '<input type="file" name="' + inputIdName + '" id="' + inputIdName + '" style="width:80%">';
	for ( var i = 0; i < attributes.length; i++) {
		if (attributesLabels[i]) {
			newdiv.innerHTML += '<br><label>' + attributesLabels[i] + '</label>';
			newdiv.innerHTML += '<input type="text" name="' + inputIdName + '_' + attributes[i] + '" id="' + inputIdName + '_' + attributes[i] + '"><br><br>';
		}
	}

	newdiv.innerHTML += ' <a class="sqButton" href="javascript:" onclick="removeHFileField(\'' + name + '\',\'' + divIdName + '\');">' + removeLabel + '</a>';

	ni.appendChild(newdiv);
	num++;
	length++;
	document.getElementById(name + '_counter').value = num;
	document.getElementById(name + '_length').value = length;

	// hidding add

	if (max > 0 && num >= max && document.getElementById(name + '_add')) {
		document.getElementById(name + '_add').style.display = 'none';
	}

}

function removeHFileField(name, divNum) {

	var d = document.getElementById(name + '_div');
	var min = document.getElementById(name + '_min').value * 1;
	var max = document.getElementById(name + '_max').value * 1;
	var num = document.getElementById(name + '_counter').value * 1;

	if (num <= min)
		return false;

	var olddiv = document.getElementById(divNum);
	d.removeChild(olddiv);
	num--;

	document.getElementById(name + '_counter').value = num;
	// showing add
	if (num < max && document.getElementById(name + '_add')) {
		document.getElementById(name + '_add').style.display = 'block';
	}
}

function get_html_translation_table(table, quote_style) {
	// Returns the internal translation table used by htmlspecialchars and
	// htmlentities
	// 
	// version: 906.401
	// discuss at: http://phpjs.org/functions/get_html_translation_table
	// + original by: Philip Peterson
	// + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// + bugfixed by: noname
	// + bugfixed by: Alex
	// + bugfixed by: Marco
	// + bugfixed by: madipta
	// + improved by: KELAN
	// + improved by: Brett Zamir (http://brett-zamir.me)
	// + bugfixed by: Brett Zamir (http://brett-zamir.me)
	// % note: It has been decided that we're not going to add global
	// % note: dependencies to php.js. Meaning the constants are not
	// % note: real constants, but strings instead. integers are also supported
	// if someone
	// % note: chooses to create the constants themselves.
	// * example 1: get_html_translation_table('HTML_SPECIALCHARS');
	// * returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}

	var entities = {}, histogram = {}, decimal = 0, symbol = '';
	var constMappingTable = {}, constMappingQuoteStyle = {};
	var useTable = {}, useQuoteStyle = {};

	// Translate arguments
	constMappingTable[0] = 'HTML_SPECIALCHARS';
	constMappingTable[1] = 'HTML_ENTITIES';
	constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
	constMappingQuoteStyle[2] = 'ENT_COMPAT';
	constMappingQuoteStyle[3] = 'ENT_QUOTES';

	useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
	useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

	if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
		throw new Error("Table: " + useTable + ' not supported');
		// return false;
	}

	if (useTable === 'HTML_ENTITIES') {
		entities['160'] = '&nbsp;';
		entities['161'] = '&iexcl;';
		entities['162'] = '&cent;';
		entities['163'] = '&pound;';
		entities['164'] = '&curren;';
		entities['165'] = '&yen;';
		entities['166'] = '&brvbar;';
		entities['167'] = '&sect;';
		entities['168'] = '&uml;';
		entities['169'] = '&copy;';
		entities['170'] = '&ordf;';
		entities['171'] = '&laquo;';
		entities['172'] = '&not;';
		entities['173'] = '&shy;';
		entities['174'] = '&reg;';
		entities['175'] = '&macr;';
		entities['176'] = '&deg;';
		entities['177'] = '&plusmn;';
		entities['178'] = '&sup2;';
		entities['179'] = '&sup3;';
		entities['180'] = '&acute;';
		entities['181'] = '&micro;';
		entities['182'] = '&para;';
		entities['183'] = '&middot;';
		entities['184'] = '&cedil;';
		entities['185'] = '&sup1;';
		entities['186'] = '&ordm;';
		entities['187'] = '&raquo;';
		entities['188'] = '&frac14;';
		entities['189'] = '&frac12;';
		entities['190'] = '&frac34;';
		entities['191'] = '&iquest;';
		entities['192'] = '&Agrave;';
		entities['193'] = '&Aacute;';
		entities['194'] = '&Acirc;';
		entities['195'] = '&Atilde;';
		entities['196'] = '&Auml;';
		entities['197'] = '&Aring;';
		entities['198'] = '&AElig;';
		entities['199'] = '&Ccedil;';
		entities['200'] = '&Egrave;';
		entities['201'] = '&Eacute;';
		entities['202'] = '&Ecirc;';
		entities['203'] = '&Euml;';
		entities['204'] = '&Igrave;';
		entities['205'] = '&Iacute;';
		entities['206'] = '&Icirc;';
		entities['207'] = '&Iuml;';
		entities['208'] = '&ETH;';
		entities['209'] = '&Ntilde;';
		entities['210'] = '&Ograve;';
		entities['211'] = '&Oacute;';
		entities['212'] = '&Ocirc;';
		entities['213'] = '&Otilde;';
		entities['214'] = '&Ouml;';
		entities['215'] = '&times;';
		entities['216'] = '&Oslash;';
		entities['217'] = '&Ugrave;';
		entities['218'] = '&Uacute;';
		entities['219'] = '&Ucirc;';
		entities['220'] = '&Uuml;';
		entities['221'] = '&Yacute;';
		entities['222'] = '&THORN;';
		entities['223'] = '&szlig;';
		entities['224'] = '&agrave;';
		entities['225'] = '&aacute;';
		entities['226'] = '&acirc;';
		entities['227'] = '&atilde;';
		entities['228'] = '&auml;';
		entities['229'] = '&aring;';
		entities['230'] = '&aelig;';
		entities['231'] = '&ccedil;';
		entities['232'] = '&egrave;';
		entities['233'] = '&eacute;';
		entities['234'] = '&ecirc;';
		entities['235'] = '&euml;';
		entities['236'] = '&igrave;';
		entities['237'] = '&iacute;';
		entities['238'] = '&icirc;';
		entities['239'] = '&iuml;';
		entities['240'] = '&eth;';
		entities['241'] = '&ntilde;';
		entities['242'] = '&ograve;';
		entities['243'] = '&oacute;';
		entities['244'] = '&ocirc;';
		entities['245'] = '&otilde;';
		entities['246'] = '&ouml;';
		entities['247'] = '&divide;';
		entities['248'] = '&oslash;';
		entities['249'] = '&ugrave;';
		entities['250'] = '&uacute;';
		entities['251'] = '&ucirc;';
		entities['252'] = '&uuml;';
		entities['253'] = '&yacute;';
		entities['254'] = '&thorn;';
		entities['255'] = '&yuml;';
	}

	if (useQuoteStyle !== 'ENT_NOQUOTES') {
		entities['34'] = '&quot;';
	}
	if (useQuoteStyle === 'ENT_QUOTES') {
		entities['39'] = '&#39;';
	}
	entities['60'] = '&lt;';
	entities['62'] = '&gt;';

	// ascii decimals for better compatibility
	entities['38'] = '&amp;';

	// ascii decimals to real symbols
	for (decimal in entities) {
		symbol = String.fromCharCode(decimal);
		histogram[symbol] = entities[decimal];
	}

	return histogram;
}

function htmlspecialchars(string, quote_style) {
	// Convert special characters to HTML entities
	// 
	// version: 906.401
	// discuss at: http://phpjs.org/functions/htmlspecialchars
	// + original by: Mirek Slugen
	// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// + bugfixed by: Nathan
	// + bugfixed by: Arno
	// + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// + bugfixed by: Brett Zamir (http://brett-zamir.me)
	// - depends on: get_html_translation_table
	// * example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
	// * returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
	var histogram = {}, symbol = '', tmp_str = '', entity = '';
	tmp_str = string.toString();

	if (false === (histogram = this.get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
		return false;
	}

	histogram["'"] = '&#039;';
	for (symbol in histogram) {
		entity = histogram[symbol];
		tmp_str = tmp_str.split(symbol).join(entity);
	}

	return tmp_str;
}

$(function() {

	// character counter
	$('input[maxlength].counter,[class*=maxLength].counter').live('focus keyup', function(e) {
		var $this = $(this);
		// get current length
		var chars = $this.val().length;
		// get max length
		if ($this.attr('maxlength') > 0) {
			var maxLength = $this.attr('maxlength');
		} else {
			rulesParsing = $this.attr('class');
			rulesRegExp = /\[(.*)\]/;
			getRules = rulesRegExp.exec(rulesParsing);
			if (getRules == null)
				return false;
			str = getRules[1];
			pattern = /\[|,|\]/;
			result = str.split(pattern);
			var maxLength = result[0];
		}

		if (maxLength > 0) {
			var counterValue = maxLength - chars;
			if (counterValue <= 0) {
				$this.val($this.val().substr(0, maxLength));
				counterValue = 0;
			}

			if ($this.siblings('span[class=counter]').length == 0) {
				$this.after($('<span></span>', {
				    'class' : 'counter',
				    'html' : counterValue
				}).css('left', $this.outerWidth(true) + 5).fadeIn());
			} else {
				$this.siblings('span[class=counter]').html(counterValue).fadeIn();
			}
		}
	});
	$('input[maxlength].counter,[class*=maxLength].counter').live('blur', function(e) {
		$(this).siblings('span[class=counter]').fadeOut();
	});

	// add and remove image fields
	$('a.addImageLink').bind('click', function(e) {

		e.preventDefault();

		var $parent = $(this).parent();
		var $this = $(this);

		var count = $parent.children('div.imageField').length;
		var baseName = $parent.children('input.baseName').val();
		var max = $parent.children('input.maxImages').val();

		// work out what elements we need
		if (count < max) {
			var newImageUpload = $('<div></div>', {
				'class' : 'imageField'
			}).prepend($('<input></input>', {
			    'id' : baseName + 'file_' + count,
			    'name' : baseName + 'file_' + count,
			    'type' : 'file'
			}).after($('<a></a>', {
			    'class' : 'removeImageLink',
			    'href' : 'javascript:',
			    'title' : 'Remove image'
			}).prepend($('<img></img>', {
			    'src' : '/images/squirrel/remove.png',
			    'alt' : 'remove'
			}))));

			$this.before(newImageUpload);

		} else {
			alert('You can only add ' + max + ' images');
		}

	});

	$('a.removeImageLink').live('click', function(e) {
		e.preventDefault();
		var $parent = $(this).parent();
		var $this = $(this);
		if ($parent.children('img').length > 0) {
			// there's already an image here so add the delete field
			$parent.addClass('imageRemoved');

			var imageId = $parent.children('input').attr('name').match(/([0-9]+)/g)[0];
			var baseName = $parent.parent().children('input.baseName').val();
			var max = $parent.children('input.maxImages').val();

			$parent.children('a.removeImageLink').remove();

			$parent.children('img').css('height', '20px');
			$parent.children('input').hide();
			$parent.prepend($('<input></input>', {
			    'type' : 'hidden',
			    'name' : baseName + 'del[' + imageId + ']',
			    'value' : 'true'
			}).after($('<a></a>', {
			    'class' : 'undoRemoveImageLink',
			    'href' : 'javascript:',
			    'title' : 'Restore image',
			    'click' : function() {
				    var $parent = $(this).parent();
				    var $this = $(this);
				    $parent.removeClass('imageRemoved');
				    $parent.children('img').css('height', 'auto');
				    $parent.children('input[type=hidden]').remove();
				    $parent.children('input').show();
				    $parent.children('a.undoRemoveImageLink').remove();
				    $parent.append($('<a></a>', {
				        'class' : 'removeImageLink',
				        'href' : 'javascript:',
				        'title' : 'Remove image'
				    }).prepend($('<img></img>', {
				        'src' : '/images/squirrel/remove.png',
				        'alt' : 'remove'
				    })));
			    }
			}).append($('<img></img>', {
			    'src' : '/images/squirrel/undo.png',
			    'alt' : 'undo'
			}))));
		} else {
			$parent.remove();
		}
	});

	// add and remove file fields
	$('a.addFileLink').bind('click', function(e) {

		e.preventDefault();

		var $parent = $(this).parent();
		var $this = $(this);

		var count = $parent.children('div.fileField').length;
		var baseName = $parent.children('input.baseName').val();
		var max = $parent.children('input.maxFiles').val();

		if (count < max) {
			// work out what elements we need
			var newFileUpload = $('<div></div>', {
				'class' : 'fileField'
			}).prepend($('<input></input>', {
			    'id' : baseName + 'file_' + count,
			    'name' : baseName + 'file_' + count,
			    'type' : 'file'
			}).after($('<a></a>', {
			    'class' : 'removeFileLink',
			    'href' : 'javascript:',
			    'title' : 'Remove file'
			}).prepend($('<img></img>', {
			    'src' : '/images/squirrel/remove.png',
			    'alt' : 'remove'
			}))));

			$this.before(newFileUpload);
		} else {
			alert('You can only add ' + max + ' files');
		}

	});

	$('a.removeFileLink').live('click', function(e) {
		e.preventDefault();
		var $parent = $(this).parent();
		var $this = $(this);
		if ($parent.children('a').length > 1) {
			// there's already an image here so add the delete field
			$parent.addClass('fileRemoved');

			var fileId = $parent.children('input').attr('name').match(/([0-9]+)/g)[0];
			var baseName = $parent.parent().children('input.baseName').val();

			$parent.children('a.removeFileLink').remove();

			$parent.children('input').hide();
			$parent.prepend($('<input></input>', {
			    'type' : 'hidden',
			    'name' : baseName + 'del[' + fileId + ']',
			    'value' : 'true'
			}).after($('<a></a>', {
			    'class' : 'undoRemoveFileLink',
			    'href' : 'javascript:',
			    'title' : 'Restore file',
			    'click' : function() {
				    var $parent = $(this).parent();
				    var $this = $(this);
				    $parent.removeClass('fileRemoved');
				    $parent.children('input[type=hidden]').remove();
				    $parent.children('input').show();
				    $parent.children('a.undoRemoveFileLink').remove();
				    $parent.append($('<a></a>', {
				        'class' : 'removeFileLink',
				        'href' : 'javascript:',
				        'title' : 'Remove file'
				    }).prepend($('<img></img>', {
				        'src' : '/images/squirrel/remove.png',
				        'alt' : 'remove'
				    })));
			    }
			}).append($('<img></img>', {
			    'src' : '/images/squirrel/undo.png',
			    'alt' : 'undo'
			}))));
		} else {
			$parent.remove();
		}
	});

	/**
	 * Javascript to control the tags form element
	 */
	var BACKSPACE = 8;
	var DELETE = 0; // needs to be checked
	var ENTER = 13;
	var SPACE = 32;
	var COMMA = 44;
	var STOP = 46;
	var SEMICOLON = 59;
	var COLON = 58;

	// make array of tag separators
	var SEPARATORS = [ ENTER, COMMA, STOP, SEMICOLON, COLON ];

	// trim for IE
	if (typeof String.prototype.trim !== 'function') {
		String.prototype.trim = function() {
			return this.replace(/^\s+|\s+$/g, '');
		};
	}

	$('input.tagInput').each(function(n) {

		var $this = $(this);
		var $parent = $(this).parent().parent();
		var baseName = $(this).attr('name');

		// now remove the name to stop the form element overwriting the hidden
		// fields
		$(this).removeAttr('name');

		// catch paste
		$this.bind('paste', function(e) {
			var $el = $(this);
			setTimeout(function() {
				var pastedText = $.trim($el.val());
				var pastedTags = pastedText.split(/[.,;:]+/);
				// create the tags for each one
				for (i in pastedTags) {
					var tag = pastedTags[i].replace(/,+$/, "").trim().toLowerCase();
					if (tag != '' && tag.length > 2) {
						// check that the tag isn't already inserted
						if (isNew(tag)) {
							createTag(tag);
						}
						// clear the input text
						$this.val('');
					}
				}
			}, 100);
		});

		$this.bind('keypress', function(e) {
			// console.log('Pressed: '+e.which);
			if ($.inArray(e.which, SEPARATORS) > -1) {
				// add the tag
				e.preventDefault();

				var tag = $this.val().replace(/,+$/, "").trim().toLowerCase();

				if (tag != '' && tag.length > 2) {
					// check that the tag isn't already inserted
					if (isNew(tag)) {
						createTag(tag);
					}
					// clear the input text
					$this.val('');
				}

			}
		});

		// bind event to form to collect final tag if it's left in the input
		// field
		$this.closest('form').bind('submit', function() {
			$(this).find('input.tagInput').each(function() {
				var tag = $(this).val().replace(/,+$/, "").trim().toLowerCase();
				if (tag != '' && tag.length > 2) {
					if (isNew(tag)) {
						createTag(tag);
					}
				}
			});
		});

		function isNew(tag) {
			var result = true;
			$parent.children('li.tagChoice').each(function() {
				var value = $(this).children('input').val();
				if (value == tag) {
					$(this).effect('highlight', {}, 1000);
					result = false;
				}
			});
			return result;
		}

		function createTag(tag) {
			$parent.children('li.tagInputItem').before($('<li></li>', {
				'class' : 'tagChoice'
			}).html(tag).append($('<a></a>', {
				'href' : 'javascript:'
			}).html('x')).append($('<input>', {
			    'type' : 'hidden',
			    'name' : baseName + '[]',
			    'value' : tag
			})).fadeIn('fast'));
			// clear the input text
			$this.val('');
		}

		$parent.bind('click', function() {
			$this.focus();
		});

		$('li.tagChoice a').live('click', function() {
			$(this).parent().fadeOut('fast', function() {
				$(this).remove();
			});
		});

		$this.autocomplete({
		    minLength : 2,
		    source : function(request, response) {
			    $.ajax({
			        'url' : '/autocomplete.php',
			        'dataType' : 'json',
			        'data' : {
			            'table' : 'tagList',
			            'term' : request.term
			        },
			        success : function(data) {
				        response($.map(data, function(item) {
					        return {
					            label : item,
					            value : item
					        };
				        }));
			        }
			    });
		    },
		    select : function(event, ui) {
			    if (isNew(ui.item.value)) {
				    createTag(ui.item.value);
			    }
			    // Cleaning the input.
			    $this.val('');

			    // Prevent the tag input to be update with the chosen value
			    return false;
		    }
		});
	});

	// language tabs
	$('ul.languageTabsVertical li a,ul.languageTabsHorizontal li a').bind('click', function(e) {

		e.preventDefault();

		var $this = $(this);
		var codeRegex = new RegExp(/langauage_([a-z]{2})/);
		// hide the currently select forms and unselcect the tabs
		$('.languageTabsVertical li a[class*="current"],.languageTabsHorizontal li a[class*="current"],.tabForm[class*="current"]').removeClass('current');

		// now select the correct ones
		var newClass = $this.attr('class');
		$('.' + newClass).addClass('current');

	});

});


/*
Cross-browser prompt class.
Copyright 2007 Craig Manley.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

/*
$Id: Prompt.js,v 1.5 2007/03/22 17:11:46 cmanley Exp $

In yet another sly move by Micro$oft, MSIE 7 has been designed to suppress the javascript
prompt function, yet at the same time always allow their MSIE-specific showModalDialog method.
This has broken millions of web sites. The work-arounds to this problem are any of these:
 1. Use the showModalDialog method instead and thereby only support MSIE browsers (they wish).
 2. Do away with using prompt dialogs completely.
 3. Use simulated modal dialogs with layer's and key capturing (complicated and messy).
 4. Use this class to simulate the javascript prompt function by using showModalDialog for MSIE 7 and up.

Usage:
1. Place the files Prompt.js, Prompt.html, and Prompt.png together into any directory in your site.
   Do not rename any of the files or else it won't work.
2. Place this line in the head section of your html:
   <script type="text/javascript" src="/path/to/Prompt.js"></script>
3. Call the Prompt.show method where you would normally call the javascript prompt function:
   var name  = Prompt.show('Who are you?');
   var sides = Prompt.show("How many sides does a square have?", 4, 'Silly question dialog');
   var count = Prompt.show("How many\nlines\ndo\n\n\nyou see\nhere?", '', 'Answer this');
*/


function Prompt() {

	/*** Private properties ***/
	var _msie = (navigator.appVersion.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Opera') == -1);
	var _simulate = navigator.appVersion.match(/\bMSIE (\d+)/) && (RegExp.$1 >= 7) && window.showModalDialog;
	var _script_uri_path = (
		function(basename) {
			var tags = document.getElementsByTagName('script');
			var result = '';
			for (var i=0; i < tags.length; i++) {
				var src = tags[i].getAttribute('src');
				if (!src) {
					continue;
				}
				var x = src.lastIndexOf('/');
				if (x == src.length - 1) {
					continue;
				}
				if (basename != (x == -1 ? src : src.substr(x + 1))) {
					continue;
				}
				// found
				result = (x == -1) ? src : src.substr(0,x + 1);
				break;
			}
			return result;
		})('Prompt.js');


	/*** Private methods ***/

	// Returns the estimated dimensions of the given string when rendered as text (not html).
	// Functionally similar to the Windows API function GetTextExtent(h,txt).
	// 'opts' is an optional object in which you may pass styles such as 'fontFamily' or 'fontSize'.
	// EXPERIMENTAL:
	//   Requires more testing.
	//   Perhaps the 1st argument should be a DOM element to be cloned instead of using opts.
	var _getTextExtent = function(txt, opts) {
		var div = document.createElement('div');
		if (opts) {
			if (opts['fontFamily']) {
				div.style.fontFamily = 'font-family: ' + opts['fontFamily'];
			}
			if (opts['fontSize']) {
				div.style.fontSize = opts['fontSize'];
			}
		}
		div.style.position = 'absolute';
		div.style.top = 0;
		div.style.left = 0;
		div.style.whiteSpace = 'nowrap';
		div.style.overflow = 'hidden';
		div.zIndex = 6322;
		var lines;
		// MSIE bug (tested with MSIE 7) String.split() doesn't keep empty matches, so this hack is required:
		if (_msie) {
			lines = [];
			while (txt.length && txt.match(/^([^\r\n]*)(\r\n|\n\r|\r|\n)?/)) {
				lines.push(RegExp.$1);
				txt = txt.substr(RegExp.$2 ? RegExp.$1.length + RegExp.$2.length : RegExp.$1.length);
			}
		}
		else {
			lines = txt.split(/\r\n|\n\r|\r|\n/);
		}
		for (var i = 0; i < lines.length; i++) {
			div.appendChild(document.createTextNode(lines[i] == ' ' ? '' : lines[i]));
			if (i < lines.length - 1) {
				div.appendChild(document.createElement('br'));
			}
		}
		div.style.visibility = 'hidden';
		//div.style.backgroundColor = 'green';
		var container = document.body;
		if (container.firstChild) {
			container.insertBefore(div, container.firstChild);
		}
		else {
			container.appendChild(div);
		}
		var dims = [div.offsetWidth, div.offsetHeight];
		container.removeChild(div);
		div = null;
		return dims;
	};


	/*** Public methods ***/
	// Either calls or simulates the javascript prompt function.
	// The first 2 arguments are the same as for the javascript prompt function.
	// An optional 3rd argument can be passed which is the caption to be used
	// in the title bar, but this only applies to MSIE 7+.
	this.show = function(msg) {
		var argv = arguments;
		if (msg && (typeof(msg) == 'string')) {
			msg = msg.replace(/^\s+|\s+$/g,'');
		}
		var input = argv.length <= 1 ? '' : argv[1];
		var caption = argv.length <= 2 ? '' : argv[2];
		var result;
		if (_simulate) {
			var dims = _getTextExtent(msg, {fontFamily: 'Arial, sans-serif', fontSize: '10pt'});
			var w = dims[0] + 60;
			if (w < 250) {
				w = 250;
			}
			var h = dims[1] + 115;
			result = window.showModalDialog(
				_script_uri_path + 'Prompt.html',
				{ msg: msg, input: input, caption: caption },
				'dialogWidth: ' + w + 'px; dialogHeight: ' + h + 'px');
		}
		else {
			result = prompt(msg, input);
		}
		return result;
	};
}
Prompt.show = function(msg) {
	var argv = arguments;
	var input = argv.length <= 1 ? '' : argv[1];
	var caption = argv.length <= 2 ? '' : argv[2];
	var p = new Prompt();
	return p.show(msg, input, caption);
};

$(document).ready(function() {
	
	$('button.weight:even img').attr("src","/images/admin/up_tree.png");
	$('button.weight:odd img').attr("src","/images/admin/down_tree.png")
	
	$('#handle_open').click(function() {
		$('#handle_open').css("display", "none");
		$('#handle_close').css("display", "block");
		$('div.right_container').animate( {
			right : '+=145'
		}, 500, function() {

		});
	});
	
	$('#handle_close').click(function() {
		$('#handle_close').css("display", "none");
		$('#handle_open').css("display", "block");
		$('div.right_container').animate( {
			right : '-=145'
		}, 500, function() {
		});
	});
	
	$('ul.menu > li').hover(function() {
			$(this).find('ul').fadeIn(200);
			$(this).find('.dropdown').addClass('open');
			}, function() {
			$(this).find('ul').fadeOut(200);
			$(this).find('.dropdown').removeClass('open');
			});

		
		
	

});

/* Sticky Tooltip script (v1.0)
* Created: Nov 25th, 2009. This notice must stay intact for usage 
* Author: Dynamic Drive at http://www.dynamicdrive.com/
* Visit http://www.dynamicdrive.com/ for full source code
*/


var stickytooltip={
	tooltipoffsets: [20, -30], //additional x and y offset from mouse cursor for tooltips
	fadeinspeed: 200, //duration of fade effect in milliseconds
	tooltipdelay: 400, //delay before tooltip pops up
	
	//***** NO NEED TO EDIT BEYOND HERE

	isdocked: false, //initialising docked variable

	positiontooltip:function($, $tooltip, e){
		var x=e.pageX+this.tooltipoffsets[0], y=e.pageY+this.tooltipoffsets[1]
		var tipw=$tooltip.outerWidth(), tiph=$tooltip.outerHeight(), 
		x=(x+tipw>$(document).scrollLeft()+$(window).width())? x-tipw-(stickytooltip.tooltipoffsets[0]*2) : x
		y=(y+tiph>$(document).scrollTop()+$(window).height())? $(document).scrollTop()+$(window).height()-tiph-10 : y
		$tooltip.css({left:x, top:y})
	},
	
	showbox:function($, $tooltip, e){
		$tooltip.delay(this.tooltipdelay).fadeIn(this.fadeinspeed)
		this.positiontooltip($, $tooltip, e)
	},

	hidebox:function($, $tooltip){
		if (!this.isdocked){
			$tooltip.stop(false, true).hide()
		}
	},

	init:function(targetselector, tipid){
		jQuery(document).ready(function($){
			var $targets=$(targetselector)
			var $tooltip=$('#'+tipid).appendTo(document.body)
			if ($targets.length==0)
				return
			var $alltips=$tooltip.find('div.tooltips')
			
			$targets.bind('mouseenter', function(e){
				$alltips.hide().filter('#'+$(this).attr('data-tooltip')).show()
				stickytooltip.showbox($, $tooltip, e)
			})
			$targets.bind('mouseleave', function(e){
				stickytooltip.hidebox($, $tooltip)
			})
			$targets.bind('mousemove', function(e){
				if (!stickytooltip.isdocked){
					stickytooltip.positiontooltip($, $tooltip, e)
				}
			})
			$tooltip.bind("mouseenter", function(){
				stickytooltip.hidebox($, $tooltip)
			})
			$tooltip.bind("click", function(e){
				e.stopPropagation()
			})
			$(this).bind("click", function(e){
				if (e.button==0){
					stickytooltip.isdocked=false
					stickytooltip.hidebox($, $tooltip)
				}
			})

		}) //end dom ready
	}
}

stickytooltip.init("*[data-tooltip]", "tooltipdiv")



