/* variables */
var am_loading='templates/domainbullies/img/icon_loader.gif';
var am_notloading='templates/domainbullies/img/icon_loader_not.gif';

/********* ajax.js *********/

// explicitly replaces the content of specified HTML element with result of requesting src_url
// ajaxSetContent
function aasn(element_id, src_url){
		var callback = function(response_text, response_xml){

			// Execute js if any in the response <
			if (response_text.lastIndexOf('<!--endjs-->') != -1) {

				// Save js for executin later <
				var js = response_text.substring(0, response_text.lastIndexOf('<!--endjs-->'));

				// Remove js from html code <
				response_text = response_text.substring(response_text.lastIndexOf('<!--endjs-->'));
			}

			// Replace the content with a new one <
			aafc( element_id, response_text);

			// Execute js if any <
			if (js) {
				eval_custom(js.replace(/<!--endjs-->/gi, ''));
			}
			
			// Enable controls of for mif set up <
			if (submit_form_name != undefined) {
				aaec(submit_form_name);
			}
		};
		return aarq( src_url, callback);
}

// Override this to be ablwe to put params in post by prefixing them with _POST_ <
function aarq( src_url, success_handler, error_handler ){
		var req = null;

		if((!src_url) || (!success_handler))
			return false;

		if (window.XMLHttpRequest){
			req = new XMLHttpRequest();
		}else{
			if (window.ActiveXObject){
				ajaxIsIE = true;
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		if (req) {
			req.onreadystatechange = function(){
				if (req.readyState == 4) {
					try{
						if (req.status == 200) {
							success_handler(req.responseText, req.responseXML);
						} else {
							if(error_handler)
								error_handler();
						}
					}
					finally{}
				}
			};
			
			// Get all params <
			var src_url_arr = src_url.split('?');
			var params_str = src_url_arr[1];
			var url_pref = src_url_arr[0];
			
			var params = params_str == undefined ? '' : params_str.split('&');
			
			var get = '';
			var post = '';
			for (var i = 0; i < params.length; i++) {
				if (params[i].indexOf('_POST_') == 0) {
					post += (post == '' ? '' : '&') + params[i].substring(6);
				} else {
					get += (get == '' ? '' : '&') + params[i];
				}
			}
		
			// Send the request <
		    if (post == '') {   
		        req.open("GET", src_url, true);
		        req.send(null);
		    } else {		    	
		        req.open("POST", url_pref + '?' + get, true );            
		        req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		        req.send(post);    
		    }			
		}
		return false;
}

function setVisibility(element,visible){
	var eltag = document.getElementById( element );
	if(debug && !eltag)alert('No element by name "'+element+'"');
	eltag.style.display=visible?"block":"none";
}

/* eval -> eval_custom */
function aaej(src_url, spinner, argument){
	if(spinner)spinner_on(spinner);
		var callback = function(response_text, response_xml){
		aafc( element_id, response_text);
		eval_custom(response);
	};

		return aarq( src_url, callback);
}

var last_session_check = 0;

function checkSession(url,key){ 
        if(key==undefined)key='session is expired, relogin';
        // decoding encoded string
        else key=key.replace(/=/g,' ');
        
        var callback=function(response_text,response_xml){
                if(response_text.search(key)!=-1){
                        alert('Your session has expired. Please log in again.');
                        window.location='main.php';
                        return false;
                }
        }

        var curtime = new Date;
        if (last_session_check + 5000 < curtime.getTime()) {
        	last_session_check = curtime.getTime();
        	aarq(url, callback);	
        } else {
        	return true;
        }
}

function submitForm(form,spinner){
		var callback = function(response_text, response_xml){
			response_text = response_text.replace(/<!--endjs-->/gi, '');
			if(response_text){
				try {
						eval(response_text);
				}catch(e){
					// checking if session is expired and login is requested
					re = /session is expired, relogin/;
					if (response_text.search(re)!=-1){
						alert('Your session has expired. Please log in again.');
						window.location='main.php';
						return false;
					};

					eval_custom(response_text);
				}
			} else {
				//alert("Warning: Empty response from server");
			}
			if(spinner)spinner_off(spinner);
		};
		return aasf(form,null,callback);
}

/********* amodules3.js *********/
/* direct props set -> class change */
function expander_flip(name,id,button,expander_url){
	/*
	 * This opens / closes lister's expander. Use this function
	 * under 'onclick' for your table row. It will take care of
	 * adding additional row and loading content there. expander_url is
	 * a prefix, which will have id appended
	 */

	row=document.getElementById(name+"_"+id);

	expander_status = expander_is_open(name,id,button);
	if(expander_status=="_closing"){
		nextrow=row.nextSibling;
		row.parentNode.removeChild(nextrow);

		button_off(name+"_"+button+"_"+id);
	}else if(expander_status=="inline_active"){
		inline_hide(name,id);
		expander_flip(name,id,button,expander_url);
	}else if(expander_status=="_opening"){


		tmp=row.parentNode.firstChild;
		if(!tmp.firstChild)tmp=tmp.nextSibling;
		var header = tmp.firstChild;
		for(cs=1;header=header.nextSibling;cs++);

		newrow=document.createElement("tr");
		nextrow=row.nextSibling;
		if(!nextrow){
			row.parentNode.appendChild(newrow);
		}else{
			row.parentNode.insertBefore(newrow,nextrow);
		}
		/* -- rem by chk
		my_td=document.createElement("td");
		my_td.colspan=cs;
		-- /rem by chk*/

		/* TODO: here is some template-dependant stuff. It's better to move this thing
		 * out. Not sure if the temporary thing can me removed easily, but the background
		 * color should be customizable. And it's even better to use class names, BTW!
		 */
		bg="#FFFFFF";

		/* chk */
		//tmp = row./*parentNode.firstChild.*/childNodes;
		//alert(tmp.length);

		cll = newrow.insertCell(0);
		cll.className = 'inner_cell';
		/*
		cll.style.backgroundColor = bg;
		cll.style.borderWidth = '0 1px 1px 1px';
		cll.style.borderColor = '#000';
		cll.style.borderStyle = 'solid';
		cll.style.padding = '15px'; */

		cll.colSpan = cs; //row.parentNode.firstChild.childNodes.length;

		//cll.id = name+"_expandedcontent_"+id;
		cll.setAttribute('id', name+"_expandedcontent_"+id);

		cll.innerHTML = '<table border="0" height="200"><tr><td><div class="loader" style="display: block;">Loading. Stand by...</div></td></tr></table>';

		/* /chk */

		//newrow.innerHTML='<td style="background: '+bg+'; border: 1px solid black; border-top: 0px; padding: 15px" colspan="'+cs+'" id="'+name+"_expandedcontent_"+id+'" ><table cellspacing=0 cellpadding=0 border=0><tr><td valign=top><img src=amodules3/img/loading.gif></td><td>&nbsp;</td><td class="smalltext" align=center id="autoexpander_'+id+'" valign=top><b>Loading. Stand by...</b></td></tr></table></td>';
		// http://dev.adevel.com/chk/fssub.html
		// http://dev.adevel.com/chk/tmp/aaa&bbb=ccc

		aasn(name+"_expandedcontent_"+id, expander_url+id);

		//aasn(name+"_expandedcontent_"+id, 'http://php5.chk/freespech/admin/'+expander_url+id);
		expand('autoexpander_'+id,0);

		button_on(name+"_"+button+"_"+id);
	}else{
		/* other button is active. Close that one and open new one */
		expander_flip(name,id,expander_status,expander_url);
		expander_flip(name,id,button,expander_url);
	}

}
/* js executing, eval_custom */
function reloadGridRow(url,name,row_id,callback,settitle, reload_col){
		//row contents could not be replaced with aasn
		set_row_c=function(response_text, response_xml){
			// Execute js if any in the response <
			if (response_text.lastIndexOf('<!--endjs-->') != -1) {
				var js = response_text.substring(0, response_text.lastIndexOf('<!--endjs-->'));

				// Remove js from html code <
				response_text = response_text.substring(response_text.lastIndexOf('<!--endjs-->'));
			}

			//exploding string to an array of column values
			cols=response_text.split('<row_end>');
			id=name+'_'+row_id;
			row=document.getElementById(id);
			col=row.firstChild;
			i=0;
			while(col){
				if(col.innerHTML!=undefined){
					if ((reload_col == undefined) || (col.id == reload_col)){
						value=cols[i].split('<t>');
						col.innerHTML=value[0];
						//alert(row.parentNode.name);
						//row.parentNode.parentNode.refresh();
						if(settitle==true)col.title=value[1];
						// value[2] contains styles separated by <s>
						if(value[2]!=''){
							styles=value[2].split('<s>');
							for(j=0;j<styles.length;j++){
							// style cannot be assigned directly,
							// so we analyze and set every property
							style=styles[j].split('::');
							switch(style[0]){
								case 'color':
									col.style.color=style[1];
									break;
								case 'cursor':
									col.style.cursor=style[1];
									break;
								case 'title':
									col.title=style[1];
									break;
							}
						}
					}
				}
				i++;
			}
			col=col.nextSibling;
		}

		if(js!=undefined)eval_custom(js.replace(/<!--endjs-->/gi, ''));

		try {
			if(typeof(callback) != 'undefined') eval_custom(callback);
		} catch(e) {

		}
	}
	aarq(url, set_row_c);
}

function resetForm(form){
	var frm = document.getElementById(form);
	frm.reset();
	
	// Clear ip containers if any on the form <
	var ip_conts = document.getElementsByName('ip_cont');
	
	for (var i = 0; i < ip_conts.length; i++) {
	    ip_conts.item(i).innerHTML = '';
	}
	
}
