function supports_local_storage() {
  return !!window.localStorage;  
};

$(function(){

  var $htmleditor = CodeMirror.fromTextArea("code_editor", {
    parserfile: ["parsexml.js"],
    path: "/javascripts/codemirror/js/",
    tabmode: "spaces",
    
    stylesheet: "/javascripts/codemirror/css/xmlcolors.css",
    initCallback: function(editor){
      $(editor.win.document).keydown(function(e){
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) {
          render_form("/render/output");
        }
      });
    }
    
  });
  
  var $csseditor = CodeMirror.fromTextArea("css_editor", {
    parserfile: ["parsecss.js"],
    path: "/javascripts/codemirror/js/",
    tabmode: "spaces",
    
    stylesheet: "/javascripts/codemirror/css/csscolors.css",
    initCallback: function(editor){
      $(editor.win.document).keydown(function(e){
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) {
          render_form("/render/output");
        }
      });
    }
  });
  
  var $jseditor = CodeMirror.fromTextArea("js_editor", {
    parserfile: ["tokenizejavascript.js", "parsejavascript.js"],
    path: "/javascripts/codemirror/js/",
    tabmode: "spaces",
    stylesheet: "/javascripts/codemirror/css/jscolors.css",
    initCallback: function(editor){
      $(editor.win.document).keydown(function(e){
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) {
          render_form("/render/output");
        }
      });
    }
  });
  
  
  
  /* jQuery tabs */
  $tabs = $(".tabs").tabs();

  //hide the IE message
  
  if(!$.browser.msie){
    $("#ie_notice").hide();
  }

  // when they click the 'don't show' checkbox
  // use localstorage to persist that option.
  $("#hide_intro").click(function(e){
    if( supports_local_storage()){
      localStorage.setItem("hide_intro_dialog", $(this).attr("checked"));
    };
  });  
  
  if( supports_local_storage()){
    if ( localStorage.getItem("hide_intro_dialog") !== "true" ){
      show_intro_dialog();
    }else{
      // stil need to hide the div that
      // contains the intro text
      $("#intro").hide();
    };
  }else{
    $("#hide_intro_form").hide();  // gotta not show this checkbox to anyone.
    show_intro_dialog();
  };
  
  function show_intro_dialog(){
    $("#intro").dialog({
      bgiframe: true,
      width: 400,
      modal: true,
      autoOpen: true
    });
  };
  
  function display_error(err){
    var notice = $("#notice");
    notice.css("color", "#fff");
    notice.css("background-color", "#ff0000");
    notice.html(err);
  }

  /* Observe all links with class "popup" and make them
     in a new window
  */
  $(".popup").click(function(e){
    e.preventDefault();
    window.open($(this).attr("href"));
  });
  
  
  /* support for clicking the notice to render */
  $("#notice").click(function(){
    render_form("/render/output");
  });
  
  /* support for clicking the render button */
  $('#render_button').click(function(e){
    e.preventDefault();
    render_form("/render/output");
  });
  
  
  /* Observe the preview button click so the
     source preview appears on the export tab
  */
  $('#preview_button').click(function(e){
    e.preventDefault();
    render_form_for_export("/render/preview");
  });
  
  $('#permalink_button').click(function(e){
    e.preventDefault();
    create_permalink();
  });
  
  /* Handle loading the examples */
  $('a.example_link').click(function(e){
    e.preventDefault();
    render_example($(this).attr("href"));
  });
  
  /* saves code and sends back permalink */
  function create_permalink(){
    url = "/render/permalink"
    load_form_from_editor();
    $.ajax({
      type: "POST",
      url: url,
      dataType: 'json',
      data: $("#rendera_editor").serialize(),
      
      success: function(data){
        var url = data["url"];
        $("#permalink_url").html("Saved! Share at <a href='" + url + "'>" + url + "</a>");
      }
    });
  }
  
  /* Loads the example into the form fields and renders it */
  function render_example(url){
    setup_notice();
    
    $.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      success: function(data){
        var code = data["source_code"];
        var css = data["source_css"];
        var js = data["source_script"];
        
        var example_script = data["example_script"];
        var example_code = data["example_code"];
        var example_css = data["example_css"];
        
        // Fill in the form fields
        $('#code_editor').val(example_code);
        $('#css_editor').val(example_css);
        $('#js_editor').val(example_script);
        
        load_editor_from_form();
        
        if(data["code_type"] == "haml"){
          $("#type_haml").attr('checked', true);
        }else{
          $("#type_html").attr('checked', true);
        }
        
        if(data["css_type"] == "sass"){
          $("#css_type_sass").attr('checked', true);
        }else{
          $("#css_type_css").attr('checked', true);
        }
        
        if(data["script_type"] == "coffee"){
          $("#script_type_coffee").attr('checked', true);
        }else{
          $("#script_type_js").attr('checked', true);
        }
        
        $('#results').html(data["render"]);
        $('#source_code').val(code);
        $('#source_css').val(css);
        $('#source_js').val(js);
        reset_notice();    
        $("#tab_html").click();
      },
    });
  }
  
  /* return the results of the output renderer */
  function render_form(url){
    setup_notice();
    
    load_form_from_editor();
    
    $.ajax({
      type: "POST",
      url: url,
      dataType: 'json',
      data: $("#rendera_editor").serialize(),
      success: function(data){
        $('#results').html(data["render"]);
        $('#source_code').val(data["source_code"]);
        $('#source_css').val(data["source_css"]);
        $('#source_js').val(data["source_script"]);
        reset_notice();    
      },
    });
  }
  
  function render_form_for_export(url){
    setup_notice();
    
    load_form_from_editor();
    
    $.post(url, $("#rendera_editor").serialize(), function(data){
      $('#export_output').val(data);
      reset_notice();
    });
  }
  
  function setup_notice(){
    var notice = $('#notice');
    notice.html("...rendering...");
    notice.css("background-color", "#eec");
  }
  
  function reset_notice(){
    var notice = $('#notice');
    notice.html("Click me or press 'Enter' in the editor fields to render.");
    notice.css("background-color", "#97FF9E");
  }

  $("#lorem").click(function(e){
    l = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    $htmleditor.replaceSelection(l);
  });
  
  $("#list").click(function(e){
    if(isHamlOn()){
      l = "%ul\n  %li One\n  %li Two";
    }else{
      l = "<ul>\n  <li>One</li>\n  <li>Two</li>\n</ul>";
    }
    $htmleditor.replaceSelection(l);
  });
  
  $("#table").click(function(e){
    if(isHamlOn()){
      l = "%table\n  %tr\n    %th heading one\n    %th heading two\n  %tr\n    %td row 1 col 1\n    %td row 1 col 2\n  %tr\n    %td row 2 col 1\n    %td row 2 col 2\n"
    }else{
      l = "<table>\n  <tr>\n    <th>heading one</th>\n    <th>heading two</th>\n  </tr>\n  <tr>\n    <td>row 1 col 1</td>\n    <td>row 1 col 2</td>\n  </tr>\n  <tr>\n    <td>row 2 col 1</td>\n    <td>row 2 col 2</td>\n  </tr>\n</table>";
    }
    $htmleditor.replaceSelection(l);
  });
  
  $("#img").click(function(e){
    if(isHamlOn()){
      l = '%img{:id=> "red_flower", :width=> "240", :height=>"161", :src=>"http://farm2.static.flickr.com/1108/1423464589_e42c6182ac_m.jpg", :alt=>"A white flower"}';
      
    }else{
      l = '<img id="red_flower" width="240" height="161" src="http://farm2.static.flickr.com/1108/1423464589_e42c6182ac_m.jpg" alt="A white flower">';
            
    }
    $htmleditor.replaceSelection(l);
  });
  
  $("#form").click(function(e){
    if(isHamlOn()){
    l = '%form{:method=>"get", :action=>"#", :id=> "my_form"}\n\
  %fieldset\n\
    %legend Form\n\
    %ol\n\
      %li\n\
        %label{:for=>"name"}Name\n\
        %input{:type=>"text", :name=>"name", :id=>"name"}\n\
      %li\n\
        %label{:for=>"name"}Email\n\
        %input{:type=>"email", :name=>"email", :id=>"email"}\n\
      %li\n\
        %input{:type=>"submit", :name=>"submit", :value=>"submit", :id=>"submit"}\n';
    }else{
      l = '<form method="get" action="#" id="my_form">\n\
  <fieldset>\n\
    <legend>Form</legend>\n\
    <ol>\n\
      <li>\n\
        <label for="name">Name</label>\n\
        <input type="text" name="name" id="name" >\n\
      </li>\n\
      <li>\n\
        <label for="name">Email</label>\n\
        <input type="email" name="email" id="email" >\n\
      </li>\n\
      <li>\n\
        <input type="submit" name="submit" value="submit" id="submit" >\n\
      </li>\n\
    </ol>\n\
  </fieldset>\n\
</form>';            
    }
    $htmleditor.replaceSelection(l);
  });
  
  $("#select").click(function(e){
    if(isHamlOn()){
      l = '%label{:for => "states"}States\n\
%select{:name => "states", id="states"}\n\
  %option{:value=>"IL"}Illinois\n\
  %option{:value=>"MN"}Minnesota\n\
  %option{:value=>"WI"}Wisconsin';
    }else{
      l = '<label for=\"states\">States</label>\n\
<select>\n\
  <option value=\"IL\">Illinois</option>\n\
  <option value=\"MN\">Minnesota</option>\n\
  <option value=\"WI\">Wisconsin</option>\n\
</select>';
    }
    $htmleditor.replaceSelection(l);
  });
  function isSassOn(){
    return ($("#css_type_sass").attr('checked') == true);
  }
  
  function isHamlOn(){
    return ($("#type_haml").attr('checked') == true);
  }
  
  // copy the code from the editors into the actual form
  // so that it can be submitted
  function load_form_from_editor(){
    $("#code_editor").val($htmleditor.getCode());
    $("#css_editor").val($csseditor.getCode());
    $("#js_editor").val($jseditor.getCode());
  }
  
  // load code into the editor from the form so that it can
  // be displayed and edited
  function load_editor_from_form(){
    $htmleditor.setCode($('#code_editor').val());
    $csseditor.setCode($('#css_editor').val());
    $jseditor.setCode($('#js_editor').val());
  }

  $("#source .css, #source .script").hide();

  $tabs.bind('tabsselect', function(event, ui) {
    if (ui.panel.id == "html") {
      $("#source .html, #source .css, #source .script").hide();
      $("#source .html").show()
    };
    if (ui.panel.id == "css") {
      $("#source .html, #source .css, #source .script").hide();
      $("#source .css").show()
    };
    if (ui.panel.id == "javascript") {
      $("#source .html, #source .css, #source .script").hide();
      $("#source .script").show()
    };
  });
    

  $("#css").click(function(e){
    $("#source .html, #source .css, #source .script").hide();
    $("#source .css").show();
  });
  
  $("#script").click(function(e){
    $("#source .html, #source .css, #source .script").hide();
    $("#source .script").show();
  });
  
  

});

