// checker2.js
// Some javascript functions. Yay!
// (c) 2005-2007 by Checker Software Systems, LTD.
// (Yaron)

function OpenPopupWin (url, name, params)
{          
	var w = window.open(url, name, params);
	//var w=window.open($url, 'kelev');
	w.focus();
}

function openInNewWindow(url) {
	// Change "_blank" to something like "newWindow" to load all links in the same new window
	// This function is like <a href=url target=_blank>, or supposed to be.
	// taken from:
	// http://www.456bereastreet.com/archive/200605/using_javascript_instead_of_target_to_open_new_windows/
	var newWindow = window.open(url, '_blank');
	newWindow.focus();
	return false;
}

function DaysInMonth (Date, Year) 
// Retuns how many days there are in the month in year
// needs year for the leap-year considerations.
// Taken from: http://www.smartwebby.com/DHTML/date_validation.asp
{

}

// get today date
function getDateandTime(fieldDay, fieldMonth, fieldYear, fieldHour, fieldMin, fieldSec)
{ 
	getDate(fieldDay, fieldMonth, fieldYear);

	var today= new Date();                              
	//var hour=0; var min=0; var sec=0;
	var todayStr;

	var hour=today.getHours();
	var min=today.getMinutes();
	var sec=today.getSeconds();
	min=checkTime(min);
	sec=checkTime(sec);

	var minResult = min % 5;
	if (minResult != 0) min = (min - minResult); 

	var secResult = sec % 5;
	if (secResult != 0) sec = (sec - secResult);

	if (/msie/i.test (navigator.userAgent)) //only override IE
		{
		var hField = changeGetElementById(fieldHour);
		var mField = changeGetElementById(fieldMin);
		var sFiels = changeGetElementById(fieldSec);
	}
	else
		{
		var hField = document.getElementById(fieldHour);
		var mField = document.getElementById(fieldMin);
		var sFiels = document.getElementById(fieldSec);
	}

	hField.selectedIndex=hour;    

	for (var im=0;im<mField.options.length;im++) { 
		if (mField.options[im].text == min) { 
			mField.selectedIndex = im; 
			break; 
		} 
	}  

	for (var is=0;is<sFiels.options.length;is++) { 
		if (sFiels.options[is].text == sec) { 
			sFiels.selectedIndex = is; 
			break; 
		} 
	}       
}

function checkTime(i){
	if (i<10){
		i="0" + i;
	}
	return i;
}

function changeGetElementById(id){
	if (/msie/i.test (navigator.userAgent)) //only override IE
		{
		document.nativeGetElementById = document.getElementById;
		//document.getElementById = function(id)
		{
			var elem = document.nativeGetElementById(id);
			if(elem)
				{
				//make sure that it is a valid match on id
				if(elem.attributes['id'].value == id)
					{ 
					return elem;
				}
				else
					{
					//otherwise find the correct element
					for(var i=1;i<document.all[id].length;i++)
					{
						if(document.all[id][i].attributes['id'].value == id)
							{ 
							return document.all[id][i];
						}
					}
				}
			}  
			return null;
		};
	} 
}

function getDate(fieldDay, fieldMonth, fieldYear)
{ 
	var today= new Date();                              
	var day=0; var month=0; var year=0;
	var todayStr;
	day= today.getDate();
	month= today.getMonth()+1;
	year= today.getFullYear();

	if (/msie/i.test (navigator.userAgent)) //only override IE
		{ 
		var d = changeGetElementById(fieldDay);  
		var m = changeGetElementById(fieldMonth);
		var y = changeGetElementById(fieldYear);
	}
	else{   
		var d = document.getElementById(fieldDay);  
		var m = document.getElementById(fieldMonth);
		var y = document.getElementById(fieldYear);
	}      
	//d.selectedIndex=day;
	//m.selectedIndex=month;  
	for (var ida=0;ida<d.options.length;ida++) { 
		if (d.options[ida].text == day) { 
			d.selectedIndex = ida; 
			break; 
		} 
	}      

	for (var i=0;i<m.options.length;i++) { 
		if (m.options[i].text == month) { 
			m.selectedIndex = i; 
			break; 
		} 
	}  

	for (var index=0;index<y.options.length;index++) { 
		if (y.options[index].text == year) { 
			y.selectedIndex = index; 
			break; 
		} 
	}  
}

//Set focus to field ID and scroll to this field
function SetFocusandSelect(fieldID)
{   
	var field = document.getElementById(fieldID);
	field.focus();
	field.select;
	field.scrollIntoView();     
}  

function DateYearOrMonthChangeEvent (BaseFieldName)
// Each time someone changes the year or the month,
// we should calculate how many days we have in that month.
{
} 


function CheckRadioButton (id)
// Simply marks the radio button whose id was specified. 
// Currently in the combination of HandleDateRangesForReportForm and DateInputField
{
	rad = document.getElementById(id);
	rad.checked = true;
}

function askForEmailAddressAndSubmit(form, promptText, destinationField, promptForMessage, messageField)
// Uses the js prompt() function to ask for an email address. If one specified, then sets the given destination field in the form, and 
// submits the form.
// Used in TableReport, inside function tr_PrintExportOrEmailButton_OrPerformExport()
{
	var theEmail;
	var theMessage;
	theEmail = prompt(promptText);  
	if(Echeck(theEmail))
		{
		theMessage = prompt(promptForMessage);
		if (theEmail)
			{
			form.elements[destinationField].value = theEmail;
			if (theMessage) 
				{ 
				form.elements[messageField].value = theMessage;
			}
			return true; 
		}
	}
	else return false;       
} 

//email validation
function Echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		alert("Invalid E-mail ID")
		return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		alert("Invalid E-mail")
		return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		alert("Invalid E-mail")
		return false
	}

	if (str.indexOf(at,(lat+1))!=-1){
		alert("Invalid E-mail")
		return false
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		alert("Invalid E-mail")
		return false
	}

	if (str.indexOf(dot,(lat+2))==-1){
		alert("Invalid E-mail")
		return false
	}

	if (str.indexOf(" ")!=-1){
		alert("Invalid E-mail")
		return false
	}

	return true          
}

//set value in textbox and removing value from combobox
function setCombobox(comboField,textFiled,imgFiled,totalTextBox,dataID,hiddenTextFiled)
{    
	var tNew_sel=new Array();
	var counter=0;           
	if(parseInt(totalTextBox) >parseInt(document.getElementById('hidd'+dataID).value))
		{
		for(i=0;i<document.getElementById(comboField).length;i++)
		{   

			if(document.getElementById(comboField).options[i].selected==true)
				{                                           
				//setting combobox selected value into textbox
				curr_textFiled=textFiled+'_'+document.getElementById('hidd'+dataID).value;
				curr_imgFiled=imgFiled+'_'+document.getElementById('hidd'+dataID).value;
				curr_hiddenTextFiled=hiddenTextFiled+'_'+document.getElementById('hidd'+dataID).value;                                      
				document.getElementById(curr_textFiled).value=document.getElementById(comboField).options[i].text;                                               
				document.getElementById(curr_hiddenTextFiled).value=document.getElementById(comboField).options[i].value;
				//               if(document.getElementById(comboField).options[i].value == -3){
				//                 SelectedText = document.getElementById(comboField).options[i].text;  
				//                 SelectedValue = document.getElementById(comboField).options[i].value;  
				//                 BlockForIrrelevantOption(comboField, textFiled, imgFiled, totalTextBox, dataID, hiddenTextFiled, SelectedText, SelectedValue);
				//                 break; 
				//              }

				for(k=0;k<document.getElementById('hidd'+dataID).value;k++)
				{                  
					prevImgFiled=imgFiled+'_'+k;                    
					document.getElementById(prevImgFiled).style.display='none';
				}                  
				//show hide image icons 
				document.getElementById(curr_imgFiled).style.display='';                  
				document.getElementById('hidd'+dataID).value=parseInt(document.getElementById('hidd'+dataID).value)+parseInt(1);           
			}
			else
				{
				//remaining combobox value stored into variable
				tNew_sel[counter]=new Array();
				tNew_sel[counter]['text'] = document.getElementById(comboField).options[i].text;
				tNew_sel[counter]['value'] =document.getElementById(comboField).options[i].value;             
				counter++;
			}
		}
	}  
	//Resetting combobox value
	//alert(document.getElementById(comboField).length);          
	if(counter != 0)
		{              
		document.getElementById(comboField).length=0;
		for(j=0;j<counter;j++)
		{
			document.getElementById(comboField).options[j] = new Option(tNew_sel[j]['text'],tNew_sel[j]['value']);


		}
	}
	else if(counter == 0 && document.getElementById(comboField).length==1)
		{
		document.getElementById(comboField).length=0; 
	}         
}   

//remove value from textbox and add value in combobox
function deleteFromTextBox(comboField,textFiled,imgFiled,totalTextBox,dataID,hiddenTextFiled)
{     
	//setting value into textbox    
	varHidden=parseInt(document.getElementById('hidd'+dataID).value)-1;
	curr_textFiled=textFiled+'_'+varHidden;
	curr_imgFiled=imgFiled+'_'+varHidden;
	//active last texbox image
	if(parseInt(varHidden)>0)
		prev_imgFiled=imgFiled+'_'+(varHidden-1);  

	curr_hiddenTextFiled=hiddenTextFiled+'_'+varHidden;                    

	//remove textbox value and setting into combobox
	document.getElementById(comboField).length=parseInt(document.getElementById(comboField).length)+1;         
	document.getElementById(comboField).options[parseInt(document.getElementById(comboField).length)-1] = new Option(document.getElementById(curr_textFiled).value,document.getElementById(curr_hiddenTextFiled).value);        
	document.getElementById('hidd'+dataID).value=parseInt(document.getElementById('hidd'+dataID).value)-1;
	document.getElementById(curr_textFiled).value='';
	document.getElementById(curr_hiddenTextFiled).value='';

	document.getElementById(curr_imgFiled).style.display='none';
	if(parseInt(varHidden)>0)  
		document.getElementById(prev_imgFiled).style.display='block';
}

function HideMe(field)
{
	$("#" + field).hide();
	//	document.getElementById(field).style.display="none";
}

function ShowMe(field)
{
	$("#" + field).show();
	//	document.getElementById(field).style.display="block";
}

function HideMeName(fieldName){
	document.getElementsByName(fieldName).style.display="none";
}
function ShowMeName(fieldName){
	document.getElementsByName(fieldName).style.display="block";
}

function ClearMe(field){
	document.getElementById(field).value="";
}

function showHideText(fieldNamecntr ,fieldName,total){              
	fieldNamecntr='id'+fieldNamecntr;
	for(i=0;i<total;i++)
	{                    
		curr='id'+fieldName+''+i;                 
		if(curr==fieldNamecntr)                      
			document.getElementById('id'+fieldName+i).style.display='block';                    
		else
			document.getElementById('id'+fieldName+i).style.display='none';                      
	}              
}


function LimitAttach(form, file, extArray) {
	//extArray = new Array("gif", "jpg", "png"); 
	allowSubmit = false;
	if (!file) return;
	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);
	ext = file.slice(file.indexOf(".") + 1).toLowerCase(); 
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { allowSubmit = true; break; }
	}
	if (allowSubmit) 
		form.submit();
	else
		{
		alert("Please only upload files that end in types:  " 
		+ (extArray.join("  ")) + "\nPlease select a new "
		+ "file to upload and submit again.");
		return false;
	}
}

function promptCallback(val, form) {
	if(Echeck(val))
		{   
		if (val)                              
			{ 
			document.getElementById('destinationEmailAddress').value = val;

			document.getElementById('emailform').submit(); 
		}
	}
	else return false;   
}

function submit_preset_form_button() {
	if (typeof(preset_button_to_submit) !== 'undefined' && preset_button_to_submit){                                      
		var submit_me = document.getElementById(preset_button_to_submit);
		if (submit_me){ 
			submit_me.click(); 
		}
	}
}


///////////////////////////////////////////////////////////
// Usage IEprompt("dialog descriptive text", "default starting value");
// 
// IEprompt will call promptCallback(val)
// Where val is the user's input or null if the dialog was canceled.
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
// This source code has been released into the public domain
// January 14th, 2007.
// You may use it and modify it freely without compensation
// and without the need to tell everyone where you got it.
///////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////
// You must create a promptCallback(val) function to handle
// the user input.  If you don't this script will fail and
// Bunnies will die.
///////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////
// These are global scope variables, they should remain global.
///////////////////////////////////////////////////////////
var _dialogPromptID=null;
var _blackoutPromptID=null;
///////////////////////////////////////////////////////////

function IEprompt(innertxt, form, def) {

	that=this;

	// Check to see if this is MSIE 7.   This isn't a great general purpose
	// detection system but it works well enough just to find MSIE 7.
	var _isIE7=(navigator.userAgent.indexOf('MSIE 7')>0);

	this.wrapupPrompt = function (cancled) {
		// wrapupPrompt is called when the user enters or cancels the box.
		// It's called only by the IE7 dialog box, not the non IE prompt box
		if (_isIE7) {
			// Make sure we're in IE7 mode and get the text box value
			val=document.getElementById('iepromptfield').value;
			// clear out the dialog box
			_dialogPromptID.style.display='none';
			// clear out the screen
			_blackoutPromptID.style.display='none';
			// clear out the text field
			document.getElementById('iepromptfield').value = '';
			// if the cancel button was pushed, force value to null.
			if (cancled) { val = '' }
			// call the user's function
			promptCallback(val, form);
		}
		return false;
	}

	//if def wasn't actually passed, initialize it to null
	if (def==undefined) { def=''; }

	if (_isIE7) {
		// If this is MSIE 7.0 then...
		if (_dialogPromptID==null) {
			// Check to see if we've created the dialog divisions.
			// This block sets up the divisons
			// Get the body tag in the dom
			var tbody = document.getElementsByTagName("body")[0];
			// create a new division
			tnode = document.createElement('div');
			// name it
			tnode.id='IEPromptBox';
			// attach the new division to the body tag
			tbody.appendChild(tnode);
			// and save the element reference in a global variable
			_dialogPromptID=document.getElementById('IEPromptBox');
			// Create a new division (blackout)
			tnode = document.createElement('div');
			// name it.
			tnode.id='promptBlackout';
			// attach it to body.
			tbody.appendChild(tnode);
			// And get the element reference
			_blackoutPromptID=document.getElementById('promptBlackout');
			// assign the styles to the blackout division.
			_blackoutPromptID.style.opacity='.9';
			_blackoutPromptID.style.position='absolute';
			_blackoutPromptID.style.top='0px';
			_blackoutPromptID.style.left='0px';
			_blackoutPromptID.style.backgroundColor='#555555';
			_blackoutPromptID.style.filter='alpha(opacity=90)';
			_blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
			_blackoutPromptID.style.display='block';
			_blackoutPromptID.style.zIndex='50';
			// assign the styles to the dialog box
			_dialogPromptID.style.border='2px solid blue';
			_dialogPromptID.style.backgroundColor='#DDDDDD';
			_dialogPromptID.style.position='absolute';
			_dialogPromptID.style.width='330px';
			_dialogPromptID.style.zIndex='100';
		}
		// This is the HTML which makes up the dialog box, it will be inserted into
		// innerHTML later. We insert into a temporary variable because
		// it's very, very slow doing multiple innerHTML injections, it's much
		// more efficient to use a variable and then do one LARGE injection.
		var tmp = '<div style="width: 100%; background-color: blue; color: white; font-family: verdana; font-size: 10pt; font-weight: bold; height: 20px">Input Required</div>';
		tmp += '<div style="padding: 10px">'+innertxt + '<BR><BR>';
		tmp += '<form action="" onsubmit="return that.wrapupPrompt()">';
		tmp += '<input id="iepromptfield" name="iepromptdata" type=text size=46 value="'+def+'">';
		tmp += '<br><br><center>';
		tmp += '<input type="submit" value="&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;">';
		tmp += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
		tmp += '<input type="button" onclick="that.wrapupPrompt(true)" value="&nbsp;Cancel&nbsp;">';
		tmp += '</form></div>';
		// Stretch the blackout division to fill the entire document
		// and make it visible.  Because it has a high z-index it should
		// make all other elements on the page unclickable.
		_blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
		_blackoutPromptID.style.width='100%';
		_blackoutPromptID.style.display='block';
		// Insert the tmp HTML string into the dialog box.
		// Then position the dialog box on the screen and make it visible.
		_dialogPromptID.innerHTML=tmp;
		_dialogPromptID.style.top=parseInt(document.documentElement.scrollTop+(screen.height/3))+'px';
		_dialogPromptID.style.left=parseInt((document.body.offsetWidth-315)/2)+'px';
		_dialogPromptID.style.display='block';
		// Give the dialog box's input field the focus.
		document.getElementById('iepromptfield').focus();
	} else {
		// we are not using IE7 so do things "normally"
		promptCallback(prompt(innertxt, def), form);
	}
}

function toggleButton (button, text) {
	// Make button disables when clicked so users wont click it twice
	button.value=text;
	//if (typeof button.disabled != "undefined")
	//    button.disabled = !button.disabled;
	//  else if (button.clicked) {
	//    button.clicked = false;
	//    button.value = button.oldValue;
	//  }
	//  else {
	//    button.clicked = true;
	//    button.oldValue = button.value;
	//    button.value = 'DISABLED';
	//  }
}

function togglelinks (postid) {
	// Will make links show 'ok' instead of the original text
	//var whichpost = document.getElementById(postid);
	var whichpost = postid;
	//whichpost.removeAttribute("href");
	//whichpost.style.display='none';
	whichpost.innerHTML='please wait';
	return true;
}

function show_confirm(text, msg1, msg2)
{   
	var r=confirm(text);
	if (r)
		return true;
	else
		return false;

}

// bitamar 2010-06-07 - commenting out the copies of checkUncheckAll from many files and putting one here  
var checkflag = "false";
function checkUncheckAll(tableId, checkboxName, selectTranslation, unselectTranslation, noFilters)
{
	var ret;
	if (checkflag == "false") // bitamar 2010-06-07 - on select all, ignore filtered options
		{
		if (noFilters)
			{
			checkboxes = document.getElementsByName(checkboxName);
			for (i=0; i<checkboxes.length; i++)
			{
				checkboxes[i].checked = true;
			}              
		}
		else
			{
			$("#" + tableId + " tbody tr td.report-firstcol").each(function(){			
				if ($(this).attr("filtermatch") != "false")
					{			
					$(this).find("input").attr("checked", "checked");
				}	
			});
		}
		checkflag = "true";
		return unselectTranslation;
	}
	else // bitamar 2010-06-07 - on unselect all, uselect all
		{	  
		checkboxes = document.getElementsByName(checkboxName);
		for (i=0; i<checkboxes.length; i++)
		{
			checkboxes[i].checked = false;
		}
		checkflag = "false";
		return selectTranslation;
	}
}

function toggle(id)
{ $('#' + id).toggle(); } 

function check_if_value_selected(fieldNameToCheck, valueToFind)
{
	var elLength = 0;
	var fieldToCheck = null;
	
	if (document.getElementById(fieldNameToCheck)) {
		fieldToCheck = document.getElementById(fieldNameToCheck);
	}
	else if (fieldNameToCheck) {
		fieldToCheck = fieldNameToCheck;
	}
	else {
		return false;
	}
	
	elLength = fieldToCheck.length;

	if (fieldToCheck.value==valueToFind) {
		return true;
	}
	else if (elLength > 0)
	{
		for (i=0; i<elLength; i++) {
	        if (fieldToCheck && fieldToCheck.options && fieldToCheck.options[i].value==valueToFind && fieldToCheck.options[i].selected==true){
	            return true;
	        }
	    }
	}
	return false;
}

function retrive_selected_value(fieldNameToCheck){
	if (document.getElementById(fieldNameToCheck)){
		return document.getElementById(fieldNameToCheck).value;
	}
	else{
		return null;
	}
}

function ShowHideOtherAddition(fieldNameToCheck, valueToFind, fieldNameToShowHide){
	if (document.getElementById(fieldNameToShowHide)){
		if (check_if_value_selected(fieldNameToCheck, valueToFind)){
			document.getElementById(fieldNameToShowHide).style.display="block";
		}
		else{
			document.getElementById(fieldNameToShowHide).style.display="none";
		}
	}
}

function CreateXmlHttpObject() { //fuction to return the xml http object
	var xmlhttp=false;	
	try{
		xmlhttp=new XMLHttpRequest();//creates a new ajax object
	}
	catch(e)	{		
		try{			
			xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");//this is for IE browser
		}
		catch(e){
			try{
				req = new ActiveXObject("Msxml2.XMLHTTP");//this is for IE browser
			}
			catch(e1){
				xmlhttp=false;//error creating object
			}
		}
	}
	return xmlhttp;
}

function updateFieldFromURL(strURL, ddToUpdate, ddToClear){
	var req = CreateXmlHttpObject(); // fuction to get xmlhttp object
	if (req){
		req.onreadystatechange = function(){
			if (req.readyState == 4) { //data is retrieved from server
				if (req.status == 200) { // which represents ok status                    
					document.getElementById(ddToUpdate).innerHTML=req.responseText;//put the results of the requests in or element

					if (ddToClear) {
						document.getElementById(ddToClear).innerHTML = "";
					}
				}
				else {
					alert("There was a problem while using XMLHTTP:\n");
				}
			}
		}
		req.open("GET", strURL, true); //open url using get method
		req.send(null);//send the results
	}
}

function open_export_type_dialogue(form_name){
	$("#exportSPAN"+form_name).dialog();
	$("#exportSPAN"+form_name).dialog( "option", "modal", true);
	$("#exportSPAN"+form_name).dialog( "open");
}
