/******************************************************************************************
* @autor: Michael Daxberger (md@isag.at)
******************************************************************************************/

/**
 * Simple setter method
 *
 * @param form (the form number)
 * @param element (the element number in the specified form)
 */
function setFocus(form, element) {
  document.forms[form].elements[element].focus();
}

/**
 * simple image changer method
 */
function changeImg(objImg, img) {
  objImg.src = img;
}

/**
 * Opens a new window for a specified file 
 */
function openWindow(file, width, height) {
  var date = new Date();
  var ms = date.getMilliseconds();

  var win = window.open(file, ms, "width=" + width + ",height=" + height + ",scrollbars=yes");  
  win.moveTo(screen.width / 2 - (width / 2),screen.height / 2 - (height / 2));
  win.focus();
}

/**
 * Closes the current window
 */
function closeWindow() {
  self.close();
}

/**
 * Resizes the current window
 */
function resizeWindow(width, height) {
  window.resizeTo(width, height);
}

/**
 * Closes the current window
 * and relaods the opener
 */
function closeWindowReloadOpener() {
  opener.location.reload();
  closeWindow();
}

/**
 * Trim function - removes white spaces at
 * the beginning / end of a string
 */
function trim(str) {
   return str.replace(/^\s*|\s*$/g,"");
}


/**
 * Checks the validity of a form value
 * This one is just called from checkMandatoryFields()
 */
function isValid(value) {
  value = trim(value);
  if (value != null &&
      value != "") {
    return true;    	
  }
  return false;
}

/**
 * Checks the validity of an email address
 * This one is just called from checkMandatoryFields()
 */
function isValidEmail(email) {
  email = trim(email);
  if (email.indexOf("@") == -1 ||
      email.indexOf("@") == 0  ||
      email.indexOf(".") == -1 ||
      email.length < 6) {
    return false;    	
  }
  return true;
}

/**
 * Checks the validity of a phone number
 * This one is just called from checkMandatoryFields()
 */
function isValidPhone(phone) {
  var isCorrectNumber = true;
  var validChars = "0123456789 -+";
  phone = trim(phone);
  for (j=0; j < phone.length; j++) {
    if (validChars.indexOf(phone.charAt(j)) == -1) {
      isCorrectNumber = false;
      break;
    }
  }
  if (phone.length < 4) {
    isCorrectNumber = false;
  }
  return isCorrectNumber;
}

/**
 * Checks all mandatory fields of a form with
 * CLASS="mandatory" - Fields
 */
function checkMandatoryFields(formObject) {
  var allFilled = true;
  var fields = formObject.elements;
  for (i=0; i < fields.length; i++) {
    if (fields[i].className == "mandatory") {
      if (!isValid(fields[i].value)) {
      	alert(unescape("Bitte f%FCllen Sie alle farbig hinterlegten Felder aus."));
      	formObject.elements[i].focus();
      	allFilled = false;
      	break;
      }
      if (fields[i].name && fields[i].name.toLowerCase().indexOf("mail") != -1) {
      	if (!isValidEmail(fields[i].value)) {
      	  alert(unescape("Bitte geben Sie eine g%FCltige E-Mail Adresse an."));
          formObject.elements[i].select();
          allFilled = false;
          break;
        }
      }
      if (fields[i].name && (fields[i].name.toLowerCase().indexOf("phon") != -1 ||
                             fields[i].name.toLowerCase().indexOf("fon") != -1 ||
                             fields[i].name.toLowerCase().indexOf("tel") != -1 ||
                             fields[i].name.toLowerCase().indexOf("mobile") != -1)) {
      	if (!isValidPhone(fields[i].value)) {
      	  alert(unescape("Bitte geben Sie eine g%FCltige Telefonnummer an."));
          formObject.elements[i].select();
          allFilled = false;
          break;
        }
      }
      // also check combo boxes ...
      if (fields[i].type.indexOf("select") != -1) {
        if (!isValid(fields[i].options[fields[i].options.selectedIndex].value)) {
          alert(unescape("Bitte f%FCllen Sie alle farbig hinterlegten Felder aus."));
          formObject.elements[i].focus();
          allFilled = false;
          break;
        }
      }
    }
  }
  
  return allFilled;
}

/**
* get some price (as string) and convert it to float
*/
function getValueAsFloat(valueObject) {
  var val = valueObject.value;

  // make float(1000000.35) of string(1.000.000,35)
  if (val.indexOf(",") > -1) {
    if (val.indexOf(".") > -1) {
      val = val.replace(/[.]/g, "");
    }
    val = val.replace(/[,]/g, ".");
  }
/*
  val = val.replace(/[.]/g, "");
  val = val.replace(/[,]/g, ".");
*/
  val = parseFloat(val);

  return val.toFixed(2);
}

/**
* format a number to string 
* (including pending comma chars, decimal and thousands seperators)
*/
function formatNumber(floatNumber, decimals, decimalPoint, thousandsPoint) {
  var tmpNumberString = String(floatNumber);
  if (tmpNumberString.indexOf(".") != -1) {
    var tmpNumberArray = tmpNumberString.split(".");
    // cut / fillup comma chars
    if (tmpNumberArray[1].length > decimals) {
      tmpNumberArray[1] = tmpNumberArray[1].substr(0,2);
    }
    else {      	
      while (tmpNumberArray[1].length != decimals) {
        tmpNumberArray[1] = tmpNumberArray[1] + "0";
      }
    }
    // set thousands seperator
    var charCounter = 0;
    for (i = tmpNumberArray[0].length - 3; i > 0; i -= 3) {
      tmpNumberArray[0] = tmpNumberArray[0].substr(0,i) + thousandsPoint + tmpNumberArray[0].substr(i,tmpNumberArray[0].length - i);
    }
  }
    
  return tmpNumberArray[0] + decimalPoint + tmpNumberArray[1];
}

/**
* copy a given text to clipboard with javascript
*/
function copy_clipboard(mytext) {
 if (window.clipboardData) {
   window.clipboardData.setData("Text", mytext);
 }
 else if (window.netscape) { 
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
   if (!clip) return;
   
   var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
   if (!trans) return;
   
   trans.addDataFlavor('text/unicode');
   var str = new Object();
   var len = new Object();
   
   var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
   var copytext=mytext;
   str.data=copytext;
   
   trans.setTransferData("text/unicode",str,copytext.length*2);
   
   var clipid=Components.interfaces.nsIClipboard;
   if (!clip) return false;
   
   clip.setData(trans,null,clipid.kGlobalClipboard);
 }
 else {
   alert("Well ... seems as wouldnt work this with your exotic browser. Please try IE or Mozilla ... ;-)");
 }
 return false;
}

/**
* simple function to call a new url
*/
function jumpTo(link) {
  if (link != "") {
    location.href = link;
  }
  createWaitingMessage("Loading");
}

/**
* get inner width of window (cross-browser)
*/
function getWindowInnerWidth() {
  var innerWidth;

  // all except Explorer
  if (self.innerHeight) {
    innerWidth = self.innerWidth;
  }
  // Explorer 6 Strict Mode
  else if (document.documentElement && document.documentElement.clientHeight) {
    innerWidth  = document.documentElement.clientWidth;
  }
  // other Explorers
  else if (document.body) {
    innerWidth = document.body.clientWidth;
  }

  return innerWidth;
}

/**
* get inner height of window (cross-browser)
*/
function getWindowInnerHeight() {
  var innerHeight;

  // all except Explorer
  if (self.innerHeight) {
    innerHeight = self.innerHeight;
  }
  // Explorer 6 Strict Mode
  else if (document.documentElement && document.documentElement.clientHeight) {
    innerHeight  = document.documentElement.clientHeight;
  }
  // other Explorers
  else if (document.body) {
    innerHeight = document.body.clientHeight;
  }

  return innerHeight;
}

/**
* function for checking all checkboxes with a given prefix in their name
*/
function cbx_check(checkboxPrefix,check) {
  var docElements = document.getElementsByTagName("input");
  for (i=0; i < docElements.length; i++) {
    currentElem = docElements[i];
    if (currentElem.type == "checkbox" && 
        currentElem.name.indexOf(checkboxPrefix) == 0) {
      currentElem.checked = check;
    }
  }
}

/**
* get part of name of all checked checkboxes as array
*/
function cbx_getSelectedValues(checkboxPrefix) {
  var selectedValues = new Array();
  var docElements = document.getElementsByTagName("input");
  for (i=0; i < docElements.length; i++) {
    currentElem = docElements[i];
    if (currentElem.type == "checkbox" && 
        currentElem.name.indexOf(checkboxPrefix) == 0 &&
        currentElem.checked) {
      selectedValues.push(currentElem.name.substring(checkboxPrefix.length));
    }
  }
  return selectedValues;
}

/**
* variables used for waiting dialog boxes
*/
var processDots = 1;
var processDotMessage = "";
var processImage = "";

/**
* append dots at the end of a message
*/
function dotIt() {
  var processMessage = processDotMessage + " ";
  for (dotCounter=0; dotCounter < processDots; dotCounter++) {
    processMessage += ".";
  }
  if (document.getElementById("process")) {
    document.getElementById("process").firstChild.nodeValue = processMessage;
  }
  processDots++;
  if (processDots > 3) {
    processDots = 1;
  }
}

/**
* create a message on screen with 3 "process-dots" at the end
*/
function createWaitingMessage(showMessage) {
  var dialogue = document.createElement("div");
  dialogue.className = "dialog";
  dialogue.style.top = ((getWindowInnerHeight() / 2) - 25) + "px";
  dialogue.style.left = ((getWindowInnerWidth() / 2) - 100) + "px";

  // a process-image was defined ... show it
  if (processImage != "") {
    var img = document.createElement("img");
    img.setAttribute("src",processImage);
    img.setAttribute("alt",showMessage);
    dialogue.appendChild(img);
  }
  var span = document.createElement("span");
  span.appendChild(document.createTextNode(" "));
  span.setAttribute("id","process");
  dialogue.appendChild(span);

  document.getElementsByTagName("body")[0].appendChild(dialogue);

  // init the status message
  processDotMessage = showMessage;
  dotIt();
  window.setInterval("dotIt()",500);
}

function showStatusSearching() {
  createWaitingMessage("searching");
}

function showHidePlusMinus(plus_minus_link,element_id) {
  var expand = "[+]";
  var collapse = "[-]";

  var element = document.getElementById(element_id);
  if (element) {
	if (element.style.display == "none") {
	  element.style.display = "";
	  plus_minus_link.firstChild.nodeValue = collapse;
	}
	else {
	  element.style.display = "none";
	  plus_minus_link.firstChild.nodeValue = expand;
	}
  }
}

/**
* get listprice (as string) and convert it to float
*/
function getValueAsFloat(valueObject) {
  var val = (typeof(valueObject) == "object" ? valueObject.value : valueObject);
  
  // default to 0 to prevent NaN errors
  if (val.length == 0) val = "0";

  // make float(1000000.35) of string(1.000.000,35)
  val = val.replace(/[.]/g, "");
  val = val.replace(/[,]/g, ".");
  val = parseFloat(val);

  return val.toFixed(4);
}
  
/**
* format a float value to string 
* (including pending comma chars and thousands seperators)
*/
function createFormatedPriceStringFromFloat(priceAsFloat) {
  var retVal = priceAsFloat;

  var tmpPriceString = String(priceAsFloat);
  if (tmpPriceString.indexOf(".") != -1) {
    var tmpPriceArray = tmpPriceString.split(".");
    // cut / fillup comma chars
    if (tmpPriceArray[1].length > 4) {
      tmpPriceArray[1] = tmpPriceArray[1].substr(0,4);
    }
    else {        
      while (tmpPriceArray[1].length < 2 ) {
        tmpPriceArray[1] = tmpPriceArray[1] + "0";
      }
    }
    // set thousands seperator (donīt forget the possible negativ flag here ...)
    var charCounter = 0;
    for (i = tmpPriceArray[0].length - 3; i > (priceAsFloat < 0 ? 1 : 0); i -= 3) {
      tmpPriceArray[0] = tmpPriceArray[0].substr(0,i) + "." + tmpPriceArray[0].substr(i,tmpPriceArray[0].length - i);
    }
     
    retVal = tmpPriceArray[0] + "," + tmpPriceArray[1];
  }
  else {
	retVal = tmpPriceString + ",00";
  }
    
  return retVal;
}
  
/**
* do some number format face lift ...
*/
function beautifyNumber(objNumberInputField) {
  objNumberInputField.value = createFormatedPriceStringFromFloat(getValueAsFloat(objNumberInputField));
}

function bgLock() {
  lock = document.createElement("div");
  lock.className = "bglock";
  lock.setAttribute("id","bglock");
  document.getElementsByTagName("body")[0].appendChild(lock);
}
 
function bgUnLock() {
  var lock = document.getElementById("bglock");
  if (lock) {
 document.getElementsByTagName("body")[0].removeChild(lock);
  }
}

