// --------------------------------------------------------------------
//
//      AUTHOR :  Roman Zhovtulya
//
// JavaScript Library for Uportal CMS
// --------------------------------------------------------------------
//
//      Versions :
//
//      date         version         By whoom and what was done
// --------------------------------------------------------------------
//      20.10.2002    V 1.0	     Roman, optimizing
//      
//                                  
//     
//
// --------------------------------------------------------------------



// function for displaying hidden layers
// added 2006-12-17 by Christian


var menuStates = new Object();
function displayMenu(id, inputFieldName) {
	if (menuStates[id] == 'visible') {
		document.getElementById(id).style.visibility = 'hidden';
		menuStates[id] = 'hidden';
	}
	else {
		for (var menuId in menuStates) {
			menuStates[menuId] = 'hidden';
			document.getElementById(menuId).style.visibility = 'hidden';
		}
		document.getElementById(id).style.visibility = 'visible';
		menuStates[id] = 'visible';
		document.getElementById(inputFieldName).select();
		
	}
}


//function that closes the current window:

  function closewindow()
{
    window.close();
}





//function that refreshes the target window to the location (LocString) provided
// (used for automatic refresh when select box value is changed):


function popUpNav(LocString,wTarget) 
{
	if (LocString != "") {
		wTarget.location.href = LocString;
	}
}




//function that checkes user input:

function ValidForm(theForm)
{
  if (theForm.team_name.value == "")
  {
    alert("Please enter the team name!");
    theForm.team_name.focus();
    return (false);
  }

  if (theForm.student1.value == "")
  {
    alert("Please enter the name of the 1st memeber!");
    theForm.student1.focus();
    return (false);
  }

  if (theForm.student2.value == "")
  {
    alert("Please enter the name of the 2nd memeber!");
    theForm.student2.focus();
    return (false);
  }

}



//function opens a window based on the provided information:

function openwindow (url, w, h, name) 
{

window.open(url,name,'toolbar=no,resizable=yes, directories=no,status=no,scrollbars=yes,resize=no,menubar=no,width='+w+',height='+h);

}




// function for loading the URL content into the parent window (used in FHO Portal search engine):

function loadIntoParent(url) {
 opener.location.href=url;
}




// new function used to open a window in CMS editor in such a way that it would later be possible to close it and reload the parent page in Mozilla as well

function openwindowNew(url, w, h, name) 
{

child = window.open(url,name,'toolbar=no,resizable=yes,directories=no,status=no,scrollbars=yes,resize=no,menubar=no,width='+w+',height='+h);

}


// new function used to open a window in CMS editor in such a way that it would later be possible to close it and reload the parent page in Mozilla as well
// one more set of the same functionality to have the two independent windows with the above mentioned functionality:

function openwindowNewExtra(url, w, h, name) 
{

childExtra = window.open(url,name,'toolbar=no,resizable=yes,directories=no,status=no,scrollbars=yes,resize=no,menubar=no,width='+w+',height='+h);

}



// function for closing the edit window and refreshing the parent
// (in administration "edit data" scrips):

//function closeChild() {

//child.close();
 
// self.location.reload();
//}


function closeChild() {

child.close();

parent.location.reload();


}





function closeChildExtra() {

 childExtra.close();
 
 parent.location.reload();
}




// function for closing the child window from within the child window
// (for administration "edit data" scrips):

function endNow() {
 opener.location.href="JavaScript:closeChild()";
}


function endNowExtra() {
 opener.location.href="JavaScript:closeChildExtra()";
}



// the same as "endNow()", but it reloads the window specified:

function endNowWindow(winName) {

window.close();

// var win = window.open('', winName); 

//win.location.reload();

}



function endNowUrl(urlToUpdateTo) 
{


opener.location.href=urlToUpdateTo;

// parent.location.href=urlToUpdateTo;


 window.close();

}


// reloads the window specified to the given url:


function endNowUrlWin(urlToUpdateTo, winName) 
{

// closing the current window: 
	window.close();

// getting the window by its name:
	var win = window.open('', winName); 

// updating the window to the url passed:
	win.location.href=urlToUpdateTo;
}


function endNowSimple() {
 opener.location.href="JavaScript:closeChild()";
}


// function for keeping the windows open:
function open_popup(page) {

     top.window_handle = open(page,'popupWindowName', "width=600,height=800");
    top.window_handle.focus();
    if (!top.window_handle.opener) top.window_handle.opener = self;
    return false;
}


// function for closing the child window from within the child windowype=educationFHO&editType=ins
// (for administration "edit data" scrips):

// additional functionality to pass the element name and the new value to the parent
// window (used for informing the "list.jsp" element of the new id of the element 
// (in case there is a nested insert (e.g. during inserting the "educationFHO" (first level) we need to insert a new thesis)))

// also, adding "objectId" to reload the page with the given objectId to avoid duplicate object creation

function endNow(elementNameToUpdate, elementValueToUpdate, objectId)
{
var urlToUpdateTo=opener.location.href+'&'+elementNameToUpdate+'='+elementValueToUpdate+'&o='+objectId;
opener.location.href=urlToUpdateTo;
window.close();
}


// function for loading the URL content into the specified target frame
// (used in previewing while browsing files in upload window)
function loadIntoFrame(url) {
 parent.fhoportalSelectFilePreview.location.href=url;
}

// function that checks whether everything is correct for the upload:
function validFormUploadFile(theForm)
{
var filePath=theForm.FILE1.value;

// checking if the file name contains forbidden characters (space, +, etc):
	
	// looking for a file name substring:
		// getting the index of the last occurance of "\":
		
		var lastSlashIndex=0;

		// looping through the file path and checking for "\" position:
		// (we've got to use "\\", since a single "\" is interprited as an escape character only:
		for(i=0; i<filePath.length; i++)
			{
		  	if ( filePath.charAt(i)=='\\')
		  		{
		  		lastSlashIndex=i;
		  		}
			}
		
		
	// getting the file name:

	var fileName=filePath.substring(lastSlashIndex+1, filePath.length);

	if (fileName.match(/ /))
	{
	   alert("Sorry spaces are not allowed in file names - Sorry, Lehrzeichen in Dateinamen sind nicht erlaubt!");
	   return (false);
	}

	if (fileName.match(/\+/))
	{
	   alert("Sorry plus signs are not allowed in file names - Sorry, plus Zeichen in Dateinamen sind nicht erlaubt!");
	   return (false);
	}

}





// functions for left menu

  function MM_findObj(n, d) { //v4.0
      var p,i,x;if(!d) d=document;if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document;n=n.substring(0,p);}
      if(!(x=d[n])&&d.all) x=d.all[n];for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
      for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
      if(!x && document.getElementById) x=document.getElementById(n);return x;
    }
    
    function MM_showHideLayers() { //v3.0
      var i,p,v,obj,args=MM_showHideLayers.arguments;
      for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) {v=args[i+2];
        if (obj.style) {obj=obj.style;v=(v=='show')?'visible':(v='hide')?'hidden':v;}
        obj.visibility=v;}
    }
    
    function MM_openBrWindow(theURL,winName,features) { //v2.0
      window.open(theURL,winName,features);
    }



    var isDOM      = (typeof(document.getElementsByTagName) != 'undefined'
                      && typeof(document.createElement) != 'undefined')
                   ? 1 : 0;
    var isIE4      = (typeof(document.all) != 'undefined'
                      && parseInt(navigator.appVersion) >= 4)
                   ? 1 : 0;
    var isNS4      = (typeof(document.layers) != 'undefined')
                   ? 1 : 0;
    var capable    = (isDOM || isIE4 || isNS4)
                   ? 1 : 0;
    // Uggly fix for Opera and Konqueror 2.2 that are half DOM compliant
    if (capable) {
        if (typeof(window.opera) != 'undefined') {
            capable = 0;
        }
        else if (typeof(navigator.userAgent) != 'undefined') {
            var browserName = ' ' + navigator.userAgent.toLowerCase();
            if (browserName.indexOf('konqueror') > 0) {
                capable = 0;
            }
        } // end if... else if...
    } // end if
    var fontFamily = 'arial, geneva, sans-serif';
    var fontSize   = 'small';
    var fontBig    = 'large';
    var fontSmall  = '12';
    var fontLarge  = '12';    
    
    var isServer   = true;





// methods for calender window:

var auxiliarValue;

function openCalendar(field, year, month, day)
{
	
	var left = 300;
	var top = 300;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY)
	{
		left = e.pageX;
		top = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		left = e.clientX + document.body.scrollLeft;
		top = e.clientY + document.body.scrollTop;
	}


	month --;

	calendar = window.open('core/calendar/calendar.jsp?year='+year+'&month='+month+'&day='+day+'&action=2','calendar','toolbar=no,location=no,directories=no,resizable=yes,status=no,scrollbars=no,left=' + left + ',top=' + top + ',width=200,height=145');
	//calendar.field = field;
	auxiliarValue = field;

	if (window.focus) {calendar.focus()}
}

function fillTimeSelection(selectBox){
	addOption(selectBox,12,0,true);
	for(var i=1;i<=11;i++){
		addOption(selectBox,i,i*2,true);
	}
	addOption(selectBox,12,24,false);
	for(var i=1;i<=11;i++){
		addOption(selectBox,i,(12+i)*2,false);
	}
}

function addOption(selectBox,hour,value,isMorning){
	var option = document.createElement("OPTION");
	option.text=hour+":00 "+(isMorning?"AM":"PM");
	option.value=value;
	selectBox.options.add(option);
	
	option = document.createElement("OPTION");
	option.text=hour+":30 "+(isMorning?"AM":"PM");
	option.value=value+1;
	selectBox.options.add(option);
}



var addonsOptionShow = false;

function showHideSection(sectionId){
	
	if(addonsOptionShow){
		//document.getElementById('addonsOption').innerHTML="Hide";
		document.getElementById(sectionId).style.display="block";
		addonsOptionShow=false;
		
	}else{
		//document.getElementById('addonsOption').innerHTML="Show";
		document.getElementById(sectionId).style.display="none";
		addonsOptionShow=true;
		
	}
}

function changeBadgeName()
{
    var elem = document.getElementById("badgeTitle");
    var firstN_elem = document.getElementById("firstName");
    var lastN_elem = document.getElementById("lastName");
    var org_elem = document.getElementById("organization");
    var rad_index = get_radio_value();
    if(rad_index==1)
    {
        elem.innerHTML = "<b>"+firstN_elem.value+"</b>";
    }
    if(rad_index==2)
    {
        elem.innerHTML = "<b>"+firstN_elem.value+" "+lastN_elem.value+"</b>";
    }
    if(rad_index==3)
    {
        elem.innerHTML = "<b>"+firstN_elem.value+"</b>"+"<br>"+org_elem.value;
    }
    if(rad_index==4)
    {
        elem.innerHTML = "<b>"+firstN_elem.value+" "+lastN_elem.value+"</b>"+"<br>"+org_elem.value;
    }
}
function changePhrase(phraseNo)
{
    if(phraseNo==1)
    {
        var elem = document.getElementById("phrase1");
        var sel_index = document.getElementById("fieldSelect1");
    }
    if(phraseNo==2)
    {
        var elem = document.getElementById("phrase2");
        var sel_index = document.getElementById("fieldSelect2");
    }
    if(sel_index.options.selectedIndex==0)
    {
        elem.innerHTML = sel_index.options[sel_index.options.selectedIndex].value;
        alert(sel_index.options[sel_index.options.selectedIndex].value);
    }
    else
    {
        elem.innerHTML = sel_index.options[sel_index.options.selectedIndex].value;
        alert(sel_index.options[sel_index.options.selectedIndex].value);
    }
}
function get_radio_value()
{
    for (var i=0; i < document.OnSiteRegistration.badgeName.length; i++)
    {
        if (document.OnSiteRegistration.badgeName[i].checked)
        {
            var rad_val = document.OnSiteRegistration.badgeName[i].value;
        }
    }
    return rad_val;
}

function changeEndDate(inElem, dataType, timeDifferenceMinutes)
 {
    var endDateString=inElem.value;
    var date=endDateString;
    
    // apply date addition/subtraction only if timeDifferenceMinutes is not 0:
    if (timeDifferenceMinutes!=0)
        {
    var endDateFormatted=parseDate(endDateString, dataType);
    endDateFormatted.setMinutes(endDateFormatted.getMinutes()+timeDifferenceMinutes);
    var month = endDateFormatted.getMonth() + 1;
    var day = endDateFormatted.getDate();
    if (day<10) 
    day = "0"+day;
    var year = endDateFormatted.getFullYear();
    if (year>=2000)
    year-=2000;
    else
    year-=1900;
    var hours = endDateFormatted.getHours();
    if (hours>=12)
    AorP="pm";
    else
    AorP="am";
    if (hours>=13) hours-=12;
    var minutes = endDateFormatted.getMinutes();
    date = month + '/' + day + '/' + year + " "+hours+":"+minutes+" "+AorP;
        }

    var curId = parseInt(inElem.id)+1;
    var elem = document.getElementById(curId);
    elem.value = inElem.value;
    elem.value = date; //endDateFormatted;
 }

function openEmailForm(url, w, h, name, userId)
{
	var isOpen=false;
	if(winEmailForm!="undefined" && winEmailForm!=null)
	{
		isOpen=true;
	}
	else
	{
		isOpen=false;
	}

	if(!isOpen)
	{
		winEmailForm = window.open(url,name,'toolbar=no,resizable=yes,directories=no,status=no,scrollbars=yes,resize=no,menubar=no,width='+w+',height='+h);
	}
	else
	{
		// deal with duplicate emails:
		var newRecipient=window.open('../../Insight/jsp/putNewRecipient.jsp?userId='+userId,'NewRecipients','toolbar=no,resizable=yes,directories=no,status=no,scrollbars=yes,resize=no,menubar=no,width='+w+',height='+h);
	}

}


function doSearch(){
	document.getElementById('action').value='search';
	document.getElementById('inputForm').submit();
        document.reloadParent();
}
function cmdEnter(event){
	if(event.keyCode == 13){
		doSearch();
	}
}

function stopRKey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}

function parseDate(str, fmt) {
	var today = new Date();
	var y = 0;
	var m = -1;
	var d = 0;
	var a = str.split(/\W+/);
	var b = fmt.match(/%./g);
	var i = 0, j = 0;
	var hr = 0;
	var min = 0;
	for (i = 0; i < a.length; ++i) {
		if (!a[i])
			continue;
		switch (b[i]) {
		    case "%d":
		    case "%e":
			d = parseInt(a[i], 10);
			break;

		    case "%m":
			m = parseInt(a[i], 10) - 1;
			break;

		    case "%Y":
		    case "%y":
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
			break;

		    case "%b":
		    case "%B":
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
			}
			break;

		    case "%H":
		    case "%I":
		    case "%k":
		    case "%l":
			hr = parseInt(a[i], 10);
			break;

		    case "%P":
		    case "%p":
			if (/pm/i.test(a[i]) && hr < 12)
				hr += 12;
			else if (/am/i.test(a[i]) && hr >= 12)
				hr -= 12;
			break;

		    case "%M":
			min = parseInt(a[i], 10);
			break;
		}
	}
	if (isNaN(y)) y = today.getFullYear();
	if (isNaN(m)) m = today.getMonth();
	if (isNaN(d)) d = today.getDate();
	if (isNaN(hr)) hr = today.getHours();
	if (isNaN(min)) min = today.getMinutes();
	if (y != 0 && m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	y = 0; m = -1; d = 0;
	for (i = 0; i < a.length; ++i) {
		if (a[i].search(/[a-zA-Z]+/) != -1) {
			var t = -1;
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
			}
			if (t != -1) {
				if (m != -1) {
					d = m+1;
				}
				m = t;
			}
		} else if (parseInt(a[i], 10) <= 12 && m == -1) {
			m = a[i]-1;
		} else if (parseInt(a[i], 10) > 31 && y == 0) {
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
		} else if (d == 0) {
			d = a[i];
		}
	}
	if (y == 0)
		y = today.getFullYear();
	if (m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	return today;
};

var formattedDate;
var olAppointmentItem = 1; //fixed for different properties of outlook object

//export to outlook
function exportOutlook()
{
    var duration = 120; //number of minutes (duration in Outlook being in minutes)
    SetTimeForAppointment();//time of appoinment was fixed
    try
    {
        var objOutlook = new ActiveXObject( "Outlook.Application" );
    }
    catch(e)
    {
        alert("Outlook needs to be installed on the machine for data to export.");
        alert(e.name+": "+e.message);
        return false;
    }
    var objAppointment = objOutlook.CreateItem(olAppointmentItem);

    objAppointment.Subject = "Appointment exported to Outlook from a web application";
    objAppointment.Body = "This is an appointment being exported into Outlook using a web-application.";
    objAppointment.Start = formattedDate;
    objAppointment.Duration = duration;
    objAppointment.ReminderSet = false;
    objAppointment.Save();

    alert("An appointment was exported successfully to your Outlook calendar in todays date.");
    return true;
}

function SetTimeForAppointment()
{
    var currentDate = new Date();
    var month = currentDate.getMonth();
    var day = currentDate.getDate();
    var year = currentDate.getFullYear();
    formattedDate = (month+1) + "/" + day + "/" + year + " 08:00AM";
}
function getUTCGoogleCalendarDate(y,m,d,h,min) {
var timeObj = new Date(y,m-1,d,h,min);
var dateStr = "" + timeObj.getUTCFullYear();
dateStr += stringPad(timeObj.getUTCMonth()+1);
dateStr += stringPad(timeObj.getUTCDate());
dateStr += "T" + stringPad(timeObj.getUTCHours());
dateStr += stringPad(timeObj.getUTCMinutes()) + "00Z";
return dateStr;
}

function show_hide_onclick(id)
{
    if(document.getElementById(id).style.display=="none") {
        document.getElementById(id).style.display="inline";
    }
    else {
        document.getElementById(id).style.display="none";
    }
}
