function changeMainMenuNav(sex_filter){
  setCurrentPageNb(1);
  $('#cams').html(getLoaderHtml());
  $.get(ajax_url,
    {
      task: 'setSexPref',
      sex_filter: sex_filter
    },function(data){
      var response = JSON.parse(data);
      if(response.result == true)
         var values = new Array();
         values.push(sex_filter);
         checkSearchValues('category',values); // laat de category checkboxes volgen
         // als de pagina profiel is; redirect dan naar de main page
         if(getCurrentPage() == 'profile'){
           window.location = base_url;
         }else{
           reloadCams();
         }
         
    });
}

function resetToDefault(){
  $('#cams').html(getLoaderHtml());
  $.get(ajax_url,
    {
      task: 'resetToDefault'
    },function(data){
      var response = JSON.parse(data);
      if(response.result == true)
         window.location= base_url;         
    });
}

function checkSearchValues(id,values){

  $('ul#'+id+' li input').attr('checked',false); // zet alle checkboxes op unchecked
  
  $('ul#'+id+' li input').each(function(idx,el){
    if( $.inArray($(this).val(),values) != -1 ){
      $(this).attr('checked',true);
      $('div#'+$(this).attr('id')+'_image').removeClass('checkbox_unchecked');
      $('div#'+$(this).attr('id')+'_image').addClass('checkbox_checked');
    }else{
      $('div#'+$(this).attr('id')+'_image').removeClass('checkbox_checked');
      $('div#'+$(this).attr('id')+'_image').addClass('checkbox_unchecked');
    }    
  });
}

var reloadCamsRequest = null;

function reloadCams(loader){
  if(reloadCamsRequest != null){
    reloadCamsRequest.abort();
  }
    
  
  // haal gegevens op
  last_refresh = getTimestamp();
  
  // haal page op 
  if(loader == true)
  $('#cams').html(getLoaderHtml());
  
  reloadCamsRequest = $.get(ajax_url,
    {
      task: 'reloadCams',
      size: getCurrentSize(),
      pagenb: getCurrentPageNb()
    },function(data){
      try{
        var response = JSON.parse(data);
        if(response.result == true)
          $('#cams').html(response.html);
      }catch(e){
        return false;
      }
      return false;
    });
}

function doNicknameSearch(search_value){
  $('#cams').html(getLoaderHtml());
  
   $.get(ajax_url,{
     task: 'nicknameSearch',
     values: search_value
   },function(data){
     if(getCurrentPage() == 'profile'){
        window.location = base_url;
      }
     setCurrentPageNb(1);
     reloadCams();
   });
}

function toggleFavorite(el){
  var element = $(el);
  var account = $(el).attr('alt');
  
  if(element.attr('src').indexOf(fav_on) != -1){
    element.attr('src',fav_off);
    removeFromFavorites(account);    
  }else{
    element.attr('src',fav_on);
    addToFavorites(account);
  }
}

function removeFromFavorites(account){
  // verwijder via webservice; verwijder uit pagina array; verwijder cam object
  jQuery.getJSON("http://cams.dnxlive.com/webservices/gateway.php?task=removeFromFavorites&account=" + account + "&jsoncallback=?");
  var favorites = getFavoritesArray();
  var idx = $.inArray(account,favorites);
  favorites.splice(idx,1);
  setFavoritesArray(favorites);
  $("#favorites_wrapper").find('#'+account).remove(); // verwijder uit favorieten
  $('body').find('.tipsy').remove(); // tipsy tooltips bleven staan
  $('#'+account+' .icons li img.icon_fav').attr('src',fav_off); // maak hartje weer grijze
  $('#profile_favorite').attr('src',fav_off); // en ook het hartje als je in profiel view zit
}

function addToFavorites(account){
  jQuery.getJSON("http://cams.dnxlive.com/webservices/gateway.php?task=addToFavorites&account=" + account + "&jsoncallback=?");
  var favorites = getFavoritesArray();
  favorites.unshift(account); // verwijder account uit de array
  setFavoritesArray(favorites); // stel de favorites array in (globaal)
  refreshFavoritesBox(); // refresh de favorieten box
}

function syncDnxliveFavorites() {
  
  jQuery.getJSON("http://cams.dnxlive.com/webservices/gateway.php?task=getAllPreferences&scope=favorites&jsoncallback=?", 
  function(data) {
    if($.isArray(data.favorites)) {
      setFavoritesArray(data.favorites);
      refreshFavoritesBox();
      setProfileFavorite(); // in profiel view, maak hartje roos
      $.each(data.favorites, function(i, cammer) {
        $('#'+cammer+' img.icon_fav').attr('src',fav_on);
      });
    }
  });

}

function setProfileFavorite(){
  var favorites_array= getFavoritesArray();
  if($.inArray($('#profile_favorite').attr('alt'),favorites_array) != -1)
    $('#profile_favorite').attr('src',fav_on);
}

function refreshFavoritesBox(){
  var favorites = getFavoritesArray().join('-');
  $.get(ajax_url,{
    task: 'getFavorites',
    favorites: favorites
  },function(data){
    var response = JSON.parse(data);
    if(response.result == true){
      $('#favorites').html(response.html);
    }
  });
}

function setTooltips(){

 $('#wrapper img.icon_fav').tipsy({
   live: true,
   opacity: 1,
   title: function(){
     if($(this).attr('src').indexOf(fav_on) != -1)
      return remove_favorite_tooltip;
    else
      return add_favorite_tooltip;
   }
  });
  
  $('#wrapper img.icon_profile').tipsy({
    live: true,
    opacity: 1,
    title: function(){
      return view_profile_tooltip;
    }
  });
  
  $('#wrapper img.icon_video.active').tipsy({
    live: true,
    opacity: 1,
    title: function(){return videos_tooltip;}
  });
    
  $('#wrapper img.icon_audio.active').tipsy({
    live: true,
    opacity: 1,
    title: function(){return audio_tooltip;}
  });
  
  $('#wrapper img.icon_video.inactive').tipsy({
     live: true,
     opacity: 1,
     title: function(){return no_videos_tooltip;}
   });

   $('#wrapper img.icon_audio.inactive').tipsy({
     live: true,
     opacity: 1,
     title: function(){return no_audio_tooltip;}
   });
   
   $('#sidebar #force_search,#sidebar #search_nickname_clear').tipsy({
      live: true,
      opacity: 1
    });
  
  
  $('#wrapper div.rate_score').tipsy({
    live: true,
    opacity: 1
  });
  
  $('#profile_top .profile_nav_prev,#profile_top .profile_nav_next,#profile_top .profile_nav_all_cams, #profile_top .profile_close').tipsy({
    live: true,
    opacity: 1
  });
}

function startChat(account,subservice) {
  if(subservice === undefined)
    url = '/out.php?service=' + account;
  else
    url = '/out.php?service=' + account + '&subservice='+subservice;
  
  if(!flash_supported) {
    window.location = url;
    return false;
  }
  features = 'scrollbars=1,resizable=1,menubar=0,toolbar=0,location=0,status=0,top=0,left=0,screenX=0,screenY=0,';
  if (window.screen) {
    aw = screen.availWidth;
    ah = screen.availHeight;
    features = features + 'width=' + (aw-20) + ',height=' + (ah-55);
  }
  else {
    features = features + 'width=' + width + ',height=' + height;
  }
  window.open(url, 'auth', features);
  return false;
}

function showDisclaimer(url) {
  window.open(url, 'disclaimer', 'toolbar=no,menubar=no,scrollbars=yes,status=no,resizable=auto,width=625,height=600'); 
  return false;
}

function refreshSnapshot(){
   if(!$('#profile_preview').hasClass('online'))
    return false;
    
   var id = '#profile_snapshot';
   d = new Date();
   var filename =  $(id).css("background-image").split('?');  
   filename = filename[0].replace(/"/g,"").replace(/url\(|\)$/ig, "");  
   filename = filename.split('?');  
   filename = filename[0]+'?'+d.getTime() ;
   $(id).css("background","url("+filename+")");
   return true;
 }
 
 
var last_refresh = getTimestamp();
var has_focus = true;
var timer_id;

//Wordt opgeroepen wanneer de pagina focus krijgt of verliest
function pageFocus(bool) {
  if(bool)
    has_focus = true;
  else
    has_focus = false;
}

//We gaan een timer starten die de pagina automatisch gaat refreshen
$(document).ready(function() {
  timer_id = setInterval("checkPageReload()", 5000);
  //om de 15 minuten volledige page refesh om sessie actief te houden
  setInterval("refreshPage()", 15*60*1000);
});

function refreshPage() {
  location.reload(true);
}

//Deze functie wordt om de 5 seconden opgeroepen, en gaat nakijken dat de pagina gerefreshed moet worden
function checkPageReload() {

  var now = getTimestamp();
  //Als de snapshots ouder zijn dan 1 minuut gaan we refresh doen
  if(now > (last_refresh + 60))
    reloadCams(true);
}
 

function getLoaderHtml(){
  return '<div id="loader"><img src="/images/ajax-loader-bar.gif" /></div>';
}

function setFavoritesArray(favorites){
  favorites_array = favorites;
}

function getFavoritesArray(){
  return favorites_array;
}

function getCurrentSize(){
  return current_size;
}

function setCurrentSize(ncurrent_size){
  current_size = ncurrent_size;
}

function getCurrentPageNb(){
  return current_pagenb;
}

function setCurrentPageNb(ncurrent_pagenb){
  current_pagenb = ncurrent_pagenb;
}

function getCurrentPage(){
  return current_page;
}

function getTimestamp() {
  return Math.floor(new Date().getTime()/1000);
}

function popupWindow(url, w, h){
  var middleLeft = 400 - w;
  var middleTop = 10;
        
  if (window.screen) {
    middleLeft = (screen.availWidth / 2) - (w / 2);
  }
		          
   window.open(url, '', 'scrollbars=1,resizable=0,menubar=0,toolbar=0,location=0,status=0,top='+middleTop+',left='+middleLeft+',width='+w+',height='+h);
}

function setDisclaimerCookie(session_id) {
  $('.disclaimer_bg').hide();
  $('.disclaimer_wrapper').hide();
  createCookie("dp", session_id, cookie_expire_time, cookie_domain);
  return false;
}

//We gaan de hoogte van de grijze disclaimer achtergrond aanpassen
function updateDisclaimerHeight() {
  if($(".disclaimer_bg").length > 0) {
    $('.disclaimer_bg').height($(document).height());
  }
}

//Cookie zetten
function createCookie(name, value, expire_time, domain) {
  var date = new Date();
  date.setTime(date.getTime()+(expire_time * 1000));
  document.cookie = name + "=" + escape(value) + "; expires=" + date.toGMTString() + "; path=/; domain=" + escape(domain);
}

//Show Preview Stream
var active_previews = new Array();
function addPreviewListeners(account) {
   if($("#t_"+account).length > 0) {
     $("#t_"+account).bind(
       "mouseenter",
         function(event) {
           var arr = this.id.split("_");
           var account = arr[1];
           if($('#teaser_'+account).length == 0) {
             $('#t_'+account).append('<div id="teaser_'+account+'"></div>');
           }
           $.each(active_previews, function(index, val) {
             swfobject.removeSWF("teaser_"+val);
           });
           if($.inArray(account, active_previews) < 0) {
             active_previews = new Array();
             active_previews.push(account);
             var width = $('#t_'+account).width();
             var height = $('#t_'+account).height();
             var teaser_flashvars = { gateway: amf_gateway };
             var teaser_params = { wmode: "transparent", allowScriptAccess: "sameDomain"};
             var teaser_attributes = {};
             var account_flashvars = teaser_flashvars;
             account_flashvars["account"] = account;
             swfobject.embedSWF(base+"swf/live_preview_public.swf", 'teaser_'+account, width, height, "9.0.0", "swf/expressInstall.swf", account_flashvars, teaser_params, teaser_attributes);
             $('#teaser_'+account).addClass('teaser_stream');
           }
         }
     );
     $("#t_"+account).bind(
       "mouseleave",
         function(event) {
           var arr = this.id.split("_");
           var account = arr[1];
           hidePreview(account);
         }
     );
   }
 }
 function hidePreview(account) {
   active_previews = $.grep(active_previews, function(val) { return val != account; });
   swfobject.removeSWF("teaser_"+account);
 }
