/* --------------------------------------------------------------
   $Id: general.js,v 1.1.1.1 2008/10/27 07:55:55 cvs Exp $   

   XT-Commerce - community made shopping
   http://www.xt-commerce.com

   Copyright (c) 2003 XT-Commerce
   --------------------------------------------------------------
   based on: 
   (c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
   (c) 2002-2003 osCommerce(general.js,v 1.2 2001/05/20); www.oscommerce.com 
   (c) 2003	 nextcommerce (general.js,v 1.4 2003/08/13); www.nextcommerce.org

   Released under the GNU General Public License 
   --------------------------------------------------------------*/

function SetFocus() {
  if (document.forms.length > 0) {
    var field = document.forms[0];
    for (i=0; i<field.length; i++) {
      if ( (field.elements[i].type != "image") && 
           (field.elements[i].type != "hidden") && 
           (field.elements[i].type != "reset") && 
           (field.elements[i].type != "submit") ) {

        document.forms[0].elements[i].focus();

        if ( (field.elements[i].type == "text") || 
             (field.elements[i].type == "password") )
          document.forms[0].elements[i].select();
        
        break;
      }
    }
  }
}


function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
}

function check_func(func,value){
	switch(func){
		case 'valid_email_address':
			return echeck(value);
			break;
		case 'code':
			var illegalChars = /[^a-z]/;
  			// allow only letters, numbers, and underscores
    		if (illegalChars.test(value)) {
       			return false;
    		} else {
    			return true;
    		}
			break;
		case 'int':
			if(value != parseInt(value))
				return false;
			else
				return true;
			break;
		case 'float':
			if(value != parseFloat(value))
				return false;
			else
				return true;
			break;
	}
}

function _validate_form_checkfield(field_preferences,field){
	var alert_str = '';
	var min = field_preferences['min'];
	var title = field_preferences['title'];
	if(field_preferences['validate_func']){
		if(!check_func(field_preferences['validate_func'],field.value))
			alert_str = title+"\r\n";
	}else{
		if(field.value.length < min){
			alert_str = title+"\r\n";
		}
	}
	return alert_str;
}

function validate_form(formname){
	alert_str = '';
	dom = document.forms[formname];
	validate_fields = checkfields.length;
	for(i=0;i<validate_fields;i++){
		el = dom.elements[ checkfields[i]['field'] ];
		// PRUEFEN OB FELD EIN ARRAY IST
		fieldname = checkfields[i]['field'];
		fieldsize = 1;
		if(fieldname.match(/\[\]$/)){
			if(dom.elements[fieldname].length){
				fieldsize = dom.elements[fieldname].length;
			}
		}
		if(fieldsize == 1){
			alert_str += _validate_form_checkfield(checkfields[i],el);
		}else{
			for(fs=0;fs<fieldsize;fs++){
				el = dom.elements[ checkfields[i]['field'] ][fs];
				alert_str += _validate_form_checkfield(checkfields[i],el);
			}
		}
	}
	if(typeof validate_form_addon != "undefined"){
		alert_str = alert_str + validate_form_addon(dom);
	}
	if(alert_str != ''){
		show_yes_alertbox(DEF_REQUIRED_FIELDS+'\r\n'+alert_str,400,250);
		return false;
	}else{
		dom.submit();
	}
}

function pager_row_onmouseover(tr,overcssclass,box_active){
	if(typeof (active_row) == 'undefined')
		active_row = tr;
	if(box_active){
		if(tr == active_row)
			return true;
	}
	tr_el = document.getElementById(tr);
	tr_el.className=overcssclass;
	tr_el.style.cursor='pointer';
}

function pager_row_onmouseout(tr,outcssclass,box_active){
	if(typeof(active_row) == 'undefined')
		active_row = tr;
	if(box_active){
		if(tr == active_row)
			return true;
	}
	tr_el = document.getElementById(tr);
	tr_el.className=outcssclass;
}

function pager_row_click(tr,clickcssclass,href,outcssclass,id){
	if(tr == active_row)
		return true;
	tr_el_active = document.getElementById(active_row);
	tr_el_active.className = outcssclass;
	active_row = tr;
	tr_el = document.getElementById(tr);
	tr_el.className=clickcssclass;
	ajax_show_tab(id);
}

var pager_tab_div_id = 'pager_tab';

function set_pager_tab_div_id(value){
	pager_tab_div_id = value;
}

var snippet_counter = 0;
function ajax_show_snippet(divid,page,additional_params){
  snippet_div_id = divid;
  params = 'page='+page+additional_params;
  var myAjax = new Ajax.Request(
    'ajax_snippet.php',
    { 
    	method: 'get', 
		parameters: params,
    	onComplete: show_snippet 
    }
  );
}
function show_snippet( originalRequest ) {
   $(snippet_div_id).innerHTML = originalRequest.responseText;
   snippet_counter++;
   // muss in der template datei definiert sein, zb in der customers_overview.html
   load_snippets();
}

var snippet_div_id = '';
function ajax_snippet_href(divid,get_params){
  snippet_div_id = divid;
  params = get_params;
  var myAjax = new Ajax.Request(
    'ajax_snippet.php',
    { 
    	method: 'get', 
		parameters: params,
    	onComplete: show_snippet_href 
    }
  );
}
function show_snippet_href( originalRequest ) {
   $(snippet_div_id).innerHTML = originalRequest.responseText;
}



function ajax_show_tab(id){
  if(typeof id!='undefined'){
	  params = 'id='+id+'&page='+AJAX_PAGER_VALUE;
  }else{
  	  params = 'empty=1';
  }
  var myAjax = new Ajax.Request(
    pager_tab_file,
    { 
    	method: 'get', 
	parameters: params,
    	onComplete: show_tab 
    }
  );
}

function show_tab( originalRequest ) {
   $(pager_tab_div_id).innerHTML = originalRequest.responseText;
}

function ajax_box_action(id,action){
  params = "id="+id+"&action="+action+"&page="+AJAX_PAGER_VALUE;
  var myAjax = new Ajax.Request(
    pager_tab_file,
    { 
    	method: 'get', 
	parameters: params,
    	onComplete: show_tab 
    }
  );
}

function checkbox_toggle(formid,checkboxid,status){
	dom = document.forms[formid];
	for(i=0;i<dom.elements[checkboxid].length;i++){
		dom.elements[checkboxid][i].checked = status;
	}
}

function pager_list_action(form_instance,action,add_parameter){
	if(action == '')
		return false;
	dom = form_instance;
	var checkboxid = 'id[]';
	var checked_elements = 0;
	if(dom.elements[checkboxid].length){
		for(i=0;i<dom.elements[checkboxid].length;i++){
			if(dom.elements[checkboxid][i].checked == true){
				checked_elements++;
			}
		}
	}else{
		if(dom.elements[checkboxid].checked == true){
			checked_elements++;
		}
	}
	if(checked_elements > 0){
		var go = true;
		confirming = get_pager_list_action_confirm(action);
		if(confirming){
			yes = confirm( confirming );
			if(!yes){
				go = false;
			}
		}
		if(go){
			dom.elements['action'].value = action;
			dom.elements['action_parameter'].value = add_parameter;
			dom.submit();
		}
	}
}

function get_pager_list_action_confirm(action){
	switch(action){
		case 'mark_as_read':
			return YES_JS_CONFIRM_REALLY_MARKASREAD;
			break;
		case 'delete':
			return YES_JS_CONFIRM_REALLY_DELETE;
			break;
		default:
			return false;
			break;
	}
}

function lightbox_on_click(el,url){
	clb = new lightbox(el);
	clb.content = url;
	clb.activate();
}

function toggleBox(szDivID) {
  if (document.layers) { // NN4+
    if (document.layers[szDivID].visibility == 'visible') {
      document.layers[szDivID].visibility = "hide";
      document.layers[szDivID].display = "none";
//      document.layers[szDivID+"SD"].fontWeight = "normal";
    } else {
      document.layers[szDivID].visibility = "show";
      document.layers[szDivID].display = "inline";
//      document.layers[szDivID+"SD"].fontWeight = "bold";
    }
  } else if (document.getElementById) { // gecko(NN6) + IE 5+
    var obj = document.getElementById(szDivID);
//    var objSD = document.getElementById(szDivID+"SD");

    if (obj.style.visibility == 'visible') {
      obj.style.visibility = "hidden";
      obj.style.display = "none";
//      objSD.style.fontWeight = "normal";
    } else {
      obj.style.visibility = "visible";
      obj.style.display = "inline";
//      objSD.style.fontWeight = "bold";
    }
  } else if (document.all) { // IE 4
    if (document.all[szDivID].style.visibility == 'visible') {
      document.all[szDivID].style.visibility = "hidden";
      document.all[szDivID].style.display = "none";
//      document.all[szDivID+"SD"].style.fontWeight = "normal";
    } else {
      document.all[szDivID].style.visibility = "visible";
      document.all[szDivID].style.display = "inline";
//      document.all[szDivID+"SD"].style.fontWeight = "bold";
    }
  }
}

//**************************************************************************
// AJAX INLINE-PAGE-FORM FUNCTION

   var http_request = false;
   var POSTRequestTargetScript = '';
   var POSTRequestForm = '';
   var POSTRequestAfterFunction = false;
   var POSTRequestAlertResult = true; // YES ALERTBOX NACH SUBMIT?
   var POSTRequestFormDIV  = '';
   function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            if(POSTRequestAlertResult){
	            show_yes_alertbox(result,500,350);
	        }else{
	        	if($(POSTRequestFormDIV).style.display == 'none'){
	        		$(POSTRequestFormDIV).toggle();
	        	}
	            document.getElementById(POSTRequestFormDIV).innerHTML = result;
	        }
	    if(POSTRequestAfterFunction){
		makePOSTRequestAfterFunction(result);
	    }
         } else {
            alert('There was a problem with the request.');
         }
      }
   }

   function makePostStr(){
	poststr = '';
	dom = document.forms[POSTRequestForm];
	saved_el = new Array();
	for(i=0;i<dom.length;i++){
		switch(dom[i].type){
			case 'button':
			case 'submit':
				break;
			default:
				el_name = dom[i].name;
				is_array = el_name.match(/\[\]/);
				if(is_array){
					if(!saved_el[el_name]){
						if(dom.elements[el_name].length){
							for(j=0;j<dom.elements[el_name].length;j++){
								if(dom.elements[el_name][j].checked == true){
									poststr += "&"+el_name+"="+dom.elements[el_name][j].value;
								}
							}
						}else{
							poststr += "&"+el_name+"="+encodeURI( document.getElementById(el_name).value );
						}
						saved_el[ el_name ] = true;
					}
				}else{
					poststr += "&"+el_name+"="+document.getElementById(el_name).value;
				}
				break;
		}
	}
	return poststr;
   }
   
   function get(obj) {
	poststr = makePostStr();
	makePOSTRequest(POSTRequestTargetScript, poststr);
   }
//**************************************************************************

var form_updater_div = '';
/**
 * WENN AN DEN STRING php_function_name EIN | ANGEHAENGT WIRD GEFOLGT VON EINEM INPUT-FELD-NAMEN
 * WIRD DIESER ALS 2. PARAMETER FUER DIE PHP FUNKTION VERWENDET  
*/
function ajax_update_dropdown(source_element,target_element_div,target_element_name,form_name,php_function_name){
	var func_split = php_function_name.split("\|");
	var second_parameter = '';
	if(func_split.length > 1){
		php_function_name = func_split[0];
		form_element_name = func_split[1];
		second_parameter = document.forms[form_name].elements[form_element_name].value;
		second_parameter = '&id2='+second_parameter;
	}
	third_parameter = '';
	source_onchange_element = document.forms[form_name].elements[target_element_name];
	target_onchange = source_onchange_element.getAttribute('onchange');

	if(target_onchange != null){
		third_parameter = '&onchange='+escape(target_onchange);
	}
	params = 'id='+source_element.value+'&target_element_name='+target_element_name+'&func='+php_function_name+second_parameter+third_parameter;
	form_updater_div = target_element_div;
	new Ajax.Updater(form_updater_div, 'ajax_form_element_updater.php', {
	  method: 'get',
	  parameters: params
	});
}

/**
SPEZIALFUNKTION FUER ANLEGEN EINES NEUEN LEEREN EXPORT_TARGETS
**/
var SSIRDhttp_request = false;
function set_ship_invoice_recipient_default(val){
 
	SSIRDhttp_request = false;
 
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            SSIRDhttp_request = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            try {
                SSIRDhttp_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    SSIRDhttp_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
 
        if (!SSIRDhttp_request) {
            alert('Ende :( Kann keine XMLHTTP-Instanz erzeugen');
            return false;
        }
        SSIRDhttp_request.open('GET', 'ajax_form_element_updater.php?action=shipinvoicecompany&id='+val, true);
        SSIRDhttp_request.onreadystatechange = set_ship_invoice_recipient_default_process;
        SSIRDhttp_request.send(null);
}
 
function set_ship_invoice_recipient_default_process() {
        if (SSIRDhttp_request.readyState == 4) {
              val = SSIRDhttp_request.responseText;
              document.forms['export_targets'].elements['invoice_recipient_id'].value = val;
        }
}


function lightbox_form_submit(forminstance){
  pager_tab_div_id = forminstance.name;
  formlink = forminstance.action;
  params = '';
  var myAjax = new Ajax.Request(
    formlink,
    { 
    	method: 'post', 
		parameters: params,
    	onComplete: show_tab 
    }
  );
}

function ajax_multiselect_add(formname,target_selectfieldname,yaliinstance){
	selectfield = document.forms[formname].elements[target_selectfieldname];
	positionelement = $('yaliposdiv'+target_selectfieldname);
	yali_start_from_link(selectfield,yaliinstance,positionelement);
}

function ajax_multiselect_remove(formname,target_selectfieldname){
	selectfield = document.forms[formname].elements[target_selectfieldname];
	selecteds = 0;
	for(i=0;i<selectfield.length;i++){
		if(selectfield.options[i].selected && selectfield.options[i].value != ''){
			selectfield.options[i] = null;
			selecteds++;
		}
	}
	for(i=0;i<selectfield.length;i++){
		selectfield.options[i].selected = true;
	}
	selectfield.size = selectfield.size - selecteds;
	if(selectfield.length < 1){
		selectfield.options[0] = new Option(YES_JS_TEXT_SELECT,'',false);
		selectfield.size = 1;
	}

}

function yes_tooltip(div_id,show){
	if(show)
		$(div_id).show();
	else
		$(div_id).hide();
}