
function isArray(obj){
    return (obj.constructor.toString().indexOf("Array") != -1); 
}

/*
 * debug output
 */ 
function showObj(obj){
    if (obj == null) {
        alert('OBJ == null');
        return;
    }
    
    var output = '';
    if (isArray(obj)) {
        output = 'ARRAY: ';
    }
    else {
        output = 'OBJ: ';
    }
    
    for (prop in obj) {
        if (isArray(obj)) {
            if (typeof (obj[prop]) == 'function') {
                continue;
            }
            output = output + " [" + prop + "] -> " + obj[prop] + ", ";
            continue;
        }
        if (typeof(eval("obj." + prop)) == 'function') {
            continue;
        }
        output = output + " " + prop + ":" + eval("obj." + prop) + ", ";
    }
    //console.log(output);
    alert(output);
}
/*
 * EXTJS
 */
Ext.ns('beeline');
beeline=new Object();
beeline.version=0.7;

/*
 * update given div with given url
 */
beeline.bpmupdate = function(divElement, strURL){
    el = Ext.get(divElement);
    if (!el) 
        return;
    var DivUpdater = el.getUpdater();
    
    var start = new Date().getTime();
    var end = 0;
	
    DivUpdater.update({
        scripts: true,
        url: strURL,
        callback: function(el, success, response, opt){
            if (success) {
							beeline.ajaxCallback();
              return true;
            }else{
							beeline.ajaxFailureCallback();
						}
        }
    });
    return;
}

/*
 * load url content in given div if div is empty
 * otherwise send command per ajax
 */
beeline.bpmload = function(divId, strURL){

    el = Ext.get(divId);
    if (!el) 
        return;
    
    // if not exist load
    if (el.dom.childNodes.length < 2) {
        Ext.Ajax.request({
            url: strURL + '?bpmload=1',
            success: function(XMLHttpRequest){
                alert('onreadystatechange: ' + XMLHttpRequest.onreadystatechange);
                var newEl = Ext.DomHelper.insertBefore(el, XMLHttpRequest.responseText);
                el = el.replaceWith(newEl).setStyle('display', 'block');
                
            }
            
        });
    }
    else { // just set as active
        Ext.Ajax.request({
            url: strURL,
            success: function(XMLHttpRequest){
                // do nothing or ingnore
            }
        });
    }
    
}
/*
 * parse parameter form url
 */
beeline.getParameter = function(url, parameter){
    parameter = parameter.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + parameter + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null) 
        return "";
    else 
        return results[1];
}
/*
 * create "GET" url out of form
 */
beeline.getUrlFormParameter = function(Form){
    var parameter = '';
    var symbol = '';
    
    for (i = 0; i < Form.elements.length; i++) {
        symbol = (parameter == '') ? '?' : '&';
        var HTMLInputElement = Form.elements[i];
        
        switch (HTMLInputElement.type) {
            case "text":
            case "textarea":
						case "password":
						case "file":
				      if (HTMLInputElement.className.substring(0,3)=='mce'){
					      var editor=tinyMCE.get(HTMLInputElement.id);
					      parameter = parameter + symbol + HTMLInputElement.name + '=' + encodeURIComponent(editor.getContent());
					      break;
				      }
            case "hidden":
			      case "select-one":
						  if (HTMLInputElement.name == 'CSPCHD' && HTMLInputElement.value == '') {
								alert('Fatal error CSPCHD missing');
							} 
              parameter = parameter + symbol + HTMLInputElement.name + '=' + encodeURIComponent(HTMLInputElement.value);
				      //parameter = parameter + symbol + HTMLInputElement.name + '=' + cspEncodeUTF8(HTMLInputElement.value);
              break;
            case "radio":
				      if (HTMLInputElement.checked)
					      parameter = parameter + symbol + HTMLInputElement.name + '=' + encodeURIComponent(HTMLInputElement.value);
				        break;
            case "button":
            case "submit":
                break;
            /*case "file":
				      Form.action="bpm.html.content.cPage.cls";
				      Form.submit();
				     */
				return "";    
            case "checkbox":
                if (HTMLInputElement.checked && HTMLInputElement.type!='hidden') {
                    parameter = parameter + symbol + HTMLInputElement.name + '=1';
                }
                else {
                    parameter = parameter + symbol + HTMLInputElement.name + '=0';
                }
                break;			
            default:
                alert("'getUrlFormParameter() todo: default for "+HTMLInputElement.type);
        }
    }
    return parameter;
}
/*
* return the value of the radio button that is checked
* return an empty string if none are checked, or
* there are no radio buttons
*/
beeline.getCheckedValue = function(radioObj){
    if (!radioObj) {
        return '';
    }
    var radioLength = radioObj.length;
    if (radioLength == undefined) 
        if (radioObj.checked) 
            return radioObj.value;
        else 
            return '';
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return '';
}
/*
 * split domain from url
 */
beeline.getUrl = function(url){
    var array = url.split("?");
    return array[0];
}
/*
 * create parameterstring for "GET" url 
 */
beeline.convertParameter = function(parmString){
    
	var convertedParms='';
	var parms=parmString.split('&');
	for (i = 0; i < parms.length; i++) {
		if ('CSPCHD' == parms[i].split('=')[0]) {
			convertedParms = convertedParms + parms[i].split('=')[0] + '=' + parms[i].split('=')[1] + '&';
		}
		else {
			convertedParms = convertedParms + parms[i].split('=')[0] + '=' + encodeURIComponent(parms[i].split('=')[1]) + '&';
		}
	}	
	return convertedParms;
}
/*
 * send Ajaxcommand/request as url
 */
beeline.sendCommand = function(ajaxUrl){
    Ext.Ajax.request({
        url: ajaxUrl,
        success: function(XMLHttpRequest){
            return;
        }
    });
}
/*
 * print array items to console
 */
showParm = function(parms){
  for (i = 0; i < parms.length; i++) {
    console.log(parms[i]);
  }  
}
/*
 * default alertBox
 * todo move to web
 */
beeline.alert = Ext.extend(Ext.util.Observable, {

    title: 'Überschrift',
    content: 'Inhalt',
    shadeBg: true,
    
    constructor: function(config){
        config = config || {};
        // check options
        if (typeof config.title == "undefined") {
            this.title = Ext.select('title').item(0).dom.innerHTML;
        }
        
        if (typeof config.content == "undefined") {
            this.content = title;
        }
        
        Ext.apply(this, config);
        beeline.alert.superclass.constructor.call(this, config);
        
        this.createBackground();
        this.createDom();
        this.makeDraggable();
    },
    
    createBackground: function(){
        if (Ext.get('alertBg') == null) {
            Ext.DomHelper.append(document.body, {
                tag: 'div',
                id: 'alertBg',
                cls: 'alertBg'
            });
        }
        Ext.get('alertBg').setStyle('display', 'block');
        if (this.shadeBg == false) {
            Ext.get('alertBg').setStyle('background-image', 'none');
        }
    },
    
    createDom: function(){
        if (Ext.get('alertbox') == null) {
            Ext.DomHelper.append(document.body, {
                tag: 'div',
                id: 'alertbox'
            });
        }
        var alertboxSpec = {
            tag: 'div',
            id: 'alertbox',
            cls: 'alertbox',
            children: [{
                tag: 'p',
                cls: 'alertboxTopLeft'
            }, {
                tag: 'p',
                cls: 'alertboxTopRight',
                html: this.title + '<span class="alertboxClose">&nbsp;</span>'
            }, {
                tag: 'div',
                cls: 'alertboxMiddleLeft',
                children: [{
                    tag: 'div',
                    cls: 'alertboxMiddleRight',
                    html: this.content
                }]
            }, {
                tag: 'p',
                cls: 'alertboxBottomLeft'
            }, {
                tag: 'p',
                cls: 'alertboxBottomRight'
            }]
        };
        Ext.get('alertbox').replaceWith(alertboxSpec);
        
        // position overlay box		
        var posX = this.getX();
        var posY = this.getY();
        
        Ext.get('alertbox').setX(posX);
        Ext.get('alertbox').setY(posY);
        // close overlay box
        Ext.select('.alertboxClose').addListener('click', function(){
            Ext.get('alertbox').setStyle('display', 'none');
            Ext.get('alertBg').setStyle('display', 'none');
        });
    },
    
    makeDraggable: function(){
    
        var posX = this.getX();
        var posY = this.getY();
        
        var diffToLeft = diffToTop = 0;
        Ext.select('.alertboxTopRight').addListener('mousedown', function(eventObj, target){
            diffToLeft = eventObj.xy[0] - posX;
            diffToTop = eventObj.xy[1] - posY;
            Ext.get(target).setStyle('cursor', 'move');
        });
        
        Ext.getBody().addListener('mousemove', function(eventObj){
            if (diffToLeft != 0) {
                var pos = eventObj.getXY();
                posX = pos[0] - diffToLeft;
                posY = pos[1] - diffToTop;
                Ext.get('alertbox').setXY([posX, posY]);
                Ext.get('alertbox').focus();
            }
        });
        
        Ext.getBody().addListener('mouseup', function(eventObj, target){
            diffToLeft = diffToTop = 0;
            Ext.get(target).setStyle('cursor', 'default');
        });
    },
    
    getX: function(){
        var X = parseInt(beeline.getInnerSize()[0] / 2) + parseInt(Ext.get('alertBg').getLeft()) - parseInt(Ext.get('alertbox').getWidth() / 2);
        return X < 10 ? 10 : X;
    },
    
    getY: function(){
        var Y = parseInt(beeline.getInnerSize()[1] / 2) + parseInt(Ext.get('alertBg').getTop()) - parseInt(Ext.get('alertbox').getHeight() / 2);
        return Y < 10 ? 10 : Y;
    }
    
});

/*
 * return browsersize as array [0]=width [1]=height
 */
beeline.getInnerSize=function() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
	return [ myWidth, myHeight ];
}
/*
 * return scrollsize as array [0]=X [1]=Y
 */	 
beeline.getScrollOffset=function() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

String.prototype.trim = function () {
    return this.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

beeline.ajaxCallback= function(){
	// override it in beeline.book or beeline.web
}

beeline.ajaxFailureCallback= function(){
  // override it in beeline.book or beeline.web
}
