var submenu;
var lang;
var user;

function loggedIn(){
  return user.authUrl!="";
}

function showError(message){
  // TODO - translate
  window.scrollTo(0, 1);
  $("#errorMessage").hide().html('<p style="text-align:center;">'+message+'</p>').fadeIn();
}

function showConfirm(message){
  // TODO - translate
  var result = TrimPath.processDOMTemplate("confirmTemplate",{"message":message});

  $("#ontv_content_holder").hide().html('<p style="text-align:center; margin-top:15px;">'+result+'</p>').fadeIn();
}

// showSubmenuAllowChangeHeightOnContent
var showSubmenuAllowChangeHeightOnContent = true;
function showSubmenu(){
  if(showSubmenuAllowChangeHeightOnContent) {
    $("#ontv_content_holder").animate( {height: $("#ontv_content_holder").height() - 100});
  }
  $("#ontv_submenu_holder").animate( {height: 92},
    {
      complete:function(){
        $("#ontv_submenu_holder").show();
      }
    }
  );
  submenu = true;
}

function hideSubmenu(){
  if(submenu) {
    if(showSubmenuAllowChangeHeightOnContent) {
	  $("#ontv_content_holder").animate( {height: $("#ontv_content_holder").height() + 100});
	}
	  $("#ontv_submenu_holder").animate( {height: 0},
	    {
	      complete:function(){
	        $("#ontv_submenu_holder:visible").hide();
	      }
	    }
	  );
	  submenu = false;
  }
}

function showPreloader(){
  // Adding a loading icon while we wait for the data
  $("#ontv_content_holder").html($("#preloader").html()).fadeIn();
}

// adjust to size of tvguide
function adjustHeight(val){
  if(val==-1) {
    return; // doesn't support resizing
  }
  savePref("height",val);
  
  var slack = 20;
  var heights = [cssDimensions.minY,
    cssDimensions.normalY,
    cssDimensions.maxY,
    min(tvguideHeight+cssDimensions.contentWindowDiff+slack,cssDimensions.maxY)];
  resize(window.innerWidth,heights[val]);
}

// populate and show a section
function show(id,url,postProcess){
  hideSubmenu();

  // Stores old data if it should be used again
  preloadOldContent = $("#ontv_content_holder").html();

  showPreloader();

  $.getJSON(urls.api+url+user.authUrl+"&callback=?",
  function(data){
    if(data.action && data.action.result=="ERROR"){
	    $("#ontv_content_holder").hide().html(preloadOldContent).fadeIn();
      showError(lang.must_be_logged_in);
      return;
    }
    if(postProcess){
      data = postProcess(data);
    }
    
    // get template(s) from html doc
    var result = TrimPath.processDOMTemplate(id+"Template",data);
    // expand template and replace
    $("#ontv_content_holder").hide().html(result).fadeIn();
    // holder for error messages
    $("#ontv_content_holder").prepend("<div id='errorMessage' style='display: none;'></div>");
    // Append class odd to all odd elements of type li and tr
    $('#ontv_content_holder li:even, #ontv_content_holder tr:even').addClass('odd');

    // only do version check once per run
    if(doVersionCheck){
      checkVersion();
      doVersionCheck = false;
    }
    
    // TODO: special case, not nice
    if(id=='tvguide'){
      tvguideHeight = ($("#channel_holder").height()>0)?$("#channel_holder").height():tvguideHeight;
      adjustHeight(loadPref("height"));
    }
  });
}

function updateChannels(){
    // fetch channel names
  $.getJSON(urls.api+"channels.php?foo"+user.authUrl+"&callback=?",function(data){

    // get template from html doc
    var result = TrimPath.processDOMTemplate("channelSelectorTemplate",data);
    // expand template and replace
    $("#goToChannelSelector").html("<option value='0'>"+lang.right_now+"</option>");
    $("#goToChannelSelector").append(result);
    
  });
}

function logIn(username,password,onSuccess,onError){
  $.getJSON(urls.api+"user.php?username="+username+"&password="+password+"&callback=?",
  function(data){
    if(data.action && data.action.result=="ERROR"){
      // reset session
      user.authUrl = "";
      onError();
    } else {
      // save to persistent layer (platform specific)
      savePref("username",username);
      savePref("password",password);
      
      // 1-1 correspondance
      user = data;
      
      // save for this session
      user.authUrl = "&username="+username+"&password="+password;
            
      onSuccess();
    }
    // update channel list
    updateChannels();
    
  }
);
}

function showProfile(){
  // try to get from persistent mem
   logIn(loadPref('username'),loadPref('password'),
     // on success, show profile
     function(){
       var data = { "profile" : { "username" : loadPref("username") }};
       var result = TrimPath.processDOMTemplate("profileTemplate",data);
       $("#ontv_content_holder").hide().html(result).fadeIn();
     },
     function(){
       // on error, show login-box
       var result = TrimPath.processDOMTemplate("loginTemplate",{});
       // expand template and replace
       $("#ontv_content_holder").hide().html(result).fadeIn();
       // holder for error messages
       $("#ontv_content_holder").prepend("<div id='errorMessage' style='display: none;'></div>");
       // Append class odd to all odd elements of type li and tr
       $('#ontv_content_holder li:even, #ontv_content_holder tr:even').addClass('odd');          
     }
   );
}

function logOff(){
  user.authUrl = "";
  user.isPro = false;
  user.pushEnabled = false;
  savePref("username","");
  savePref("password","");
  updateChannels();
  showProfile();
}

function submitLogin(){
  logIn($("#email").val(),hex_md5($("#password").val()),
    // if we log in, update pro-status and show profile
    showProfile,
    function(){
      // if not, show an error
      showError(lang.invalid_user_pass);
    });
}

function category(type){
  show('category',"category.php?type="+type,markJustEnded);
}

function tvguide(){
	// select Just Now
	$("#gotoChannelSelector option:first").attr('selected','selected');
  show('tvguide',"tvguide.php?foo",null);
}
/*var mouseOverDelete = false;
function fadeBetween(state,from,to) {
	console.log('my state: '+state +' and existing state: '+mouseOverDelete);
	if(mouseOverDelete != state) {
		$(from).fadeToggle('fast');
		$(to).fadeToggle('fast');
		mouseOverDelete = state;
		console.log('DO IT');
	}
}*/

function addToCalendar(id){
  $.getJSON(
    urls.api+"action.php?action=addToCalendar&program="+id+user.authUrl+"&callback=?",
    function(data){
      if(data.action.result=="ERROR"){
        showError(data.action.message);
      } else {
        showConfirm(lang.program_added_to_calendar+'<br><br><a href="javascript:showProgram('+id+');">'+lang.go_to_program_info+'</a><br><a href="javascript:tvguide();">'+lang.go_to_tvguide+'</a>');
      }
    }
  );
}

function addReminder(id){
  var minutesBefore = $("#minutesBefore").val();
  var type = $("#reminderType").val();
  $.getJSON(
    urls.api+
    "action.php?action=addReminder&program="+id+"&minutesBefore="+minutesBefore+"&type="+type+
    user.authUrl+"&callback=?",
    function(data){
      if(data.action.result=="ERROR"){
        showError(data.action.message);
      } else {
        showConfirm(lang.reminder_created+'<br><br><a href="javascript:showProgram('+id+');">'+lang.go_to_program_info+'</a><br><a href="javascript:tvguide();">'+lang.go_to_tvguide+'</a>');
      }
    }
  );
}

function appendDates(data){
  // append next 7 dates
  var dates = [];
  var d = new Date();
  for(i=0; i<=13; i++){
    dates[i] = d.defaultView();
    d.setDate(d.getDate()+1);
  }
  data.dates = dates;
  return data;
}

function goToChannel(i) {
  // Loads today's schedules for the selected channel i
  if(i===0){
    tvguide();
  } else {
    show("channel","channel.php?id="+i,appendDates); 
  }
  document.getElementById('goToChannelValue').innerText = 
  document.getElementById('goToChannelSelector').options[
  document.getElementById('goToChannelSelector').selectedIndex
  ].innerText;
}


function showProgram(programId){
  if(user.isPro){
    // open i widget/gadget
    show("program","program.php?id="+programId);
  } else {
    // open link externally (platform dependant)
    extLink("http://ontv.dk/info/"+programId);
  }
}

function translateHtml(){
  // translate html
  var key;
  for(key in lang_html){
    if($("#lang_"+key).length>0){
      // append lang_ to element id
      $("#lang_"+key).html(lang_html[key]);
    } else {
      // dont
      $("#"+key).html(lang_html[key]);
    }
  }
}

function addListeners(){
  $("#tvguideBtn").click(tvguide);

  // define button functions
  // toggle menu
  $("#categoriesBtn").click(function(){
    if (submenu){
      hideSubmenu();
    } else {
      showSubmenu();
    }
  });

  $("#remindersBtn").click(function(){
    if(loggedIn()){
      show("reminders","reminders.php?");
    } else {
      showError(lang.must_be_logged_in);
    }
  });

  $("#profileBtn").click(showProfile);

  $("#calendarBtn").click(function(){
    if(loggedIn()){
      show("calendar","calendar.php?");
    } else {
      showError(lang.must_be_logged_in);
    }
  });
}

function markJustEnded(data){
  var now = new Date().getTime()/1000; // timestamp, seconds
  for(var c=0; c < data.category.channel.length; c++){
      for(p=0; p<data.category.channel[c].programs.length;p++){
        data.category.channel[c].programs[p].program.justEnded = 
        (data.category.channel[c].programs[p].program.endTime<now);
      }
  }
  return data;
}

function renderHeightPrefs(){
  if(loadPref("height")!=-1){
    var names = [lang.minimum,lang.normal,lang.maximum,lang.adapted_to_tvguide];
    var heights = [];
    for(var i=0;i<names.length;i++){
      heights[i] = {
        val: i,
        name: names[i],
        checked: (i==loadPref("height"))?"checked":""
      };
    }
    return TrimPath.processDOMTemplate("heightPrefsTemplate",{heights: heights});
  } else {
    return "";
  }
}

function showOptional(descriptor,value){
  if(value!="" && value!==undefined) {
    return "<p>"+descriptor+": "+value+"</p>";
  }
  return "";
}

function translate(key){
  return lang[key]!==undefined?lang[key]:key;
}


