var DOM = document.getElementById ? true : false;
var ie = document.all ? true : false;
var nn4 = document.layers ? true : false;

var cookieExpDate = "Wednesday, 09-Nov-10 23:12:40 GMT";
var openSectionImgSrc = "images/btn_plus.gif";
var closeSectionImgSrc = "images/btn_minus.gif";

var selectedTab = "";

var iframeids=[];
var iframeurls=new Array();
var iframehide="yes";
var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeCaller() {
	var dyniframe=new Array()
	for (i=0; i<iframeids.length; i++){
		if (document.getElementById){
			resizeIframe(iframeids[i])
		}
		if ((document.all || document.getElementById) && iframehide=="no"){
			var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i])
			tempobj.style.display="block"
		}
	}
}

function resizeIframe(frameid){
	var currentfr=document.getElementById(frameid)
		if (currentfr && !window.opera){
			currentfr.style.display="block"
			if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight){ //ns6 syntax
				currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight;
			}
			else if (currentfr.Document && currentfr.Document.body.scrollHeight){ //ie5+ syntax
				currentfr.height = currentfr.Document.body.scrollHeight;
			}
			if (currentfr.addEventListener){
				currentfr.addEventListener("load", readjustIframe, false)
			}
			else if (currentfr.attachEvent){
				currentfr.detachEvent("onload", readjustIframe) 
				currentfr.attachEvent("onload", readjustIframe)
			}
		}

}

function readjustIframe(loadevt) {
	var crossevt=(window.event)? event : loadevt
	var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
	if (iframeroot){
		resizeIframe(iframeroot.id);
	}
}

function IFrameLoadStarted(name) {
	var iframe_div	= GetIFrameDiv(name);
	if (iframe_div != null)
		iframe_div.style.display="block";

}

function IFrameLoadFinished(name) {
//	alert(name);
	var iframe_div	= GetIFrameDiv(name);
	
//	alert(frames[name].location.href.indexOf(iframeurls[name]));
/*	if (frames[name].location.href.indexOf(iframeurls[name])<0 && iframeurls[name]) {
		var url = frames[name].location.href;
		if (!self.name)
			url = url.replace('iframe.aspx', 'system.aspx');
		location.href = url;
		document.close();
	}*/

	if (iframe_div != null)
		iframe_div.style.display="none";
}

function alreadyInArray (elem, array) {
	for (i=0;i<array.length ;i++ ) {
		if (elem==array[i]) return true;
	}
	return false;
}

function AddIFrame(name) {
	if (!alreadyInArray("list",iframeids))  {
		iframeids[iframeids.length] = name;
	}
	//if (!mrg) mrg=5;
	//document.write("<DIV style='margin-bottom:"+mrg+"px' id='iframe_preload_"+name+"'><b><font color=#6666FF> <img src=images/icons/loading.gif border=0>&nbsp;&nbsp;Loading data, please wait...</font></b></DIV>");
}


function GetIFrameDiv(name) {
	  var iframe_div = document.getElementById("iframe_preload_"+name);				
	  return iframe_div;
}

function loadintoIframe(iframeid, url){
	if (document.getElementById)
		document.getElementById(iframeid).src=url
}

if (window.addEventListener)
	window.addEventListener("load", resizeCaller, false)
else if (window.attachEvent){
	window.attachEvent("onload", resizeCaller)
}
	else
		window.onload=resizeCaller



function openWin(url,name,w,h,scroll,status) {
        var sc;
        if (scroll) sc="0"; else sc="yes";
        showToolbar = '0';
		if (status) st="1"; else st="0";
        
		return window.open( url,
                name,
                "WIDTH="+w+",HEIGHT="+h+",STATUS="+st+",TOOLBAR="+showToolbar+",SCROLLBARS="+sc+",RESIZABLE=yes");
        //return true;
}

//getting element
function getElement(name) {
	if (ie) { return document.all[name]; }
	 else if(DOM){ return document.getElementById(name); }
		  else { return document.name; }
}


function storeCaret (textEl)
{
        if (navigator.appName.indexOf("Microsoft")==-1) return;
        if (textEl.createTextRange) textEl.caretPos =
                document.selection.createRange().duplicate();
        
}
function insertAtCaret (textEl, text)
{
        if (navigator.appName.indexOf("Microsoft")==-1) {
                textEl.value+=text;
                return;
        }
        if (textEl.createTextRange && textEl.caretPos)
        {
                var caretPos = textEl.caretPos;
                caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
        }
        else
                textEl.value  += text;
}
function selectionAtCaret(textEl) {
        if (navigator.appName.indexOf("Microsoft")==-1)
                return '';
        if (textEl.createTextRange && textEl.caretPos)
			return textEl.caretPos.text;
		return '';		
}


// submit form with specified action & method
function submit_form(action, method, target) {

	// find form
	for (i=0; i<document.forms.length; i++)
		if (document.forms[i].elements['__VIEWSTATE'])
			f = document.forms[i];
	
	// save form attributes
	f_action = f.action;
	f_method = f.method;
	f_target = f.target;

	// hide some form elements
	var special_elems = Array('__EVENTTARGET','__EVENTARGUMENT','__VIEWSTATE');
	for (i=0; i<special_elems.length; i++)
		f.elements[special_elems[i]].disabled = true;

	eval('f.action = action;');
	eval('if (method) f.method = method;');
	eval('if (target) f.target = target;');
	eval('f.submit();');

	for (i=0; i<special_elems.length; i++)
		f.elements[special_elems[i]].disabled = false;

	// restore form attributes
	f.action = f_action;
	f.method = f_method;
	f.target = f_target;




}



function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;
}



function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
		var end = document.cookie.indexOf(";", begin);
		if (end == -1)
			end = dc.length;
		return unescape(dc.substring(begin + prefix.length, end));
}


function deleteCookie(name,path,domain) { 
   if (getCookie(name)) document.cookie = name + "=" + 
      ( (path) ? ";path=" + path : "") + 
      ( (domain) ? ";domain=" + domain : "") + 
      ";expires=Thu, 01-Jan-70 00:00:01 GMT"; 
} 


function SectionVisibility(sectionName, doInvert, defaultState){
	sectionState = getCookie(sectionName);
	//debug alert
	//alert(sectionName + " : State_in_cookie["+sectionState+"], DoCloseOpenAction:["+doInvert+"], DefaultState:["+defaultState+"]");
	if (((sectionState == "opened")&&(!doInvert))||((sectionState == "closed")&&(doInvert))||((defaultState=="opened")&&(sectionState==null)&&(!doInvert))||((defaultState!="opened")&&(sectionState==null)&&(doInvert))) {
		openSectionBox(sectionName,doInvert); 
		if (((sectionState == "closed")&&(doInvert))){
			resizeCaller();
		}
	} else {
		closeSectionBox(sectionName,doInvert); 
	}
}

function openSectionBox(sectionName, doSetCookie){
	var SectionBox = getElement(sectionName);
	SectionBox.style.display = "block";
	//
	var SectionBoxImgBtn = getElement(sectionName + "_img");
	SectionBoxImgBtn.src = closeSectionImgSrc;
	//
	if (doSetCookie)
		setCookie(sectionName,'opened',cookieExpDate);
}

function closeSectionBox(sectionName, doSetCookie){
	var SectionBox = getElement(sectionName);
	SectionBox.style.display = "none";
	//
	var SectionBoxImgBtn = getElement(sectionName + "_img");
	SectionBoxImgBtn.src = openSectionImgSrc;
	//
	if (doSetCookie)
		setCookie(sectionName,'closed',cookieExpDate);
}


/* To refactor a bit - just a fast fix  for filters on pages to be working ok */
function switchTab (object){
	var area = getElement("tab_"+object);
	var line = getElement("line_"+object);
	var tabarea = getElement("filterArea");
	if (tabarea && area)
	{
		if (area.style.display == "none") {
			area.style.display = "block"
			tabarea.style.padding = "5px";
		}
		else { 
			area.style.display = "none"
			tabarea.style.padding = "0px";
		}
	}
	
	if (area && !tabarea)
	{
		if (area.style.display == "none") {
			area.style.display = "block";
			line.style.display = "none";
		}
		else { 
			area.style.display = "none";
			line.style.display = "block";
		}
	}
}
function switchGridTab(object, tabgroup) {
	if (tabgroup == "tickets") {
		selectedTab = object;
		var tickettabs = new Array("tgeneral", "tpostreply", "tparticipants", "tassociations", "filter");
		hideTabObj(object, tickettabs);
	}
}
function hideTabObj(showtab, tablist) {
	displayTab(showtab);
	for (i=0;i<tablist.length;i++)
	{
		if (tablist[i] != showtab)
		{
			hideTab(tablist[i]);
		}
	}
}
function displayTab(objid) {
	result = getElement("tab_"+objid);
	if (!result)
		{
			return;
		}
	result.style.display = "block";

	resultlink = getElement(objid);
	if (!resultlink)
	{
		return;
	}

	resultlinkLeftCorner = getElement(objid+"_left");
	resultlinkRightCorner = getElement(objid+"_right");
	resultlink.className = "act";
	resultlinkLeftCorner.className = "actLeft";
	resultlinkRightCorner.className = "actRight";
}

function hideTab(objid) {
	var result = getElement("tab_"+objid);
	if (!result)
		{
			return;
		}
	result.style.display = "none";

	resultlink = getElement(objid);
	if (!resultlink)
	{
		return;
	}
	resultlinkLeftCorner = getElement(objid+"_left");
	resultlinkRightCorner = getElement(objid+"_right");
	resultlink.className = "inactive";
	resultlinkLeftCorner.className = "inactiveLeft";
	resultlinkRightCorner.className = "inactiveRight";
}

var popupCalendar = null;

function showFancyCalendar(id, format, showsTime, showsOtherMonths) {
	var el = document.getElementById(id);
	if (popupCalendar != null) {
		popupCalendar.hide();
	} else {
		var cal = new Calendar(1, null, calSelected, calCloseHandler);
		if (typeof showsTime == "string") {
			cal.showsTime = true;
			cal.time24 = (showsTime == "24");
		}
		if (showsOtherMonths) {
			cal.showsOtherMonths = true;
		}
		popupCalendar = cal;
		cal.setRange(1900, 2070);
		cal.create();
	}
	popupCalendar.setDateFormat(format);
	popupCalendar.parseDate(el.value);
	popupCalendar.sel = el;

	popupCalendar.showAt(0,0);

//	popupCalendar.showAtElement(el, "Br");

	return false;
}

function calSelected(cal, date) {
	cal.sel.value = date;
	if (cal.dateClicked && (cal.sel.id == "dateInput"))
	cal.callCloseHandler();
}

function calCloseHandler(cal) {
	cal.hide();
	popupCalendar = null;
}

/*
==================================================================
			TO DO - COPIED FROM WIKI (wikibits.js)
==================================================================
*/

function addButton(textboxId, imageFile, speedTip, tagOpen, tagClose, sampleText) {
	imageFile=escapeQuotesHTML(imageFile);
	speedTip=escapeQuotesHTML(speedTip);
	tagOpen=escapeQuotes(tagOpen);
	tagClose=escapeQuotes(tagClose);
	sampleText=escapeQuotes(sampleText);

	var mouseOver="";

	// we can't change the selection, so we show example texts
	// when moving the mouse instead, until the first button is clicked
	if(!document.selection) {
		// filter backslashes so it can be shown in the infobox
		var re=new RegExp("\\\\n","g");
		tagOpen=tagOpen.replace(re,"");
		tagClose=tagClose.replace(re,"");
		mouseOver = "onMouseover=\"if(!noOverwrite){document.infoform.infobox.value='"+tagOpen+sampleText+tagClose+"'};\"";
	}

	document.write("<a href=\"javascript:insertTags");
	document.write("('"+textboxId+"','"+tagOpen+"','"+tagClose+"','"+sampleText+"');\">");

	document.write("<img width=\"21\" height=\"21\" hspace=\"2\" vspace=\"2\" src=\""+imageFile+"\" border=\"0\" alt=\""+speedTip+"\" title=\""+speedTip+"\""+mouseOver+">");
	document.write("</a>");
	return;
}


function addInfobox(infoText,text_alert) {
	alertText=text_alert;
	var clientPC = navigator.userAgent.toLowerCase(); // Get client info

	var re=new RegExp("\\\\n","g");
	alertText=alertText.replace(re,"\n");

	// if no support for changing selection, add a small copy & paste field
	// document.selection is an IE-only property. The full toolbar works in IE and
	// Gecko-based browsers.
	if(!document.selection && !is_gecko) {
 		infoText=escapeQuotesHTML(infoText);
	 	document.write("<form name='infoform' id='infoform'>"+
			"<input size=80 id='infobox' name='infobox' value=\""+
			infoText+"\" readonly='readonly'></form>");
 	}

}

function escapeQuotes(text) {
	var re=new RegExp("'","g");
	text=text.replace(re,"\\'");
	re=new RegExp("\\n","g");
	text=text.replace(re,"\\n");
	return escapeQuotesHTML(text);
}

function escapeQuotesHTML(text) {
	var re=new RegExp('&',"g");
	text=text.replace(re,"&amp;");
	var re=new RegExp('"',"g");
	text=text.replace(re,"&quot;");
	var re=new RegExp('<',"g");
	text=text.replace(re,"&lt;");
	var re=new RegExp('>',"g");
	text=text.replace(re,"&gt;");
	return text;
}

// apply tagOpen/tagClose to selection in textarea,
// use sampleText instead of selection if there is none
// copied and adapted from phpBB
function insertTags(ctrlID, tagOpen, tagClose, sampleText) {
	//alert("disabled"); return; // TO DO
	var txtarea = getElement(ctrlID);
	// IE
	if(document.selection  && ie) {
		var theSelection = document.selection.createRange().text;
		if(!theSelection) { theSelection=sampleText;}
		txtarea.focus();
		if(theSelection.charAt(theSelection.length - 1) == " "){// exclude ending space char, if any
			theSelection = theSelection.substring(0, theSelection.length - 1);
			document.selection.createRange().text = tagOpen + theSelection + tagClose + " ";
		} else {
			document.selection.createRange().text = tagOpen + theSelection + tagClose;
		}

	// Mozilla
	} else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
 		var startPos = txtarea.selectionStart;
		var endPos = txtarea.selectionEnd;
		var scrollTop=txtarea.scrollTop;
		var myText = (txtarea.value).substring(startPos, endPos);
		if(!myText) { myText=sampleText;}
		if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
			subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
		} else {
			subst = tagOpen + myText + tagClose;
		}
		txtarea.value = txtarea.value.substring(0, startPos) + subst +
		  txtarea.value.substring(endPos, txtarea.value.length);
		txtarea.focus();

		var cPos=startPos+(tagOpen.length+myText.length+tagClose.length);
		txtarea.selectionStart=cPos;
		txtarea.selectionEnd=cPos;
		txtarea.scrollTop=scrollTop;

	// All others
	} else {
		var copy_alertText=alertText;
		var re1=new RegExp("\\$1","g");
		var re2=new RegExp("\\$2","g");
		copy_alertText=copy_alertText.replace(re1,sampleText);
		copy_alertText=copy_alertText.replace(re2,tagOpen+sampleText+tagClose);
		var text;
		if (sampleText) {
			text=prompt(copy_alertText);
		} else {
			text="";
		}
		if(!text) { text=sampleText;}
		text=tagOpen+text+tagClose;
		document.infoform.infobox.value=text;
		// in Safari this causes scrolling
		if(!is_safari) {
			txtarea.focus();
		}
		noOverwrite=true;
	}
	// reposition cursor if possible
	if (txtarea.createTextRange) txtarea.caretPos = document.selection.createRange().duplicate();
}
