/**
 * ============================================= 
 * Ginger - Coop Management
 *
 * Author: Oded Cnaan 
 * Email: oded@hi-take.com
 * Website: http://www.hi-take.com/coop.html 
 *
 * Copyright (c) 2008 Oded Cnaan
 * ============================================= 
 * PHP Version: 5.1
 * =============================================
 * Description: Various Javascript tools
 */        

var isIE=(document.all) ? true : false;
var isNN=(!document.all&&document.getElementById) ? true : false;
var isN4=(document.layers) ? true : false;
/**
 * Mail adddress validation
 */ 
function validateMailAddress(address){
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
  if (filter.test(address))
    return true;
  else{
    return false;
  }
}

/**
 * Allows typing only numeric keys
 */ 
function isNumberKey(evt) {
     var charCode = (evt.which) ? evt.which : evt.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
  
     return (charCode != 13);
}

/**
 * Allows typing only numeric keys, space and dash (not as first chars)
 */ 
function isPhoneNumberKey(evt) {
     var charCode = (evt.which) ? evt.which : evt.keyCode;
     if (charCode == 45 || charCode == 46) // - . 
      return true;
     len = (isIE ? evt.srcElement.value.length : evt.target.value.length); 
     if (len > 0 && charCode == 32) // SPACE
      return true;
     if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
     }   

     return (charCode != 13);
}

/**
 * Allows typing only numeric keys and dot (not as first char)
 */ 
function isFloatNumberKey(evt) {
   var charCode = (evt.which) ? evt.which : evt.keyCode;

   if (charCode == 46) { // .
    if (isIE)     
      period = evt.srcElement.value.indexOf('.');
    else
      period = evt.target.value.indexOf('.');
    return (period < 0);
   }
   if (charCode == 45) { // -
    return (isIE ? evt.srcElement.value == "" : evt.target.value == "");
   }
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return (charCode != 13);
}

function isLatin(evt) {
   var charCode = (evt.which) ? evt.which : evt.keyCode;
   if (charCode == 13 || charCode == 9 || charCode == 8 || (charCode>=37 && charCode<=40)) // enter, tab, backslash, arrows
    return true; 
   var latin = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@.-_";
   keychar = String.fromCharCode(charCode);   
   return (latin.indexOf(keychar) != -1);
}

function forceLatinWithMsg(evt) {
  lat = isLatin(evt);
  if (!lat) 
    alert('בשדה זה ניתן להכניס רק תוים באנגלית ומספרים\nעיברו לאנגלית והקלידו שנית');
    
  return lat;  
}
/**
 * Prevents form submission on ENTER
 */ 
function noenter() {
  return !(window.event && window.event.keyCode == 13); 
}

/**
 * Extending String with trim function
 */ 
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

String.prototype.startsWith= function(c){
  return (c)? (this.search(c)== 0): this.charAt(0);
}

/**
 * Loads a page into an innerHTML
 */
function loadFragmentInToElement(fragment_url, element_id) {   
   var xmlhttp = new XMLHttpRequest();
   var element = document.getElementById(element_id);   
   element.innerHTML = '<p><em>Loading ...</em></p>';   
   xmlhttp.open("GET", fragment_url,false);   
   xmlhttp.onreadystatechange = function() {   
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {   
           element.innerHTML = xmlhttp.responseText;   
       }   
   }   
   xmlhttp.send(null);   
}  

function getXmlHttpRequest() {
  if (!window.XMLHttpRequest) 
    return new ActiveXObject('Microsoft.XMLHTTP');
  else
    return new XMLHttpRequest();
}

function asyncOperation(url) {   
   var xmlhttp = getXmlHttpRequest();
   xmlhttp.open("GET", url,false);   
   //xmlhttp.onreadystatechange = function() {   
   //    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {   
   //        ;
   //    }   
  // }   
   xmlhttp.send(null);   
}  

/**
 * Open and external window
 */ 
function openExtWindow(url) {
  window.open(url,"extwin","status=0,toolbar=0,scrollbars=1,width=860,height=400,resizable=1");
}

function navigate(url) {
	window.location = url;
}

/**
 * Converts a price to a scale price (adding decimal digit on the right place)
 */ 
function convertToScalePrice(oldValue) {
  newValue = oldValue;
  if (oldValue.indexOf('.') == -1) {
    len = oldValue.length;
    if (len == 1)
      newValue = "0.0" + oldValue;
    else if (len == 2) {
      newValue = "0." + oldValue;
    }
    else if (len == 3) {
      newValue = oldValue.charAt(0) + "." + oldValue.substring(1);
    }
    else if (len >= 4) {
      newValue = oldValue.substring(0,len-2) + "." + oldValue.substring(len-2);
    }
  }
  return newValue;
}

function toggle_it(itemID){ 
    // Toggle visibility between none and inline 
    if ((document.getElementById(itemID).style.display == 'none')) 
    { 
      document.getElementById(itemID).style.display = 'inline'; 
    } else { 
      document.getElementById(itemID).style.display = 'none'; 
    } 
} 

function showElement(id) {
	document.getElementById(id).style.display = "inline";
}

function hideElement(id) {
  document.getElementById(id).style.display = "none";
}


function ajaxSend(url, reloadPageAfter, callback, callbackParam) {	
  var xmlhttp = getXmlHttpRequest()
  if (callback) {
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        callback(xmlhttp.status,callbackParam);
      }
    }
  }     
  xmlhttp.open("GET", url,(callback!=null));
  xmlhttp.send(null);  
  if (reloadPageAfter == true)
    reloadPage();
  else if (reloadPageAfter == false)
  	;
  else if (reloadPageAfter != "") {
  	window.location = reloadPageAfter;
  }
}

function ajaxSendPost(url, data, reloadPageAfter, callback, callbackParam) {	
  var xmlhttp = getXmlHttpRequest()
  if (callback) {
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        callback(xmlhttp.status,callbackParam);
      }
    }
  }     
  xmlhttp.open("POST", url,(callback!=null));
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send(data);  
  if (reloadPageAfter == true)
    reloadPage();
}

function ajaxRetrieve(url, callback, callbackParam) {	
  var xmlhttp = getXmlHttpRequest()
  if (callback != null && typeof callback == 'function') {
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        callback(xmlhttp.status,xmlhttp.responseText,callbackParam);
      }
    }
  }
  xmlhttp.open("GET", url,(callback!=null));
  xmlhttp.send(null); 
}

function reloadPage() {
  window.location = window.location;
}

function formatDateFromDB(dbdate) {
  var dateArray = dbdate.split('-');
  if (dateArray.length != 3)
    return "00-00-0000";
  return dateArray[2] + "-" + dateArray[1] + "-" + dateArray[0]; 
}

function formatDateTimeFromDB(dbdatetime) {
  var dateTime = dbdatetime.split(' ');
  var dateArray = dateTime[0].split('-');
  if (dateArray.length != 3)
    return "00-00-0000 00:00:00";
  return dateArray[2] + "-" + dateArray[1] + "-" + dateArray[0] + " " + dateTime[1]; 
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function remove_number_format(number,thousands_sep) {
    var t = thousands_sep == undefined ? "," : thousands_sep;
	s = number.toString().replace(t,'');
	return new Number(s);	
}

function getInnerHtmlPriceById(id) {
  obj = document.getElementById(id);
  return getInnerHtmlPriceByElement(obj);
}

function getInnerHtmlPriceByElement(obj) {
  if (obj == null)
    return null;
  return remove_number_format(obj.innerHTML);
}

function setInnerHTMLPriceById(id,price) {
  obj = document.getElementById(id);
  return setInnerHtmlPriceByElement(obj,price);
}

function setInnerHtmlPriceByElement(obj,price) {
  if (obj == null)
    return null;
  obj.innerHTML = number_format(price,2);
}

function openCalculator() {
  window.open("/calc.html","extwin","status=0,toolbar=0,scrollbars=0,location=0,menubar=0,width=233,height=300,resizable=0");	
}

//helper function to create the form
function getNewSubmitForm(){
 var submitForm = document.createElement("form");
 document.body.appendChild(submitForm);
 submitForm.method = "POST";
 return submitForm;
}

//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
 var newElement = document.createElement("input");
 newElement.setAttribute('name',elementName);
 newElement.setAttribute('type','hidden');
 //var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>");
 inputForm.appendChild(newElement);
 newElement.value = elementValue;
 return newElement;
}

function addTabHeader(tabID, title, index) {
	//<li class="tab"><a href="#tab1">title</a></li>
	ul = document.getElementById(tabID);
	var li = document.createElement('li');
	li.setAttribute("className","tab"); // IE
	li.setAttribute("class","tab"); // FF
	var a = document.createElement('a');
	a.setAttribute("href","#tab"+index);
	a.innerHTML = title;
	li.appendChild(a);
	ul.appendChild(li);		
}

function getRadioCheckedValue(myform,mygroup) {
	var radioGrp = document['forms'][myform][mygroup];
	for( i = 0; i < radioGrp.length; i++ ) {
		if( radioGrp[i].checked == true )
			return radioGrp[i].value;
	}
	return null;	
}

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);    // Not entirely sure if this is necessary
    form.submit();
}
