function initializeWidgets() {
	//adjustHeightCatNavBarListView();
	adjustClupMenu();
    $("ul.clup-menu-bar").supersubs({ 
		minWidth:    6,   // minimum width of sub-menus in em units 
		maxWidth:    30,   // maximum width of sub-menus in em units 
		extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
		                   // due to slight rounding differences and font-family 
	}).superfish({ 
		delay:       100,                            // one second delay on mouseout 
		animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
		speed:       'normal',                          // faster animation speed 
		autoArrows:  false,                           // disable generation of arrow mark-up 
		dropShadows: false                            // disable drop shadows 
	});
	$('.channel-group-toggle').buttonset();
	$('.week-days').buttonset();

	var catlis = $('#adv-search-cat-list .toggle-button');
	if (catlis.length > 0) {
		catlis.bind('click', function() {
			var li = $(this).closest('li');
			if (li.is('.collapsed')) {
				li.switchClass('collapsed','expanded',200);
			} else {
				li.switchClass('expanded','collapsed',200);
			}
			return false;
		});
	}
	if ($('#complex-search').length > 0) {
		var emptyText = $('.search-filter-summary .auto').first().text();
		updateAdvancedSearchFilterFeedback(emptyText);
		$('#complex-search #q').bind('keyup', function() {
			updateAdvancedSearchFilterFeedback(emptyText);
		});
		$('#complex-search select').bind('change', function() {
			updateAdvancedSearchFilterFeedback(emptyText);
		});
		$('#complex-search :checkbox').bind('click', function() {
			updateAdvancedSearchFilterFeedback(emptyText);
		});
	}
/*	if ($('[id^=save-search-form]').length > 0) {
		$('[id^=save-search-form] input:text').bind('keyup', function() {
			savedSearchFormInputChanged($(this));
		});
	}*/
	window.name = "tvtv_main";
	if (document) {
	    var lv;
	    lv = document.getElementById("listView");
	    if (lv) {
	    	// open daytime period
	        checkCookie();
	    }
	}
}

function adjustHeightCatNavBarListView() {
	var top = $('#catNavBar').offset().top;
	var bottom = $('#footer').offset().top;
	var height = bottom - top;
	//$('#catNavBar').height(height);
	$('#listView').height(height);
}

function adjustClupMenu() {
	var moreItem = $('#clup-menu-more-item');
	if (moreItem.length) {
		var lastReg = moreItem.prev();
		var lastRegTop = lastReg.offset().top;
		var first = moreItem.siblings(':first');
		var firstTop = first.offset().top;
		if (lastRegTop <= firstTop) {
			moreItem.remove();
		} else {
			var maxWidth= $('#clup-menu-bar').width();
			var menuItems = $('#clup-menu-bar').children(':not(#clup-menu-more-item)');
			var moreW = moreItem.width();
			var w = moreW;
			menuItems.each(function(i) {
				w = w + $(this).width();
				if (w >= maxWidth) {
					moreItem.append($(this).remove());
				}
			});
			moreItem.children('li').wrapAll(document.createElement('ul'));
			moreItem.removeClass('hidden');
		}
	}
}

function updateAdvancedSearchFilterFeedback(emptyText) {
	var autoTextNodes = $('.search-filter-summary .auto');
	autoTextNodes.empty();
	autoTextNodes.append($('#complex-search #q').val());
	// categories are checked separately
	var noDefSelects = $('#complex-search table option:selected').not('.default');
	if (noDefSelects.length) {
		noDefSelects.each(function() {
			if (autoTextNodes.text().length) autoTextNodes.append(", ");
			autoTextNodes.append($.trim($(this).text()));
		});
	}
	var catlis = $('#adv-search-cat-list').children('li');
	if (catlis.length) {
		catlis.each(function() {
			var checkbox = $(this).children('input');
			var mcSelected = checkbox.is(':checked');
			var mcText = checkbox.attr('title');
			var subCatlis = $(this).find('option:selected').not('.default');
			$(this).removeClass('subselects');
			var subtext = "";
			if (subCatlis.length) {
				// toggle the class 'subselects' on the mc li
				$(this).addClass('subselects');
				subCatlis.each(function() {
					if (subtext.length) subtext = subtext + ", ";
					subtext = subtext + $.trim($(this).text());
				});
			}
			if (mcSelected | subtext.length) {
				if (autoTextNodes.text().length) autoTextNodes.append(", ");
				autoTextNodes.append(mcText);
				if (subtext.length) autoTextNodes.append(" (" + subtext + ")");
			}
		});
	}
	var checked = $('#complex-search input:checked').not('.input-mc');
	if (checked.length) {
		checked.each(function() {
			if (autoTextNodes.text().length) autoTextNodes.append(", ");
			autoTextNodes.append($(this).attr('title'));
		});
	}
	if (!autoTextNodes.text().length) {
		autoTextNodes.append(emptyText);
		disableSubmit($('.search-submit'), true);
		$('.search-filter-summary input:hidden').val('');
	} else {
		disableSubmit($('.search-submit'), false);
		$('.search-filter-summary input:hidden').val(autoTextNodes.first().text());
	}
}

function savedSearchFormInputChanged(inputObj) {
	var text = inputObj.val();
	$('[id^=save-search-form] input:text').val(text);
	if (text.length) {
		text = text.trim();
	}
	var disable = (text.length <= 0);
	disableSubmit($('[id^=save-search-form]'), disable);
}

function disableSubmit(jqObj,disable){
	if (disable) {
		jqObj.find('input:submit').attr('disabled','disabled');
	} else { 
		jqObj.find('input:submit').removeAttr('disabled');
	}
}

//---------------------------------------------------------------- Pop Ups ---------------------------------------//
function popup(link) {
	var win = window.open(link, "tvtv_details", "width=600,height=601,dependent=yes");
	win.focus();
	// return false will prevent the href from which this function was called to be processed
	return false;
}
    
function helpPopup(link) {
	var win = window.open(link, "tvtv_details", "width=700,height=600,resizable=yes,dependent=yes");
	win.focus();
	// return false will prevent the href from which this function was called to be processed
	return false;
}


// needed to start the person search triggered from the program details.
function searchPerson(person,url) {
	if (window.opener && !window.opener.closed) {
		window.opener.location = url;
		window.opener.focus();
	} else {
		var newWin = window.open(url,"tvtv_main","menubar=yes,scrollbars=yes,resizable=yes,status=yes,width=1000,height=700,dependent=no");
		newWin.focus();
	};
}

function searchPersonFb(prefix,person,url) {
	searchPs(prefix,person);
	searchPerson(person, url);
}



// Open the content popup window with a specific root node to start with
// Apparently not used except in shared/test/java/testdata/repository (which I know nothing about)
function contentPopup(document,rootid) {
	var win = window.open("web/content_popup.vm?document=" + document + "&popuproot=" + rootid,
			"tvtv_popup","width=600,height=600,resizable=yes");
	win.focus();
	// return false will prevent the href from which this function was called to be processed
	return false;
}
	    
//---------------------------------------------------------------- Hide and Show ---------------------------------------//     

//**
// * This function opens or closes the category menu identified by key. Then,
// * the link is called.
// */
function toggleCategoryAndLink(key, link) {
	toggleCategory(key);
	window.location.href=link;
}

//**
// * This function opens or closes the category menu identified by key. Then,
// * the function linkCategoryWithParams is called with the link.
// */
function toggleCategoryAndLink2(key, link) {
	toggleCategory(key);
	linkCategoryWithParams(link);
}

//**
// * This function reads all hidden attributes from the category result page
// * in order to generate the complete link with all selected days and 
// * channelGroups.
// */
function linkCategoryWithAllParams(mainTemplate) {
	var parameters = "index.vm?mainTemplate=" + mainTemplate;
	
	var element = document.getElementById("mcid");
	
	if(element != null && element != "") {
		parameters = parameters + "&mcid=" + element.value;
	}

	element = document.getElementById("scid");

	if(element != null && element != "") {
		parameters = parameters + "&scid=" + element.value;
	}
	linkCategoryWithParams(parameters);
}

//**
// * This function reads all hidden attributes from the category result page
// * in order to generate the complete link with all selected days and 
// * channelGroups.
// *#
function linkCategoryWithParams(link) {
	var parameters = "";

	if (document.DayArray) {
		for(var i = 0; i <= 20; i++) {
			aValue = document.DayArray.elements[i].value;
			aName = document.DayArray.elements[i].name;
			parameters = parameters + "&" + aName + "=" + aValue;
		}
	}
	
	var elements = document.getElementsByName("cgid");
	
	for(var j = 0; j < elements.length; j++) {
		if(elements[j].checked) {
			parameters = parameters + "&cgid=" + elements[j].value;
		}
	}

	var completeLink = link + parameters;
	window.location.href = completeLink;
}

function toggleVisibility(key) {
	obj1 = document.getElementById(key);
	if (obj1) {
		visible = (obj1.style.visibility == "visible");
		if (visible) {
			obj1.style.visibility="hidden";
		} else {
			obj1.style.visibility="visible";
		}
	}
}

function toggleDisplay(key) {
	obj1=document.getElementById(key);
	if (obj1) {
		displayed = (obj1.style.display != "none");
		if (displayed) {
			obj1.style.display="none";
		} else {
			obj1.style.display="block";
		}
	}
}

function toggleDiv(key) {
	obj1 = document.getElementById(key);
	if (obj1) {
		visible = (obj1.style.display != "none");
		if (visible) {
		  obj1.style.display="none";
		  setCookie(key, "no");
		} else {
		  obj1.style.display="";         
		  setCookie(key, "yes");
		}
	}
}

function toggleOnOff(key) {
	toggleDiv(key + "_on");
	toggleDiv(key + "_off");		
}

function toggleCategory(key) {
	toggleOnOff("cat_" + key);

	var catMaxValue;
	catMaxValue = getCookie("catMaxValue");
	if(catMaxValue == "" | catMaxValue < key) {
		setCookie("catMaxValue", key);
	}
}

function toggleBlock(key) {
	toggleOnOff("timeTab" + key);
	toggleDiv(key + "1");
	toggleDiv(key + "2");
	toggleDiv(key + "3");
}


function toggleTipOfDay() {
	toggleOnOff("TipOfDay0");		
	toggleDiv("TipOfDay1");
	toggleDiv("TipOfDay2");
}

function toggleMorning()	{ toggleBlock("Morn"); }
function toggleEve()		{ toggleBlock("Eve"); }
function toggleDay()		{ toggleBlock("Day"); }
function toggleNight()		{ toggleBlock("Night"); }

function checkOnOff(key) {
	checkDiv(key + "_on");
	checkDiv(key + "_off");		
}

function checkDiv(key) {
	obj1=document.getElementById(key);
	visible = getCookie(key);
	
	if (obj1) {
		if (visible == "no") {
		  obj1.style.display="none";
		} else if (visible == "yes") {
		  obj1.style.display="";          
		}
	}
}  

function checkBlock(key) {
    checkOnOff("timeTab" + key);
    checkDiv(key + "1");
    checkDiv(key + "2");
    checkDiv(key + "3");

    var value;
    value = getCookie("timeTab" + key + "_on");

    if (! value) {
        // No cookie defined
        
        var jetzt = new Date();
		var Std = jetzt.getHours();
		var nowKey = "";
		if (Std >= 5 && Std < 12) {
		  nowKey = "Morn";
		} else if (Std >= 12 && Std < 18) {
		  nowKey = "Day";
		} else if (Std >= 18 && Std <= 23) {
		  nowKey = "Eve";
		} else if (Std >= 0 && Std < 5) {
		  nowKey = "Night";
		}
        
        if (key == nowKey) {
            toggleBlock(key);
        }
    }
}

function checkBlockTipOfDay() {
	checkOnOff("TipOfDay0");	
	checkDiv("TipOfDay1");
	checkDiv("TipOfDay2");
}

function checkCookie() {
    checkBlockTipOfDay();
    checkBlock("Morn");
    checkBlock("Day");
    checkBlock("Eve");
    checkBlock("Night");
}

function checkCategory(){
    var catMaxValue;
    
    catMaxValue = getCookie("catMaxValue");
    if(catMaxValue != "") {
        for(var i = 0; i <= catMaxValue; i++) {
			checkOnOff("cat_" + i);
		}
    }  
    checkOnOff("mytvtv");	
}
	
//---------------------------------------------------------------- Cookies ---------------------------------------

function cookiesEnabled() {
	var d = new Date();
	d.setTime(d.getTime() + 10000);
	document.cookie = "cookie_check=yes; path=/; expires=" + d.toUTCString() + ";";
	return document.cookie && document.cookie.length > 0;
}

function setCookie(key,value) {
	// if ((${consumer} && $consumer.isUseCookies()) || !${consumer})
    	document.cookie= key + "=" + escape(value);    	
    // end
}

function getCookie(key) {
    var value = "";
	// if ((${consumer} && $consumer.isUseCookies()) || !${consumer})
	if (document.cookie.length>0) {
		c_start = document.cookie.indexOf(key + "=")

		if (c_start != -1) { 
			c_start = c_start + key.length+1 
			c_end = document.cookie.indexOf(";",c_start)
			if (c_end==-1) {
				c_end=document.cookie.length
			}
			value = unescape(document.cookie.substring(c_start,c_end))
		}
	}
	// end
	return value;
}

//------------------------------------------------ Scrollbars and other style stuff ---------------------------------------

function getBarHeight()
{
	var bar1;
	var bar2;
//	var catBar;
	var height;
	var channels;
	
	bar1 = document.getElementById("top_bar1");
	height = getHeight(bar1);
	
	bar2 = document.getElementById("top_bar2");
	if (bar2) {
		height += getHeight(bar2);
	}
	
	channels = document.getElementById("channelGroup");
	height += getHeight(channels);
	
	return height;
}
	
function getFooterHeight() {
	var height;
    var footer;
    footer = document.getElementById("footer");
	height = getHeight(footer);
	return height;
}

function getHeaderHeight() {
	var height;
    var header;
    header = document.getElementById("header");
	height = getHeight(header);
	return height;
}

function getFooterHeaderHeight() {
    var heightDelta;
	
    heightDelta = getFooterHeight();
    heightDelta += getHeaderHeight()
	heightDelta += getBarHeight();
	
	return heightDelta;
}
	
function adjustLeft() {
	var h;
	if (self.innerHeight) { // all except Explorer
	    h = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
	    h = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
	    h = document.body.clientHeight;
	}		
	
	var footer;
	var header;
	var height;
	var hheight;
	
	var addHeight;
	addHeight = getFooterHeaderHeight();
	
	var catNavBar;
	catNavBar = document.getElementById("catNavBar");    
	catNavBar.style.height = h - addHeight - 45;
	    
	var mainleft;
	mainleft = document.getElementById("main_left");    
	
	header = getHeaderHeight()
	footer = getFooterHeight();
	f = header + footer;
	if (header > 0) {
		// f += 10;
	}
	
	if (footer > 0) {
		//f += 1;
	}
	mainleft.style.height = h - f;
	//	mainleft.style.top = hheight;
}

function adjustMain() 
{
	var w,h;
	if (self.innerHeight) { // all except Explorer
	    w = self.innerWidth;
	    h = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) {
	    w = document.documentElement.clientWidth;
	    h = document.documentElement.clientHeight;
	}
	else if (document.body) { // other Explorers
	    w = document.body.clientWidth;
	    h = document.body.clientHeight;
	}	

	var mainRight;
	var listView;
	var header = getHeaderHeight();
	var footer = getFooterHeight();
	var bar = getBarHeight();
	var heightDelta = header + footer + bar + 10;
		
	listView = document.getElementById("listView");
	if (listView) {
	    listView.style.height = h - heightDelta;
	    listView.style.width = w - 180; 
	}
	
	var checkBoxTable = document.getElementById("checkBoxTable");
	if(checkBoxTable) {
		checkBoxTable.style.top="-3px";
	}
}

function adjustAll() {
	adjustMain();
	adjustLeft();
}

function getHeight(element) {
	var h = 0;
	if (element) {
		if (document.getComputedStyle) {
		    hheight = window.getComputedStyle(element,'null').getPropertyValue('height');
		} else {
		    prop = element.currentStyle.height;
		}
		if (prop == "auto" || prop == "") {
		    h = element.offsetHeight;
		} else {
		    // the actual height is reported as e.g. 90px, so 
		    // we have to strip off the px at the end
		    h = prop.slice(0, prop.length - 2);
		}
	}
	return parseInt(h);
}

var channelGroupRows;
function init() {
	window.name = "tvtv_main";
	checkCategory();
	
	if (navigator.appName == "Microsoft Internet Explorer") {
	    adjustAll(); 
	}
	
	if (document) {
	    var lv;
	    lv = document.getElementById("listView");
	    if (lv) {
	        checkCookie();
	        if (channelGroupRows > 1) {
	            lv.style.top = (70 + (channelGroupRows-1)*15) + "px";
	        }
	    }
	}
}

//if (navigator.appName == "Microsoft Internet Explorer") {
//	window.onresize=adjustAll; 
//}
    
// If the day is changed, and the additionalChannelView is shown, a different link must be called
// than when the day is changed in the listview.
function openListviewOrAddChnls(link,isAddChannels) {
	var selectedIds = getCookie("selAddChnls");
	if(isAddChannels) {
		link = link + "&chnl=" + selectedIds;
	}
	window.location.href = link;
}
    
// resize iframe
function resizeIframe(id) {
	try {
		frame = document.getElementById(id);
		innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
		objToResize = (frame.style) ? frame.style : frame;
	    var is_ie/*@cc_on = {
	      // quirksmode : (document.compatMode=="BackCompat"),
	      version : parseFloat(navigator.appVersion.match(/MSIE (.+?);/)[1])
	    }@*/;
		if (is_ie) {
			objToResize.height = innerDoc.body.scrollHeight;
		} else {
			objToResize.height = innerDoc.body.offsetHeight;
		}
		var elmt = document.getElementById('mg_width');
		objToResize.width = elmt.value;
		//objToResize.width = innerDoc.body.screollWidth;
	} catch (e) {
		window.status = e.message;
	}
}

// Misc
function cookieCheck(msg) {
	if (cookiesEnabled()) {
		return true;
	} else {
		alert(msg);
		return false;
	}
}