(function(jQuery, $)
{

window.displayRememberMeNew = function displayRememberMeNew(new_background_img)
{
	//document.getElementById('remember_me').style.display='inline';
	$('#remember_me').show('slow');
	$('.header_kewego_connexion').css('background-image', 'url('+new_background_img+')').css('height', '90px');
	$('.header_kewego').css('height', '100px');
}

window.displayRememberMeDefault = function displayRememberMeDefault()
{
	//document.getElementById('remember_me').style.display='inline';
	$('#remember_me').css('display', 'inline');
}

// Trim function
// Because doesn't exist in JS
window.trimAll = function trimAll(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;
}

// Starts a timeout
window.timeout = function timeout(functionRef, param, timer)
{
	if(functionRef.timerID)
		window.clearTimeout(functionRef.timerID);
	var func = function()
	{
		functionRef.timerID=null;
		functionRef(param);
	}
	functionRef.timerID = window.setTimeout(func, timer);
}


window.tosPopup = function tosPopup()
{
	sizeX = 600;
	sizeY = 400;
	topP = (screen.availHeight - sizeY) / 2;
	leftP = (screen.availWidth - sizeX) / 2;
	var popupTos = window.open('/tos/index.php', 'TOS', 'left='+leftP+',top='+topP+',width='+sizeX+',height='+sizeY+',scrollbars=yes,resizable=yes');
	if(!popupTos)
		window.alert(JST_COULDNT_OPEN_FULLSCREEN)
}


window.SetCookie = function SetCookie (name, value) {
	var argv=window.SetCookie.arguments;
	var argc=window.SetCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=name+"="+escape(value)+
		((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
		((path==null) ? ";path=/" : ("; path="+path))+
		((domain==null) ? "" : ("; domain="+domain))+
		((secure==true) ? "; secure" : "");
}

window.getCookieVal = function getCookieVal(offset) {
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1)
      		endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

window.GetCookie = function GetCookie (name) {
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen) {
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg)
                        return getCookieVal (j);
                i=document.cookie.indexOf(" ",i)+1;
                        if (i==0) break;}
	return null;
}


window.displayImpressum = function displayImpressum(partner_folder)
{
	if (partner_folder.length == 0) {
		partner_folder = 'default';
	}

	sizeX = 600;
	sizeY = 400;
	topP = (screen.availHeight - sizeY) / 2;
	leftP = (screen.availWidth - sizeX) / 2;
	var popupIm = window.open('/impressum/'+partner_folder+'/', 'TOS', 'left='+leftP+',top='+topP+',width='+sizeX+',height='+sizeY+',scrollbars=yes,resizable=yes');
	if(!popupIm)
	{
		window.alert(JST_COULDNT_OPEN_FULLSCREEN)
	}
}


/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
window.Querystring = function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get

	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &

// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name

		this.params[name] = value
	}
}

window.Querystring_get = function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;

	var value=this.params[key]
	if (value==null) value=default_;

	return value
}

window.getUnhashedUrl = function getUnhashedUrl(url)
{
    url = url.replace(/h\-t\-t\-p\-:\-\/\-\/\-/, 'http://');
	url = url.replace(/h\-t\-t\-p\-s\-:\-\/\-\/\-/, 'https://');
	
	return url;
}

window.gotoURL = function gotoURL(url)
{
	url = getUnhashedUrl(url);

	window.location.href = url;
}

window.gotoNewURL = function gotoNewURL(url)
{
    url = getUnhashedUrl(url);
    
    window.open(url);
}

// Simple XHTML protection
window.htmlentities = function htmlentities(s)
{
	if (typeof(s) === 'undefined') {
		return undefined;
	}

	s = s.replace(new RegExp('<', 'g'), '&lt;');
	s = s.replace(new RegExp('>', 'g'), '&gt;');
	s = s.replace(new RegExp('&', 'g'), '&amp;');
	s = s.replace(new RegExp('"', 'g'), '&quot;');

	return s;
}

// Convert XML node to inline string
// Fix for JQuery .html() on XML
// Lines commented are correct verification, but not supported by IE6 ! :(
window.xmlnodes_toString = function xmlnodes_toString(xml)
{
	var final_str = '';
	// Accept one parameter, for concact string
	if (typeof(window.xmlnodes_toString.arguments[1]) != 'undefined' && !!window.xmlnodes_toString.arguments[1])
	{
		final_str = window.xmlnodes_toString.arguments[1];
	}

	for (var i = 0; i < xml['childNodes'].length; i++)
	{
		if (!!xml['childNodes'].item(i)['childNodes'] && xml['childNodes'].item(i)['nodeType'] == 1)
		//if (xml['childNodes'].item(i).toString() == '[object Element]')
		{
			final_str += '<' + xml['childNodes'].item(i)['nodeName'];

			if (!!xml['childNodes'].item(i)['attributes'])
			//if (xml['childNodes'].item(i)['attributes'].toString() == '[object NamedNodeMap]')
			{
				for (var attr_i = 0; attr_i < xml['childNodes'].item(i)['attributes'].length; attr_i++)
				{
					final_str += ' ';
					final_str += xml['childNodes'].item(i)['attributes'].item(attr_i).nodeName;
					final_str += '="';
					final_str += xml['childNodes'].item(i)['attributes'].item(attr_i).nodeValue;
					final_str += '"';
				}
			}

			final_str += '>';

			if (!!xml['childNodes'].item(i)['childNodes'])
			//if (xml['childNodes'].item(i)['childNodes'].toString() == '[object NodeList]')
			{
				final_str = window.xmlnodes_toString(xml['childNodes'].item(i), final_str);
			}

			final_str += '</' + xml['childNodes'].item(i)['nodeName'] + '>';
		}
		else if (!!xml['childNodes'].item(i)['nodeValue'] && xml['childNodes'].item(i)['nodeType'] == 3)
		//else if (xml['childNodes'].item(i).toString() == '[object Text]')
		{
			final_str += xml['childNodes'].item(i).nodeValue;
		}
	}

	return final_str;
}

// Extract background image from css
window.getBackgroundImage = function getBackgroundImage(container)
{
	var background_image = $(container).css('background');
	if (!background_image)
	{
		background_image = $(container).css('background-image');
	}

	if (background_image.indexOf('url("' != -1))
	{
		var regexp = new RegExp('(.*)url\\(([\'"]*)([^\'"]+)(([\'"])*)\\)(.*)', 'g');
        regexp = regexp.exec(background_image);

        if (regexp != null && typeof(regexp[3]) != 'undefined')
        {
			return regexp[3];
		}
	}

	return '';
}

// Remove all <>
window.removeXHTML = function removeXHTML(xhtml)
{
    var clean = '';
	var in_tag = false;

	var i = 0;
	var len = xhtml.length;
	for (; i < len; i++)
	{
		if (in_tag === true)
		{
		    if (xhtml.charAt(i) === '>')
		    {
   				in_tag = false;
			}

		}
		else
		{
		    if (xhtml.charAt(i) === '<')
			{
				in_tag = true;
				i--;
			}
			else
			{
                clean += xhtml.charAt(i);
			}
		}
	}

	return clean;
}

// Create hook for TOP proposal links
window.top_proposal_links = function top_proposal_links()
{
	// TOP proposals links
	$('.search_link_top a[href=/top/]').mouseover(function()
	{
		$('.top_proposal_links').trigger('mouseover');
	});
	
	$('.top_proposal_links').bind('mouseover', function()
	{
		display_top_proposal_links($(this));
	});
	$('.top_proposal_links').bind('mouseout', function()
	{
		hide_top_proposal_links($(this));
	});
}

// Display TOP proposal links into the container
window.display_top_proposal_links = function display_top_proposal_links(container)
{
	$(container).css({display: 'block'});
}

// Hidde the container
window.hide_top_proposal_links = function hide_top_proposal_links(container)
{
	$(container).css({display: 'none'});
}

// Generate the possibilities saved selects
window.save_top_possibilities = function save_top_possibilities(filters, periods, possibilities)
{	
	// Save the periods
	
	document.saved_top_periods = new Array();
	
	$('option', periods).each(function()
	{
		document.saved_top_periods[$(this).val()] = new Array();
		document.saved_top_periods[$(this).val()]['text'] = $(this).html();
		document.saved_top_periods[$(this).val()]['selected'] = $(this).attr('selected') || false;
	});	
	
	// Remove nodes for make empty select
	empty_top_possibilities(filters, periods, possibilities);
}

// Make empty selects
window.empty_top_possibilities = function empty_top_possibilities(filters, periods, possibilities)
{
	$('option', periods).each(function()
	{
		$(this).remove();	
	});
}

// Selects switcher - populate select's
window.top_possibilities = function top_possibilities(filters, periods, possibilities)
{
	empty_top_possibilities(filters, periods, possibilities);
	
	if (typeof(possibilities[$(filters).val()]) != 'undefined')
	{
		var poss = possibilities[$(filters).val()];
		for (var i = 0; i < poss.length; i++)
		{
			var option = $('<option value="' + poss[i] + '" ' +  (document.saved_top_periods[poss[i]]['selected'] ? 'selected="selected"' : '') + '>' + document.saved_top_periods[poss[i]]['text'] + '</option>');
			$(periods).append(option);
		}
	}
}

// Change the selection and "disable" the select
window.disable_most_recent_select = function disable_most_recent_select()
{
	$('#top select[name="period"]').val('3');
	$('#top select[name="period"]').fadeTo('slow', 0.20, function()
	{
		// Disable the select
		$(this).attr('disabled', 'disabled');
		$(this).parent().append('<input type="hidden" class="equivalent_disabled" name="period" value="3" />');
	});
}

// Revert the action
window.revert_most_recent_select = function revert_most_recent_select()
{
	
	$('#top select[name="period"]').attr('disabled', '');
	$('#top select[name="period"]').fadeTo('slow', 1);

	$('#top .equivalent_disabled').remove();
}



$(document).ready( function() {
	var rss_url = '';
	$('.rss_feed_icon').children('a').click( function() {
		rss_id = $(this).attr('id');

		if (typeof rss_id != 'undefined' && rss_id != '')
		{
			rss_url = $("link[id='"+rss_id+"'][rel='alternate'][type='application/rss+xml']").attr('href');
		}
		else
		{
			rss_url = $("link[rel='alternate'][type='application/rss+xml']").attr('href');
		}

		if (rss_url != '' && (typeof rss_url) != 'undefined')
		{
			window.location.href = rss_url;
			return false;
		}
	});

	// Enable tooltip for top proposal links
	top_proposal_links();

	// Manage the TOP select's
	if (typeof(possibilities) != 'undefined')
	{		
		// 1. Save the select's
		save_top_possibilities($('#top select[name="filter"]'),
							 	$('#top select[name="period"]'),
								possibilities);
							
		// 2. Enable change hook
		$('#top select[name="filter"]').change(function()
		{
			top_possibilities(
								$('#top select[name="filter"]'),
							 	$('#top select[name="period"]'),
								possibilities
							  );
		});
	
		// 3. Populate default select's
		$('#top select[name="filter"]').trigger('change');
	
		// Hide the select if the most recent filter is selected
		// Because most recent 1 day == most recent all time
		$('#top select[name="filter"]').change(function()
		{
			if ($(this).val() == '2')
			{
				disable_most_recent_select();
			}
			else
			{
				revert_most_recent_select();
			}
		});
		if ($('#top select[name="filter"]').val() == '2')
		{
			disable_most_recent_select();
		}
	}
	
	return false;
});

})($kwg, $kwg);

