jQuery.noConflict();

/* **************************
 * section: google maps
 * **************************/
var map;
var gdir;
var geocoder = null;
var addressMarker;
var addressMarker;

function buildGoogleMaps() {
  if (jQuery('div#gmap_form').length > 0) {
    initialize();
  }

  else if (jQuery('#map_canvas').length > 0) {
    if (GBrowserIsCompatible()) {
      var map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng(longitude, latitude), 16);
      var point = new GLatLng(longitude, latitude);
      map.addOverlay(new GMarker(point));
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
    }
  }
}

function initialize() {
  if (jQuery('#map_canvas').length > 0) {
    if (GBrowserIsCompatible()) {
      map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng(longitude, latitude), 16);
      var point = new GLatLng(longitude, latitude);
      map.addOverlay(new GMarker(point));
      gdir = new GDirections(map, document.getElementById("directions"));
      GEvent.addListener(gdir, "load", onGDirectionsLoad);
      GEvent.addListener(gdir, "error", handleErrors);
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
    }
  }
}

function setDirections(fromAddress, toAddress, locale) {
  jQuery("#directions").html("");
  gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

function handleErrors() {
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert(gmap_unknown_address);
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert(gmap_server_error);
  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert(gmap_bad_key);
  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    alert(gmap_bad_request);
  else
    alert(gmap_unknown_error);
}

function onGDirectionsLoad() {
}

/* **************************
 * section: singleview
 * **************************/
function toggleTags() {
  jQuery("#fulltags").click(function() {
    if (jQuery("#full").css('display') == 'none') {
      jQuery("#fulltags").text(tags_hide);
    }

    else {
      jQuery("#fulltags").text(tags_show);
    }

    jQuery('#half').toggle();
    jQuery('#full').toggle();
  });
}

/* **************************
 * section: jstree
 * **************************/

function buildTree() {
  jQuery("#position_tree").jstree({

    "defaults" : {
      "html_titles" : false,
      "load_open"   : true
    },

    "themes" : {
      "theme" : "default",
      "dots"  : true,
      "icons" : true
    },

    "json_data" : {
      "ajax" : {
        "url" : url_ajax,
        "data" : function (n) {
          return { "id" : n == -1 ? entry_tree : n.attr("id")};
        },
        "dataType" : "jsonp",
        "success" : function (t) {
          if (t.length == 0) return false;
        }
      }
    },

    "plugins" : [ "themes","json_data","ui","hotkeys" ]
  })

    .bind("select_node.jstree", function (e, data) {
      var $id = jQuery(".jstree-clicked").parent().attr("id");
      var $name = jQuery(".jstree-clicked").text();

      var pos_info = jQuery.ajax({
        url: url_position.replace(/%25ID%25/, $id),
        async: false,
        success: function(pos_info) {

          if (pos_info.length > 0) {
            jQuery("#position_head").html('Information zu ' + $name);
            jQuery("#position_info").html(pos_info);
            jQuery("#position").show();
          } else {
            jQuery("#position_head").html('Information zu' + $name);
            jQuery("#position_info").html('Keine Informationen verfügbar');
            jQuery("#position").hide();
          }
        },
        beforeSend : function(xhr) {
          var $wait = '<div>' + url_indicator + '<\/div>';
          jQuery("#position_info").html($wait);

		  jQuery("#nameinfo").hide();
		  jQuery("#pinfo").hide();
        }
      });

      var html = jQuery.ajax({
        url: url_list + "/" + $id,
        dataType : "jsonp",
        async: false,
        success: function(data) {
          var string = "";
          jQuery(data).each(function (i) {
            string += '<a onClick="javascript:showPerson2(' + data[i].show + ');">' + data[i].name + '<\/a> <span style="color:#888;"> - ' + data[i].title + '<\/span><br />';
          });

          jQuery("#namelist").text($name);
          if (jQuery(string).text() == "") {
            jQuery("#plist").html(msg_noposition.replace(/%position%/, $name));
          } else {
            jQuery("#plist").html(string);
          }

        },
        beforeSend : function(xhr) {
          var $wait = '<div>' + url_indicator + '<\/div>';
          jQuery("#namelist").text(msg_position_label);
          jQuery("#plist").html($wait);
          jQuery("#pinfo").html(msg_position_descr);
          jQuery("#nameinfo").parent().hide();
        }
      });
    });

  if (entry_node > 0) {
    var $id = jQuery(".jstree-clicked").parent().attr("id");
    var $name = jQuery(".jstree-clicked").text();

    var pos_info = jQuery.ajax({
      url: url_position.replace(/%25ID%25/, entry_node),
      async: false,
      success: function(pos_info) {

        if (pos_info.length > 0) {
          jQuery("#position_head").html('Information');
          jQuery("#position_info").html(pos_info);
          jQuery("#position").show();
        } else {
          jQuery("#position_head").html('Information');
          jQuery("#position_info").html('Keine Informationen verfügbar');
          jQuery("#position").hide();
        }
      },
      beforeSend : function(xhr) {
        var $wait = '<div>' + url_indicator + '<\/div>';
        jQuery("#position_info").html($wait);
      }
    });

    var html = jQuery.ajax({
      url: url_flist + "/id/" + entry_node,
      dataType : "jsonp",
      async: false,
      success: function(data) {

        var string = "";
        jQuery(data).each(function (i) {
          string += '<a onClick="javascript:showPerson2(' + data[i].show + ');">' + data[i].name + '<\/a> <span style="color:#888;"> - ' + data[i].title + '<\/span><br />';
        });

        jQuery("#namelist").html('<b>Positionen</b>');
        if (jQuery(string).text() == "") {
          jQuery("#plist").html(msg_noposition.replace(/%position%/, $name));
        } else {
          jQuery("#plist").html(string);
        }
      },
      beforeSend : function(xhr) {
        var $wait = '<div>' + url_indicator + '<\/div>';
        jQuery("#namelist").text(msg_position_label);
        jQuery("#plist").html($wait);
        jQuery("#pinfo").html(msg_position_descr);
        jQuery("#nameinfo").parent().hide();
      }
    });
  }
}






function success(data) {
}

function mconvert(name) {
  name = name.toLowerCase();
  name = name.replace(/^\s+/, "");
  name = name.replace(/\s+$/, "");
  name = name.replace(/ä/, "ae");
  name = name.replace(/Ä/, "ae");
  name = name.replace(/ö/, "oe");
  name = name.replace(/Ö/, "oe");
  name = name.replace(/ü/, "ue");
  name = name.replace(/Ü/, "ue");
  name = name.replace(/ß/, "ss");
  name = name.replace(/[^a-z0-9-]/, "-");
  name = name.replace(/-+/, "-");

  return name;
}


function showPerson2(id, name) {
  named = mconvert(name);

  var html = jQuery.ajax({
    url: url_info.replace(/0000/, id).replace(/1111/, named),
    async: false,
    success: function (item) {
      jQuery("#pinfo").html(item);
      jQuery("#nameinfo").text(msg_about.replace(/%name%/, name));
      jQuery("#nameinfo").parent().show();

		  jQuery("#nameinfo").show();
		  jQuery("#pinfo").show();
    },
    beforeSend : function(xhr) {
      jQuery("#pinfo").html('<p>' + url_indicator + '<\/p>');
    }
  }).responseText;
}


/* **************************
 * section: listview
 * **************************/

function customvRange(input) {
  var prefix;

  var nmlength = input.id.length;

  var vfid = "valid_from_date";
  var vtid = "valid_to_date";

  var vflength = vfid.length;
  var vtlength = vtid.length;

  if (input.id.substring(nmlength - vtlength) == vtid) {
    prefix = input.id.substring(0, nmlength - vtlength);
  } else {
    prefix = input.id.substring(0, nmlength - vflength);
  }

  jQuery("#valid_from_date").val(jQuery("#valid_from_date").val());

  return {
    minDate :(input.id.substring(nmlength - vtlength) == vtid ?
      jQuery('#' + prefix + vfid).datepicker("getDate") : null),
    maxDate :(input.id.substring(nmlength - vflength) == vfid ?
      jQuery('#' + prefix + vtid).datepicker("getDate") : null)
  };
}

function customsRange(input) {
  var prefix;

  var nmlength = input.id.length;

  var vfid = "visible_from_date";
  var vtid = "visible_to_date";

  var vflength = vfid.length;
  var vtlength = vtid.length;

  if (input.id.substring(nmlength - vtlength) == vtid) {
    prefix = input.id.substring(0, nmlength - vtlength);
  } else {
    prefix = input.id.substring(0, nmlength - vflength);
  }


  if (jQuery('#' + prefix + 'archived_at').val() != '') {
    jQuery('#' + prefix + 'visible_to_date').change(function () {
      jQuery('#' + prefix + 'archived_at_date').val(jQuery('#' + prefix + 'visible_to_date').val());
    });
  }

  return {
    minDate :(input.id.substring(nmlength - vtlength) == vtid ?
      jQuery('#' + prefix + vfid).datepicker("getDate") : null),
    maxDate :(input.id.substring(nmlength - vflength) == vfid ?
      jQuery('#' + prefix + vtid).datepicker("getDate") : null)
  };
}


function searchFormFields() {
  jQuery("#valid_from_date").datepicker({beforeShow: customvRange});
  jQuery("#valid_from_date").datepicker(jQuery.datepicker.regional['de']);

  jQuery("#valid_to_date").datepicker({beforeShow: customvRange});
  jQuery("#valid_to_date").datepicker(jQuery.datepicker.regional['de']);

  if (jQuery("#datetime").val() != 'none') {
    jQuery(".vd").hide();
  }

  else {
    jQuery(".vd").show();
  }

  jQuery("#datetime").change(function() {
    if (jQuery("#datetime").val() == 'none') {
      jQuery(".vd").show();
    }

    else {
      jQuery(".vd").hide();
    }
  });

  if (jQuery("#region").val() != 'SEARCH') {
    jQuery(".locality").hide();
  }

  else {
    jQuery(".locality").show();
  }

  jQuery("#region").change(function() {
    if (jQuery("#region").val() == 'SEARCH') {
      jQuery(".locality").show();
    }

    else {
      jQuery(".locality").hide();
    }
  });

  jQuery("#cl").click(function() {
    if (jQuery("#tagcloud").css('display') == 'none') {
      jQuery("#cl").text(cloudHideString);
      jQuery("#tagcloud").show();
    }

    else {
      jQuery("#cl").text(cloudShowString);
      jQuery("#tagcloud").hide();
    }
  });

  jQuery("#search").click(function() {
    if (jQuery('#pdf').attr('checked')) {
      jQuery('#pdf').hide();
      jQuery('span#pdftext').html(pdftext);
    }
  });


  jQuery("#autocomplete_l").autocomplete(json_locality, jQuery.extend({},
    {
      dataType: 'jsonp',
      parse:    function(data) {
        var parsed = [];
        for (key in data) {
          parsed[parsed.length] = { data: [ data[key], key ], value: data[key], result: data[key] };
        }
        return parsed;
      }
    }, { max: 20, minChars: 3 })).result(function(event, data) {
      jQuery("#l").val(data[1]);
    });


  jQuery("#autocomplete_account_home_locality_id").autocomplete(json_locality, jQuery.extend({},
    {
      dataType: 'jsonp',
      parse:    function(data) {
        var parsed = [];
        for (key in data) {
          parsed[parsed.length] = { data: [ data[key], key ], value: data[key], result: data[key] };
        }
        return parsed;
      }
    }, { max: 20, minChars: 3 })).result(function(event, data) {
      jQuery("#l").val(data[1]);
    });

}


function tableSorter(table, field, order) {
  jQuery(table).tablesorter({sortList: [
    [field,order]
  ]});
}


jQuery('.slide img[src^="http://assets.t3"]').each(function(k, v) {
  jQuery(v).click(function() {
    jQuery.fancybox({'href': v.src, 'padding': 0,'changeFade': 0,'transitionIn':'none','transitionOut':'none','type':'image','titlePosition':'inside'});
  });
});

