function en_fieldattach(id, defaultValue) {
  el = jQuery('#'+id);
  el.focus(function() { en_fieldclick(id, defaultValue); });
  el.blur(function() { en_fieldblur(id, defaultValue); });
  en_fieldblur(id, defaultValue);
}
function en_fieldclick(id,defaultValue) {
  el = jQuery('#'+id);
  if (el.val() == defaultValue) el.val("");
  el.css("color", "#000000");
}
function en_fieldblur(id,defaultValue) {
  el = jQuery('#'+id);
  if (el.val() == "" || el.val() == defaultValue) {
    el.css("color", "#666666");
    el.val(defaultValue);
  }
}
function en_cart_add(url, elid, producttext) {
  jQuery.ajax({
    url: url,
    beforeSend: function(){
      jQuery("#"+elid+'_free').hide();
      jQuery("#"+elid+'_processing').show();
    },
    success: function(a, b, c){
      newcount = c.getResponseHeader('x-newproductcount');
      if (newcount != null) {
        el = jQuery('#cart_link');
        if (newcount == "") {
          var results = /\((\d+)\)/.exec(el.html());  // list ["x (1)", "1"]
          if (results == null) newcount = 1;
          else newcount = 1 + ((/\((\d+)\)/.exec(el.html()))[1] - 0);
        }
        el.html(cart_str['CART_NEWCOUNT'] + ' (' + newcount + ')');
      }
      
      went_ok = c.getResponseHeader('x-cartadd');
      if (went_ok != null) {
        jQuery("#"+elid).html(cart_str['CART_PUTINTO']);
      } else {
        window.location.href = url;
      }
      jQuery("#"+elid+'_free').show();
      jQuery("#"+elid+'_processing').hide();
    },
    error: function() {
      jQuery("#"+elid+'_free').show();
      jQuery("#"+elid+'_processing').hide();
      window.location.href = url;
    }
  });
  
  return false;
}

function trustee_checkboxhandler(domain_hash, domain) {
  var checkbox = jQuery('div#trustee_'+domain_hash+' input').first();
  if (checkbox.attr('checked')) {
    en_cart_add_trustee('/cart/edit-trustee.php?domain='+domain, domain_hash);
  }
  else {
    en_cart_add_trustee('/cart/edit-trustee.php?domain='+domain+'&action=del', domain_hash);
  }
}

function trustee_handlechoice(notecontainer_id, trustee_in_cart) {
  var checkbox = jQuery('div#trustee_'+notecontainer_id+' input').first();
  if (checkbox) {
    checkbox.attr('checked', trustee_in_cart);
  }
  jQuery('div#'+notecontainer_id+' .trustee_needed').each(function(dropdown) {
    dropdown.attr('disabled', !trustee_in_cart);
    dropdown.css('background-color', (trustee_in_cart) ? "#fff" : "#ccc");
  });
}

function en_cart_add_trustee(url, notecontainer_id) {
  jQuery.ajax({
    url: url,
    success: function(a, b, c){
      newcount = c.getResponseHeader('x-newproductcount');
      if (newcount != null) {
        el = jQuery('#cart_link');
        if (newcount == "") {
          var results = /\((\d+)\)/.exec(el.html());  // list ["x (1)", "1"]
          if (results == null) newcount = 1;
          else newcount = 1 + ((/\((\d+)\)/.exec(el.html()))[1] - 0);
        }
        el.html(cart_str['CART_NEWCOUNT'] + ' (' + newcount + ')');
      }
      
      if (c.getResponseHeader('x-cartadd') != null) {
          trustee_handlechoice(notecontainer_id, true);
      } else if (c.getResponseHeader('x-cartdel') != null) {
          trustee_handlechoice(notecontainer_id, false);
      }

      // if trustee was just added but not neccessarily needed, reload page, 
      // so even non-local contacs are offered via the dropdown
      if (jQuery('div#'+notecontainer_id+' .trustee_needed').length == 0){
          window.location.reload();
      }
    },
    error: function() {
      trustee_handlechoice(notecontainer_id, false);
    }
  });
}

function hintGetPos(src, was) {
  var val;
  var elem;
  if (was == "Left") val = src.offsetWidth;
  if (was == "Top") val = src.offsetHeight;

  elem = src; //.offsetParent;
  while (elem != null) {
    val += elem["offset"+was];
    elem = elem.offsetParent;
  }
  return val;
}
function hintGetElement() {
  return document.getElementById("hintDiv");
}
function hintShow(show) {
  jQuery('#hintDiv').css('visibility', (show ? "visible" : "hidden"));
}
var hintTimeoutId = false;
function hintMe(src, hintId){
  var box = hintGetElement();
  var cap = hints_cap[hintId];
  var text = hints_text[hintId];
  if (hintTimeoutId != false) {
      window.clearTimeout(hintTimeoutId);
      hintTimeoutId = false;
  }
  box.innerHTML = "<div class=hintTitle>" + cap + "</div><div class=hintText>" + text + "</div><div class=hintFooter>&nbsp;</div>";
  var v;
  v = hintGetPos(src,"Left") + 2; // 2px space between image and box
	if ((v+300)>window.innerWidth) {
		// 300px fensterbreite
		box.style.left = (v-300) + "px";
	} else {
		box.style.left = v + "px";
	}
  v = hintGetPos(src,"Top") - 11;
  box.style.top = v + "px";
  hintShow(true);
}

function hintZap() {
  hintTimeoutId = window.setTimeout("hintShow(false)", 300);
}
/* FrontForm support */
function validateInput_RenderResult(id, value, type, required, isError) {
  var fChk = document.getElementById("chk_"+id);
  if (fChk != null) {
    fChk.className = (isError) ? 'errorrow' : '';
  }
  var fRow = document.getElementById("row_"+id);
  if (fRow != null) {
    fRow.className = (isError) ? 'errorrow' : '';
  }
}
function validateInput(field, type, required) {
  var rowid = field.parentNode.parentNode.id;
  rowid = rowid.substring(4,rowid.length);
  var val = field.value.toString();
  validateFieldValue(rowid, val, type, required, validateInput_RenderResult);
  return;
}
function validateFieldValue(fieldname, value, type, required, callback) {
    // need to catch empty fields ASAP
    // IE6 cannot send empty headers and then flashes out js errors :(
    if (!value || value == '') {
        callback(fieldname, value, type, required, required);
        return;
    }

    var xreq = false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
     try {
      xreq = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       xreq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       xreq = false;
      }
     }
    @end @*/
    if (!xreq && typeof XMLHttpRequest!='undefined') {
        try {
            xreq = new XMLHttpRequest();
        } catch (e) {
        }
    }

    if (!xreq) return false;

    // set up our callback
    xreq.onreadystatechange = function () {
        try {
            if (xreq.readyState != 4) {
                // request is not yet complete
                return;
            }

            if (!xreq.responseXML || xreq.responseXML == null) {
                // not really necessary because we are in a try{} block,
                // but makes my life easier when debugging
                return;
            }

            var items = xreq.responseXML.firstChild.childNodes;
            var cfield = "";
            var cstate = "";
            if (items.length == 0) {
                // IE workaround
                items = xreq.responseXML.childNodes.item(1).childNodes;
            }

            for (var i = 0; i < items.length; i++) {
                if (items[i].nodeName == "result") {
                    cstate = items[i].textContent;
                    if (typeof cstate=='undefined') {
                        cstate = items[i].text;    // IE workaround
                    }
                }
                if (items[i].nodeName == "field") {
                    cfield = items[i].textContent;
                    if (typeof cfield=='undefined') {
                        cfield = items[i].text;    // IE workaround
                    }
                }
            }
            callback(fieldname, value, type, required, (cstate == 'ERROR'));

        } catch (e) {
        }
    }

    xreq.open("GET", "/util/checkfield.php", true);
    xreq.setRequestHeader("X-EN-CheckField", fieldname);
    xreq.setRequestHeader("X-EN-CheckType", type);
    xreq.setRequestHeader("X-EN-CheckValue", value);
    xreq.send("");
    return;
}
function contact_editSelected(DomainId, dropDownControlId, CookieName) {
  var el = document.getElementById(dropDownControlId);
  Cookie.set(CookieName, el.value, 0.5);
  document.location = '/profiles/handle/edit.php?id=' + el.value + '&flow=' + FlowLink + '&flowdomain=' + DomainId;
  return false;
}
function contact_bindEditLink(DomainId, dropDownControlId, editLinkContainerId) {
  var el = document.getElementById(dropDownControlId);
  var CookieName = 'FormSave' + DomainId + dropDownControlId;
  if (Cookie.get(CookieName) != null) {
      el.value = Cookie.get(CookieName);
  }
  Cookie.erase(CookieName);
  var html_a = '<a href="#" onClick="javascript:contact_editSelected(\'' + DomainId + '\',\'' + dropDownControlId + '\',\'' + CookieName + '\');return false;">';
  var html_a_end = '</a>';
  document.getElementById(editLinkContainerId).innerHTML = html_a + '<img src="/images/iface/edit.png" align=absmiddle">' + html_a_end + ' ' + html_a + cart_str['HANDLE_EDIT'] + html_a_end;
}
function generate_password(field) {
  var len = 8;
  var pw = '';
  var signs = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0");
  for(i = 0; i < len; i++) {
    var sign = Math.ceil(Math.random() * 1000) % 36;
    pw += signs[sign];
  }
  jQuery("#"+field+"_hint").css({display: "none"});
  var obj = jQuery('#'+field);
  obj.val(pw);
  obj.removeClass("incorrect");
}
function tour_forward(langsel, img_index, tour_strings) {
  var field = document.getElementById('tour_img');
  var tour_text = document.getElementById('tour_text');

  var new_index = img_index+1;
  if (new_index > 8) {
      new_index = 1;
  }

  field.innerHTML = '<img src="/images/tour/tour_' + langsel + '_'+ new_index +'.png" alt="">';
  tour_text.innerHTML = '<div id="tour_left"><img onclick="tour_backward(\'' + langsel + '\', ' + new_index + ', tour_strings)" src="/images/tour_left.png" alt="" style="cursor:pointer"></div><div id="tour_text_value"> ' + tour_strings[new_index] + ' </div><div id="tour_right"><img src="/images/tour_right.png" onclick="tour_forward(\'' + langsel + '\', ' + new_index + ', tour_strings)" alt="" style="vertical-align: middle; cursor:pointer"></div>';
}
function tour_backward(langsel, img_index, tour_strings) {
  var field = document.getElementById('tour_img');
  var tour_text = document.getElementById('tour_text');

  var new_index = img_index-1;
  if (new_index < 1) {
      new_index = 8;
  }

  field.innerHTML = '<img src="/images/tour/tour_' + langsel + '_'+ new_index +'.png" alt="">';
  tour_text.innerHTML = '<div id="tour_left"><img onclick="tour_backward(\'' + langsel + '\', ' + new_index + ', tour_strings)" src="/images/tour_left.png" alt="" style="cursor:pointer"></div><div id="tour_text_value"> ' + tour_strings[new_index] + ' </div><div id="tour_right"><img src="/images/tour_right.png" onclick="tour_forward(\'' + langsel + '\', ' + new_index + ', tour_strings)" alt="" style="vertical-align: middle; cursor:pointer"></div>';
}

function showJSConfirmTD(tableid, rowid, delid, text, url, colspan) {
  var table = document.getElementById(tableid);
  var start_row = document.getElementById(rowid);
	document.getElementById(delid).style.display = "none";

  var new_row = table.insertRow(start_row.rowIndex+1);
  new_row.style.background = "#fffbb6";

	var new_cell = new_row.insertCell(0);
	new_cell.colSpan = colspan;
	new_cell.style.verticalAlign = "middle";
	new_cell.style.padding="5px 10px 5px 10px";
	new_cell.innerHTML= '<img src="/images/neweasydesign/warning_16.png" class="inline_image"/>'+text + '<br><button class="confirm_button" onclick=\'deleteJSRow(this, "'+ tableid+ '", "'+delid+'")\'>nein</button><button class="confirm_button" id="'+rowid+'_yes" onclick="location=\''+url+'\'"\'">ja</button>';
  document.getElementById(rowid+"_yes").focus();
}

function deleteJSRow(rowid, table, delid) {
	var row_to_delete = rowid.parentNode.parentNode.rowIndex;
	document.getElementById(delid).style.display = "";
  document.getElementById(table).deleteRow(row_to_delete);
}
function show (layer){
  var el = jQuery('#'+layer);
  if (el) el.show();
}
function hide (layer){
  var el = jQuery('#'+layer);
  if (el) el.hide();
}
function show_or_hide(layer) {
  var el = jQuery('#'+layer);
  if (el) el.toggle();
}
function hide_multiple (id_array){
  for (var i = 0; i < id_array.length; i++) {
    hide(id_array[i]);
  };
}
function show_multiple (id_array){
  for (var i = 0; i < id_array.length; i++) {
    show(id_array[i]);
  };
}
function switch_to(args1, args2) {
  for (var i = 0; i < args1.length; i++) {
    show(args1[i]);
  };
  for (var i = 0; i < args2.length; i++) {
    hide(args2[i]);
  };
}
function switch_around(args1, args2) {
  for (var i = 0; i < args1.length; i++) {
    if (document.getElementById) {
      if (document.getElementById(args1[i]).style.display == "none") {
        show(args1[i]);
      }
      else if (document.getElementById(args1[i]).style.display == "block" || document.getElementById(args1[i]).style.display == ""){
        hide(args1[i]);
      }
    }
  };

  for (var i = 0; i < args2.length; i++) {
    if (document.getElementById) {
      if (document.getElementById(args2[i]).style.display == "none") {
        show(args2[i]);
      }
      else if (document.getElementById(args2[i]).style.display == "block" || document.getElementById(args2[i]).style.display == ""){
        hide(args2[i]);
      }
    }
  };
}

function switch_around_check(args1, args2, args3) {
  for (var i = 0; i < args1.length; i++) {
    if (document.getElementById) {
      if (document.getElementById(args1[i]).style.display == "none") {
        show(args1[i]);
      }
      else if (document.getElementById(args1[i]).style.display == "block" || document.getElementById(args1[i]).style.display == ""){
        hide(args1[i]);
      }
    }
  };
  for (var i = 0; i < args2.length; i++) {
    if (document.getElementById) {
      if (document.getElementById(args2[i]).style.display == "none") {
        show(args2[i]);
      }
      else if (document.getElementById(args2[i]).style.display == "block" || document.getElementById(args2[i]).style.display == ""){
        hide(args2[i]);
      }
    }
  };
  for (var i = 0; i < args3.length; i++) {
    if (document.getElementById) {
      if (document.getElementById(args3[i]).checked == "true") {
        document.getElementById(args3[i]).checked = "false";
      } else if (document.getElementById(args3[i]).checked == "false"){
        document.getElementById(args3[i]).checked = "true";
      }
    }
  };
}
function selectAllCheckfields(id_prefix, nr_of_elements, actor) {
	if (document.getElementById(actor).checked == true) {
		var newstatus = true;
	} else {
		var newstatus = false;
	}
	for (var i = 1; i <= nr_of_elements; i++) {
		document.getElementById(id_prefix + i).checked = newstatus;
	}
}

function pointer_cursor(element) {
	element.style.cursor="pointer";
}
function default_cursor(element) {
	element.style.cursor="default";
}
function saveReload(message) {
  var configForm = document.getElementById('configForm');
  var postField = document.getElementById('jscomm');
  postField.value = message;
  configForm.submit();
  return false;
}
function splitDomain(el) {
  return saveReload('action=splitdomain;domain='+el.innerHTML);
}
function addContact(el,tld,contacttype) {
  return saveReload('action=contact_add;tld='+tld+';type='+contacttype);
}
function editSelectedContact(dropDownControlId) {
  var el = document.getElementById(dropDownControlId);
  return saveReload('action=contact_edit;contact='+el.value);
}
function updateStatus(){
  saveReload('action=savestatus');
}
function updaterow(dropdown,id,tld,contact,type) {
  if(dropdown != "") {
    var contact = dropdown.options[dropdown.selectedIndex].value;
  }
  jQuery(document).ajaxStart(function(){
    jQuery("#load_"+id+"_"+type).show();
  });
  jQuery.post('/cart/configure.php?action=changedomainconfig&id='+id+'&tld='+tld+'&contact='+contact+'&handle='+type, function() {
    jQuery.post('/cart/configure.php?action=updatehandlenotes', function(data) {
      jQuery('#additionaluserinput').html(data);
    });
  });
  jQuery(document).ajaxStop(function(){
    jQuery("#load_"+id+"_"+type).hide();
  });
}
function importHandles(tld,id) {
  var textfield = document.getElementById("current_domains_" + id);
  var domainname = textfield.value;
  if(domainname == '---') return false;
  var handle_registrant = document.getElementById("hregistrant"+id);
  var handle_admin = document.getElementById("hadmin"+id);
  var handle_tech = document.getElementById("htech"+id);
  var handle_zone = document.getElementById("hzone"+id);

  jQuery.getJSON('/cart/configure.php?action=importhandles&tld='+tld+'&domain='+domainname, function(data) {
    if(data.registrant) {
      for (i=0;i < handle_registrant.length;i++) {
        if(handle_registrant.options[i].value == data.registrant) {
          handle_registrant.options[i].selected = true;
          updaterow("",id,tld,data.registrant,"registrant");
        }
      }
    }
    if(data.admin) {
      for (i=0;i < handle_admin.length;i++) {
        if(handle_admin.options[i].value == data.admin) {
          handle_admin.options[i].selected = true;
          updaterow("",id,tld,data.admin,"admin");
        }
      }
    }
    if(data.tech) {
      for (i=0;i < handle_tech.length;i++) {
        if(handle_tech.options[i].value == data.tech) {
          handle_tech.options[i].selected = true;
          updaterow("",id,tld,data.tech,"tech");
        }
      }
    }
    if(data.zone) {
      for (i=0;i < handle_zone.length;i++) {
        if(handle_zone.options[i].value == data.zone) {
          handle_zone.options[i].selected = true;
          updaterow("",id,tld,data.zone,"zone");
        }
      }
    }
  });
}
function setSelectedContactForAllDomains(dropDown) {
  var contact = dropDown.options[dropDown.selectedIndex].value;
  if (contact != "") {
    jQuery.post("/cart/configure.php?action=showconfigureform&contactid=" + contact, function(data){
      jQuery('#other_configform').html(data);
    });
  }
}

function translate_async(string_key, new_text, success_func) {
    if (new_text == null || new_text.trim().length == 0) return;

    if (success_func == null) {
        success_func = function(data) {
            // replace changed text in all elements w/ that string-key on current screen
            jQuery('span[data-stringkey="'+string_key+'"]').each(function(index) { jQuery(this).html(data); });
        }
    }
    jQuery.post('/ajax/translation.php', 
                {'action': 'settext', 'key': string_key, 'translation': new_text },
                success_func
                );

}

function show_translatebox(source_element) {
    var string_key = jQuery(source_element).attr('data-stringkey');
    var box = jQuery('<div />').addClass('translation_box');
    box.append(jQuery('<h2 />').append('Translate Text'));
    box.append(jQuery('<span />'));

    jQuery.get('/ajax/translation.php', 
                {'action': 'gettext-srclang', 'key': string_key, 'return_escaped': '1'},
                function (data) {
                    box.children('span').html(data);
                });

    box.append('<br />');
    box.append(jQuery('<textarea />'));
    box.append('<br />');
    box.append(jQuery('<button />').text('Save').click(function() {
        translate_async(string_key, box.children('textarea').val());
        box.remove();
    }));
    box.append(jQuery('<button />').text('Cancel').click(function() {
        box.remove();
    }));
    jQuery('body').append(box);
    box.children('textarea').focus();
}

var translation_tooltip = function() {
    var tooltip = null;
    var timer = 3000;
    var id = 'translation_tooltip';
    return  {
        show:function(event, source_span) {
            if (tooltip  != null) tooltip.remove();
            tooltip = jQuery('<div />').attr('id', id);
            tooltip.append('Translate');
            tooltip.css('display', 'block');
            tooltip.css('top', event.clientY+'px');
            tooltip.css('left', event.clientX+10+'px');
            tooltip.click(function() { jQuery(source_span).dblclick();});
            jQuery('body').append(tooltip);
        },
        hide:function(event, elid) {
           // if (tooltip  != null) {
           //     clearTimeout(tooltip.timer);
           //     tooltip.timer = setTimeout(function() {
           //             tooltip.fadeOut(400, function() { tooltip.remove();});
           //         }, timer);
           // }
        }
    };
}();

