var CAN_COMMENT = true;

jQuery(document).ready(function() {
  jQuery(".timeago").timeago();
});

$(function () {
    $("ul.inline-tabs").tabs()
});

jQuery.fn.tabs = function () {
    function a(d) {
        return /#([a-z][\w.:-]*)$/i.exec(d)[1];
    }
    var b = window.location.hash.substr(1);
    return this.each(function () {
        var d = null,
            c = null;
        $(this).find("li a").each(function () {
            var e = $("#" + a(this.href));
            if (e != []) {
                e.hide();
                $(this).click(function () {
                    c && c.hide();
                    d && d.removeClass("selected");
                    c = e.show();
                    d = $(this).addClass("selected");
                    if($("#map").length != 0) {    
                      if((map != null) && ($("#map").length != 0)) {
                        google.maps.event.trigger(map, 'resize');
                        map.setZoom( map.getZoom() );
                        if(marker != null) {
                          map.setCenter(marker.getPosition());
                        } else {
                          map.setCenter(center);
                        }
                      } 
                    }
                    return false;
                });
                $(this).hasClass("selected") && $(this).click()
            }
        });
        $(this).find("li a[href='#" + b + "']").click();
        c == null && $($(this).find("li a")[0]).click();
    })
};

jQuery.timeago.settings.strings = {
   prefixAgo: "hace",
   prefixFromNow: "dentro de",
   suffixAgo: "",
   suffixFromNow: "",
   seconds: "menos de un minuto",
   minute: "un minuto",
   minutes: "unos %d minutos",
   hour: "una hora",
   hours: "%d horas",
   day: "un d\u00EDa",
   days: "%d d\u00EDas",
   month: "un mes",
   months: "%d meses",
   year: "un a\u00F1o",
   years: "%d a\u00F1os"
};

var form_eliminar = {
  message: null,
  open: function (dialog) {
      dialog.overlay.fadeIn(200);
      dialog.container.fadeIn(200);
      dialog.data.fadeIn(200);
  },
  show: function (dialog) {
      $('#form_data').submit(function (e) {                        
        return false;
      });
      $('input[name=eliminar]').click(function() {
        var item_id = $("#item_id").val();
        $.post("/bin/ajax/item/eliminar", { id: item_id }, function(json) {
          $("#item_" + item_id).hide();  
          dialog.overlay.fadeOut(200);
          $.modal.close();              
        }, "json");
        return false;
      });	    
  },
  close: function (dialog) {
      dialog.overlay.fadeOut(200);
      $.modal.close();
  }
};

function eliminar_item(id) {
  $.post("/bin/ajax/item/eliminar/form", { id: id }, function(json) {
    var form = json.form;
    $(form).modal({          
      overlayId: "form-overlay",
      containerId: "form-container",
      closeClass: "form-close",
      onOpen: form_eliminar.open,
      onShow: form_eliminar.show,
      onClose: form_eliminar.close
    });
  }, "json");
}

var uploading = false;
var uploading_simple = false;
var uploading_modal = false;
var textarea_parsed = false;

var form_upload = {
  message: null,
  open: function (dialog) {
      dialog.overlay.fadeIn(200);
      dialog.container.fadeIn(200);
      dialog.data.fadeIn(200);
  },
  show: function (dialog) {
      $('#form_upload_modal').submit(function (e) {                        
        return false;
      });
      $('input[name=aceptar]').click(function() {
        var item_id = $("#item_id").val();
        var file_name = $("#image_preview_image").val();
        $("#" + item_id).attr("src", "/bin/image?f=" + file_name + "&w=40");
        $("#" + item_id + "_input").val(file_name);
        dialog.overlay.fadeOut(200);
        $.modal.close();              
        return false;
      });	    
  },
  close: function (dialog) {
      dialog.overlay.fadeOut(200);
      $.modal.close();
  }
};

function upload_modal(item_id) {
  var image = $("#" + item_id + "_input").val();
  $.post("/bin/ajax/upload/form", { item_id: item_id, image: image }, function(json) {
    var form = json.form;
    $(form).modal({          
      overlayId: "form-overlay",
      containerId: "form-container",
      closeClass: "form-close",
      onOpen: form_upload.open,
      onShow: form_upload.show,
      onClose: form_upload.close
    });
  }, "json");
}

function upload_modal_change() {
  $.post("/bin/ajax/utils/sid", { }, function(json) {
    var new_sid = json.sid;
    uploading_modal = true;
    $("#form_upload_modal").attr("action", "/cgi-bin/upload.cgi?sid=" +  new_sid);    
    $("#form_upload_modal").attr("target", "destination_simple_modal");
    $("#form_upload_modal").submit();
    $("#form_upload_modal_submit").click();
    upload_modal_change_progress(new_sid);
    $("#form_upload_modal").attr("action", "");
    $("#form_upload_modal").removeAttr("target");
  }, "json");    
}

function upload_modal_change_progress(new_sid) {
  $.post("/bin/ajax/upload/status", { sid: new_sid }, function(json) {
    if(json.error == undefined) {    
      if(json.end != undefined) {
        uploading_modal = false;    
        $.post("/bin/ajax/upload/image", { sid: new_sid, image: $("#image_preview_image").val() }, function(json) {
          if(json.file_name != undefined) {                       
            $("#image_preview").css("background", "url(/bin/image?f=" + json.file_name + "&w=40) 0 0 no-repeat");
            $("#image_preview_image").val(json.file_name);
          }
        }, "json");        
      } else {
        setTimeout("upload_modal_change_progress('" + new_sid + "')", 1000);
      }
    } else {
      uploading = false;
      alert("Error: " + json.error);
      location.reload();
    }
  }, "json");
  return true;
}

function upload_simple(item_id, width) {
  $("#" + item_id).css("background", "url(/css/images/ajax_32.gif) no-repeat center center");
  $.post("/bin/ajax/utils/sid", { }, function(json) {
    var new_sid = json.sid;
    uploading_simple = true;
    $("#main_form").attr("action", "/cgi-bin/upload.cgi?sid=" +  new_sid);    
    $("#main_form").attr("target", "destination_simple");
    $("#main_form").submit();
    $("#submit").click();
    upload_simple_progress(new_sid, item_id, width);
    $("#main_form").attr("action", "");
    $("#main_form").removeAttr("target");
    // $("#upload_simple_file_selector").attr("value", "");
  }, "json");  
}

function upload_simple_progress(new_sid, item_id, width) {  
  $.post("/bin/ajax/upload/status", { sid: new_sid }, function(json) {
    if(json.error == undefined) {
      if(json.percent != undefined) {
        // $("#pbUpload").progressBar(Math.floor(json.percent));        
        // $("#pbText").text("Tama\u00f1o: " + json.total_size + " Subido: " + json.uploaded + " Progreso: " + json.percent + "% Velocidad: " + json.speed + " kbps Tiempo restante: " + json.time_left);
      }
      if(json.end != undefined) {
        uploading_simple = false;    
        $.post("/bin/ajax/upload/image", { sid: new_sid, image: $("#" + item_id + "_image").val(), width: width }, function(json) {
          if(json.file_name != undefined) {
            $("#" + item_id).css("background", "url(/bin/image?f=" + json.file_name + "&w=50) 0 0 no-repeat");
            // $("#profile_image_view").attr("src", "/bin/image?f=" + json.file_name + "&w=40");            
            $("#" + item_id + "_image").val(json.file_name);
          }
        }, "json");        
      } else {
        setTimeout("upload_simple_progress('" + new_sid + "', '" + item_id + "', " + width + ")", 1000);
      }
    } else {
      uploading = false;
      alert("Error: " + json.error);
      location.reload();
    }
  }, "json");
  return true;
}


function upload_simple_resize(item_id, width) {
  $("#" + item_id).css("background", "url(/css/images/ajax_32.gif) no-repeat center center");
  $.post("/bin/ajax/utils/sid", { }, function(json) {
    var new_sid = json.sid;
    uploading_simple = true;
    $("#main_form").attr("action", "/cgi-bin/upload.cgi?sid=" +  new_sid);    
    $("#main_form").attr("target", "destination_simple");
    $("#main_form").submit();
    $("#submit").click();
    upload_simple_resize_progress(new_sid, item_id, width);
    $("#main_form").attr("action", "");
    $("#main_form").removeAttr("target");
    // $("#upload_simple_file_selector").attr("value", "");
  }, "json");  
}

function upload_simple_resize_progress(new_sid, item_id, width) {  
  $.post("/bin/ajax/upload/status", { sid: new_sid }, function(json) {
    if(json.error == undefined) {
      if(json.percent != undefined) {
        // $("#pbUpload").progressBar(Math.floor(json.percent));        
        // $("#pbText").text("Tama\u00f1o: " + json.total_size + " Subido: " + json.uploaded + " Progreso: " + json.percent + "% Velocidad: " + json.speed + " kbps Tiempo restante: " + json.time_left);
      }
      if(json.end != undefined) {
        uploading_simple = false;    
        $.post("/bin/ajax/upload/image/resize", { sid: new_sid, image: $("#" + item_id + "_image").val(), width: width }, function(json) {
          if(json.file_name != undefined) {
            $("#" + item_id).css("width", json.width);
            $("#" + item_id).css("height", json.height);
            $("#" + item_id).css("background", "url(" + json.file_name + ") 0 0 no-repeat");
            // $("#profile_image_view").attr("src", "/bin/image?f=" + json.file_name + "&w=40");            
            $("#" + item_id + "_image").val(json.file_name);
          }
        }, "json");        
      } else {
        setTimeout("upload_simple_resize_progress('" + new_sid + "', '" + item_id + "', " + width + ")", 1000);
      }
    } else {
      uploading = false;
      alert("Error: " + json.error);
      location.reload();
    }
  }, "json");
  return true;
}




function upload_zip() {
  var file_name = $("#my_file").val().toLowerCase();
  file_name = file_name.substring(file_name.length - 3);
  if(file_name == "zip") {
    upload();
  } else {
    $("#my_file").val("");
    alert("El archivo debe ser un archivo comprimido en formato ZIP");
  }  
}

function upload_mp3() {
  var file_name = $("#my_file").val().toLowerCase();
  file_name = file_name.substring(file_name.length - 3);
  if(file_name == "mp3") {
    upload();
  } else {
    $("#my_file").val("");
    alert("El archivo debe ser un archivo de audio en formato MP3");
  }  
}

function upload() {
    uploading = true;
    $("#file_selector").hide();
    $("#progress_bar").show();
    $("#form_body").show();    
    $("#file_submit").click();
    var file_name = $("#my_file").val();
    while(file_name.indexOf("/") > 0) {
      file_name = file_name.substring(file_name.indexOf("/") + 1);
    }
    while(file_name.indexOf("\\") > 0) {
      file_name = file_name.substring(file_name.indexOf("\\") + 1);
    }
    file_name = file_name.substring(0, file_name.length - 4);
    $("#input_title").val(file_name);
    upload_progress();
}

function upload_progress() {
  $.post("/bin/ajax/upload/status", { sid: sid }, function(json) {
    if(json.error == undefined) {    
      if(json.percent != undefined) {
        $("#pbUpload").progressBar(Math.floor(json.percent));        
        $("#pbText").text("Tama\u00f1o: " + json.total_size + " Subido: " + json.uploaded + " Progreso: " + json.percent + "% Velocidad: " + json.speed + " kbps Tiempo restante: " + json.time_left);
      }
      if(json.end != undefined) {
        uploading = false;    
        $("#file_form").hide();      
        if($('#auto_submit').is(":checked")) {
          $("#submit").click();
        } else {
          $('#auto_submit_container').hide();
          $("#submit").show();
          if($("#collage_image").length != 0) {
            $("#collage_container").show();
            generar_collage();
          }
        }
      } else {
        setTimeout('upload_progress()', 1000);
      }
    } else {
      uploading = false;
      alert("Error: " + json.error);
      location.reload();
    }
  }, "json");
  return true;
}

function generar_collage() {
  $("#collage").css("background-image", "url(/css/images/ajax.gif)");
  var image = $("#collage_image").val();
  $.post("/bin/ajax/image/collage", { sid: sid, image: image }, function(json) {
    $("#collage").css("background-image", "url(" + json.collage + ")");
    $("#collage_image").val(json.collage);
  }, "json");
  return true;  
}

function generar_collage_from_database(id) {
  $("#collage").css("background-image", "url(/css/images/ajax.gif)");
  var image = $("#collage_image").val();
  $.post("/bin/ajax/image/collage", { post_id: id, image: image }, function(json) {
    $("#collage").css("background-image", "url(" + json.collage + ")");
    $("#collage_image").val(json.collage);
  }, "json");
  return true;  
}

function ajax_audio_add_play(sid) {
  $.post("/bin/ajax/audio", { sid: sid }, function(json) {    
    if(json.audio_play_count != undefined) {
      $("#audio_play_count_" + sid).text(json.audio_play_count);
    }
  }, "json");
}

function ajax_image_index(increment) {
  if(increment > 0) {
    index = index < (image_count - 1) ?  index + 1 : (image_count - 1);
  } else {
    index = index > 1 ? index - 1 : 0;    
  }
  $.post("/bin/ajax/image/index", { id: id, index: index }, function(json) {        
    $("#album").css("background-image", "url(" + json.image + ")");
    $("#album_info").text("Foto " + (index + 1) + " de " + image_count);
  }, "json");
}

function ajax_user_status() {
  var description = $("#user_status").val();
  if(description.length > 0) {
    $.post("/bin/ajax/user/status", { description: description }, function(json) {
      $("#user_status").val("");
      $("#user_status").trigger("keyup");
      $("#global_user_status").html(json.description);    
      $("#user_status_date").attr("title", json.date);
      $("#user_status_date").text(jQuery.timeago(json.date));
    }, "json");
  }
}

function charts_add_track() {
  $("#track_index").text($("#track_list").children().size());  
  var copy = $(".track_item_clone").clone();
  copy.removeClass("track_item_clone");
  copy.addClass("track_item");
  copy.removeAttr('id');
  // var file = copy.find("input:eq(0)").get(0);
  var id = new Date().getTime();
  id = "_" + id;
  var image = copy.find("img:eq(0)");
  image.attr("id", id);
  var link = copy.find("a:eq(0)");
  link.bind("click", function() {
    upload_modal(id);
    return false;
  });
  var image_input = copy.find("input:eq(2)");
  image_input.attr("id", id + "_input");    
  $("#track_list").append(copy);
  // $(".track_item_clone:eq(1)").removeAttr('id');  
  copy.show();
  charts_sort();
  $(".track_name").autocomplete("/bin/ajax/track/name/autocomplete", {
    dataType: "json",        
    multiple: false,  
    parse: function(data) {
      data = data.items;
      return $.map(data, function(row) { return { data: row, value: row.data, result: row.data } });
    },
    formatItem: function(row) {      
      return row.data;
		}
  }).result(function(e, item) {      
    $(this).parent().parent().find("img:eq(0)").attr("src", "/bin/image?f=" + item.image + "&w=40");
    $(this).parent().parent().find("input:eq(1)").val(item.id);
    $(this).parent().parent().find("input:eq(2)").val(item.image);
	});
}

function charts_remove_track(e) {
  if($("#track_list").children().size() > 2) {
    e.parents("li").remove();
    charts_sort();
  }  
}

function charts_sort() {
  var length = $("#track_list").children().size();
  for(var i = 0; i < length; i++) {
    // $("#track_list li:eq(" + i + ") div(0) span(0)").text(id);
    var selector = "#track_list li:eq(" + i + ") div:eq(0) span:eq(0)";
    $(selector).text((i + 1));
  }
}

function current_image(id) {  
  $("#comment_list").html('<center><div style="padding: 7px;"><img src="/css/images/ajax_i.gif" alt=""/></div></center>');
  $.post("/bin/ajax/fotos/comentarios", { id: id }, function(json) {
    $("#fotos_comentarios").html(json.html);
    $(".timeago").timeago();
  }, "json");    
}

function fotos_comment(id) {  
  if(id != undefined) {
    var comment = $("#input_comment").val();
    $.post("/bin/ajax/fotos/comentarios", { id: id, description: comment }, function(json) {
      $("#fotos_comentarios").html(json.html);
    }, "json");    
  }
}

$(document).ready(function() {  
  $("#user_status").keyup(function() {
    var length = 140 - $(this).val().length;
    if(length >= 0) {
      $("#user_status_char_count").text(length);      
    } else {      
      $("#user_status").val($("#user_status").val().substr(0, 140));
    }    
  });  
  $("#user_status").autocomplete("/bin/ajax/user/status/autocomplete", {
    dataType: "json",
    matchStarts: "@",    
    multiple: true,    
    parse: function(data) {
      data = data.items;
      return $.map(data, function(row) { return { data: row, value: row.data, result: row.data } });
    },
    formatItem: function(row) {      
      return row.data;
		}
  });
  $(".track_name").autocomplete("/bin/ajax/track/name/autocomplete", {
    dataType: "json",        
    multiple: false,  
    parse: function(data) {
      data = data.items;
      return $.map(data, function(row) { return { data: row, value: row.data, result: row.data } });
    },
    formatItem: function(row) {      
      return row.data;
		}
  }).result(function(e, item) {
    $(this).parent().parent().find("img:eq(0)").attr("src", "/bin/image?f=" + item.image + "&w=40");
    $(this).parent().parent().find("input:eq(1)").val(item.id);
    $(this).parent().parent().find("input:eq(2)").val(item.image);
	});
  $("#message_to").autocomplete("/bin/ajax/user/alias/autocomplete", {
    dataType: "json",        
    multiple: false,  
    parse: function(data) {
      data = data.items;
      return $.map(data, function(row) { return { data: row, value: row.data, result: row.data } });
    },
    formatItem: function(row) {      
      return row.data;
		}
  }).result(function(e, item) {
		$("#message_to").css("background", "url(/bin/image?f=" + item.image + "&w=20) no-repeat 4px 4px");
		$("#message_to").css("padding-left", "26px");		
	});
  $("#audio_styles").autocomplete("/bin/ajax/track/style/autocomplete", {
    dataType: "json",        
    multiple: true,  
    parse: function(data) {
      data = data.items;
      return $.map(data, function(row) { return { data: row, value: row.data, result: row.data } });
    },
    formatItem: function(row) {      
      return row.data;
		}
  });	
  window.onbeforeunload = function() {    
    if(uploading || uploading_simple || uploading_modal) {
      return "Est\xe1s en medio de un proceso de subida de archivos y debes esperar hasta que termine.\r\n\xbfQuieres cancelar el proceso?";
    }
  }
  if($("#track_list").length != 0) {
    $("#track_list").sortable({
      opacity: 		0.8,
      fx:				100,
      axis:			'vertically',
      opacity:		0.4,
      revert:			true,
      update: function() {
        charts_sort();
      }
    });
  }
  if($(".input_textarea").length != 0) {
    $(".input_textarea").autogrow();
  }
  if($("#comment_text_area").length != 0) { 
    $("#comment_text_area").keyup(function() {
      if($(this).val() == "") {
        textarea_parsed = false;
        $("#status_content").hide();
      }
      if(!textarea_parsed) {        
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        var array = $(this).val().split(" ");
        if(array.length == 1 && array[0] == "") {
          $("#status_content").hide();
          $("#ext_content").val("");
        } else {          
          for (var n = 0; n < array.length; n++) {
            if(regexp.test(array[n])) {
              $("#status_content").html('<div style="margin: 4px;"><img src="/css/images/ajax_32.gif" alt="Cargando"/></div>');
              $("#status_content").show();
              textarea_parsed = true;
              $.post("/bin/ajax/content/parser", { url: array[n] }, function(json) {
                if(json.html != undefined) {                  
                  $("#status_content").html(json.html);
                  $("#ext_content").val(json.url);              
                } else {                
                  $("#status_content").hide();
                  $("#ext_content").val("");
                } 
              }, "json");                      
            }
          }
        }
      }
    });    
  }
  if($(".list_item").length != 0) {
    $(".list_item").bind("mouseenter", function(e) {
      var id = "#list_controls_" + $(this).attr("id");
      $(id).show();
    });
    $(".list_item").bind("mouseleave", function(e) {
      var id = "#list_controls_" + $(this).attr("id");
      $(id).hide();
    });
    $(".list_item_delete").bind("mouseenter", function(e) {
      var id = "#" + $(this).attr("id").substring(1);      
      $(id).css("background-color", "#eeeeff");
    });
    $(".list_item_delete").bind("mouseleave", function(e) {
      var id = "#" + $(this).attr("id").substring(1);
      $(id).css("background-color", "#ffffff");
    });
  }
  if($(".delete-comment").length != 0) {    
    $(".delete-comment").bind("mouseenter", function(e) {
      var id = $(this).attr("id").substring($(this).attr("id").indexOf("_") + 1);
      id = "#comment_id_" + id;      
      $(id).css("background-color", "#eeeeff");
    });
    $(".delete-comment").bind("mouseleave", function(e) {
      var id = $(this).attr("id").substring($(this).attr("id").indexOf("_") + 1);
      id = "#comment_id_" + id;
      $(id).css("background-color", "#ffffff");
    });  
    $(".delete-comment").bind("click", function(e) {
      var id = $(this).attr("id").substring($(this).attr("id").indexOf("_") + 1);
      delete_comment(id);      
    });  
  }
  if($("#status").length != 0) {
    $("#status").autogrow( { editor: false } );
    $("#status").focus(function() {
      if($("#status").val() == "\u00BFQu\u00E9 haces\u003F") {
       $("#status").val("");
       $("#status").css("font-size", "12px");
       $("#status_controls").show();
       textarea_parsed = false;
      }      
    });
    $("#status").blur(function() {
      if($("#status").val() == "") {
       $("#status").val("\u00BFQu\u00E9 haces\u003F");
       $("#status").css("font-size", "20px");
       $("#status_controls").hide();
      }            
    });
    $("#status").keyup(function() {
      if($(this).val() == "") {
        textarea_parsed = false;
        $("#status_content").hide();
      }
      if(!textarea_parsed) {        
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        var array = $(this).val().split(" ");
        if(array.length == 1 && array[0] == "") {
          $("#status_content").hide();
        } else {
          for (var n = 0; n < array.length; n++) {
            if(regexp.test(array[n])) {
              $("#status_content").html('<div style="margin: 4px;"><img src="/css/images/ajax_32.gif" alt="Cargando"/></div>');
              $("#status_content").show();
              textarea_parsed = true;
              $.post("/bin/ajax/content/parser", { url: array[n] }, function(json) {
                if(json.html != undefined) {                  
                  $("#status_content").html(json.html);                
                } else {                
                  $("#status_content").hide();
                } 
              }, "json");                      
            }
          }
        }
      }
    });
    $("#status").autocomplete("/bin/ajax/user/status/autocomplete", {
      dataType: "json",
      matchStarts: "@",    
      multiple: true,    
      parse: function(data) {
        data = data.items;
        return $.map(data, function(row) { return { data: row, value: row.data, result: row.data } });
      },
      formatItem: function(row) {      
        return row.data;
		  }
    });
  }
  if($(".comment_form").length != 0) {
    ajax_comment();
  }
  if($("#map").length != 0) {    
    var mapOptions = {
      zoom: zoom,
      center: center,
      navigationControl: true,
      scaleControl: true,
      mapTypeId: google.maps.MapTypeId.SATELLITE      
    }
    map = new google.maps.Map(document.getElementById("map"), mapOptions );
    geocoder = new google.maps.Geocoder();
    if(zoom == 15) {
      createMarker(center);
    }
    google.maps.event.addListener(map, 'click', function(event) {
      findingAddress = true;
      if(marker == null) {
        createMarker(event.latLng);
      } else {
        marker.setPosition(event.latLng);
      }
      $("#lat").val(event.latLng.lat());
      $("#lng").val(event.latLng.lng());
      geo(event.latLng);
      findingAddress = false;
      return false;
    });    
  }
  test_processing();
  if($("form").length > 0) {
    setTimeout("ticket()", 3000);
  }  
  $(".lightbox").lightbox({
    fitToScreen: true,
    imageClickClose: true
  });
  if($(".audio-comments").length != 0) {    
    $(".audio-comments").click(function(e) {
      if($(this).hasClass("can-comment") && CAN_COMMENT == true) {
        var id = $(this).attr("id");
        id = id.substring(id.indexOf("_") + 1);    
        var offset = $(this).offset();
        var relativeX = Math.ceil(e.pageX - offset.left);
        time_comment(id, relativeX, e.clientX, e.clientY);    
      }
    });
  }
  if($(".timestamped-comment").length != 0) {    
    $(".timestamped-comment").click(function(e) {
      CAN_COMMENT = false;
      return false;
    });
    $(".timestamped-comment").bind("mouseleave", function(e) {
      CAN_COMMENT = true;
      return false;            
    });    
  }  
  $(".tip").tooltip();
  if($("#radio-items").length != 0) {
    setTimeout("radioParrillaUpdate()", 15000);
  }  
  if($("#radio-sidebar").length != 0) {
    setTimeout("radioSidebarUpdate()", 15000);
  }  
});

function radioSidebarUpdate() {
  var radioItem = $("#radio-item").find("div:eq(0)");
  var array = radioItem.attr("id").split("-");
  var data = new Object();  
  data["id"] = array[2];
  data["type"] = "sidebar";
  $.post("/bin/ajax/radio/parrilla/update", { data: data }, function(json) {
    if(json.html != undefined) {
      $("#radio-sidebar").html(json.html);
      $(".timeago").timeago();
    }
  }, "json");     
  setTimeout("radioSidebarUpdate()", 15000);
}

function radioParrillaUpdate() {
  var radioItem = $("#radio-items").find("li:eq(0)");
  var array = radioItem.attr("id").split("-");
  var data = new Object();
  data["id"] = array[2];
  data["type"] = "parrilla";
  $.post("/bin/ajax/radio/parrilla/update", { data: data }, function(json) {
    if(json.html != undefined) {
      $("#parrilla-radio").html(json.html);
      $(".timeago").timeago();
    }
  }, "json");      
  setTimeout("radioParrillaUpdate()", 15000);
}

function ticket() {
  $("form").each(function() {
    $(this).append('<input type="hidden" name="ticket" value="1" />');
  });    
}

function createMarker(l) {
  marker = new google.maps.Marker({
      title: 'Lugar',
      position: l, 
      map: map,
      draggable: true
  });      
  map.setCenter(l);
  google.maps.event.addListener(marker, 'dragend', function() {
    geo(marker.getPosition());
    map.setCenter(marker.getPosition());
    $("#lat").val(marker.getPosition().lat());
    $("#lng").val(marker.getPosition().lng());    
  });
}

var findingAddress = false;

function findAddress() {
  if(!findingAddress) {
    var address = document.getElementById("direccion").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        map.setZoom(15);
        // alert(results[0].formatted_address);
        // $("#direccion").val(results[0].formatted_address);
        if(marker == null) {
          createMarker(results[0].geometry.location);
        } else {
          marker.setPosition(results[0].geometry.location);
        }
        $("#lat").val(results[0].geometry.location.lat());
        $("#lng").val(results[0].geometry.location.lng());
      }
    });
  }
}

function geo(l) {
  geocoder.geocode({'latLng': l}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {      
      if(results.length > 0) {
        $("#direccion").val(results[0].formatted_address);
      }
    }
  });    
}

function ajax_comment() {
  $(".comment_form").submit(function() {      
    if(location.href.match(/\/sesiones\//i) || location.href.match(/\/producciones\//i)) {
      var data = $(this).serialize();
      $.post("/bin/ajax/item/comentario", { data: data }, function(json) {
        if(json.html != undefined) {
          $("#comment_container").html(json.html);
          $(".timeago").timeago();
          ajax_comment();          
          setTimeout("ticket()", 3000);
        }
      }, "json");      
      return false;
    }
    return true;
  });
}

function getUrl(s) {
  var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
  var array = s.split(" ");
  for (var n = 0; n < array.length; n++) {
    if(regexp.test(array[n])) {
      return array[n];
    }
  } 
  return null; 
}

function ajax_content_create(e) {
  var url = getUrl(e.val());
  var content = e.val();
  $.post("/bin/ajax/content/create", { url: url, content: content }, function(json) {
    if(json.error == undefined) {
      location.reload();
    } else {
      alert(json.error);
    }
  }, "json");                      
}

function comunidad_comentario_star(id) {
  $.post("/bin/ajax/comunidad/star", { id: id }, function(json) {
    $("#comunidad_star_" + id).html(json.html)
    $("#comunidad_star_" + id).show();
  }, "json");
  return false;
}

function item_favorito(id) {
  $.post("/bin/ajax/item/favorito", { id: id }, function(json) {
    if(json.error == undefined) {
      if(json.count != undefined) {
        $("#favorito_" + id).text(json.count);
      }
    } else {
      alert(json.error);
    }
  }, "json");
  return false;
}

function external_content(url, width, height, div) {
  url = url + "&rnd=" + Math.floor(Math.random()*11000);
  $("#" + div).show();
  swfobject.embedSWF(url, div, width, height, "9.0.0", "expressInstall.swf");
}

function submit_fotos() {
  $.post("/bin/ajax/fotos/progress/form", { }, function(json) {
    var form = json.form;
    $(form).modal();
    $("#submit_hidden").click();
  }, "json");
}

function test_processing() {
  if($(".processing").length > 0) {    
    $(".processing").each(function(i, selected){ 
      var id = $(selected).attr("id"); 
      id = id.substring(id.indexOf("_") + 1);
      $.post("/bin/ajax/item/processed", { id: id }, function(json) {
        if(json.html != undefined) {
          $("#item_" + json.id).html(json.html);
          $("#item_" + json.id).removeClass("processing");
          $(".timeago").timeago();
        }
      }, "json");
      
    });
    if($(".processing").length > 0) {
      setTimeout("test_processing()", 3000);     
    }
  } 
}


var form_comentario_time = {
  message: null,
  open: function (dialog) {    
    dialog.overlay.fadeIn(200);
    dialog.container.fadeIn(200);
    dialog.data.fadeIn(200);
  },
  show: function (dialog) {      
      $('#form_data').submit(function (e) {                        
        return false;
      });
      $('input[name=aceptar]').click(function() {
        var item_id = $("#item_id").val();
        var time = $("#time").val();
        var text = $("#comentario_text").val();
        $.post("/bin/ajax/item/comentario/time", { id: item_id, time: time, text: text }, function(json) {
          $.post("/bin/ajax/item/comentario/time/html", { id: item_id }, function(json) {
            $("#comments_" + item_id).html(json.html);
            $("#comments_" + item_id).find(".tip").tooltip();            
          }, "json");        
          dialog.overlay.fadeOut(200);
          $.modal.close();              
        }, "json");
        return false;
      });	    
  },
  close: function (dialog) {
      dialog.overlay.fadeOut(200);
      $.modal.close();
  }
};

function time_comment(id, relativeX, pageX, pageY) {  
  $.post("/bin/ajax/item/comentario/time/form", { id: id, time: relativeX }, function(json) {
    var form = json.form;
    $(form).modal({
      position: [pageY, pageX],
      overlayId: "form-overlay-dialog",
      containerId: "form-container-dialog",
      closeClass: "form-close-dialog",
      onOpen: form_comentario_time.open,
      onShow: form_comentario_time.show,
      onClose: form_comentario_time.close
    });    
  }, "json");  
}

function delete_comment(id) {
  $.post("/bin/ajax/item/comentario/delete", { id: id }, function(json) {
    location.reload();
  }, "json");    
}

function message_send() {
  if($("#message_id").length != 0) {
    $("#message_form").submit();
    return true;
  } else {
    var alias = $("#message_to").val();
    $.post("/bin/ajax/user/test/exist/alias", { alias: alias }, function(json) {
      if(json.result == true) {
        $("#message_form").submit();
        return true;
      } else {
        alert("El usuario no existe");
        return false;
      }
    }, "json");      
    return false;
  }
}

function message_delete(id, from) {
  $.post("/bin/ajax/user/message/delete", { id: id, from: from }, function(json) {
    if(json.url != undefined) {
      window.location = json.url;
    }    
  }, "json");      
}

function log(message) {
  $.post("/bin/ajax/user/test/exist/alias", { msg: message }, function(json) {
  }, "json");   
}
