var blindPossible = true;
var currentFilterType = null;
var currentView = null;
var currentAction = null;
var semaphore = 0;
var completeRefresh = null;
var refreshTimeout = null;
var timeoutType = 'short';

function changeClassName(element, className){
	$(element).addClassName('submenu-click');
	return false;
}

function addLoadEvent(func) {
    Event.observe(window, 'load', func);
}

function removeMySelection(divId, url, contentId)
{
	
	var divOb = $(divId);
	if (divOb != null){
		new Ajax.Updater(divId, url, {asynchronous:true, evalScripts:false, onComplete: function(){copyMySelectionDivContent(divId, contentId);}});	
	}
		
    var divOb = $('TIP'+divId);
    if (divOb != null){
        new Ajax.Updater('TIP'+divId, url, {asynchronous:true, evalScripts:false});	
    }
	return false;
}

function copyMySelectionDivContent(mainDivID, targetDivID) 
{
	var mainDivOb = $(mainDivID);
	var targetDivOb = $("MySelection" + targetDivID);
	if ((mainDivOb == null) || (targetDivOb == null)) return;
	
	targetDivOb.innerHTML = mainDivOb.innerHTML;
}

function addMySelection(divId, url, detailDivId)
{
	var divOb = $(divId);
	if (divOb != null){
		new Ajax.Updater(divId, url, {asynchronous:true, evalScripts:false, onComplete: function(){copyMySelectionDivContent(divId, detailDivId);}});
	}

    var divOb = $('TIP'+divId);
    if (divOb != null){
        new Ajax.Updater('TIP'+divId, url, {asynchronous:true, evalScripts:false});	
    }
	return false;
}

function profileToggle(divId)
{
    var divOb = $(divId);
    
    //var history = new historyObject(divId, detailsUrl);
    //dhtmlHistory.add("test", history);
    
    if(Element.visible(divOb))
    {
        Effect.BlindUp(divId, {duration:1});
    }
    else
    {
    	Effect.BlindDown(divId, {duration:1});
    }
    return false;
}

function otherDeviceToggle(divId,divswitch,RadioId,TextId,HiddenId, MessageId, Message2Id)
{
    var divOb = $(divId);
    if(divswitch == 'off')
    {
        Effect.BlindUp(divId, {duration:1});
        var radio = $(RadioId);
        var text = $(TextId);
        var hidden = $(HiddenId);
        var message = $(MessageId);
        var message2 = $(Message2Id);
        radio.checked=true;
        text.disabled=false;
        hidden.value='';
        message2.hide();
        message.show();
    }
    else
    {
    	Effect.BlindDown(divId, {duration:1});
    }
    return false;
}

function submitOtherDeviceForm(hiddenId){
	var hidden = $(hiddenId);
	if(hidden != null){
		if(hidden.value == ''){
			document.createuser.submit();
		}
	}
	return false;
}

function passwordToggle(divId, linkId, newPasswordId, confirmPasswordId, changePasswordId, change, cancel)
{
    var divOb = $(divId);
    var linkOb = $(linkId);
    
    if(Element.visible(divOb))
    {
        Effect.BlindUp(divId, {duration:1});
        linkOb.innerHTML = change;
        //Reset password fields
        $(newPasswordId).value = '';
        $(confirmPasswordId).value = '';
        $(changePasswordId).value = '';
    }
    else
    {
    	Effect.BlindDown(divId, {duration:1});
    	linkOb.innerHTML = cancel;
    	$(changePasswordId).value = 1;
    }
    return false;
}

function avatarToggle(divId, linkId, change, cancel, filename)
{
    var divOb = $(divId);
    var linkOb = $(linkId);
    
    if(Element.visible(divOb))
    {
        Effect.BlindUp(divId, {duration:1});
        linkOb.innerHTML = change;
        avatarReset(filename);
    }
    else
    {
    	Effect.BlindDown(divId, {duration:1});
    	linkOb.innerHTML = cancel;
    }
    return false;
}

function startUpload(divId){
    var divOb = $(divId);
   	
   	divOb.show();
	return true;
}

function stopUpload(success, filename, filelink){
	//var result = '';
    divOb = $('result');
    divOb2 = $('f1_upload_process');
    divOb3 = $('hiddenavatar');
        
    if (success == 1){
    	divOb.innerHTML = '<span class="msg">The file '+filename+' was uploaded successfully!<\/span><br/>';
    	divOb3.innerHTML = '<input type="hidden" name="avatar" id="avatar" value="'+filename+'" />';
    	document.testavatar.src = '/uploads/'+filename+'';
    } else {
    	divOb.innerHTML = '<span class="emsg">There was an error during file upload!<\/span><br/>';
    }
    
    divOb2.hide();
    return true;
}


function avatarReset(filename){
	divOb = $('result');
	divOb.innerHTML = '<br/>';
	document.testavatar.src = '/uploads/'+filename+'';
	return false	
}


function removeMS(contentId, tableId, className, alternateClassName){
	var rowOb = $('short' + contentId);
	if(rowOb != null){
		rowOb.hide();
		fixTableLayout(tableId, className, alternateClassName);
	}
}


//EPG-view functions
var currentDetails = null;
var currentUrl = null;
var currentProgramId = null;
var currentProgramColor = null;
var currentClassName = null;
var currentBackgroundColor = null;

var currentStartTime = null;

function programDetailsToggle(divId, programId, detailsUrl, className, backgroundColor)
{
if(typeof(className) != 'string'){
	if(currentClassName != undefined){
		className = currentClassName;
	} else {
		className = 'epgProgramSelected';
	}
} else {
	currentClassName = className;
}

if(typeof(backgroundColor) != 'string'){
	if(currentBackgroundColor != undefined){
		backgroundColor = currentBackgroundColor;
	} else {
		backgroundColor = '#034865';
	}
} else {
	currentBackgroundColor = backgroundColor;
}


if (blindPossible == true) {
	blindPossible = false;

    //var history = new historyObject(divId, detailsUrl);
    //dhtmlHistory.add("test", history);
    
	//Restore old color
	if(currentProgramId != null && currentProgramColor != null){
		var oldProgramOb = $(currentProgramId);
		if (oldProgramOb != null){
			oldProgramOb.removeClassName(className);
			oldProgramOb.style.backgroundColor = currentProgramColor;	
		}
    
    //Enable the tooltip
    enableTooltip('markSmall_' + getContentId(currentProgramId));
    
	}
	
  if((divId == null) && (programId == null) && (detailsUrl == null) && (currentDetails != null)){
		blindPossible = false;
		$(currentDetails).hide();
		currentDetails = null;
	  	currentUrl = null;
		currentProgramColor = null;
		currentProgramId = null;
		//Set selected item for List view
    	currentShowDetails = null;
		blindPossible = true;
		if($('timeline')){
			$('timeline').show();
		}
		trackGoogleAnalytics('closeProgramDetails')
		return false;
	}
		
	
	var divOb = $(divId);
	var programOb = $(programId);
	
	if(Element.visible(divOb))
    {
		if($('timeline')){
			$('timeline').show();
		}
        if(currentUrl == detailsUrl)
        {
			$(divId).hide();
			blindPossible = true;
			currentDetails = null;
            currentUrl = null;
			currentProgramColor = null;
			currentProgramId = null;
			//Set selected item for List view
            currentShowDetails = null;
            trackGoogleAnalytics('closeProgramDetails')
        }
        else
        {
            //Set selected item for List view
            currentShowDetails = programId.substring(10, programId.length);
            showLoader();
            new Ajax.Updater(divId, detailsUrl + '&view=' + currentView, {asynchronous:true, evalScripts:true,
							 onSuccess:function(request, json){ currentDetails = divId;
            													currentUrl = detailsUrl;
							 									currentProgramId = programId;
																currentProgramColor = programOb.style.backgroundColor;
																programOb.addClassName(className);
																programOb.style.backgroundColor = backgroundColor;
                                //Disable the tooltip
                                disableTooltip('markSmall_' + getContentId(programId));
																blindPossible = true;},
							onComplete: function(){trackGoogleAnalytics('openProgramDetails');hideLoader();}
							});
            
		     }
    }
    else
    {
		if($('timeline')){
			$('timeline').hide();
		}
        var currentDetailsElement =  $(currentDetails); 
		if(currentDetailsElement != null)
        {
            //Effect.BlindUp(currentDetails, {duration:1}});
		    currentDetailsElement.hide();
		    //Set selected item for List view ??
        }

        //Set selected item for List view
        currentShowDetails = programId.substring(10, programId.length);
        showLoader();
        new Ajax.Request(detailsUrl + '&view=' + currentView, {asynchronous:true, evalScripts:true,
            onSuccess:function(transport){ 		$(divId).update(transport.responseText);
            									currentDetails = divId;
												
        										currentUrl = detailsUrl;
		      									currentProgramId = programId;
												currentProgramColor = programOb.style.backgroundColor;
												programOb.addClassName(className);
												programOb.style.backgroundColor = backgroundColor;
												//Effect.BlindDown(divId, {duration:1, afterFinish: function(){blindPossible = true;}});
												$(currentDetails).show();
                        						//Disable the tooltip
                        						disableTooltip('markSmall_' + getContentId(programId));
												blindPossible = true;
												},
			onComplete: function(){trackGoogleAnalytics('openProgramDetails');hideLoader();}
			});
			currentShowDetails = null; 
		}
	}
}


function showProgramDetails()
{
	if((currentDetails != null) && (currentUrl != null) && (currentProgramId != null)){
		var divOb = $(currentDetails);
		var programOb = $(currentProgramId);
		if((divOb != null) && (programOb != null)){
			new Ajax.Updater(currentDetails, currentUrl + '&view=' + currentView, {asynchronous:true, evalScripts:true,
            onSuccess:function(request, json){ 	currentProgramColor = programOb.style.backgroundColor;
											   	programOb.addClassName('epgProgramSelected');
												programOb.style.backgroundColor = "#034865";
												divOb.show();}}); 
		}
	}
	var blindPossible = true;
	
}

//Strips the content_id form some string, the string has to be of the form: some_value _ contentId
function getContentId(stringValue){
  var result = "";
  if(typeof(stringValue) == 'string'){
    var index = stringValue.lastIndexOf('_');
    if(index != -1 && index < stringValue.length - 1){
      result = stringValue.substr(index + 1);
    }
  }
  return result;
}

function hideDetailsNowNext(event){
	if (!event){
		var event = window.event;
	}
	Event.stop(event);
	var element = Event.element(event);
	if(element != undefined && element.hasClassName('icon-close')){
		programDetailsToggle();
	}
}


function triggerToggle(divId, divId2){
    var divOb = $(divId);
    var divOb2 = $(divId2);
    
    if(Element.visible(divOb))
    {
        divOb2.show();
        divOb.hide();
		        
    }
    else
    {
    	divOb.show();
    	divOb2.hide();
    }
    return false;
}

function redirect(link) {
	window.top.location = link;
}

//Slider functions

function calculateNewRatingValue(sliderValue, currentRating){
	if(currentRating >= 0.5 ) {
			if(sliderValue == 1)
				return -10;
			else if(sliderValue == 2)
				return Math.round(currentRating - 1.5);
			else if(sliderValue == 3)
				return -11;
			else if((sliderValue == 4) && (currentRating < 10))
				return Math.round(Math.min((currentRating + 3), 10));
			else if ((sliderValue == 5) && (currentRating < 10))
				return 10;
			else 
				return -11; 
	} else {
		if(sliderValue == 1)
			return -11;
		else if(sliderValue == 2)
			return -11;
		else if(sliderValue == 3)
			return -11;
		else if(sliderValue == 4)
			return 5;
		else if(sliderValue == 5)
			return 10; 
	}
}

function initSliderEPG(handleId, trackId, currentRating, url){
	new Control.Slider(handleId, trackId,{
//        onSlide:function(v){changeSliderTrack(v, trackId);},
        onChange:function(v){storeSliderValueEPG(v, currentRating, url);},
        range:$R(1,5),
        values:[1,2,3,4,5],
		sliderValue:3});
}


function storeSliderValueEPG(v, currentRating, url) {
      var rating = calculateNewRatingValue(v, currentRating);
      if(rating != -11){
 		blindPossible = false;
 		url = url.replace('xxx', rating);
     	currentDetails = null;
     	showLoader();
     	new Ajax.Request(url, {asynchronous:true, 
      						 evalScripts:true,
      						 onSuccess: function(transport){currentDetails = null;
														    currentUrl = null;
															currentProgramColor = null;
															currentProgramId = null;
      						 								updateEPG('channelguide');
      						 								blindPossible = true},
      						 onComplete: function(){hideLoader();}
      						 });
      }
}
      
function changeSliderTrack(v, trackId) {
	trackOb = $(trackId);
	if(trackOb != null){
		for(i = 1; i <= 5; i++){
			if(i == v){
				trackOb.addClassName('track' + i);
			} else {
				trackOb.removeClassName('track' + i);
			}
		}
	}	
}

function initSliderList(handleId, trackId, currentRating, url){
		new Control.Slider(handleId, trackId,{
//          		onSlide:function(v){changeSliderTrack(v, trackId);},
          		onChange:function(v){storeSliderValueList(v, currentRating, url);},
          		range:$R(1,5),
        		values:[1,2,3,4,5],
          		sliderValue:3});	
}

function storeSliderValueList(v, currentRating, url) {
      rating = calculateNewRatingValue(v, currentRating);
      if(rating != -11){
      	url = url.replace('xxx', rating);
      	showLoader();
		new Ajax.Request(url, {asynchronous:true, 
      						 evalScripts:true,
      						 onSuccess: function(transport){updateTable('content');},
      						 onComplete: function(){hideLoader();}
      						 });
      }
}

var updateEPGUrl = '/tvguide/channels';
var updateChannelGuideUrl = '/tvguide/channelsUpdate';

function updateEPG(elementId, startTime, filterType, completeRefresh){
	if(currentView == 'myselection'){
			elementId = 'content';
	} else if(currentView == 'EK'){
			elementId = 'content';
	}		
	
	var elementOb = $(elementId);
	if((elementOb != null)){
		if(currentView == 'tvguide'){
			updateEPGUrl = updateEPGUrl_TVGuide;
			updateChannelGuideUrl = updateChannelGuideUrl_TVGuide;
		} else if(currentView == 'myselection'){
			updateEPGUrl = updateEPGUrl_MySelection;
			updateChannelGuideUrl = updateEPGUrl_MySelection; //updateChannelGuideUrl_MySelection;
		} else if(currentView == 'EK'){
			updateEPGUrl = updateEPGUrl_EK;
			updateChannelGuideUrl = updateChannelGuideUrl_EK;
		} else if (currentView = 'minitvguide'){
			var elementOb = $('miniepg');
			updateEPGUrl = updateEPGUrl_MiniTVGuide;
			updateChannelGuideUrl = updateChannelGuideUrl_MiniTVGuide;	
		}		
		if(completeRefresh){
			url = updateEPGUrl + '?';
		} else {
			url = updateChannelGuideUrl + '?';
		}
		if((startTime != null)) {
			url = url +  'starttime=' + startTime + '&';
		} else  if((currentStartTime != null)){
			url = url +  'starttime=' + currentStartTime + '&';	
		} 
		
		if(filterType != null){
			url = url +  'filterType=' + filterType;
		} else  if(currentFilterType != null){
			url = url +  'filterType=' + currentFilterType;	
		} 
		showLoader();
		new Ajax.Request(url, {	asynchronous:true, 
								onSuccess: function(transport){	elementOb.update(transport.responseText);
																if(startTime != null){
																	currentStartTime = startTime;
																}
																showProgramDetails()},
								onComplete: function(){hideLoader();}
								});
	}
	return false;
}

function filterEPG(filterType) {
  if (filterType != currentFilterType) {
  	updateEPG('channelguide', currentStartTime, filterType);
	currentFilterType = filterType;   
  }
}

function filterList(filterType) {
	if (filterType != currentFilterType) {
		if (currentFilterType == 0) {
			if (filterType == 1) {
				if (!((currentSortIndex == 6) && (currentSortOrder == -1))) {
					SortableTable.sort(tableId, (6 + 1), -1);
				}
			} else {
				//filterType = 2
				currentSortIndex = 6;
				currentSortOrder = -1;
				updateTable('content', currentStartTime, filterType);
			}
		} else if (currentFilterType == 1) {
			if (filterType == 0) {
				if (!((currentSortIndex == 9) && (currentSortOrder == 1))) {
					SortableTable.sort(tableId, (9 + 1), 1);
				}
			} else {
				//filterType = 2
				currentSortIndex = 6;
				currentSortOrder = -1;
				updateTable('content', currentStartTime, filterType);
			} 
		} else {
			//currentFilterType = 2
			if (filterType == 0) {
				currentSortIndex = 9;
				currentSortOrder = 1;
				updateTable('content', currentStartTime, filterType);
			} else {
				//filterType = 1
				currentSortIndex = 6;
				currentSortOrder = -1;
				updateTable('content', currentStartTime, filterType);
			}
		}
	currentFilterType = filterType;   
  	}
}

function initOverLabels () {
  if (!document.getElementById) return;  
  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // LABELs with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
	
    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      }

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };


      // Handle clicks to LABEL elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};


function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}

function updateFilter(){
	var url = '';
	if (currentView == 'tvguide'){
		if (currentAction == 'channels'){
			if(currentFilterType == 2){
				currentFilterType = 0;
			}
			url = '/filter/showChannels';
		} else {
			url = '/filter/showPrograms';
		}
	} else if(currentView == 'myselection'){
		if (currentAction == 'channels'){
			url = '/filter/showMyChannels';
		} else {
			url = '/filter/showMyPrograms';
		}
	} else if(currentView == 'EK'){
		if (currentAction == 'channels'){
			url = '/filter/showEKChannels';
		} else {
			url = '/filter/showEKPrograms';
		}
	}
		if (currentFilterType != null){
			url = url + '?filterType=' + currentFilterType;
		}
		new Ajax.Updater('filter', url , {asynchronous:true, evalScripts:true});
}

function fixEPGLayout(element){
	
	var containerOb = $('channelguide');
	var elements = $$('div#channelguide div.channelrow');
	var spacers = $$('div#channelguide div.timerow');      
	
	var nrOfElements = elements.length;
	var nrOfSpacers = spacers.length;
	var j = 0;	
	for(i = 0; i < nrOfElements; i++){
	  if((((i) % 5) == 0) && (j < nrOfSpacers)){
	    containerOb.appendChild(spacers[j]);
            j++;
	  }
	  containerOb.appendChild(elements[i]);
	}
}

var removeUrl = '/myselection/remove?contentid='

function removeMySelectionEPG(contentId){
	if(contentId != null){
	  var url = removeUrl + contentId;
	  showLoader();
	  new Ajax.Request(url, {asynchronous:true, 
      						 evalScripts:true,
      						 onSuccess: function(transport){updateEPG('channelguide');},
      						 onComplete: function(){hideLoader();}
      						 });
    currentDetails = null;
	currentUrl = null;
	currentProgramId = null;
	currentProgramColor = null;
     }	
}

function removeMySelectionList(contentId){
	 if(contentId != null){
	  var url = removeUrl + contentId;
	  showLoader();
	  new Ajax.Request(url, {asynchronous:true, 
      						 evalScripts:true,
      						 onSuccess: function(transport){removeRow(contentId);},
      						 onComplete: function(){hideLoader();}
      						 });
     }	
}

function showLoader() {
	if (semaphore < 1) {
		var loaderOb = $('loader');
		var parentOb = $('loader').up();
		loaderOb.style.display = 'block';
		loaderOb.style.height = parentOb.offsetHeight + 'px';
		loaderOb.style.width = (parentOb.offsetWidth -5) + 'px';
		loaderOb.style.left = parentOb.offsetLeft + 'px';
		loaderOb.style.top = parentOb.offsetTop + 'px';
	}
	semaphore = semaphore+1;
}

function hideLoader() {
	semaphore = semaphore-1;
	if (semaphore < 1) {
		$('loader').style.display = 'none';
	}
}

// Function to show a loader on a given div. The div has to have his own loader defined already.
function showLoaderOnDiv(divId) {
	if (semaphore < 1) {
		var loaderOb = $(divId);
		var parentOb = $(divId).up();
		loaderOb.style.display = 'block';
		loaderOb.style.height = parentOb.offsetHeight + 'px';
		loaderOb.style.width = (parentOb.offsetWidth+1) + 'px';
		loaderOb.style.left = parentOb.offsetLeft + 'px';
		loaderOb.style.top = parentOb.offsetTop + 'px';
	}
	semaphore = semaphore+1;
}

// Function to hide a loader on a given div. The div has to have his own loader defined already.
function hideLoaderOnDiv(divId) {
	semaphore = semaphore-1;
	if (semaphore < 1) {
		$(divId).style.display = 'none';
	}
}

function openFormwindow()
{
	newWindow1 = window.open('/popup.php', 
		'','width=848,height=700,resizable=no,scrollbars=no,toolbar=no,location=no,statusbar=no');
	newWindow1.focus();
}

function refresh(divId, currentUrl) {
	var timelineelement = $('timeline');
	if(timelineelement != null || timelineelement == 'undefined'){
		if (timelineelement.visible()){
			showLoader();
			new Ajax.Updater(divId, currentUrl, {asynchronous:true, evalScripts:true, 
				onComplete:function(request, json){hideLoader();}});
				return false; 
		} 
	}
}

function setTimer(refreshTime, currentUrl, divId){
	var element = $(divId);
	if(element != null || element == 'undefined'){ 
		if (refreshTimeout != null) {
				clearTimeout(refreshTimeout);
				refreshTimeout = setTimeout('refresh("'+ divId +'", "'+ currentUrl +'")', refreshTime);
	
		} else {
				refreshTimeout = setTimeout('refresh("'+ divId +'", "'+ currentUrl +'")', refreshTime);
		}
	}  
}

function selectAll(className){
  var checkboxes = $$('input.' + className);
  checkboxes.each(function(checkbox){
                      checkbox.checked = 'checked';
                    }
                  );
}

function deselectAll(className){
  var checkboxes = $$('input.' + className);
  checkboxes.each(function(checkbox){
                      checkbox.checked = '';
                    }
                  );
}

// Effect for toggling full programdetails
function toggleElement(elementId,elementSwitch,hideLink)
{
    var elementOb = $(elementId);
    var link1 = $(hideLink);
	
    if(elementSwitch == 'off')
    {
		link1.show();
		elementOb.hide();
    }
    else
    {
		link1.hide();
		elementOb.show();
    }
	
    return false;
}

// Effect for toggling full programdetails
function toggleListElement(elementId,elementSwitch,showLink, hideLink)
{
    var elementOb = $(elementId);
    if (hideLink != null)
    {
        var link1 = $(hideLink);
        link1.hide();
    }
	if (showLink != null)
    {
        var link2 = $(showLink);
        link2.show();
    }
	
    if(elementSwitch == 'off')
    {
		elementOb.hide();
    }
    else
    {
		elementOb.show();
    }
	
    return false;
}


function changeDay(divId, day, url)
{
    url = url + "/date/" + day;
    showLoaderOnDiv('loader-'+divId);
    new Ajax.Updater(divId, url, {asynchronous:true, evalScripts:true,onComplete: function(){hideLoaderOnDiv('loader-'+divId);}});
    
}

var oldTipId = null;

// TIPCLASS: Functionality for collapsing all other tips and expanding the right one
function switchTip(tipId)
{
    if (oldTipId != tipId && oldTipId != null && $('program_tip_'+oldTipId) != null)
    {
        toggleListElement('program_tip_'+oldTipId,'off', 'readmore_'+oldTipId, 'readless_'+oldTipId);
    }
    oldTipId = tipId;
    toggleListElement('program_tip_'+tipId,'on', 'readless_'+tipId, 'readmore_'+tipId);
}

function updateElement(elementId, url, params){
	if(typeof(params) != 'object'){
		params = {};
	}
	showLoader();
	new Ajax.Updater(elementId, url, {evalScripts: true, 
									  parameters: params,
									  onComplete: function(){hideLoader();}
									 });
}

function switchHomeMovieClass(divId, classname)
{
    for(x = 0 ; x < 3 ; x++)
    {
        if (x == divId)
        {
            $('homeMovie_'+x).className = classname;
        }
        else
        {
            $('homeMovie_'+x).className = '';
        }
    }
}

function setClassName(elementId, className){
  var element = $(elementId);
  if(element != null && typeof(className) == 'string'){
    if(element.className != className){
      element.className = className;
    }
  }
}

function switchHomeDiv(selectedElement, elements){
  for(i = 0; i < elements.length; i++){
    if(elements[i] != selectedElement){
      var element = $(elements[i]);
      if(element != null && element.visible()){
        $(elements[i]).hide();
      }
    } else {
      var element = $(elements[i]);
      if(element != null && !element.visible()){
        $(elements[i]).show();
      }
    }
  }
}

function expandInformation(infoId, flip, divBase)
{
    if (flip == "on")
    {
        $(divBase+infoId+"_showMore").hide();
        $(divBase+infoId+"_second").show();
        $(divBase+infoId+"_showLess").show();
        Effect.BlindDown(divBase+infoId+"_last", {duration:1});
    }
    else
    {
        Effect.BlindUp(divBase+infoId+"_last", {duration:1});
        $(divBase+infoId+"_showMore").show();
        $(divBase+infoId+"_showLess").hide();
        $(divBase+infoId+"_second").hide();
    }
  	//return false;
}

function addClassNameToElement(elementId, className){
	var elementOb = $(elementId);
	if(elementOb != null && !elementOb.hasClassName(className)){
		elementOb.addClassName(className);
	}
}

function removeClassNameFromElement(elementId, className){
	var elementOb = $(elementId);
	if(elementOb != null && elementOb.hasClassName(className)){
		elementOb.removeClassName(className);
	}
}

function showHourOver(hourId){
	addClassNameToElement("timecell"+hourId, "hour-cell-over");
	if(hourId != 23){
		addClassNameToElement("timecell"+(hourId + 1), "hour-cell-over");	
	}
	
	if(hourId != 22 && hourId != 23){
		addClassNameToElement("timecell"+(hourId + 2), "hour-cell-over");	
	}
}

function hideHourOver(hourId){
	removeClassNameFromElement("timecell"+hourId, "hour-cell-over");
	if(hourId !== 23){
		removeClassNameFromElement("timecell"+(hourId + 1), "hour-cell-over");	
	}
	if(hourId != 22 && hourId != 23){
		removeClassNameFromElement("timecell"+(hourId + 2), "hour-cell-over");	
	}
}

// This function saves the setting on the search page wether the user wants to search only in his own channels
// It enables remembering that setting without actually searching
function switchOwnChannels()
{
    var checkBox = $("ownChannels");
    if (checkBox != null) 
    {
        url = "/search/switchOwnChannels";
        if (checkBox.checked)
        {
            url = url + "/ownChannels/true";
        }
        else
        {
            url = url + "/ownChannels/false";
        }
        new Ajax.Request(url, {asynchronous:true, 
            evalScripts:true}
            );
    }

}

function hideVerticalLoader(groupId)
{
    hideLoader();

}

// CREATE USER FUNCTIONS

// Fucntion for the user create page
function createValidate(field)
{
    if (field == 'gender')
    {
        divId = field+"Check";
        value = $('gender_M').checked || $('gender_F').checked;
        value = urlencode(value);
        url = '/user/checkIcon?field=' + field + '&value=' + value;
        new Ajax.Updater(divId, url, {asynchronous:true, evalScripts:true});
        // Let the image change
        //changeImageGender();
        return true;
    }
    else if (field == 'password2')
    {
        divId = field+"Check";
        value = ($('password1').value == $('password2').value ? 1 : 0);
        if (value == 1 && $('password1').value == "")
        {
            value = 2;
        }
        url = '/user/checkIcon?field=' + field + '&value=' + value;
        new Ajax.Updater(divId, url, {asynchronous:true, evalScripts:true});
        return true;
    }
    var fieldOb = $(field);
    if (fieldOb != null)
    {
        divId = field+"Check";
        value = fieldOb.value;
        value = urlencode(value);
        url = '/user/checkIcon?field=' + field + '&value=' + value;
        new Ajax.Updater(divId, url, {asynchronous:true, evalScripts:true});
    }
}

function changeImageGender()
{
    createValidate("gender");
    imageId = "userImage";
    imageDivId = "userImageDiv";
    gender = $(imageId).src;
    if ($('gender_M').checked)
    {
        gender = gender.replace("female","none");
        gender = gender.replace("none","male");
    }
    if ($('gender_F').checked)
    {
        gender = gender.replace("male","none");
        gender = gender.replace("none","female");
    }
    $(imageDivId).update('<img src="'+gender+'" id="userImage" width="48" height="48">');
}

function highlightRow(row)
{
    rowOb = $(row+'Row');
    if (rowOb != null)
    {
        rowOb.className = 'highlightRow';
    }
    td1Ob = $(row+'Td1');
    if (td1Ob != null)
    {
        td1Ob.className = 'selectedItem-borderL';
    }
    td2Ob = $(row+'Td2');
    if (td1Ob != null)
    {
        td2Ob.className = 'selectedItem-borderR';
    }
}

function unhighlightRow(row)
{
    rowOb = $(row+'Row');
    if (rowOb != null)
    {
        rowOb.className = 'nolightRow';
    }
    td1Ob = $(row+'Td1');
    if (td1Ob != null)
    {
        td1Ob.className = 'signup-table-left';
    }
    td2Ob = $(row+'Td2');
    if (td1Ob != null)
    {
        td2Ob.className = 'signup-table-right';
    }
    createValidate(row);
}

function highlight2Row(row)
{
    rowOb = $(row+'Row');
    if (rowOb != null)
    {
        rowOb.className = 'highlightRow';
    }
    td1Ob = $(row+'Td1');
    if (td1Ob != null)
    {
        td1Ob.className = 'selectedItem-borderT';
    }
    td2Ob = $(row+'Td2');
    if (td1Ob != null)
    {
        td2Ob.className = 'selectedItem-borderB';
    }
}

function unhighlight2Row(row)
{
    rowOb = $(row+'Row');
    if (rowOb != null)
    {
        rowOb.className = 'nolightRow';
    }
    td1Ob = $(row+'Td1');
    if (td1Ob != null)
    {
        td1Ob.className = 'signup-table-top';
    }
    td2Ob = $(row+'Td2');
    if (td1Ob != null)
    {
        td2Ob.className = 'signup-table-bot';
    }
    createValidate(row);
}

function urlencode( str ) {
      var ret = str;
       
      ret = ret.toString();
      ret = encodeURIComponent(ret);
      ret = ret.replace(/%20/g, '+');
      return ret;
}

function fileMessage(message)
{
    $('fileMessage').update(message);
}

function showCurrentProgram(elementId)
{
	var element = document.getElementById(elementId);
    element.scrollIntoView(true);
}

// FUNCTIONS FOR BREADCRUMBS
function resetBreadCrumbs(link)
{
    url = "/user/resetBreadCrumbs";
    new Ajax.Request(url, {asynchronous:true, 
        evalScripts:true,
        onComplete: function(){gotoLink(link);}
        }
        );
}

function gotoLink(link)
{
    this.location.href = link;
}

function trackGoogleAnalytics(location)
{
	pageTracker._trackPageview("/" + location);
}