$(document).ready(function() {
  
  
  if (!window.console)  {
      window.console =  {
      debug: function( o )  {
      alert( o );
      }
      }
  }
  
 
  $(".exercise_textfield").focus(function () {
    // remove disaable attr if a text area gets focus
    $("#save_changes_program").removeAttr("disabled");
  });
  
  $("#program_textarea").focus(function () {
    // remove disaable attr if a text area gets focus
    $("#save_changes_program").removeAttr("disabled");
  });
  
  
  /* ************** disable submit buttom after first click ********/
  $("#submit_create_account").click(function(){
    $(this).attr("disabled", "disabled");
    $("#content form").submit();
  });
  
  
  /* Mark exercise as favourite */
  $(".favourite").click(function(){    
    return markAsFavourite($(this).attr("id"));    
  });
  
    /* Mark exercise as favourite */
  $(".no_favourite").click(function(){
    return unmarkAsFavourite($(this).attr("id"));
  });
  
  /* Select favourites option */
  $("#option_fav").click(function(){
    return selectViewOption("fav");
  });
  
  /* Select favourites option */
  $("#option_all").click(function(){
    return selectViewOption("all");
  });
  
  
  /* TOOL TIP *******************************************************/
  
  
  /* AUTOCOMPLETE ****************************************************/
  var exercise_array = "/program/autocomplete/sp/";
  var site_url = document.location.href;
  if(site_url.indexOf("/tennis") >= 0){
   var exercises_array = "/program/autocomplete/tennis/";
  }
  else{
    var exercises_array = "/program/autocomplete/sp/";
  }
  
  // autocomplete search
  $("#sok").autocomplete(exercises_array, {
    minChars: 2,
    max: 100,
    autoFill: false,
    mustMatch:false,
    delay:200,
    cacheLength:10,
    scrollHeight: 220,
    matchContains:true,
    formatItem: formatItem,
    formatResult: formatResult,
    formatMatch: formatMatch,
    selectFirst:false
  }).result(function(event, data, formatted) {
      // submit form when value is choosen in drop down list
      $("#sok").parent().submit();
   }); 
  
  // autocomplete search
  $("#sok_ovningsarkiv").autocomplete(exercises_array, {
    minChars: 2,
    max: 100,
    autoFill: false,
    mustMatch:false,
    delay:200,
    cacheLength:10,
    scrollHeight: 220,
    matchContains:true,
    formatItem: formatItem,
    formatResult: formatResult,
    formatMatch: formatMatch,
    selectFirst:false
  }).result(function(event, data, formatted) {
      // submit form when value is choosen in drop down list
      $("#sok_ovningsarkiv").parent().submit();
   }); 
   

  /* AUTOCOMPLETE END ****************************************************/


     // hide video pagination if javascrip is enabled (vidoes loaded with ajax)
     $("#video_pagination").css("display", "none");
     
     $(".colorbox").colorbox();
     
     
     /******** Övningsarkiv spela liten video *********/
     
     // play small video
    $(".small_video").click(function(){
      return playSmallVideo($(this).attr("id"));
    });
   
     
     /********* Övningsarkiv - automatic scoll *********/     

     // if we are on ovningsarkiv page and view = video
     if($("#videos").length > 0){
       $(window).scroll(function(){
         var current_scroll_pos = $(window).scrollTop();
         //alert("current:"+current_scroll_pos+" last:"+ last_scroll_pos);
           //var scroll_margin = $(document).height() / 10;
           var scroll_margin = 450;
           //if($(window).scrollTop() == $(document).height() - $(window).height() && get_videos)
           // if scroller at right pos && user scrolls down (not up) && previous request is finished, to load videos even if scrollbar isn'n at bottom
            if  (($(window).scrollTop() + scroll_margin  >= $(document).height() - $(window).height()) && (last_scroll_pos < current_scroll_pos) && get_videos)
            {
              //console.debug("get_videos=" + get_videos);  
              get_videos = false;
              //$("#videoLoader").css("display", "block");
              //$("#videoLoader").css("top", current_scroll_pos);              
                 lastPostFunc();
                 //$("#videoLoader").css("display", "none");   
            }
         last_scroll_pos = $(window).scrollTop();
    });
     }
     
     // see if to print loading videos at the end of the list.
     if($("#videos").length > 0){
       var total_nr_exercises = $("#nr_of_exercises").text();
       var limit = $("#limit").text();
       var diff = total_nr_exercises - limit;
       appendVideoLoaders("videos", diff);
     }
     
          
     /********** Program *******/ 
     
     // remove exercise from program
     $("#program ul .remove_exercise").click(function () { 
      return removeFromProgram($(this).parent().attr("id"));
    });
    
    // add exercise to program
    $("a.add_exercise").click(function () { 
        return addExerciseToProgram(this);
    });
    
    // sort exercises
    $("#program ul").sortable({ 
      containment: '#program ul',
      tolerance: 'pointer',
      //jQuery UI 1.5.3 is only compatible with jQuery 1.2.6. In order to use jQuery UI with jQuery 1.3+, you'll need the latest preview release1.6rc6. It is compatible with 1.3 (but not 1.2.6), and the final release is scheduled for tonight. See
      // call updateProgram to update db and set session when dragging stops
      update: function(event, ui) { updateProgram(); }
      });
      
    // change program name
    $("#change_program_name").click(function(){
      return changeProgramName();
    });
    
    // delete program
    $("#delete_program").click(function(){    
      return deleteProgram();
    });
    
    // add program
    $("#add_program").click(function(){    
      return addProgram();
    });
    
    // edit saved program
    $("#saved_programs ul li a").click(function(){
      return editSavedProgram($(this).parent().parent().attr("id"));
      //alert($(this).parent().attr("id"));
      //return false;
    });
    
    // add made program
    $(".made_program").click(function(){
      // get id ("made_program_XXX")
      return addMadeProgram($(this).attr("id"));
    });
    
    
    // save program text
    $("#save_changes_program").click(function(){    
      return saveProgramInfo();
    });
     

});

/* ONREADY END */

/* ******** FUNCTIONS ********** */

function markAsFavourite(ex_id){
  var id = ex_id.substring(22);
  //console.debug(id);
  
  // make ajax request
  $.ajax({
    type: "GET",
    url: "/program/mark_favourite/"+id,
    cache:false
  });
  
  $("#"+ex_id+" img").attr("src", "/images/icons/favorites_16.gif");
  $("#"+ex_id).attr("class", "no_favourite");
  $("#"+ex_id).attr("title", "Ta bort övningen från dina favoriter");
  $("#"+ex_id).unbind().click(function(){
    return unmarkAsFavourite($(this).attr("id"));
  });    
  
  return false;
}

function unmarkAsFavourite(ex_id){
  var id = ex_id.substring(22);
  //console.debug(id);
  
  // make ajax request
  $.ajax({
    type: "GET",
    url: "/program/unmark_favourite/"+id,
    cache:false
  });

  $("#"+ex_id+" img").attr("src", "/images/icons/favorites_unmarked_16.gif");
  $("#"+ex_id).attr("class", "favourite");
  $("#"+ex_id).attr("title", "Markera övningen som en favorit");
  $("#"+ex_id).unbind().click(function(){
    return markAsFavourite($(this).attr("id"));
  });    
  
  return false;
}


/* *** Autocomplete *** */
function formatItem(row, position, n, term) {
        return row[0];
  }
    
function formatResult(row) {
    return row[0];
}

function formatMatch(row) {
    return row[0];
}
  

function saveProgramInfo(){

  var parameters = "";
      
  // exercise text
  var exercise_textfield_array = $(".exercise_textfield");
  
  for(var i = 0; i < exercise_textfield_array.length; i++){    
    var exercise_id_long = $(exercise_textfield_array[i]).attr("id");
    var exercise_text = $(exercise_textfield_array[i]).attr("value");
    // remove additional text "datetextarea" from date_long
    var exercise_id = exercise_id_long.substr(18);
    //alert(exercise_id);    
    // add values to the hdden form attributes
    if(i == 0){
      parameters = parameters + exercise_id+"="+encodeURIComponent(exercise_text);
    }
    else{
      parameters = parameters + "&"+exercise_id+"="+encodeURIComponent(exercise_text);  
    }

  }
  
  // program text
  var program_textfield_value = $("#program_textarea").attr("value");
  // save program text to print div
  $("#program_text_print").html("<h2>Egna anteckningar</h2><p>" + program_textfield_value.replace(/\n\r?/g, '<br />') + "</p>");

  if(i == 0){
    parameters = parameters + "program_info=" + encodeURIComponent(program_textfield_value);
  }
  else{
    parameters = parameters + "&program_info=" + encodeURIComponent(program_textfield_value.replace(/\n\r?/g, '<br />'));
    
  }
  
  //console.debug(parameters);
  //alert(parameters);
  $.ajax({
     type: "GET",
     url: "/program/save_program_info/",
     cache:false,
     data:parameters,
     success: function (data, textStatus) {
       var data = parseXml(data);
       $("#save_changes_program").attr("disabled", "disabled");
    }
  });
  
  return false;
}


  /******* play small video ********/
  function playSmallVideo(ex_id){    
    var id = ex_id.substring(9);
    var s1 = new SWFObject("/js/player.swf","player","200","160","8","#FFFFFF");
      s1.addParam("allowfullscreen","true");
      s1.addParam("allowscriptaccess","always");
      
      //s2.addParam("flashvars","skin=modieus/stylish.swf&file=small/flashvideo_exercise_158.flv&image=small/thumbnail_1_exercise_158.jpg&mute=true&bufferlength=3&logo=watermark-small.png&controlbar=none&stretching=exactfit");
      
      s1.addParam("flashvars","skin=/js/modieus/stylish.swf&file=http://movies.styrkeprogrammet.se/flash_video/flashvideo_exercise_"+id+".flv&image=http://movies.styrkeprogrammet.se/exercise_thumbnails_420x336/thumbnail_1_exercise_"+id+".jpg&mute=true&bufferlength=5&logo=/js/watermark-small.png&controlbar=none&autostart=true&stretching=exactfit");
      s1.write(ex_id);
  }
  
  
  /* special function for IE to be able to parse xml*/
  function parseXml(xml) {
    if (jQuery.browser.msie) {
      var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.loadXML(xml);
      xml = xmlDoc;
    }
    return xml;
  }
  
  /******* Load data when scrolling ********/
  
  // global var for scrolling function
  var last_scroll_pos = 0;
  var get_videos = true;
  
  // this function is called when ajax call to load more exercises i ready - this is to disable the possibility to make many ajax calls before the one before is finished which cause the same exercises to load again.
     function load_videos_true(){
        get_videos = true;  
     }
     
  function lastPostFunc()
  { 
    // get last exercise loaded in the current selection
    var last_video_id = $(".hit_grid:last .add_exercise").attr("id");
    last_id = last_video_id.substring(12);
    var muscle_group_param = $("#muscle_group_param").text();
    var category_param = $("#category_param").text();
    var level_param = $("#level_param").text();
    var limit = $("#limit").text();
    //alert(last_id);
    
    /*
         // play small video
    $(".small_video").click(function(){
      return playSmallVideo($(this).attr("id"));
    });
    */
     $.ajax({
       type: "GET",
       url: "/program/load_more_videos/"+last_id+ "/" + limit + "/" +muscle_group_param+ "/" +category_param + "/" + level_param,
       cache:false,
       success: function (data, textStatus) {
           
           var data = parseXml(data);
           
           //alert(data);
           //console.debug($("exercise", data).length);
            /*alert($("exercise", data).length);*/
            
            if ($("exerciseExist", data).text() == "true") {
               
            var html = "";
            
            $("exercise",data).each(function(){
                            
              html += "<div class=\"hit_grid\">" + 
              "<h3>" + 
              "<a href=\"/program/add_exercise/"+$(this).find("id").text()+"\" title=\""+$(this).find("exerciseName").text()+"\" id=\"exercise_id_"+$(this).find("id").text()+"\" class=\"add_exercise\">" + 
              "<img src=\"/images/icons/add_16.gif\" alt=\"Lägg till\" class=\"icon_add\"/>" + 
              "</a>" +
              "<a title=\"Läs mer om "+$(this).find("exerciseName").text()+"\" rel=\""+$(this).find("exerciseName").text()+"\" href=\"/ovningsarkiv/"+$(this).find("id").text()+"\" class=\"exercise_name\">"+$(this).find("exerciseName").text()+"</a>" + 
              "</h3>"+
              "<a class='smallmovie movie_"+last_id+"'" +
              "  href='http://movies.styrkeprogrammet.se/mp4-420x336/"+$(this).find("id").text()+".mp4'"+
              "  style='background-image:url(http://movies.styrkeprogrammet.se/exercise_thumbnails_200x160/thumbnail_1_exercise_"+$(this).find("id").text()+".jpg)'>"+
              "  <img src='/js/play.png' class='play' alt='Play' />"+
              "</a>"+
              "</div>"; 
            });
            
           
            // remove current loaders
         $("#videos .hit_grid_loader").remove();
         
          // add html for new videos
          $("#videos").append(html);
            
          flowplayer("a.movie_"+last_id, "/js/flowplayer/flowplayer.commercial-3.2.5.swf", {
            key: conf.key, 
            logo: conf.logo, 
            plugins: conf.plugins, 
            play: conf.play, 
            clip: { scaling: "fit" }
          }).ipad;
          
          //de-activate add exercise on click
          $("a.add_exercise").unbind("click");
          
          //activate add exercise on click
          $("a.add_exercise").click(function () { 
              return addExerciseToProgram(this);
          });
          
            
            // add new loaders if neccesary
            var total_showed = $("totalshowed", data).text();
            var total_nr_exercises = $("#nr_of_exercises").text();
            
           var diff = total_nr_exercises - total_showed;
           appendVideoLoaders("videos", diff);      
          }
          
          load_videos_true();
       }
     });
       
    /*
      $.get("/program/load_more_videos/"+last_id+ "/" + limit + "/" +muscle_group_param+ "/" +category_param + "/" + level_param, function(data){     
          if (data != "") {
            
            var html = "";
            
            $("exercise",data).each(function(){
              
              
              html += "<div class=\"hit_grid\">" + 
              "<h3><a title=\""+$(this).find("title").text()+"\" href=\"/ovningsarkiv/"+$(this).find("id").text()+"\" class=\"exercise_name\">"+$(this).find("exerciseName").text()+"</a></h3>"+ 
              "<a href=\"/program/add_exercise/"+$(this).find("id").text()+" title=\""+$(this).find("title").text()+"\" id=\"exercise_id_"+$(this).find("id").text()+"\" class=\"add_exercise\"><img src=\"/images/icons/add_16.gif\" alt=\"Lägg till\" class=\"icon_add\"/></a>" 
              + "<a title=\""+$(this).find("title").text()+"\" href=\"/ovningsarkiv/"+$(this).find("id").text()+"\" class=\"exercise_name\"/>" + "<div onclick=\"\" title=\""+$(this).find("title").text()+"\" id=\""+$(this).find("id").text()+"\">" 
              + "<img src=\"http://movies.styrkeprogrammet.se/exercise_thumbnails_200x160/thumbnail_1_exercise_"+$(this).find("id").text()+".jpg\" class=\"placeholder_image\"/><img title=\"Spela video\" alt=\"\" src=\"/images/play.png\" class=\"play_button\"/></div></div>";
                    
            });
            
            // remove current loaders
         $("#videos .hit_grid_loader").remove();
         
         // add html for new videos
            $("#videos").append(html);
            
            // add new loaders if neccesary
            var total_showed = $("totalshowed", data).text();
            var total_nr_exercises = $("#nr_of_exercises").text();
            
           var diff = total_nr_exercises - total_showed;
           appendVideoLoaders("videos", diff);      
          }
      });
      */

   }
   
   /* append loader video div*/
   function appendVideoLoaders(elem_id, diff){
       if(diff > 0){
         for(var i = 0; (i < diff && i < 6); i++){
           $("#"+elem_id).append("<div class=\"hit_grid_loader\"><div><img style=\"padding:40px 0 0 65px\" src=\"/images/bigLoader.gif\" class=\"placeholder_image\"/></div></div>");
         }
       }
       
   }


     /* Confirm functions **************************************************************** */
     
     /* LIST VIEW */
    function confirmAddList(exercise_id){
      $("#"+exercise_id).parent().parent().addClass("added_exercise");
    setTimeout("removeConfirmAddList('"+exercise_id+"')", 1500);
  }
  
  function removeConfirmAddList(exercise_id){
    $("#"+exercise_id).parent().parent().removeClass("added_exercise");
  }
  
  /* VIDEO VIEW */
    function confirmAddVideo(exercise_id){
      $("#"+exercise_id).parent().addClass("added_exercise");
    setTimeout("removeConfirmAddVideo('"+exercise_id+"')", 1500);
  }
  
  function removeConfirmAddVideo(exercise_id){
    $("#"+exercise_id).parent().removeClass("added_exercise");
  }
  
  /* ITEM EXERCISE VIEW */
    function confirmAddItem(exercise_id){
      $("#"+exercise_id).parent().addClass("added_exercise");
    setTimeout("removeConfirmAddItem('"+exercise_id+"')", 1500);
  }
  
  function removeConfirmAddItem(exercise_id){
    $("#"+exercise_id).parent().removeClass("added_exercise");
  }
  
  /* MADE PROGRAM */
  function confirmAddMadeProgram(program_id){
    $("#"+program_id).parent().addClass("added_program");
    setTimeout("removeConfirmAddMadeProgram('"+program_id+"')", 1500);  
  }
  
  function removeConfirmAddMadeProgram(program_id){
    $("#"+program_id).parent().removeClass("added_program");  
  }
  
  /********************************************************************************************* */
  
     function removeFromProgram(exercise_counter){
       // update program
      
       // remove exercise
       //$("#"+exercise_counter).fadeOut("normal", function(){
         // $("#"+exercise_counter).remove();          
         //}
         
         //);
  
    $("#"+exercise_counter).remove();
    
    //update exercise_counter on existing exercises
    updateProgramJs();
    
      exercise_counter = exercise_counter.substring(17);
      //alert(exercise_counter);
      
      //make ajax call to delete exercise from db (cache = false)
        //$.get("/program/delete_exercise/"+exercise_counter);
        
        $.ajax({
         type: "GET",
         url: "/program/delete_exercise/"+exercise_counter,
         cache:false
      });
        
        return false;
    }
    
    
    function addMadeProgram(program_id){
      
      //  confirm by adding class .added_program
      if($("#"+program_id).parent().is("p")){
        // change background color temporary
        confirmAddMadeProgram(program_id);
      }
        
      program_id = program_id.substring(13);
      //make ajax call to add exercise to db
      // FIXA via ajax attr
      
      $.ajax({
         type: "GET",
         url: "/program/add_made_program/"+program_id,
         cache:false,
         success: function (data, textStatus) {
        /* XML structure to be returned 
        <program>
          <name>...</name>
          <id>...</id>
      </program>
      */
        //alert("Data Loaded: " + data);
        var data = parseXml(data);
        
        var made_program_name = $("programname", data).text();
        var made_program_name = made_program_name.substring(0, 31) + "...";
        var new_program_id = $("programid", data).text();
        
        
        $("#my_programs").append("<li id=\"saved_program_id_"+new_program_id+"\"><span><a href=\"/program/edit_program/"+new_program_id+"\" title=\""+made_program_name+"\">"+made_program_name+"</a></span></li>");
        // activate event edit saved program
        $("#saved_programs ul li a").click(function(){
          return editSavedProgram($(this).parent().parent().attr("id"));
        });
        
        return false;
         }
  
     });
    /*    
      $.get("/program/add_made_program/"+program_id, function(data){  
        
        var made_program_name = $("programname", data).text();
        var new_program_id = $("programid", data).text();
        
        
        $("#my_programs").append("<li id=\"saved_program_id_"+new_program_id+"\"><span><a href=\"/program/edit_program/"+new_program_id+"\" title=\""+made_program_name+"\">"+made_program_name+"</a></span></li>");
        // activate event edit saved program
        $("#saved_programs ul li a").click(function(){
          return editSavedProgram($(this).parent().parent().attr("id"));
        });
        
        return false;
      });
      */
      return false;
    }
    
    function addExerciseToProgram(obj){
      
      
      if($("#program ul").length > 0){
        // FIXA: check if active program exists
        
        // update program
        updateProgramJs();
        
        // get exercixe id
        var exercise_id = $(obj).attr("id");
        
        // om övningsarkiv - lista
        if($("#"+exercise_id).parent().parent().is("tr")){
          // change background color temporary
          confirmAddList(exercise_id);
        }
        // om övningsarkiv - video
        else if($("#"+exercise_id).parent().is("h3")){
          // change background color temporary
          confirmAddVideo(exercise_id);
        }
        // om övningsarkiv - specifik övning
        else if($("#"+exercise_id).parent().is("p")){
          // change background color temporary
          confirmAddItem(exercise_id);
        }
        
        //console.debug(exercise_id);
        // get exercise name by looking at clickedElem.parent.lastchild
      var parent_elem = $("#"+exercise_id).parent();    
      var atag = $(parent_elem).children().next("a");
      var title = $(atag).attr("rel"); 
      //console.debug(title);
        exercise_id = exercise_id.substring(12);

        // shorten title...
        short_title = ""
        if(title.length > 29){
          short_title = title.substring(0, 30) + "...";
        }
        else{
          short_title = title;  
        }
        
        //confrim add exercise
        // get row and add temp id
        //temp_id = "confirm" + exercise_id
        //$(obj).parent().parent().attr("id", temp_id);
        //confirmRowAdd(temp_id);
        

        
        // calculate counter to use for new item
         var exercise_counter_array = $("#program ul li");
         var next_counter = exercise_counter_array.length;
         
         // tennis och sp
         var site_url = document.location.href;
         if(site_url.indexOf("/tennis") >= 0){
           var part_url = "/tennis/ovningsarkiv/";
         }   
         else{
          var part_url = "/ovningsarkiv/";
         }
  
         // append the new exercise to the program
          $("#program ul").append("<li id=\"exercise_counter_"+next_counter+"\"><a href=\""+part_url+""+exercise_id+"\" id=\"exercice_id_"+exercise_id+"\" class=\"exercise\" title=\""+title+"\">"+short_title+"</a><a  href=\"/program/delete_exercise/"+next_counter+"\" class=\"remove_exercise\"><img class=\"icon_delete\" alt=\"ta bort\" src=\"/images/icons/cancel_16_blue.gif\" /></a></li>");
          
          // activate click action for new elements
        $("#program ul .remove_exercise").click(function () { 
            return removeFromProgram($(this).parent().attr("id"));
        });
        
         //old - cache problems in IE 
         // make ajax call to add exercise to db 
         //$.get("/program/add_exercise/"+exercise_id);
         
         // ajax call with cache = false
          $.ajax({
         type: "GET",
         url: "/program/add_exercise/"+exercise_id,
         cache:false
       });


         
         return false
       
      }
      else{
        alert("Det finns inget program aktiverat där övningen kan läggas till. Aktivera ett av dina sparade program");
        return false;  
      }
      
    }
    
    function updateProgram(){
      
      if(updateProgramJs()){
      
      // FIXA: make ajax request
       //make ajax call to add exercise to db 
      // get exercises in correct order
      if($("#program ul a.exercise").length != 0){
        var exercises = $("#program ul a.exercise");
        var segments = "";
      for(var i =0; i < exercises.length; i++){
        var exercise_id = $(exercises[i]).attr("id");
        var exercise_id = exercise_id.substring(12);
        if(i == 0){
          segments  = exercise_id;
        }
        else{
          segments = segments + "/"+exercise_id;
        }
      }
    }  
    
         // old cache problems in IE
         /*
         $.get("/program/update_program/"+segments, function(data){
           //alert("data loaded:" + data);
           }, "html"
         );
         */       
         $.ajax({
       type: "GET",
       url: "/program/update_program/"+segments,
       cache:false
     });
       
      
      }
      
       return false;
      
      
    }
    
    function testAjax(){
      $.get("/program/test_ajax/", function(data){
           alert("data loaded:" + data);
           }
         );
         return false;  
    }
    
    function updateProgramJs(){
      var exercise_array = $("#program ul li");
      for(var i = 0; i < exercise_array.length; i++){
        // update id for li element
        $(exercise_array[i]).attr("id", "exercise_counter_" + i);
        // update href for remove exercise
        $(".remove_exercise", exercise_array[i]).attr("href", "/program/delete_exercise/"+i);    

      }
      return true;  
    }
    
    // in parameter = program id
    // FIXA: Hanterar inte double quotes
    function changeProgramName(){
      var name = $("#program_name h2").attr("title");
      //console.debug(name);
      //$("#program_name").replaceWith("<div id=\"program_name\"><input id=\"name_input\" value=\""+name+"\" size=\"15\"/> <a id=\"save_program_name\" title=\"Spara\">spara</a></div>");
      
      $("#program_name").replaceWith("<div id=\"program_name\"><input id=\"name_input\" value=\""+name+"\" size=\"15\"/> <a id=\"save_program_name\" title=\"Spara\">spara</a></div>");
        
      $("#name_input").focus();
      
      // save by pressing enter key
      $("#program_name input").keypress(function (e){
        if(e.which == 13){
          var name = $("#program_name input").attr("value");
          // cannot save with empty name
          if(name.length > 0){
            saveProgramName(name);
          }
          else{
            alert("Du måste ge passet ett namn."); 
          }
        }
      });
      
      // save by clicking save
      $("#save_program_name").click(function(){
        var name = $("#program_name input").attr("value");
        // cannot save with empty name
          if(name.length > 0){
            saveProgramName(name);
          }
          else{
            alert("Du måste ge passet ett namn.");  
          }
      });
     // disable href  
     return false;
    }
    
    function saveProgramName(name){
      //console.debug(name);
      // FIXA: replaces double-quotes with single quotes before saving name
      //var name = name.replace(/"/g,"'");
  
      var program_id = $("#program ul").attr("id");
      program_id = program_id.substring(11);
      
      // FIXA: åäö pch specialtecken fungerar INTE
      // save name to db via ajax request
            
      // old - cache problems in IE
      // $.get("/program/save_name/"+encodeURIComponent(name));
       $.ajax({
       type: "GET",
       url: "/program/save_name/"+encodeURIComponent(name),
       cache:false
     });
      
      // shorten name för saved programs list
      short_name_saved_programs = ""
      if(name.length > 35){
        short_name_saved_programs = name.substring(0, 31) + "...";
      }
      else{
        short_name_saved_programs = name;  
      }
      
      // shorten name för active program
      short_name = ""
      if(name.length > 20){
        short_name = name.substring(0, 17) + "...";
      }
      else{
        short_name = name;  
      }
        
      // change name in saved programs list
      var current_saved_program = $("#my_programs li.current_program span a");
      
      current_saved_program.text(short_name_saved_programs);
      $(current_saved_program).attr("title", name);    
    
      $("#program_name").replaceWith("<div id=\"program_name\"><h2 title=\""+name+"\" alt=\""+short_name+"\">"+short_name+"</h2> <a id=\"change_program_name\" title=\"Redigera programmets namn\">byt namn</a></div>");
      $("#change_program_name").click(function(){
        changeProgramName();
      });
     // disable href  
     return false;
    }
    
    function deleteProgram(){
      var program_id = $("#program ul").attr("id");
      var program_id = program_id.substring(11); 
      if($("#program_name h2").attr("title")){
      var name = $("#program_name h2").attr("title");
       if(confirmMessage("Vill du ta bort programmet "+name+"?")){
         // old - cache problems in IE
         // $.get("/program/remove_program/"+program_id);
         $.ajax({
           type: "GET",
           url: "/program/remove_program/"+program_id,
           cache:false
       });
         // remove from saved programs in sidebar
         $("#saved_program_id_"+program_id).remove();
         // remove active program
         // FIXA: Om inget program är aktiverat - se nedan
         $("#program").replaceWith("<div id=\"program\"><p><strong>Inget aktivt pass</strong><br />Aktivera ett av dina sparade pass.</p></div>");
         // FIXA: print new program
         return false;
       }
       else{
         return false;  
       }
      }
      else{
         // FIXA: hur ska man hämta namnet om man håller på och redigerar det?
       if(confirmMessage("Vill du ta bort programmet?")){
         // old - cache problems in IE
         // $.get("/program/remove_program/"+program_id);
         $.ajax({
           type: "GET",
           url: "/program/remove_program/"+program_id,
           cache:false
       });
       // remove from saved programs in sidebar
         $("#saved_program_id_"+program_id).remove();
         // remove active program
         // FIXA: Om inget program är aktiverat - se nedan
         $("#program").replaceWith("<div id=\"program\"><p><strong>Inget aktivt program</strong><br />Aktivera ett av dina sparade program.</p></div>");
         return false;  
       }
       else{
         return false;  
       }
      }
   return false;
    }
    
    function addProgram(){
      /* old - cache problems in IE
      $.get("/program/add_program", function(data){  
        var new_pid = data;
        // Update saved program in sidebar with program
        $("#my_programs").append("<li id=\"saved_program_id_"+new_pid+"\"><span><a href=\"/program/edit_program/"+new_pid+"\" title=\"Nytt program\">Nytt program</a></span></li>");
        
        
        // edit saved program
        $("#saved_programs ul li a").click(function(){
          return editSavedProgram($(this).parent().parent().attr("id"));
          //alert($(this).parent().attr("id"));
          //return false;
        });

    });
    */
    
      // returns "xml"
      // <result><programId>1234</programId></result> 
      
         $.ajax({
           type: "GET",
           url: "/program/add_program",
           cache:false,
           success: function (data, textStatus) {
             var data = parseXml(data);
           // var new_pid = data;
           //console.debug(data);
             var new_pid = $("programId", data).text();
             //console.debug("hej" + new_pid);
            // Update saved program in sidebar with program
            $("#my_programs").append("<li id=\"saved_program_id_"+new_pid+"\"><span><a href=\"/program/edit_program/"+new_pid+"\" title=\"Nytt program\">Nytt program</a></span></li>");       
        
            // edit saved program
            $("#saved_programs ul li a").click(function(){
              return editSavedProgram($(this).parent().parent().attr("id"));
              //alert($(this).parent().attr("id"));
              //return false;
            });
        }

       });
    
        return false;
      }
    
  // the returned data has following structure
  /*
  <program name="xxx" id="xxx">
    <exercise>
      <id> ... </id>
      <name> ... </name>
    </exercise>
    <exercise>
      <id> ... </id>
      <name> ... </name>
    </exercise>
  </program>
  */
    function editSavedProgram(id){
      
      // FIXA: om inget program är aktiverat - fixa kollar.
      
      // change current program class
      $("#saved_programs ul li.current_program").removeClass("current_program");
      $("#"+id).addClass("current_program");
      //print new program/get program info with ajax

      //strip string saved_program_id_
      id = id.substring(17);
      
      // FIXA: correct xml is not return probably wrong content type. cannot set datatype to "xml"
      $.ajax({
         type: "GET",
         url: "/program/edit_program/"+id,
         cache:false,
         success: function (data, textStatus) {
           var data = parseXml(data);
           //console.debug("Data Loaded: " + data);
          
          var program_name = $("programname", data).text();
          
          //console.debug(program_name);
          
         // tennis och sp
         var site_url = document.location.href;
         if(site_url.indexOf("/tennis") >= 0){
           var part_url = "/tennis";
         }   
         else{
          var part_url = "";
         }
          
           // shorten name...
          short_name = ""
          if(program_name.length > 20){
            short_name = program_name.substring(0, 17) + "...";
          }
          else{
            short_name = program_name;  
          }
        
          var program_id = $("programid", data).text();
   
          
          // change program name
          var program_html = "<div id=\"program_name\"><h2 title=\""+program_name+"\" alt=\""+program_name+"\">"+short_name+"</h2> <a id=\"change_program_name\" title=\"Redigera programmets namn\">byt namn</a></div>";
  
          // build new ul-list for program exercises
          program_html += "<ul id=\"program_id_"+program_id+"\">";
          
          var counter = 0;
          // go through all exercise nodes
          $("exercise",data).each(function(){
            
            var exercise_id = $(this).find("id").text();
            var exercise_name = $(this).find("name").text();
            
            // shorten name...
            short_ex_name = ""
            if(exercise_name.length > 29){
              short_ex_name = exercise_name.substring(0, 30) + "...";
            }
            else{
              short_ex_name = exercise_name;  
            }
        
            program_html += "<li id=\"exercise_counter_"+counter+"\">";
            program_html += "<a id=\"exercice_id_"+exercise_id+"\" class=\"exercise\" title=\""+exercise_name+"\" href=\""+part_url+"/ovningsarkiv/"+exercise_id+"\" >"+short_ex_name+"</a>";
            program_html += "<a class=\"remove_exercise\" href=\"/program/delete_exercise/"+exercise_id+"\"><img class=\"icon_delete\" src=\"/images/icons/cancel_16_blue.gif\" alt=\"ta bort\" /></a>";
            program_html += "</li>";      
            counter = counter+1; 
          });
          program_html += "</ul>";
          
          // show and delaete program links
          program_html += "<a id=\"show_program\" href=\""+part_url+"/ovningsarkiv/visaprogram/"+program_id+"\"><img src=\"/images/icons/fields_16.gif\"/> Redigera och skriv ut pass</a>";
          program_html += "<a id=\"delete_program\" href=\"/program/remove_program/"+program_id+"\"><img src=\"/images/icons/delete_16_grey.gif\"/> Radera pass</a>";
  
          // replace entire program-div
          $("#program").replaceWith("<div id=\"program\">"+program_html+"</div>");
          
          // activate delete program link
          $("#delete_program").click(function(){    
            return deleteProgram();
          });
      
          // activate change name event
          $("#change_program_name").click(function(){
            changeProgramName();
          });
          
          // activate click action for new elements
          $("#program ul .remove_exercise").click(function () { 
              return removeFromProgram($(this).parent().attr("id"));
          });
          
          // make exercises sorlable
          $("#program ul").sortable({ 
            containment: '#program ul',
            tolerance: 'pointer',
            //jQuery UI 1.5.3 is only compatible with jQuery 1.2.6. In order to use jQuery UI with jQuery 1.3+, you'll need the latest preview release1.6rc6. It is compatible with 1.3 (but not 1.2.6), and the final release is scheduled for tonight. See
            // call updateProgram to update db and set session when dragging stops
            update: function(event, ui) { updateProgram(); }
          });
        
      }

     });


      return false;
        
    }
    
    function confirmRemoveProgram(){
      
    }
    
    function confirmMessage(message){
      return confirm(message);  
    }

