/**
 * Javascript Library for squirrel framework
 */



$(function() {
	$(".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 );
	});
	
});


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;
} 



/**
 * Convertng given string to Url compatible
 * @param string text
 * @return string converted text
 */
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, children, checked) {
	
	if ( document.getElementById('autoselect_'+id) && document.getElementById('autoselect_'+id).checked == 1 )  {
		var children = children.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, source) {

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

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

	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 = '-';
			}
		}
	}
}

function selectParent(id, parents, checked) {
	if ( document.getElementById('autoselect_'+id) && document.getElementById('autoselect_'+id).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 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 inputIdName = name + itemName + '_file_' + length;
		var delIdName = name + itemName + '_del[' + length + ']';
		var inputName = name + itemName + '_file[' + length + ']';
	
		newdiv.setAttribute('id', divIdName);
	
		if (displayLabel)
			newdiv.innerHtml = '<label for=\"' + inputIdName + '\">' + itemLabel
					+ ' :</label>';
	
		if (imageUrl != null) {
	
			newdiv.innerHTML += "<img style=\"margin: 5px\" src=\"" + imageUrl
					+ "\" />";
	
			newdiv.innerHTML += "<br/>";
	
			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> <br/>";
	
		}
	
		newdiv.innerHTML += '<input type="file" name="' + inputIdName + '" id="'
				+ inputIdName + '" style="width:80%">';
	
		for ( var i = 0; i < attributes.length; 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 href="javascript:" onclick="removeHImageField(\''
				+ 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';
	
		}
	} 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 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/buttons/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/buttons/remove.png',
						'alt': 'remove'
					}
					)));
				}
			}).append( $('<img></img>',{
				'src': '/images/buttons/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/buttons/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/buttons/remove.png',
						'alt': 'remove'
					}
					)));
				}
			}).append( $('<img></img>',{
				'src': '/images/buttons/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];


	$('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');

	});	
	
});

