function countwords(text) {
	var removeHTML = new XRegExp("<(?!\\/?(?:b|i|u|p|strong|h[1-6])(?=>|\\s.*>))\\/?.*?>", "gimsuS");
	text = text.replace(removeHTML, '');

	// replace URLs and emails with "URL" -> counts as 1 word
	var urlCleaner = new XRegExp("(?:http:\\/\\/|ftp:\\/\\/|https:\\/\\/|(?:mailto:)?[\\w]+@)?[\\w]+\\.[^\\s]+", "gimsuS");
	text = text.replace(urlCleaner, 'URL');

	var regExCount = XRegExp("[\\p{N}\\p{L}&'\\-%\\+]+","gimsuS");
	// alternative preg_match: [\\p{N}\\p{L}]+[&'\\-%\\+]?[\\p{N}\\p{L}]*
	// to count "word1 - word2" as two words not as three.
	var preg_result = text.match(regExCount);
	return preg_result ? preg_result.length : 0;
}

function highlightWord(text, keyword, wrapper_start, wrapper_end)
{
	var pattern = new XRegExp(keyword+"(?:$|(?![^<]*<\\s*/\\s*span.*>))","gims");
//	console.log("(?:"+keyword+")(?:$|(?![^<]*<\\s*/\\s*span.*>))");
	text = text.replace(pattern, '$1'+wrapper_start+'$2'+wrapper_end);
	return text;
}

/**
 * calculates the keyword density for a given string of keywords.
 * keywords need to have the form: keyword1[1-9],keyword2,keyword3[20-50]
 */
function calculateKeywordDensity(keyword_string, default_min, default_max, words_min, words_max)
{
	var density_min = 0.0;
	var density_max = 0.0;

	var keyword_string_array = keyword_string.split(",");
	var length = keyword_string_array.length;

	for (var i = 0; i < length; i++)
	{
		var regExKeyword = XRegExp("\\s*([^\\[]+)(\\[([0-9]+)\\-([0-9]+)\\])*","gimsuS");
		var keyword_matches = regExKeyword.exec(keyword_string_array[i]);

		var keyword_min = parseInt(default_min, 10);
		var	keyword_max = parseInt(default_max, 10);

		if (keyword_matches != null && $.trim(keyword_matches[1]) != "")
		{
			if (typeof keyword_matches[2] != 'undefined')
			{
				keyword_min = parseInt(keyword_matches[3], 10);
				keyword_max = parseInt(keyword_matches[4], 10);
			}

			density_min += keyword_min;
			density_max += keyword_max;
		}
	}

	density_min = density_min * 100 / words_min;
	density_min = density_min.toFixed(1);

	density_max = density_max * 100 / words_max;
	density_max = density_max.toFixed(1);

	return density_min + '% - ' +  density_max + '%';
}

/**
 * shows the keyword density on all order creation pages.
 * it needs the page structure of these pages to work properly.
 */
function showKeywordDensity()
{
	var text = "";
	if ($('#div_bulk_titles').is(':visible') && $.trim($("#bulk_titles").val()) != "")
	{
		var titles_and_keywords = $("#bulk_titles").val().split("\n");

		$.each(titles_and_keywords, function()
		{
			var regExKeyword = XRegExp("([^\\[]*)\\[KW#\\s*([^#]+)+#\\]","gimsuS");
			var matches = regExKeyword.exec(this);

			if (matches != null)
			{
				var title = $.trim(matches[1]);
				if (title != "")
				{
					title += ": ";
				}
				text += title + calculateKeywordDensity(matches[2], $("#keywords_min").val(), $("#keywords_max").val(), $("#words_min").val(), $("#words_max").val()) + "<br />";
			}
		});
		$("#show_keyword_density").html(text);
	}
	else if ($('#single_title').is(':visible'))
	{
		$("input.keywords").each(function()
		{
			var title = $.trim($(this).parent("div").parent("div").children("input.single_titles").val());
			if (title != "")
			{
				title += ": ";
			}
			text += title + calculateKeywordDensity($(this).val(), $("#keywords_min").val(), $("#keywords_max").val(), $("#words_min").val(), $("#words_max").val()) + "<br />";
		});
		$("#show_keyword_density").html(text);
	}
}

/**
 * shows the order calculations on all order creation pages.
 * it needs the page structure of these pages to work properly.
 */
function showOrderCalculations()
{
	$("#show_num_keywords").text(total_headlines);
	$("#show_total_words").text(total_headlines*total_words);
	$("#max_cost_words").text(cost_words.toFixed(2));
	$("#show_total_tb_charge").text(total_tb_charge.toFixed(2));
	$("#show_total_costs").text(total_costs.toFixed(2));

	showKeywordDensity();
}

/**
 * shows the costs on all order creation pages.
 * it needs the page structure of these pages to work properly.
 */
function show_costs(costs)
{
	var costtype = costs;

	if (typeof $('#team_id').attr('value') != "undefined")
	{
		costtype = $('#team_id').attr('value');
		category_id = get_category_id(costtype);
		$("#category_id").val(category_id);
	}
    
	if(costtype == "")
    {
	    total_words = 0;
	    total_headlines = 0;
	    total_classification = 0;
	    tb_charge = 0;
    }
    else
    {
	    total_words = get_total_words();
	    total_headlines = get_num_headlines();
	    total_classification = get_classification(costtype);
	    tb_charge = get_tb_charge(costtype);
    }

    cost_words = total_classification*total_words*total_headlines;
    total_tb_charge = tb_charge*total_headlines;
    total_costs = cost_words+total_tb_charge;

    $(document).ready
    (
    	function()
    	{
    	    showOrderCalculations();
    	}
    );
}

/*
 * jquery plugin to send a form via ajax 
 */
(function($)
{
	$.fn.ajaxform = function(options) 
	{
		/*
		 * if ajaxform is used without parameters
		 */
		if(options == undefined)
		{
			options = {};
		}
		/*
		 * default options
		 */
		var defaults = {
			callback: function(data, form){},
			result_type: 'json'
		};
		var options = $.extend(defaults, options);

		this.each(function() 
		{
			$(this).submit(function(){
				var form = $(this);
				var values = getAllForms(this);
				var action = $(this).attr("action");
				var method = $(this).attr("method").toLowerCase();
				if(method.toLowerCase() == 'post')
				{
					$.post(action, values, function(data){
						options.callback(data, form);
					}, options.result_type);
				}
				else if(method.toLowerCase() == 'get')
				{
					$.get(action, values, function(data){
						options.callback(data, form);
					}, options.result_type);
				}
				return false;
			});
		});
	};

})(jQuery);


jQuery.fn.center = function()
{
	this.css("position","absolute");
	this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
	this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
	return this;
}


/**
 * @author Rossy
 * fetches all possible form fields 
 * @param string form_id - id of form tag 
 * @return array values - key + value
 */
function getAllForms(form)
{
	if((typeof form) == "string")
	{
		form = $('form[name='+form+']');
	}
    
	var values = {};
	var inputs = $(form).find('input, textarea, select');

	inputs.each(function()
	{
		if(this.type == "checkbox")
		{
			if(this.checked)
			{
				if( this.name.indexOf('[]') != -1 )
				{
					if(!values[this.name])
					{
						values[this.name] = [];
					}
					values[this.name].push(this.value);
				}
				else
				{
					values[this.name] = this.value;
				}
			}
		}
		else if(this.multiple == true)
		{
			var multiple = $(this).find("option:selected");
			var multiple_name = this.name;
			multiple.each(function()
			{
				if(!values[multiple_name])
				{
					values[multiple_name] = [];
				}
				values[multiple_name].push(this.value);
			});
		}
		else if(this.type == "radio")
		{
			if(this.checked)
			{
				values[this.name] = this.value;
			}
		}
		else
		{
			values[this.name] = this.value;
		}
	});
    
	return values;
}


$(document).ready(function()
{
	//$('.ajaxform').ajaxform();

	$('.hover').mouseover(function()
	{
		$(this).addClass('tr-list-highlight');
	});
	$('.hover').mouseout(function()
	{
		$(this).removeClass('tr-list-highlight');
	});
});

function ShowHide(whichLayer)
{
	if (document.getElementById)
	{
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;
		style2.display = style2.display? "":"block";
	}
	else if (document.all)
	{
		// this is the way old msie versions work
		var style2 = document.all[whichLayer].style;
		style2.display = style2.display? "":"block";
	}
	else if (document.layers)
	{
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].style;
		style2.display = style2.display? "":"block";
	}
}

function HideShow(whichLayer)
{
	if (document.getElementById)
	{
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;
		style2.display = style2.display? "":"none";
	}
	else if (document.all)
	{
		// this is the way old msie versions work
		var style2 = document.all[whichLayer].style;
		style2.display = style2.display? "":"none";
	}
	else if (document.layers)
	{
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].style;
		style2.display = style2.display? "":"none";
	}
}

function ShowAndHide(toShow, toHide)
{
	ShowHide(toShow);
	HideShow(toHide);
}

function newproject(giddyup)
{
	if(giddyup==1)
	{
		ShowAndHide('new_project', 'select_project');
		ShowAndHide('new_project_csv', 'select_project_csv');
	}
}

function getEU(giddyup)
{
	//var arr=giddyup.split("%n%");
	var whichLayer = 'UsStID';
    
	if(typeof(euCountries[giddyup]) != 'undefined' && euCountries[giddyup] != null && giddyup != 'de')
	{
		$('#'+whichLayer).show();
	/*
        if (document.getElementById)
        {
            var style2 = document.getElementById(whichLayer).style;
            style2.display = style2.display="block";
        }
        else if (document.all)
        {
            var style2 = document.all[whichLayer].style;
            style2.display = style2.display="block";
        }
        else if (document.layers)
        {
            var style2 = document.layers[whichLayer].style;
            style2.display = style2.display="block";
        }
        */
	}
	else
	{
		$('#'+whichLayer).hide();
	/*
        if (document.getElementById)
        {
            var style2 = document.getElementById(whichLayer).style;
            style2.display = style2.display="none";
        }
        else if (document.all)
        {
            var style2 = document.all[whichLayer].style;
            style2.display = style2.display="none";
        }
        else if (document.layers)
        {
            var style2 = document.layers[whichLayer].style;
            style2.display = style2.display="none";
        }
        */
	}
}


function addLoadEvent(func) 
{
	var oldonload = window.onload;
	if(typeof window.onload != 'function')
	{
		window.onload = func;
	 
	}
	else
	{
		window.onload = function(){
	    
			if(oldonload)
			{
				oldonload();
			}
			func();
		}
	}
}

