function insertAfter(newElement,targetElement) {
    var parent = targetElement.parentNode;
    if (parent.lastChild == targetElement) {
        parent.appendChild(newElement);
    } else {
        parent.insertBefore(newElement,targetElement.nextSibling);
    }
}


function getSelectedOption(form_name,select_name)
{
    select_obj=eval("document."+form_name+"."+select_name);
    if (select_obj.selectedIndex<0) //select is empty
	return "";
    return select_obj.options[select_obj.selectedIndex].text;
}

function check_uncheck(form_name, check_box_name)
{
    if (eval("document."+form_name+"."+check_box_name).checked == true)
        eval("document."+form_name+"."+check_box_name).checked = false;
    else
        eval("document."+form_name+"."+check_box_name).checked = true;
}

function showHelp(subject,category)
{
    subject=escape(subject);
    category=escape(category);
    open(window.INTERFACE_URL + "help/show_help.php?subject="+subject+"&category="+category,"","width=500,height=300,scrollbars=yes,alwaysRaised=yes,dependent=yes,resizable=yes");
}

function showMultiStr(form_name,input_name,left_pad)
{
    input_obj=eval("document."+form_name+"."+input_name);
    open(window.INTERFACE_URL + "util/show_multistr.php?str="+input_obj.value+"&left_pad="+left_pad,"","width=500,height=300,scrollbars=yes,alwaysRaised=yes,dependent=yes,resizable=yes");
}

function showMultiStrByID(input_id,left_pad)
{
	input_obj = $(input_id);
	open(window.INTERFACE_URL + "util/show_multistr.php?str="+input_obj.value+"&left_pad="+left_pad,"","width=500,height=300,scrollbars=yes,alwaysRaised=yes,dependent=yes,resizable=yes");
}

/*
 user_type can be 'normal' or 'voip' used to select image and pass to user_exists.php
 update_timer: tell the timer to update the image in seconds. if set to zero, update immediately
*/
function updateUserAddCheckImage(user_type,current_username,update_timer)
{
    if(update_timer>=0)
    {
	if ((window.user_add_check_timer && window.user_add_check_timer<=0) || !window.user_add_check_timer)
	    setTimeout("updateUserAddCheckImage('"+user_type+"','"+current_username+"',-1)",500);
	window.user_add_check_timer=update_timer*1000+500;

    }
    else if (update_timer<0)
    {
	if (window.user_add_check_timer==0)
	{
	    img_obj=eval("document."+user_type+"_user_exists");
	    username=eval("document.user_edit."+user_type+"_username");
	    img_obj.src=window.INTERFACE_URL + "admin/user/check_user_for_add.php?image=t&username="+username.value+"&type="+user_type+"&current_username="+current_username;
	}
	else
	{
	    window.user_add_check_timer-=500;
	    setTimeout("updateUserAddCheckImage('"+user_type+"','"+current_username+"',-1)",500);
	}
    }
}

function showUserAddCheckWindow(user_type,current_username)
{
    username=eval("document.user_edit."+user_type+"_username");
    open(window.INTERFACE_URL + "admin/user/check_user_for_add.php?image=f&username="+username.value+"&type="+user_type+"&current_username="+current_username,"user_check","width=500,height=300,scrollbars=yes,alwaysRaised=yes,dependent=yes");
}

function changeTRColor(obj,color)
{
    if(color==null)
    {
    	if(obj.original_color)
    	    obj.style.backgroundColor=obj.original_color;
    }
    else
    {
	obj.original_color=getObjCurrentStyle(obj).backgroundColor;
    	obj.style.backgroundColor=color;
    }
}

function getObjCurrentStyle(obj)
{
    if(window.getComputedStyle)
	return window.getComputedStyle(obj,null);
    else if (obj.currentStyle)
	return obj.currentStyle;
}

function showReportLayer(layer_id, show_obj ,hpos)
{
	if (!hpos) hpos = 'right-left';
    setObjDisplayStatus(layer_id, 'toggle', show_obj, hpos, 0, true, true); 
}

function showReportLayer_original(layer_id,show_obj,hpos)//original
{
    layer_obj=document.getElementById(layer_id)
    layer_obj.style.left=0;
    toggleDisplay(layer_obj);
    obj_top=findPosY(show_obj) + show_obj.offsetTop;
//    if(show_obj.firstChild.height) //ie
//	obj_top+=show_obj.firstChild.height;
    layer_obj.style.top=obj_top;
    
    obj_left=findPosX(show_obj);
    if(!hpos || hpos=="left")
	obj_left -= layer_obj.offsetWidth;
    else if(hpos=="right") 
	obj_left += show_obj.offsetWidth;
    
    layer_obj.style.left=obj_left;
}
/////////////////////////// layer move
function moveLayer(evt,layer_obj)
{
    if(!window.start_move)
		return;
	
    if (window.event)
		evt=window.event;

    layer_obj.style.left=window.now_x+evt.clientX-window.offset_x;
    layer_obj.style.top=window.now_y+evt.clientY-window.offset_y;
	
	
    return false;
}

function startMove(evt, layer_obj)
{
    if (window.event)
		evt=window.event;

    window.start_move=true;
    window.offset_x=evt.clientX;
    window.offset_y=evt.clientY;
    window.now_x=parseInt(findPosX(layer_obj));
    window.now_y=parseInt(findPosY(layer_obj));
    document.onmousemove=function(evt) { moveLayer(evt, layer_obj); }
}

function stopMove(evt)
{
    window.start_move=false;
    document.onmousemove=null;
}
/////////////////////////// Session Date Type handlings
function sessionDateTypeChanged(http_request)
{// if request was successfull, hide the date_type select layer and change current date type
    if (http_request.readyState == 4 && http_request.status == 200) 
    {
	document.getElementById('session_date_select').style.display='none';
	document.getElementById('current_session_date_type').innerHTML=http_request.responseText;
    }    
}

function changeSessionDateType(date_type)
{// change session date_type to "date_type"
    var http_request;
    
    if (window.XMLHttpRequest)
		http_request = new XMLHttpRequest();
    else if (window.ActiveXObject) 
		http_request = new ActiveXObject("Microsoft.XMLHTTP");

    if(http_request)
    {
		http_request.onreadystatechange = function() { sessionDateTypeChanged(http_request) };
		var url=window.INTERFACE_URL + 'util/session_date_type.php?date_type='+date_type;
		http_request.open('GET', url, true);
		http_request.send(null);	
    }
    else
		alert("Browser doesn't support xmlhttp");
}

function changeShowHideMenu(menu_selected)
{// change session date_type to "date_type"
    var http_request;
    
    if (window.XMLHttpRequest)
		http_request = new XMLHttpRequest();
    else if (window.ActiveXObject) 
		http_request = new ActiveXObject("Microsoft.XMLHTTP");

    if(http_request)
    {
		var url=window.INTERFACE_URL + 'util/show_hide_menu.php?menu_selected='+menu_selected;
		http_request.open('GET', url, true);
		http_request.send(null);	
    }
    else
		alert("Browser doesn't support xmlhttp");
}


//////////////////////////
function toggleDisplay(obj)
{
    if(obj.style.display=='none')
		obj.style.display='';
    else
		obj.style.display='none';
}

function toggleShowHide(show_hide_id, target_id)
{
    show_hide_obj=document.getElementById(show_hide_id);
    target=document.getElementById(target_id);
    if(target.style.display=='none')
    {
	target.style.display='';
	show_hide_obj.innerHTML="Hide";
    }
    else
    {
	target.style.display='none';
	show_hide_obj.innerHTML="Show";
    }
    
}

function toggleVisibility(obj)
{
    if(obj.style.visibility=='hidden')
	obj.style.visibility='visible';
    else
	obj.style.visibility='hidden';
}

/*function absDateSelectChanged(select_obj,calendar_id)
{
    calendar_obj=document.getElementById(calendar_id);
    if(select_obj.value=="gregorian")
    {
	calendar_obj.date_type="G";
	calendar_obj.disabled=false;
    }
    else if (select_obj.value=="jalali")
    {
	calendar_obj.date_type="J";
	calendar_obj.disabled=false;
    }
    else
	calendar_obj.disabled=true;
}*/

function ibs_setup_calendar(input_id, trigger_id, select_id)
{
    select_obj=document.getElementById(select_id);
    if(select_obj.value=="gregorian")
	setup_calendar(input_id,trigger_id, "G");
    else if (select_obj.value=="jalali")
	setup_calendar(input_id,trigger_id, "J");
    else
    {
	if (window.DATE_TYPE == "jalali")
	    select_obj.value="jalali";
	else
	    select_obj.value="gregorian";
	
	ibs_setup_calendar(input_id, trigger_id, select_id);    
    }
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


/**
 * Attaches an event (event_str) to the inputControl
 * @param Element inputControl
 * @param String event_str focus , not onfocus
 * @param Function method
 */
function attachMyEvent(input_control , event_str , method){
    try{
        if ( typeof( input_control.addEventListener ) != "undefined" ) {//W3c
            input_control.addEventListener(event_str,method,false);
            return true;
        } else if ( typeof ( input_control.attachEvent ) != "undefined" ) {//IE
            var r = input_control.attachEvent('on'+event_str,method);
            return r;
        } else {//not supported
            eval("inputControl.on" +event_str + "= method;");
        }
    }catch(e)
    	{alert('Error : '+var_dumper(e))}
}


//Display message in message box
function showMessage(message_id)
{
    toggleDisplay(document.getElementById("message_text_truncated_"+message_id));
    toggleDisplay(document.getElementById("message_text_"+message_id));
    return false;
}

function isArray(check)
{
    if(typeof check == "object")
       return(check.constructor.toString().match(/array/i) != null);
    return false;
}



function formatPrice(price)
{//put comma between each 3 digits of price and return formatted string
    precision=2;
    var price=parseFloat(price);
    var sign=price<0?-1:1;
    price*=sign;
    if(precision)
    {
        var int_price=Math.floor(price);
	var float_part=Math.round((price-int_price)*Math.pow(10,precision));
    }
    else
    {
        var int_price=Math.round(price);
	var float_part=0;
    }
	
    int_part=String(int_price);
    var str="";
    while(int_part.length>3)
    {
        var part=int_part.substr(int_part.length-3,3);
	int_part=int_part.substr(0,int_part.length-3);
	str="," + part + str;
    }

    str=int_part+str;
    if(float_part>0)
        str+="."+float_part;
    if(sign==-1)
        str="-"+str;
    return str;
}

function formatDuration(seconds)
{ //return seconds in format HH:MM:SS
    var hours=parseInt(seconds/3600);
    if(hours<10)
	hours="0"+hours;
    var rest=seconds%3600;
    var mins=parseInt(rest/60);
    if(mins<10)
	mins="0"+mins;
    var secs=parseInt(rest%60);
    if(secs<10)
	secs="0"+secs;

    return hours+":"+mins+":"+secs;
}

function formatByte(bytes)
{
    var units=["B","K","M","G"];
    for(var i=0; i<units.length; i++)
    {
	if(bytes<1024)
	{
	    return String(Math.round(bytes))+units[i];
	}
	bytes/=1024;
    }
    return String(Math.round(bytes))+units[i];
}

//break string into multiple lines with length not more than length
function breakString(str, length, glue)
{
    var broken_str = "";
    while(str.length > length)
    {
	broken_str += str.substr(0, length) + glue;
	str = str.substr(length);
    }
    return broken_str + str;
}

/*
    handle onclick of play/pause button on refresh headers
    the play_pause image should have id "refresh_play_pause"
    
    window.refresh_timer_status is used for current state
*/
function playPauseOnClick()
{

    img_obj = document.getElementById("refresh_play_pause");
	
    switch(window.refresh_timer_status)
    {
	case "play":
	case undefined:
	    window.refresh_timer_status = "pause";
	    img_obj.src = window.INTERFACE_URL + "images/icon/play.gif";
	    break;
	
	case "pause":
	    window.refresh_timer_status = "play";
	    img_obj.src = window.INTERFACE_URL + "images/icon/pause.gif"
	    break;
//		if(window.refresh==0) //window.location stopped by user click
//		    window.location = window.location;

    }
}


/*
    return all inputs objects that are children of "id"
*/
function getChildInputs(id)
{
    var inputs = new Array();
    var stack = new Array();
    var obj = document.getElementById(id);
	if(!obj)
	{
		alert("ID Not Found "+id);
		return;
	}	

    stack.push(obj);

    while(stack.length)
    {
		obj = stack.pop();
		
		
		if(obj.tagName == "INPUT" || obj.tagName == "SELECT")
		{
		    inputs.push(obj); // return format is [obj,obj,...]
		}
		else
		{
		    for(var i in obj.childNodes)
				{stack.unshift(obj.childNodes[i]);}
		}
    }
    return inputs;    
}

function setCheckBoxesOnclick(id, method)
{
    var objs=getChildCheckBoxItems(id);
   	 for(var i in objs)
		objs[i].onclick=method;
}

//return an array of selected check boxes in child node of id
function getChildCheckBoxItems(id,only_checked)
{
    var selected=new Array();
    var stack=new Array();
    var obj=document.getElementById(id);
    stack.push(obj);

    while(stack.length)
    {
	obj=stack.pop();
	if(obj.tagName=="INPUT" && (!only_checked || obj.checked))
	    selected.push(obj); // return format is [obj,obj,...]
	else
	    for(var i in obj.childNodes)
		stack.unshift(obj.childNodes[i]);
    }
    return selected;    
}

//returns true if $key exists in $array
function inArray(key, array)
{
	for(var i in array)
	{
		if (array[i] == key)
		{
			return true;
		}
	}
	
	return false;
}
/*
    Sets the display status of an object
    obj_id(strin): the id which we show/hide it
    display_status(str): '' or 'none' or 'toggle'
    parent_obj(object): used for determining the layer position , the layer will be positioned relative to parent_obj
    alignment(str): would be left-left , left-right , right-right or right-right, relative alignement to parent_obj
    x_offset(int): add offset to x coordinance of object
    delay(int): number of miliseconds that the method will wait, before actually show/hide the object
		the delay is useful to overcome problem with old firefox
*/

function setObjDisplayStatusWithTimer(obj_id, display_status, parent_obj, alignment, x_offset, delay)
{
    if(delay){
        obj=document.getElementById(obj_id);
        if(display_status=='none'){
            obj.timer=setTimeout(function(){setObjDisplayStatus(obj_id,display_status,parent_obj, alignment, x_offset);},delay);
        }else {
            clearTimeout(obj.timer);
            setObjDisplayStatus(obj_id,display_status,parent_obj, alignment, x_offset);
        }
    }
    else{
        setObjDisplayStatus(obj_id, display_status, parent_obj, alignment, x_offset);
    }
}

/*
    Same as setObjDisplayStatusWithTimer without timer
    no_cache(boolean): if set to true, no value will be cached
    set_y(boolean): also set y position, depending on parent_obj
*/
function setObjDisplayStatus(obj_id, display_status, parent_obj, alignment, x_offset, no_cache, set_y){
    if(display_status=='toggle'){
        display_status=(document.getElementById(obj_id).style.display==''?'none':'');
    }

    if(!x_offset)
        x_offset=0;

    var layer_obj=document.getElementById(obj_id);

    var cur_display_none = layer_obj.style.display == 'none'?true:false;

    if(!layer_obj.left_set || no_cache)
    {

    	if (set_y)
		    layer_obj.style.top=findPosY(parent_obj) + parent_obj.offsetTop;

		if(cur_display_none)
		{
		    layer_obj.style.visibility='hidden';
		    layer_obj.style.display='';
		}
		
		switch(alignment)
		{
		    case 'left-left':
	                layer_obj.style.left=findPosX(parent_obj)+x_offset;
			break;
		    case 'left-right':
			layer_obj.style.left=findPosX(parent_obj)+x_offset+parent_obj.offsetWidth;
			break;
		    case 'right-right':
	                layer_obj.style.left=findPosX(parent_obj)+x_offset+parent_obj.offsetWidth-layer_obj.offsetWidth;
			break;
		    case 'right-left':
		        layer_obj.style.left=findPosX(parent_obj)-layer_obj.offsetWidth+x_offset;
	    		break;
		}
	
		if(cur_display_none)
		{
		    layer_obj.style.visibility='visible';
		    layer_obj.style.display='none';
		}
        layer_obj.left_set=true;
    }

    layer_obj.style.display=display_status;
}

/*
 * A method to attach to report forms that has e-mail view type. It checks if view type is set to e-mail
 * and asks for email address and add it to the form
 */
function reportCheckEmailViewOptions(ev)
{
	var view_options_obj = document.getElementById("view_options");
	var selected_view_obj = view_options_obj.options[view_options_obj.selectedIndex];
	
	var email_address_obj = document.getElementById("email_address");
	
	if (selected_view_obj.label == "E-Mail" && !email_address_obj)
	{

		var email_address = prompt("Please enter the E-Mail address that report will be emailed to.\n" + 
		"Warning: All of the results will be gathered and e-mailed. Result Per Page value is ignored.", "");
		
		if(!email_address)
		{
			if (ev.preventDefault)
				ev.preventDefault();
			return false;
		}
			
		var email_input= document.createElement("input");
		email_input.setAttribute("type", "hidden");
		email_input.setAttribute("name", "email_address");
		email_input.setAttribute("id", "email_address");
		email_input.setAttribute("value", email_address);
		
		selected_view_obj.insertBefore(email_input, null);
	
	}
}

function createTGSession()
{
    if (window.XMLHttpRequest)
    	http_request = new XMLHttpRequest();
    else if (window.ActiveXObject) 
    	http_request = new ActiveXObject("Microsoft.XMLHTTP");

    if(http_request)
    {
    	http_request.onreadystatechange = function() {  };
    	var url=window.INTERFACE_URL + 'util/tg_redirect.php?url=/empty&tg_request_method=GET'
    	http_request.open('GET', url, true);
    	http_request.send(null);	
    }
    else
    	showError("Browser doesn't support xmlhttp");	
}

function destroyTGSession()
{
    if (window.XMLHttpRequest)
    	http_request = new XMLHttpRequest();
    else if (window.ActiveXObject) 
    	http_request = new ActiveXObject("Microsoft.XMLHTTP");

    if(http_request)
    {
    	http_request.onreadystatechange = function() {  };
    	var url=window.INTERFACE_URL_TG + '/destroySession'
    	http_request.open('GET', url, true);
    	http_request.send(null);	
    }
    else
    	showError("Browser doesn't support xmlhttp");	
}

/*******************************
	Methods for onload handings
********************************/

function addToWindowOnloads(method)
{ // add method to run on window onload. this overrides previous onload, 
  // all methods should use this function to be loaded on startup

	if(!window.onload_methods)
		window.onload_methods = new Array();
	
	window.onload_methods.push(method);
}

function init() {
    // quit if this function has already been called
    if (window.init_done) return;

    // flag this function so we don't do the same thing twice
    window.init_done = true;

    // kill the timer
    if (_timer) clearInterval(_timer);

    // do stuff
    if(window.onload_methods)
    {
    	for(var idx=0; idx<window.onload_methods.length; idx++)
    	{
    		method = window.onload_methods[idx];
    		method();
    	}
    }
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
//IE gives non-secure item error on ssl pages with @cc_on!
///*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = init;
