var Alexandria = Alexandria || {};

Alexandria.PhotoUpload = {
  queueBytesLoaded: 0,
  queueBytesTotal: 0,
  myQueue: null,
  queueTimeouts: [],
  isUploading: false,
  watchers: [],

  queueChangeHandler: function(queue){
    this.myQueue = queue;
    var list = $('file_todo_list');
    while (list.hasChildNodes()){list.removeChild(list.firstChild);}
    for (i=0;i<queue.files.length;i++)
    {
      this.addFileToTodoList(queue.files[i].name, queue.files[i].size, i);
    }

    if( queue.files.length > 0){
      this.autoUpload();
    }
  },

  autoUpload: function(){
    if( this.isUploading ) { return; }

    this.queueTimeouts.each(function(queueTimeout){
      clearTimeout(queueTimeout);
    });

    this.queueTimeouts.push(setTimeout(function(){
      if($("file_todo_list").hasChildNodes()){
        s3_swf_1_object.startUploading();
        //$("StartButton").simulate("click");
      }
    }, 200));
  },

  uploadingStartHandler: function(){
    this.queueBytesTotal = 0;
    this.queueBytesLoaded = 0;
    for (i=0;i<this.myQueue.files.length;i++){ this.queueBytesTotal += parseInt(this.myQueue.files[i].size, 10); }
    //$('queue_size').innerHTML = readableBytes(queueBytesTotal);
    this.isUploading = true;
  },
  
  uploadingFinishHandler: function(upload_options, event){
    $('overall').select(".amount").first().style.width = '0%';
    $('overall').select(".amount_text").first().innerHTML = '0%';
    this.isUploading = false;
  },
  
  queueClearHandler: function(queue){
    $('overall').select(".amount").first().style.width = '0%';
    $('overall').select(".amount_text").first().innerHTML = '0%';
  },
  
  addFileToTodoList: function(file_name, file_size, index){
    var list = $('file_todo_list');
    var li = document.createElement("li");
    li.innerHTML = 
      "<div class='content_type <%= type %>'></div>" + 
      "  <div class='file_content'>" +
      "    <div class='file_name'>"+file_name+"</div>" +
      "    <div class='delete' onclick='javascript:s3_swf_1_object.removeFileFromQueue("+index+");'>x</div>" +
      "    <div class='progress'><div class='amount'></div></div>" +
      "    <div class='eta'>"+this.readableBytes(file_size)+"</div>" +
      "  </div>";
    list.appendChild(li);
  },
  
  progressHandler: function(progress_event){
    var current_percentage = Math.floor((parseInt(progress_event.bytesLoaded, 10)/parseInt(progress_event.bytesTotal, 10))*100)+'%';
    $('file_todo_list').select(".amount").first().style.width = current_percentage;
    $('file_todo_list').select(".eta").first().innerHTML = this.readableBytes(progress_event.bytesLoaded) + " van " + readableBytes(progress_event.bytesTotal);
  
    var overall_percentage = Math.floor(((queueBytesLoaded+parseInt(progress_event.bytesLoaded,10))/queueBytesTotal)*100)+'%';
    $('overall').select(".amount").first().style.width = overall_percentage;
    $('overall').select(".amount_text").first().innerHTML = overall_percentage;
  },
  
  uploadCompleteHandler: function(upload_options,event){
    this.queueBytesLoaded += parseInt(upload_options.FileSize, 10);
    var csrf_token = $$('meta[name=csrf-token]')[0];

    var request = new Ajax.Request("/photos.json", {
      method: "post",
      parameters: {
        authenticity_token: csrf_token.readAttribute('content'),
		    'photo[photo_file_name]' : upload_options.FileName,
	      'photo[photo_file_size]' : upload_options.FileSize,
        'photo[photo_content_type]' : upload_options.ContentType
      },
      onSuccess: this.uploadCompleteSuccess
    });
  },

  uploadCompleteSuccess: function(transport){
    var photo = transport.responseJSON;
    var photo_html = "" +
      "<li>" +
      "  <input type='hidden' value='"+photo.id+"' name='form_response[photo_ids][]'>" +
      "  <div class='file_name'>" + photo.photo_file_name +"<span class='delete'>x</span></div>" +
      "</li>";



    $("file_done_list").insert({bottom:photo_html});
    //Alexandria.PhotoUpload.startWatcher(photo.id);
  },

  buildQueryString: function(){
    var photo_ids = [];

    for(i=0,j=Alexandria.PhotoUpload.watchers.length; i<j; i++){
      photo_ids.push(Alexandria.PhotoUpload.watchers[i].photo_id);
    }

    return "&photo_ids[]=" + photo_ids.join("&photo_ids[]=");
  },

  startChecker: function(){
    if(Alexandria.PhotoUpload.checker !== undefined){ return; }

    Alexandria.PhotoUpload.checker = setInterval(function(){
      Alexandria.PhotoUpload.statusChecker();
    }, 4000); 
  },

  statusChecker: function(){
    if(Alexandria.PhotoUpload.watchers.length === 0){ return; }
    var request = new Ajax.Request("/photos/check_photos.json", {
      method: "get",
      parameters: Alexandria.PhotoUpload.buildQueryString(),
      onSuccess: function(t){ Alexandria.PhotoUpload.statusCheckerSuccess(t.responseJSON); }
    });
  },

  statusCheckerSuccess: function(photos){
    for(i=0,j=photos.length; i<j; i++){
      if(photos[i].photo.state === 3){ 
        Alexandria.PhotoUpload.updatePhoto(photos[i].photo); 
        Alexandria.PhotoUpload.removePhoto(photos[i].photo);
      }
    }
  },

  startWatcher: function(photo_id){
    Alexandria.PhotoUpload.watchers.push({
      photo_id: photo_id
    });

    Alexandria.PhotoUpload.startChecker();
  },

  removePhoto: function(photo){
    var index = null;
    for(x=0,j=Alexandria.PhotoUpload.watchers.length; i < j; i++){
      if(Alexandria.PhotoUpload.watchers[i].photo_id == photo.id){ index = x; break; }
      index++;
    }
    if( index !== null ){
      Alexandria.PhotoUpload.watchers.splice(index, 1);
    }
  },

  updatePhoto: function(photo){
    if( photo.state !== 3 ) { return; }

    var html = "" +
      "<div identifier='"+photo.id+"' class='photo'>" +
      "  <input type='hidden' value='"+photo.id+"' name='article[photo_ids][]' id='article_photo_ids_'>" +

      "  <div class='photo_image'>" +
      "    <div class='photo_wrapper'>" +
      "      <img src='"+photo.urls.gallery_thumb+"' class='' alt='"+photo.photo_file_name+"'>" +
      "    </div>" +
      "  </div>" +
      "</div>";

    var new_photo = $$("div.photo[identifier="+photo.id+"]").first();
    new_photo.replace(html);
  },

  addPhoto: function(photo, position){
    position = position || "top";

    var html = "" +
      "<div identifier='"+photo.id+"' class='photo'>" +
      "  <input type='hidden' value='"+photo.id+"' name='article[photo_ids][]' id='article_photo_ids_'>" +

      "  <div class='photo_image'>" +
      "    <div class='photo_wrapper'>" +
      "      <img src='"+photo.urls.gallery_thumb+"' class='' alt='"+photo.photo_file_name+"'>" +
      "    </div>" +
      "  </div>" +
      "</div>";

    switch(position) {
      case "top":
        $("photo_bucket").insert({"top": html});
        break;
      case "bottom":
        $("photo_bucket").insert({"bottom": html});
        break;
    }
  },

  photoStateClass: function(state){
    switch(parseInt(state, 10)){
      case 0:
      return "waiting";
      case 1:
      return "queue";
      case 2:
      return "moving";
      case 3:
      return "processing";
      case 4:
      return "done";
    }
  },

  readableBytes: function(bytes) {
    var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes)/Math.log(1024));
    return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
  }
};

document.observe("dom:loaded", function(){
  $$(".file_done_list").each(function(done_list){
    done_list.observe("click", function(event){
      if(event.element().hasClassName("delete")){
        event.element().up("li").remove();
      }
    });
  });
});


(function(){
  var TabView = Class.create({
    initialize: function(){
      document.on("click", ".tabview-tabs a", this.tabClickEvent.bind(this));

      this.checkForHashPage();
    },

    checkForHashPage: function(){
      var params = location.hash.replace("#", "").split("&");
      for( i=0, j=params.length; i < j; i++ ){
        match = params[i].match(/tab=(.*)/);
        if (match){
          $("tab_" + match[1]).simulate("click");
        } 
      }
    },

    tabClickEvent: function(event){
      event.stop();
      var element = event.element();
      if (element.hasClassName("tab_pages")) {
        // this.toggleTabs(element);
      } else {
        this.openTab(element);
      }
    },

    // toggleTabs: function(tab_page) {
    //   tab_page.up("li").down("ul").toggle();
    //   if (tab_page.hasClassName("open")) {
    //     tab_page.removeClassName("open");
    //     tab_page.addClassName("close");
    //   } else {
    //     tab_page.removeClassName("close");
    //     tab_page.addClassName("open");
    //   }
    // },

    openTab: function(tab) {
      var tabview = tab.up(".tabview");
      var index = tabview.select("> .tabview-tabs a.tab").indexOf(tab);

      tabview.select("> .tabview-contents .tabview-content").invoke("hide");
      tabview.select("> .tabview-tabs a.selected").invoke("removeClassName", "selected");
      tabview.select("> .tabview-contents .tabview-content")[index].show();
      tab.addClassName("selected");
    }
  });

  document.observe("dom:loaded", function(){
    var tab_view = new TabView();
  });
})();

(function(){
  var Toggleify = Class.create({
    initialize: function(){
      document.on("click", ".toggle .show", this.showClickEvent.bind(this));
      document.on("click", ".toggle .edit .cancel", this.cancelClickEvent.bind(this));
      document.on("click", ".toggle .edit .save", this.saveClickEvent.bind(this));
    },

      showClickEvent: function(event){
        event.stop();
        var element = event.element();
        element.up(".toggle").select(".show").invoke("hide")
    element.up(".toggle").select(".edit").invoke("show");
      },

      cancelClickEvent: function(event){
        event.stop();
        var element = event.element();
        element.up(".toggle").select(".show").invoke("show")
    element.up(".toggle").select(".edit").invoke("hide");
      },

      saveClickEvent: function(event) {
        event.stop();
        var element = event.element();
        var form = element.up("form");
        var request = new Ajax.Request(form.action + ".json", {
          parameters: form.serialize(),
            onLoading: function(t) { 
              var span = element.up(".toggle").down("span");
              span.innerText = "";
              element.up(".toggle").select("input[type!=submit]", "select").each(function(el){
                if (el.type == "radio" || el.type == "checkbox") {
                  if (el.checked) {
                    span.innerText += el.value + " ";
                  }
                } else if (el.type == "select-one") {
                  span.innerText += el.select("option[value=" + el.value + "]")[0].innerText + " ";
                } else if (el.type == "password") {
                } else {
                  span.innerText += el.value + " ";
                }
              });
              element.up(".toggle").select(".show").invoke("show");
              element.up(".toggle").select(".edit").invoke("hide");
            },
            onSuccess: function(t) {
              var response = t.responseJSON;
              if (response.errors === undefined) {
                $("errors").hide();
                element.up(".toggle").highlight();
                if ($("map_address") !== undefined) {
                  $("map_address").update(new Element("img", {"src":"http://maps.googleapis.com/maps/api/staticmap?center="+response.user.latitude+","+response.user.longitude+"&zoom=17&size=650x370&maptype=roadmap&markers=color:red%7Alabel:S%7C"+response.user.latitude+","+response.user.longitude+"&sensor=false"}));
                } 
                if ($("map_company_address") !== undefined) {
                  $("map_company_address").update(new Element("img", {"src":"http://maps.googleapis.com/maps/api/staticmap?center="+response.company.latitude+","+response.company.longitude+"&zoom=17&size=650x370&maptype=roadmap&markers=color:red%7Alabel:S%7C"+response.company.latitude+","+response.company.longitude+"&sensor=false"}));
                } 
              } else {
                response.errors.each(function(error) {
                  $("errors").update(new Element("li", {'class':'error_messages'}).update(error)).show();
                });
              }
            }
        });
      }
  });

  document.observe("dom:loaded", function(){ new Toggleify(); });
})();

