/*

You can use some global variables predefined in MessagesJScriptAndFunctions-inc.asp:

var cb_home = ASP::cb_home
var cb_timeout_warning_within = ASP::cb_timeout_warning_within
var cb_messaging_params = ASP::cb_messaging_params

*/


if(document.all && !document.getElementById) {
    document.getElementById = function(id) {
         return document.all[id];
    }
}

/*
	if width (or height) < 0 then try to load them from addFeatures argument,
	after that try to replace width=NN and height=NN in addFeatures with new
*/	
function openWindowCentered(url, title, width, height, addFeatures) {
	var x=0, y=0, ret;
	var features = addFeatures;
	
		// fetch height and width from features string
	ret = features.match(/(\s*width\s*=\s*(\d+),?)/i);
	if( ret ) {
		if( width < 0 )
			width = ret[2];
		features = features.substring(0,ret.index) + features.substring(ret.index+ret[0].length);
	}
	if( width < 0 ) 
		width = -width;
	
	ret = features.match(/(\s*height\s*=\s*(\d+),?)/i);
	if( ret ) {
		if( height < 0 )
			height = ret[2];
		features = features.substring(0,ret.index) + features.substring(ret.index+ret[0].length);
	}
	if( height < 0 ) 
		height = -height;
	features = features.replace(/\s*,\s*$/g,"");
	features += (features!='' ? ',':'') + 'width=' + width + ',height=' + height;

//	alert(features + "\n" + addFeatures);
	if( screen && screen.availWidth) {
		x = (screen.availWidth - width) / 2;
		y = (screen.availHeight - height) / 2;
	}
	if( x && y) {
		features += ',left=' + x + ',top=' + y + ',screenX=' + x + ',screenY=' + y;
	}
	return window.open(url, title, features);
}

/*
	Reloads parent window replacing or adding "r=random" GET argument
*/	 
function reloadParentWindow() {
	reloadParentReplacingArgs();
}

function reloadParentReplacingArgs(to_del,args) {
	if( ! window.opener ) 
		return;
	
	window.opener.location.href = replaceArgumentsInURL(window.opener.location.href,to_del,args);
}

function reloadReplacingArgs(to_del,args) {
	window.location.href = replaceArgumentsInURL(window.location.href,to_del,args);
}

// Removes arguments given in [to_del] as well as "r=...","user_message_type=..." and "user_message=..."
// from URL given in [old_href]. Then adds new arguments given in [args] and random value in argument "r"
// [to_del] - is optional, can be Array of arguments, or String of arguments delimitered by ","
// [args] - is optional
//
// Example 1:
// [old_href]= ...test7.asp?textr=q&answer=b;&mamal=jhjwdhjk&r=jhjhejk&r=0.77265746&user_message_type=info&user_message=xx
// [to_del] = "answer,text"
// [args] = "user_message=" + escape("xa xa xa!")
// returns http://localhost/sm/common/test7.asp?textr=q&mamal=jhjwdhjk&user_message=xa%20xa%20xa%21&r=0.9894793767008454
//
// Example 2:
// [old_href]= ...test7.asp?textr=q&answer=b;&mamal=jhjwdhjk&r=jhjhejk&r=0.77265746&user_message_type=info&user_message=xx
// [to_del] = absent
// [args] = absent
// returns ...test7.asp?textr=q&answer=b;&mamal=jhjwdhjk&r=0.45702811623467404 
//
function replaceArgumentsInURL(old_href,to_del,args) 
{
	var anchor_index = old_href.lastIndexOf("#");
	var anchor = "";
	if (anchor_index >= 0)
	{
		anchor = old_href.substr(anchor_index);
		old_href = old_href.substr(0, anchor_index);
	}
	switch( typeof(to_del)) 
	{
		case "undefined": 	to_del_array = new Array(); break;
		case "object": 		to_del_array = to_del; break;
		default: 			to_del_array = to_del.split(","); break;
	}
	to_del_array = to_del_array.concat(new Array("r","user_message_type","user_message","_check"));
	var new_href = removeGETArguments(old_href, to_del_array);
	if(typeof(args) == "undefined" || args == '') 
	{
		args = ""
	} else 
	{
		args += "&";
	}
	new_href += (new_href.indexOf('?') > 0 ? (new_href.slice(-1) == '&'? '': '&') :'?') + args + "r=" + Math.random() + anchor;
	return new_href;
}

// Removes arguments given in Array [args_to_del] from URL given in [old_href]
// Example:
// [old_href] = ...test7.asp?textr=q&answer=b;&mamal=jhjwdhjk&r=jhjhejk&user_message_type=info&user_message=xx
// [args_to_del] = Array("answer","r","text","user_message_type","user_message"
// Returns: ...test7.asp?textr=q&mamal=jhjwdhjk
function removeGETArguments(old_href,args_to_del) {
	var i, new_href, to_del;
	new_href = old_href;
	to_del = args_to_del.join("|");
	new_href = unescape(new_href).replace( new RegExp("(([?])|([&]))(" + to_del + ")=[^&]*","ig"),"$2");
	return new_href.replace(new RegExp("[&][&]","g"),"&").replace(new RegExp("[?][&]"),"?");
}


var cb_event;
var cb_xmlhttp = null;
try {
      cb_xmlhttp = new ActiveXObject("Msxml2.xmlhttp");
    } 
catch (e) 
    {  try {
             cb_xmlhttp = new ActiveXObject("Microsoft.xmlhttp");
           } 
       catch (E) 
           {
              cb_xmlhttp = null;
           }
    }
if (cb_xmlhttp == null && typeof XMLHttpRequest != 'undefined') 
{
	  cb_xmlhttp = new XMLHttpRequest();
}

function cb_is_ajax_enabled()
{
	return ((typeof(cb_xmlhttp) != 'undefined') && (cb_xmlhttp != null))
}



function time2str() {
	var d = new Date();
	var s,t;

	s = '';
	t = ''+d.getHours();	if( t.length < 2) t = '0'+t; s += t + ':';
	t = ''+d.getMinutes();	if( t.length < 2) t = '0'+t; s += t + ':';
	t = ''+d.getSeconds();	if( t.length < 2) t = '0'+t; s += t;
	return s;
}

function cb_update() {
	now = new Date();
	seconds = (cb_event - now) / 1000;
	if (seconds <= 0) {
		document.location.href = cb_home+"default.asp?timeout=true";	
		document.getElementById("countdown").innerHTML = "* Your session is timed out.";
		return;
	}
	seconds = Math.round(seconds);
	minutes = seconds / 60;
	minutes = Math.floor(minutes);
	seconds = seconds % 60;
	document.getElementById("countdown").innerHTML = "* Your session will be timed out in " + minutes + " minutes and " + seconds + " seconds.";
	
	setTimeout("cb_update();",1000);
}

function cb_countdown(timeout_warning_within) {
	document.getElementById("countdown").style.display = "block";
	var now = new Date();
	var countdown_seconds = timeout_warning_within;

	cb_event = new Date();
	cb_event.setTime(now.getTime()+ countdown_seconds*1000);
	setTimeout("cb_update();", 1000);
}

function write_message(text,type) {
	var element;
	text = text.replace(/[<>]/g,"");
	if( type != 'info') {
		element = document.getElementById('message_errors');
	}
	else {
		element = document.getElementById('message_ok');
	}
	if( element.style.display != 'none') {
		element.innerHTML += '<br>' + text;
	}
	else {
		element.innerHTML = text;
		element.style.display = '';
	}
}

function cb_check_messages() 
{
	if (!cb_is_ajax_enabled()) return;

	cb_xmlhttp.open("GET", cb_home+"Common/message.asp?v=1&r="+Math.random(),true); //verification request
	cb_xmlhttp.onreadystatechange=function() {
		if (cb_xmlhttp.readyState==4) {
			//alert(cb_xmlhttp.responseText)
			if (cb_xmlhttp.responseText=="1") { // message exist
				openWindowCentered(cb_home+"Common/message.asp","_blank", -420, -220, 
					"location=no, menubar=no,status=no, toolbar=no, resizable=no,scrollbars=no" + cb_messaging_params);
			} else {
				if (cb_xmlhttp.responseText=="2") { // session about to expire in cb_timeout_warning_within seconds
					openWindowCentered(cb_home+'Common/msgSessionTimeout.asp?r='+Math.random()+'&text='+time2str()+
						' Your session will be timed out in ' + Math.floor(cb_timeout_warning_within/60) + ' min ' + 
							(cb_timeout_warning_within % 60)+ ' sec','_blank', 400, 220,
							"location=no, menubar=no,status=no, toolbar=no, resizable=no,scrollbars=no");
					cb_countdown(cb_timeout_warning_within);
				} else {
					if (cb_xmlhttp.responseText=="3") { // session expired
						  document.location.href = cb_home+"default.asp?timeout=true"
					}
				}
			}	
		}
	}
	cb_xmlhttp.send(null);
	setTimeout("cb_check_messages()", 20000);
}

function cbCheckDatePicker(form_name,prefix) {
    var year,day,month,hour,minute,second;
    var res,t,s;
    var form = document.forms[form_name];

    res = true;
    year = parseInt(form.elements[prefix+'_dpYear'].value,10);
    if( isNaN( year ) || (0+year) < 0) 
    	{ year = 2000; res = false; }
    if( year < 80) 
    	year+= 2000;
    if( year <= 99) 
    	year+= 1900;
    month = form.elements[prefix+'_dpMonth'].value;
    day = parseInt(form.elements[prefix+'_dpDay'].value,10);
    if( isNaN( day ) ) 
    	{ day = 1; res = false; }
    if( day < 1 ) 
    	{ day = 1; res = false; }
    if( day > 31 ) 
    	{ day = 31; res = false; }
    if( day > 30 && (month==4 || month==6 || month==9 || month==11)) 
    	{ day = 30; res = false; }
    if( day > 29 && month==2) 
    	{ day = 29; res = false; }
    if( day > 28 && (month==2 && ((year%4) != 0))) 
    	{ day = 28; res = false; }
	if( typeof(form.elements[prefix+'_dpHour']) != 'undefined') {
		hour = parseInt(form.elements[prefix+'_dpHour'].value,10);
		minute = parseInt(form.elements[prefix+'_dpMin'].value,10);
		if( typeof(form.elements[prefix+'_dpSec']) != 'undefined') {
			second = parseInt(form.elements[prefix+'_dpSec'].value,10);
		} else {
			second = 0;
		}
		
	    if( isNaN( hour ) ) 
	    	{ hour = 1; res = false; }
	    if( hour < 0 ) 
	    	{ hour = 0; res = false; }
	    if( hour > 23 ) 
	    	{ hour = 23; res = false; }
	    if( isNaN( minute ) ) 
	    	{ minute = 1; res = false; }
	    if( minute < 0 ) 
	    	{ minute = 0; res = false; }
	    if( minute > 59 ) 
	    	{ minute = 59; res = false; }
	    if( isNaN( second ) ) 
	    	{ second = 1; res = false; }
	    if( second < 0 ) 
	    	{ second = 0; res = false; }
	    if( second > 59 ) 
	    	{ second = 59; res = false; }
	}
	if( typeof(form.elements[prefix]) != 'undefined') {
	    s = ''+year;
	    t = ''+month;   if( t.length < 2) t = '0'+t;  s += '-' + t;
	    t = ''+day;     if( t.length < 2) t = '0'+t;  s += '-' + t;
		if( typeof(form.elements[prefix+'_dpHour']) != 'undefined') {
		    t = ''+hour;    if( t.length < 2) t = '0'+t;  s += ' ' + t;
		    t = ''+minute;  if( t.length < 2) t = '0'+t;  s += ':' + t;
		    t = ''+second;     if( t.length < 2) t = '0'+t;  s += ':' + t;
		}
	    form.elements[prefix].value = s;
	}
    return res;
}

// extend array object with deleteAt(index) method
Array.prototype.deleteAt = function(index) {
	if ( index >= 0 && index < this.length ) {
		var res = this[index];
		this.splice(index, 1);
		return res;
	} else {
		return null;
	}
}

//Scale text area and current window
function expandTextArea(sender, textArea){
    var minCols = 40;
    var maxCols = screen.availWidth/8;
    var minRows = 12;
    var maxRows = 20;
    
    if(textArea.cols==minCols ){
        window.moveTo(0,0);
        window.resizeTo(screen.availWidth/1.01, screen.availHeight/1.03);        
    	textArea.cols=maxCols ;
    	textArea.rows=maxRows;
    	sender.value="Collapse";
    } 
    else if(textArea.cols==maxCols ){
    	textArea.cols=minCols ;
    	textArea.rows=minRows;
    	
//	    	//if no expanded TextAreas on current window, scale it
//	    	var textAreas = document.getElementsByTagName("textarea");
//            var needWindowScale = 1;
//            for(i=0;i<textAreas.length; i++)
//	        {
//		        if(textAreas(i).cols>40)
//		            needWindowScale = 0;
//	        }
//	        
//	        if(needWindowScale==1)
//	        {
//	        	window.resizeTo(600, 600);
//	        	window.moveTo((screen.availWidth-600)/2,(screen.availHeight-600)/2);
//	        }
        	
    	sender.value="Expand";
    	
    }else{
        textArea.cols=high;
        sender.value="Collapse";
    }
}

/* Looks for an HREF attribute moving higher through the elements tree */
function getClosestUpwardHref(obj) {
	var parentObj = obj;
	var parentHref = null;
	
	for(;;) {
	 parentObj = obj.parentNode;
	 if( parentObj == null || typeof(parentObj) == 'undefined') {
	  	parentObj = obj.parentElement;
	 }
	 if( parentObj == null || typeof(parentObj) == 'undefined') {
	  	break;
	 }
	 obj = parentObj;
	 parentHref = parentObj.href;
	 if( parentHref != null && typeof(parentHref) != 'undefined' && parentHref != '') {
	  	return parentHref;
	 }
	}
	return "";
}

function invokeParentHref(obj) {
	var parentHref = getClosestUpwardHref(obj);
	if( parentHref != "") {
		document.location.href = parentHref;
	}
}
