// 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"));
    }
  });
}

// 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 logOff(){
  user.authUrl = "";
  user.isPro = false;
  user.pushEnabled = false;
  savePref("username","");
  savePref("password","");
  updateChannels();
  showProfile();
}

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 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);
}

function tvguide(){
	// select Just Now
	$("#gotoChannelSelector option:first").attr('selected','selected');
  show('tvguide',"tvguide.php?foo",null);
}

// TODO: this function is "danish"
function niceDate(date){
  // match yyyy-mm-dd
  var match = /(\d{4})-(\d{2})-(\d{2})/.exec(date);
  if(match!=null){
    // remove leading zero of month and date
    var month = match[2].replace(/0(\d)/,"$1");
    var day = match[3].replace(/0(\d)/,"$1")
    var year = match[1];

    var dates = {};
    var d = new Date();
    for(i=0; i<=6; i++){
      if(i==0) name = "today"; 
      if(i==1) name = "tomorrow"
      if(i>=2) name = "day_no_"+d.getDay();
      dates[dateString(d)] = name;
      d.setDate(d.getDate()+1)
    }
    
    if(dates[year+'-'+month+'-'+day]!=undefined){
      // return nice date
      return lang[dates[year+'-'+month+'-'+day]];
    } else {
      // return Danish formatting of date
      // TODO - make configurable
      return day+"/"+month;
    }
  } else {
    // not a date object - return null
    return null
  }
}
// helper function for niceDate
// return date as a string, yyyy-(m)m-(d)d
function dateString(d){
  return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
}

/*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 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();
}

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

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

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 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 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/programinfo/"+programId);
  }
}

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 showPreloader(){
  // Adding a loading icon while we wait for the data
  $("#ontv_content_holder").html($("#preloader").html()).fadeIn();
}

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

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

  // define button functions
  // toggle menu
  $("#categoriesBtn").click(function(){
    submenu ? hideSubmenu() : 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);
    }
  });
}

// Append tag for use with Google Analytics
function analyticsTag(url,platform){
  var append = "utm_medium=widget&utm_campaign=widget&utm_source="+platform;

  if(url.indexOf("?")==-1){
    return url+"?"+append;
  } else {
    return url+"&"+append;
  }
}

function ucfirst(str){
  return str.charAt(0).toUpperCase() + str.substr(1);
}

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

// 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]);
}

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 max(a,b){
  if(a>b) {
    return a;
  } else {
    return b;
  }
}

function min(a,b){
	if(a<b) {
		return a;
	} else {
		return b;
	}
}


