function stringEndsWith(thisString, search) {
  return (thisString.lastIndexOf(search) == (thisString.length - search.length));
};
function extendSession() {
    if (typeof Liferay !== "undefined" && Liferay && Liferay.Session) {
        Liferay.Session.extend();
    }
}

function selectCheckbox(id) {
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
    	  if ((inputs[i].type == 'checkbox') && (inputs[i].id.indexOf(id) > 0)) {
        	inputs[i].checked = !inputs[i].checked;
        }
    }
    dsap();
    return false;
}

function sellectAll(s){
	var table=jQuery(s).parent().parent().parent().parent();
	if(table.get(0).tagName!="TABLE") {
		return false;
	}
	table.find("input.checkbox").trigger('click');
    dsap();
    return false;
}

function ifSelectedCheckbox(id,selectall,noselectedmsg,selectedmsg) {
    var inputs = document.getElementsByTagName("input");
    var ischeked = "no";
    for (var j = 0; j < inputs.length; j++) {
		if (((selectall == 'true') || (inputs[j].checked == true)) && (inputs[j].type == 'checkbox') && (inputs[j].id.indexOf(id) > 0)) {
			ischeked = "ok";
		}
    }
    if (ischeked == "ok"){
	    var agree=confirm(selectedmsg);
	    if (agree){
	    	return true ;
	    }else{
	    	return false ;
	    }
    }else{
	    alert(noselectedmsg);
    }
}

function lmgCheck(elem, yesId, noId, subform) {
	yesElement = window.document.getElementById(elem.id + ":0");
	noElement = window.document.getElementById(elem.id + ":1");
	try{
		if (yesElement.checked) {
			if(checkIfExists(subform + yesId)){
				document.getElementById(subform + yesId).style.display = 'inline';
			}
			if(checkIfExists(subform + noId)){
				document.getElementById(subform + noId).style.display = 'none';
				// to clear all input fileds if user change mind
				// ClearAllInputFields(subform + noId);
			}
		} else if (noElement.checked) {
			if(checkIfExists(subform + noId)){
				document.getElementById(subform + noId).style.display = 'inline';
			}
			if(checkIfExists(subform + yesId)){
				document.getElementById(subform + yesId).style.display = 'none';
				// to clear all input fileds if user change mind
				// ask Markus about clearing ClearAllInputFields(subform + yesId);
			}
		}
	}catch (e) {
	}
}

function checkIfExists(subformId){
	if (document.getElementById(subformId)!=null){
		return true;
	}
	return false;
}

function ExtractMap(map){
	// map samle data:
	// 1:10,3:56,4:88,7:0
	arr=map.split(',');
	map=new Array;
	for(i=0;i<=arr.length-1;i++){
		arr_str=arr[i];
		arr2=arr_str.split(":");
		arr2_1=arr2[0];
		arr2_2=arr2[1];
		map[arr2_1]=arr2_2;
	}
	return map;
}

function lmgRadioCheck(elem, value, subform, map) {
	map_arr=ExtractMap(map);
	var baseId = elem.id.substring(0, elem.id.lastIndexOf(":"));
	for (var i = 0; i < value; i++) {
		radioElement = document.getElementById(baseId + ":" + i);
		try {
			if(radioElement.checked){
				document.getElementById(subform + map_arr[radioElement.value]).style.display = 'inline';
			} else {
				document.getElementById(subform + map_arr[radioElement.value]).style.display = 'none';
			}
		} catch(e) {
			continue;
		}
	}
}

function lmgTableCheck(elem, divForTable) {
	if ($(elem).val() === "true") {
		divForTable.style.display = 'inline';
	} else {
		divForTable.style.display = 'none';
	}
}

var interval;
function DisableButton(b) {
	 b.disabled = true;
	 interval = setTimeout("EnableButton('"+b.id+"')",3000);
}
function EnableButton(id) {
    if (id) {
	    document.getElementById(id).disabled = false;
	    clearTimeout(interval);
	}
}

/* to clear all input fileds of subform if user change mind */
function ClearAllInputFields(subform_id){
	id="#"+subform_id+" input";
	jQuery(id).val("");
}

function clickAgain(){
	jQuery("input:radio:checked").trigger('click');
}

function openPriceField(elem,locationId){
	 selected = document.getElementById(elem.id + ":1");
	 if(selected.checked){
		 jQuery("div#price"+locationId).css({'display':'inline'});
	 }else{
		 jQuery("div#price"+locationId).css({'display':'none'});
	 }
}

function clearZone(){
		jQuery(".subzoneClass").val("");
}

var inputFieldExtraction = function(node) {
	if(node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
		node=node.childNodes[0];
	}
	if(jQuery(node).find("input").length>0){
		t=jQuery(node).find("input").val();
	} else {
		t=node.innerHTML;
	}
	return t;
};

function tableSort(){
	jQuery('.tbl_sorter').tablesorter({textExtraction: inputFieldExtraction});
}

/* function for checking for required fields */
function fireEffect(f){
	f.attr('style','background-color:#EFB7A4');
}
function clearEffect(f){
	f.attr('style','');
}

function validateRequiredInputs(f){
	jQuery("table:not(.tbl_sorter):has(td."+f+")").attr('style','border-collapse:separate;border-spacing:2px;');

	jQuery('td.'+f).each(function(i){
		var td=jQuery(this);
		td.attr('style','');
		td.find('fieldset.iceSelMnyCb.required, fieldset.iceSelOneRb.required').each(function(i){
			var l=jQuery(this).find('input:checked').length;
			if (l==0){
				fireEffect(td);
			} else {
				clearEffect(td);
			}
		});

		td.find('input.required, .iceInpTxtArea.required ,.iceSelOneMnu.required, textarea.required').each(function(i){
			if (jQuery(this).val()=="" || jQuery(this).val()=="org.jboss.seam.ui.NoSelectionConverter.noSelectionValue" ){
				fireEffect(td);
			} else {
				clearEffect(td);
			}
		});

		td.find('input:checkbox.required').each(function(i){
			if (!jQuery(this).is(':checked')){
				fireEffect(td);
			} else {
				clearEffect(td);
			}
		});

	});

}

var enable_scroll;
function scrollUp(){
	 enable_scroll=true;
	 // mark required unanswered fields
	 //validateRequiredInputs("answerInput");
	 //validateRequiredInputs("featureAnswer");
}

function checkBackSpace(e){
	t=e.target.tagName;
	kc=e.keyCode;
	if(kc==8 & t=="HTML"){
		//alert("back space");
		e.stopPropagation();
		return false;
	}
	return true;
}

jQuery(function(){
	jQuery("body").attr("onkeydown","return checkBackSpace(event);");

});

document.onkeydown = function() {
	if (Liferay.Browser.isIe()){
		var t=event.srcElement.tagName;
	    var kc=event.keyCode;
	    if(kc==8 && t!="INPUT" && t!="SELECT" && t!="TEXTAREA" && t!="SUBMIT"){
			return false;
	    }
		return true;
	}
}

function doSearchOnEnter(event){
	  var kc = event.keyCode;
	  if(kc == 13){
		  jQuery(".searchBtn").click();
	  }
}

var enable_scroll_to_previous_contracts;
function scrollToPreviousContracts(){
	enable_scroll_to_previous_contracts=true;
}

function servletLoaded(){
    $("iframe#dervletIframe").remove();
}

function callServlet(url){
		//if(Liferay.Browser.isIe()){
			window.open(url,'Download');
		//} else {
		//	jQuery("#download_iframe").append('<iframe id="servletIframe" style="display:none;" onload="servletLoaded();" src="'+url+'"></iframe>');
		//}
}

/* Function to deselect Sellect All pages checkbox */
function dsap(){
	var checkAll=jQuery('.select_all_checkbox');
	checked=checkAll.is(':checked');
	if(checked){
		checkAll.trigger('click');
	}
}

function deselectCc(c){
	c=jQuery(c);
	tr=c.parent().parent();
	cc=tr.find(".email_cc");
	if(c.is(':checked')){
		cc.attr("checked", false);
	}
}
function deselectTo(c){
	c=jQuery(c);
	tr=c.parent().parent();
	cc=tr.find(".email_to");
	if(c.is(':checked')){
		cc.attr("checked", false);
	}
}
function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

function scrollFormsToTop(){
	if(Liferay.Browser.isIe() && Liferay.Browser.getMajorVersion() == "6.0")
	{
		w=jQuery("#navigation").width();
		jQuery('html, body').animate({scrollTop:0}, 'fast');
		jQuery('html, body').animate({scrollLeft:0}, 'fast');
		jQuery("#banner").css('width',w+'px');
		w1=w-jQuery(".lfr-dock").width();
		jQuery(".lfr-dock").css('left',w1+'px');
	}
}

function fixFormLayout(){
	jQuery(".bb, .sb").each(function(){
		var bb=jQuery(this);
		var maxWidth=0;
		maxBrokenSize = 0;
		bb.find(".answInp .lbl").each(function(){
			var label = jQuery(this);
			width=label.width();
			if (width == 0) {
				size = label.text().length;
				if (maxBrokenSize < size) {
					maxBrokenSize = size;
				}
				if (maxBrokenSize > 0) {
					multicator = Liferay.Browser.isIe() ? 5.5 : 5;
					width = multicator * maxBrokenSize;
				}
			}
			if(width>maxWidth){
				maxWidth=width;
			}
		});
		if(maxWidth!=0){
			bb.find(".answInp .lbl").css("width",maxWidth+"px");
		}
		maxWidth=0;
		bb.find(".answInp").each(function(){
			var lbl=jQuery(this).find(".lbl").width();
			var answ=jQuery(this).find(".answ").width();
			var info=jQuery(this).find(".info").width();
			var nh=jQuery(this).find(".nh").width();
			w=lbl+answ+info+nh;
			if(w>maxWidth){
				maxWidth=w;
			}
		});
		if(maxWidth!=0){
			bb.find(".answInp").css("width",maxWidth+16+"px");
		}
	});
}

function repairTable(){

    var tableBodyTheadTh = jQuery('div[class="ui-datatable ui-widget testIdTenderProjectSPMappingsTbl"]').find('thead').find('tr').first().find('th');
    var tableBodyTBody = jQuery('div[class="ui-datatable ui-widget testIdTenderProjectSPMappingsTbl"]').find('tbody').find('tr');
    for (var anz=0; anz<tableBodyTBody.length; anz++) {
        var tds = tableBodyTBody[anz].cells;
        for(var b=0; b<tds.length; b++){
             var display = tds[b].style.display;
             var displayHeader = tableBodyTheadTh[b].style.display;
             if (display != displayHeader){
                tds[b].style.display = displayHeader;
             }
    	}
    }
}

function showColumns(tableId, index, leastShowHide) {

	var rows = jQuery("div[id$="+tableId+"] table:first tr");
	for (var row=0; row<rows.length;row++) {
		try {
			for (var col=(leastShowHide+1); col<rows[row].cells.length;col++) {
				if (index < col) {
					rows[row].cells[col].style.display= Liferay.Browser.isIe() ? 'block' : 'table-cell';
				} else {
					rows[row].cells[col].style.display='none';
				}
			}
		} catch (e) {
		   console.info(e);
		}
	}
	return false;
}

var lastScroll = 0;
//var currentScrolledColumn;
var scrollStep=200;

function columnScroll(e, tableId, leastShowHide) {
	lastScroll = e.scrollLeft;
	if (e.id == 'scroller1') {
		try {
			if(e.scrollLeft == "-"+document.getElementById('scroller2').scrollLeft){
				return;
			}
			document.getElementById('scroller2').scrollLeft = e.scrollLeft;
		} catch (e) {
		    console.info(e);
		    return;
		 }
	} else if (e.id == 'scroller2') {
		try {
			if(e.scrollLeft == "-"+document.getElementById('scroller1').scrollLeft){
				return;
			}
			//console.info(e.scrollLeft+"-"+document.getElementById('scroller1').scrollLeft);
			document.getElementById('scroller1').scrollLeft = e.scrollLeft;
		} catch (e) {
		     console.info(e);
        	  return;
		}
	}
	var ix = (lastScroll / scrollStep) + leastShowHide;
	//currentScrolledColumn=ix;
	showColumns(tableId, ix, leastShowHide);
}
var lastVerticalScroll = 0;
var scrollFactor = 2000;
function lineScrollFs(myComp, tableId){
   var tableDiv = jQuery("div[id$="+tableId+"] table:first");
    var tableDivHeight = tableDiv.height();
    var tableDivWidth =  tableDiv.width();
    var rows = jQuery("div[id$="+tableId+"] tbody:first tr[id*="+tableId+"]");

    var currentScroll = myComp.scrollTop;
    var scrollIndex = currentScroll / (scrollFactor / rows.length);

    if(currentScroll > lastVerticalScroll){
         var indexHide = Math.round(scrollIndex);
         hideCols(indexHide,rows);
    } else {
         var indexShow = Math.round(scrollIndex);
         showCols(indexShow,rows);
    }

     lastVerticalScroll = currentScroll;
}

function columnScrollFs(tableId){
    var tableDiv = jQuery("div[id$="+tableId+"] table:first");
    var scrollerHeight = tableDiv.height() / 3;
    jQuery("#scrollerVertical").height();
    jQuery("img[id$=scrollerVertImg]").height(scrollerHeight * 15);
    tableDiv.scrollTop = 0;
}

function hideCols(index, rows){
    var rowsLength = rows.length;
    if (index >= rowsLength){
        return;
    }

    try {
      for (var row=0; row<index; row++) {
          if (row != rowsLength){
             rows[row].hidden = true;
          }
      }
    } catch (e) {
          console.info(e);
    }

}

function showCols(index, rows){
    var rowsLength = rows.length;
    if (index > rowsLength){
        return;
    }

    try {
      var rowsLength = rows.length - 1;
      for (var row=rowsLength; row>=index; row--) {
          rows[row].hidden = false;
      }
    } catch (e) {
        console.info(e);
    }

}

function moveScroll(){
    var scroll = jQuery(window).scrollTop();
     var tableDiv = jQuery("div[id$=pst] table");
    var anchor_top = tableDiv.offset().top;
    var anchor_bottom = jQuery("#bottom_anchor").offset().top;
    if (scroll>anchor_top && scroll<anchor_bottom) {
    clone_table = jQuery("#clone");
    if(clone_table.length == 0){
        clone_table =  jQuery("div[id$=pst] table").clone();
        clone_table.attr('id', 'clone');
        clone_table.css({position:'fixed',
                 'pointer-events': 'none',
                 top:0});
        clone_table.width(jQuery("div[id$=pst] table").width());
        jQuery("#table-container").append(clone_table);
        jQuery("#clone").css({visibility:'hidden'});
        jQuery("#clone thead").css({visibility:'visible'});
    }
    } else {
    jQuery("#clone").remove();
    }
}


function columnScrollFs(myComp, tableId, leastShowHide) {

    fixHeightScrolling(tableId, leastShowHide);

    var tableDivWidth = jQuery("div[id$="+tableId+"] table").width();

    if ( (tableDivWidth < document.body.clientWidth-150) && myComp.scrollLeft > lastScroll) {
		return;
	}

	lastScroll = myComp.scrollLeft;

    if (myComp.id == 'scroller1') {
    		try {
    			if(myComp.scrollLeft == "-"+document.getElementById('scroller2').scrollLeft){
    				return;
    			}
    			document.getElementById('scroller2').scrollLeft = myComp.scrollLeft;
		} catch (e) { }
    	} else if (myComp.id == 'scroller2') {
    		try {
    			if(myComp.scrollLeft == "-"+document.getElementById('scroller1').scrollLeft){
    				return;
    			}
			console.info(myComp.scrollLeft+"-"+document.getElementById('scroller1').scrollLeft);
    			document.getElementById('scroller1').scrollLeft = myComp.scrollLeft;
                } catch (e) {
                    console.log(e);
                }
    	}
	var ix = (lastScroll / scrollStep) + leastShowHide;
	//currentScrolledColumn=ix;
	showColumnsFs(myComp, tableId, ix, leastShowHide);
}

function showColumnsFs(myComp, tableId, index, leastShowHide) {


	// var tbl  = jQuery("div[id$='pst'] table:first tr");
	try {
	    var rows = jQuery("div[id$="+tableId+"] table:first tr");
	    for (var row=0; row<rows.length;row++) {

			for (var col=(leastShowHide+1); col<rows[row].cells.length;col++) {
				if (index < col) {
					rows[row].cells[col].style.display= Liferay.Browser.isIe() ? 'block' : 'table-cell';
				} else {
					rows[row].cells[col].style.display='none';
				}
			}

	    }
	} catch (e) {
	    console.log(e);
    }
	return false;
}


function getTableClientId(tableId) {
	var elems = jQuery("div[id$="+tableId+"] table");
	for (var c = 0; c < elems.length; c++) {
		if (stringEndsWith(elems[c].id, (':' + tableId))) {
			return elems[c].id;
		}
	}
	return tableId;
}

function getTableClientIdFs(tableId) {

	var elems = jQuery("div[id$="+tableId+"] table");
	for (var c = 0; c < elems.length; c++) {
		if (stringEndsWith(elems[c].id, (':' + tableId))) {
			return elems[c].id;
		}
	}
	return tableId;
}

function getImageByClientId(imageId) {
	var img  = jQuery(imageId);
	return img;
}

function fixHeightScrolling(tableId, leastShowHide) {
	var tbl = jQuery("div[id$="+tableId+"] thead")[0];
	for (var b = 0; b < tbl.rows.length; b++) {
		var row = tbl.rows[b];
		if (row.cells.length > 0) {
            var colHeight = row.cells[0].clientHeight;
            for (var a = 0; a < row.cells.length; a++) {
                    var cell = row.cells[a];
                    cell.style.height = colHeight + "px";
            }
		}
	}
}

function fixHeight(tableId, leastShowHide) {
	var tbl = jQuery("div[id$="+tableId+"] table")[0];
	for (var b = 0; b < tbl.rows.length; b++) {
		var row = tbl.rows[b];
		if (row.cells.length > 0) {
            var colHeight = row.cells[0].clientHeight;
            for (var a = 0; a < row.cells.length; a++) {
                    if (a == (leastShowHide+1)) {
                        cell.style.borderRight = "2px black solid";
                    }
                    var cell = row.cells[a];
                    cell.style.height = colHeight + "px";
            }
		}
	}
}


//function fixWidth() {
//    var tableHeader = jQuery('div[class="ui-datatable-scrollable-header"]').find('table');
//    var tableBodyTh = jQuery('div[class="ui-datatable-scroll-x ui-datatable-scrollable-body"]').find('th');
//    var tableBodyTBody = jQuery('div[class="ui-datatable-scroll-x ui-datatable-scrollable-body"]').find('tbody').find('tr').first().find('td');
//    for (var c = 0; c < tableHeader.length; c++){
//         var tbl = tableHeader[c];
//         for (var b = 0; b < tbl.rows.length; b++) {
//              var row = tbl.rows[b];
//               var colHeight = row.cells[b].clientHeight;
//               for (var a = 0; a < row.cells.length; a++) {
//                    var myCellWidth = row.cells[a].clientWidth;
//                    var cell = tableBodyTh[a];
////                    var styleWidth = cell.style.width;
////                    var styleWidthPx = styleWidth.replace('px','');
//                     var tBodyCell = tableBodyTBody[a]
//
//                    if(tBodyCell.clientWidth < myCellWidth){
//                       cell.style.width = myCellWidth + "px";
//                       tBodyCell.style.width = myCellWidth + "px";
//                    } else {
//                       row.cells[a].style.width = tBodyCell.clientWidth + "px";
//                    }
//                    cell.style.height = colHeight + "px";
//               }
//         }
//    }
//}


function initScroller(tableId,fixedColumn){
	var tbl  = jQuery("div[id$="+tableId+"] table");
	var rows = tbl[0].getElementsByTagName('tr');
	var row=rows[0];
	var cols=row.cells.length;
	var c=cols-fixedColumn;
	//scroller_width=1000;
	scroller_width=jQuery(screen.availWidth);
	img_w=c*scrollStep+scroller_width;
	getImageByClientId('scroller1_img').width = img_w;
	getImageByClientId('scroller2_img').width = img_w;
//	if(currentScrolledColumn!=undefined){
//		showColumns(tableId, currentScrolledColumn, fixedColumn);
//		var scroll=scrollStep* (currentScrolledColumn-fixedColumn);
//		document.getElementById('scroller1').scrollLeft=scroll;
//		document.getElementById('scroller2').scrollLeft=scroll;
//	}
}

function syncTableWidths(){
	var t1=jQuery("table.algnTbl1");
	var t2=jQuery("table.algnTbl2");
	if(t2.length==0) return;
	var th1=t1.find("tr:first").find("th");
	var th2=t2.find("tr:first").find("th");
	t1.find("img.spacer").remove();
	t2.find("img.spacer").remove();
	var n=th1.length;
	var tw=0;
	var arr=new Array();
	for(i=0;i<n;i++){
		c1=jQuery(th1[i]);
		c2=jQuery(th2[i]);
		w1=jQuery(th1[i]).width();
		w2=jQuery(th2[i]).width();
		if(w1>w2){
			w=w1;
		} else {
			w=w2;
		}
		arr[i]=w;
	}
	for(i=0;i<arr.length;i++){
		c1=jQuery(th1[i]);
		c2=jQuery(th2[i]);
		w=arr[i];
		c1.prepend('<img class="spacer" src="" width="'+w+'" height="1" style="display:block">');
		c2.prepend('<img class="spacer" src="" width="'+w+'" height="1" style="display:block">');
	}
}

function attachDatepicker(styleClass,userProfile,path){
	jQuery(styleClass).each(function(e){
		var hasDatepicker=jQuery(this).parent().find("img.ui-datepicker-trigger").length>0;
		if(!hasDatepicker){
			jQuery(this).datepicker({
				showOn: 'button',
				buttonImage: path+'/images/dtpick.gif',
				buttonImageOnly: true,
				dateFormat: userProfile
			});
		}
	});
}

/* Last Two Years functionality */
function findMaxHeight(row) {
    maxHeight = 0;
    cells = jQuery(row).find("div.cur");
    for (j = 0; j < cells.length; j++) {
        h = jQuery(cells[j]).height();
        if (h >= maxHeight) {
            maxHeight = h;
        }
    }
    return maxHeight;
}

/* Last Two Years functionality */
function findMaxHeightFs(row) {
    var maxHeight = 0;
    var h;
    var cells = jQuery(row).find("div.cur");
    for (var j = 0; j < cells.length; j++) {
        h = jQuery(cells[j]).height();
        if (h >= maxHeight) {
            maxHeight = h;
        }
    }
    return maxHeight;
}

function findMaxLtyheight(row,r){
	maxHeight=0;
	cells=jQuery(row).find("div.lty table");
	for(k=0;k<cells.length;k++){
		row=cells[k].rows[r];
		h=jQuery(row.cells[0]).height();
		if(h>=maxHeight){
			maxHeight=h;
		}
	}
	return maxHeight;
}

function findMaxLtyheightFs(row, r) {
    var maxHeight = 0;
    var cells = jQuery(row).find("div.lty table");
    var row;
    var h;
    for (var k = 0; k < cells.length; k++) {
        row = cells[k].rows[r];
        h = jQuery(row.cells[0]).height();
        if (h >= maxHeight) {
            maxHeight = h;
        }
    }
    return maxHeight;
}

function syncExpandedRow(row){
	var curValMaxHeight=findMaxHeight(row);
	jQuery(row).find("div.cur").height(curValMaxHeight);
	var tbls=jQuery(row).find("div.lty table");
	if(tbls.length==0) return;
	var tbl=tbls[0];
	rows=tbl.rows.length;
	for(r=0;r<rows;r++){
		var maxLtyRowHeight=findMaxLtyheight(row,r);
		cells=jQuery(row).find("div.lty table");
		for(k=0;k<cells.length;k++){
			c=cells[k].rows[r].cells[0];
			jQuery(c).height(maxLtyRowHeight);
		}
	}
}

function syncExpandedRowFs(row) {
    var curValMaxHeight = findMaxHeightFs(row);
    jQuery(row).find("div.cur").height(curValMaxHeight);
    var tbls = jQuery(row).find("div.lty table");
    if (tbls.length == 0) return;
    var tbl = tbls[0];
    var rows = tbl.rows.length;
    var maxLtyRowHeight;
    var cells;
    var c;
    for (var r = 0; r < rows; r++) {
        maxLtyRowHeight = findMaxLtyheightFs(row, r);
        cells = jQuery(row).find("div.lty table");
        for (var k = 0; k < cells.length; k++) {
            c = cells[k].rows[r].cells[0];
            jQuery(c).height(maxLtyRowHeight);
        }
    }
}

function syncExpandedRows(tableClass){
	var table = jQuery(".expandable table."+tableClass);
	// var table = jQuery(".expandable ." + tableClass + " > div > table");
	console.log("table: " + table.attr('id'));
	expandedRows = table.find("tr.expanded, tr.expandedSelected");
	jQuery(".expandable table."+tableClass+" div.cur.action").height(80);
	jQuery(".expandable table."+tableClass+" div.cur.action").width(60);
	for(i = 0; i < expandedRows.length; i++){
		syncExpandedRow(expandedRows[i]);
	}
	jQuery(".expandable table." + tableClass + " div.lty.empty").remove();
	// jQuery(".expandable ." + tableClass + " > div > table div.lty.empty").remove();
}

function syncExpandedRowsFs(tableClass){
	var leTable = jQuery("div[id$='pst'] table")[0];
	var expandedRows = jQuery("tr.expanded").find(leTable);
	for(i = 0; i < expandedRows.length; i++){
		syncExpandedRowFs(expandedRows[i]);
	}
}

function showHideScroller(tableId){
	scroller = document.getElementById('scroller1');
	if(scroller == null) return;
	scrollerWidth=parseInt(scroller.style.width);
	var leTable = jQuery("div[id$='pst'] table").first();
	var tableWidth = leTable.width();
	if(scrollerWidth > tableWidth){
		scroller.style.display="none";
	} else {
		scroller.style.display="block";
	}
	document.getElementById('scroller2').style.display=document.getElementById('scroller1').style.display;
}

var nothingSelectedMessage;
function confirmAction(tableClass, message, number){
	var mess;
	if(number == null){
		number = jQuery('table.' + tableClass + ' tbody input.chkb:checked').length;
	}
	if (number == 0){
		util.message.displayError(nothingSelectedMessage);
		return false;
	}
	if(message == null){
		return true;
	}
	mess = message.replace("#number", number);
	return confirm(mess);
}

// Deprecated please do not use ...
var nothingSelectedMessage2;
function confirmAction2(tableClass, message, number){

	var mess;
	if(number == null){
		number = jQuery("div[id$='pst'] table:first tbody input.chkb:checked").length;
	}
	if (number == 0){
		util.message.displayError(nothingSelectedMessage2);
		return false;
	}
	if(message == null){
		return true;
	}
	mess = message.replace("#number", number);
	return confirm(mess);
}

function confirmActionAsk(message, nothingSelectedMessage, number){
    var selectAll = false;
    try{
        var selectAllCheckbox = document.getElementsByClassName("select_all_checkbox");
        if (selectAllCheckbox[0].checked){
        	selectAll = true;
        }
    } catch (err){
        console.log(err);
    }

    if (selectAll){
    	var allMsg = message.replace("#number", "ALL");
        return confirm(allMsg);
    }

    if(message == null){
    	return true;
    }

    var checkedCounter = jQuery('div[id$="pst"],div[id$="onlineTenderSuppliers"],div[id$="preselection_list_table"]').find('table:first tbody input.chkb:checked').length;
    if (checkedCounter === null || checkedCounter === undefined || checkedCounter == 0){
    		util.message.displayInfo(nothingSelectedMessage);
    		return false;
    }

	mess = message.replace("#number", checkedCounter);
	return confirm(mess);
}

function shiftLty2(tdClass){
    var tdSelector = "." + tdClass;
    var rowList = jQuery("tr.ui-expanded-row-content");
    for(i = 0; i < rowList.length; i++){
        if(jQuery(rowList[i]).find("> td").length == 1) {
            // console.log("tr: " + rowList[i] + ", id: " + rowList[i].id);
            // console.log(jQuery(rowList[i]).find(".ilColumn").size());
            var columnList = jQuery(rowList[i]).find(tdSelector);
            jQuery(columnList).insertBefore(jQuery(rowList[i]).find("> td"));
            jQuery(rowList[i]).find("td").not(tdSelector).remove();
        }
    }
}

function closeExpandedRows() {
    var rowsTarget = jQuery("tr.ui-expanded-row-content");
    for (var i = 0; i < rowsTarget.length; i++) {
		var rowTarget = jQuery(rowsTarget[i]);
		//check if checkbox is checked
		var prevDataRow = rowTarget.prev();
		do {
             if (prevDataRow.hasClass('ui-datatable-odd') || prevDataRow.hasClass('ui-datatable-even')) {
                break;
             }
             prevDataRow = prevDataRow.prev();
		}
		while (prevDataRow != undefined && prevDataRow.is('tr'));
		if (prevDataRow != undefined) {
            var input = prevDataRow.children(":nth-child(2)").children("input");
            if (input.is(":checked")) {
                rowTarget.attr('style', 'display:none;')
                rowTarget.empty();
            }
        }
    }
}

function shiftLty3(trClass){
    var trSelector = "." + trClass;
    var rowsTarget = jQuery("tr.ui-expanded-row-content table").parent().parent();

    for(var i = 0; i < rowsTarget.length; i++){
		var rowTarget = jQuery(rowsTarget[i]);
        var rowsSource = rowTarget.find(trSelector);

    	rowsSource.insertAfter(rowTarget);
        rowsSource.attr('class', rowTarget.attr('class'));
        rowTarget.attr('style', 'display:none;')
        rowTarget.empty();

        //add onlick event for correcting closing expansionRow behaviour
        var aLink = rowTarget.prev().children().first().children().first().children().first();
        aLink.click(function() {
            var theRow = $(this).parent().parent().parent();
            var theNext = theRow.next();
            do {
                if (theNext.hasClass('ui-expanded-row-content')) {
                    var rowToBeRemoved = theNext;
                    theNext = theNext.next();
                    rowToBeRemoved.empty();
                    rowToBeRemoved.attr('style', 'display:none;')
                }
                else if (theNext.hasClass('ui-datatable-odd') || theNext.hasClass('ui-datatable-even')) {
                    break;
                }
                else {
                    theNext = theNext.next();
                }
            }
            while (theNext != undefined && theNext.is('tr'));

        });
    }
}

function initializeTable(forTable, fixCol) {
            var clientId = getTableClientId(forTable);
			initScroller(clientId, fixCol);
			fixHeight(clientId, fixCol);
			//initVerticalScrolling(forTable);
}

function initializeScrolling(isIE6, forTable, fixCol) {

		if (isIE6 > 0){
		   document.getElementById('scroller1').style.width =  "800 px";
		   document.getElementById('scroller2').style.width =  "800 px";
		} else {
		  initializeWithForNonIE();
		}

		try {
			var clientId = getTableClientId(forTable);
			initScroller(clientId, fixCol);
			fixHeight(clientId, fixCol);
		} catch (e) {
			console.log("initializeScrolling: " + e);
		}
}

function initializeWithForNonIE(){
        try {
			var myWidth = screen.availWidth - 200;
			document.getElementById('scroller1').style.width = myWidth + "px";
		} catch (e) {
			document.getElementById('scroller1').style.width = "800 px";
			console.log("initializeScrolling: " + e);
		}
		try {
			var myWidth = screen.availWidth - 200;
			document.getElementById('scroller2').style.width = myWidth + "px";
		} catch (e) {
			document.getElementById('scroller2').style.width = "800 px";
			console.log("initializeScrolling: " + e);
		}
}

function copyMarker(lat, lng){

    jQuery(".geoLatitude")[0].value = lat;
    jQuery(".geoLatitude").css("color","red");
    jQuery(".geoLongitude")[0].value = lng;
    jQuery(".geoLongitude").css("color","red");
}


function fireLastTwoYearsHistory(){

   var $ltyhLink = jQuery('a[class="ui-icon ui-row-panel-toggler ui-icon-circle-triangle-e"]');
   for(i = 0; i < $ltyhLink.length; i++){
     $ltyhLink[i].click(function(){
        jQuery( this ).click();

     });
   }
}

function closeContractExport(popupId){
  var $ltyhLink = jQuery('a[class='+popupId+']');
     for(i = 0; i < $ltyhLink.length; i++){
       $ltyhLink[i].click(function(){
          jQuery( this ).click();

       });
     }
}

function closeFullScreen() {
    var isFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
        (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
        (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
        (document.msFullscreenElement && document.msFullscreenElement !== null);

    if (isFullScreen) {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

function setWidthToWindowWidth(styleName) {
    function widthInPx() {
        var widthInPx = $(window).width() - 400;
        var defaultWith = "1000"
        if (widthInPx > 1000){
            return widthInPx;
        } else {
            return defaultWith;
        }
    }
    $(document).find("." + styleName).css("width", (widthInPx()) + "px");
}

function setWidthToWindowWidthForAllSearchPanels() {
     setWidthToWindowWidth("testIdCompanyStatusInformationPanel");
     setWidthToWindowWidth("testIdRfiStepsStatusInformationPanel");
     setWidthToWindowWidth("testIdCompanyAssignmentsPanel");
     setWidthToWindowWidth("testIdCompanyLineItemNumberExtendedPanel");
     setWidthToWindowWidth("testIdGeoSearchPanel");
     setWidthToWindowWidth("testIdFilterableAtFinalSelectionPanel");
     setWidthToWindowWidth("testIdExportSearchPanel");
     setWidthToWindowWidth("testIdContractStatusInformationPanel");
     setWidthToWindowWidth("testIdCompanyFeatures");
     setWidthToWindowWidth("testIdCompanyAttributes");
     setWidthToWindowWidth("testIdCompanyAssignmentsPanel");
}

function closeL2YRows() {
     var query = "div[class='ui-datatable ui-widget testIdTenderProjectSPMappingsTbl']";
     var div = document.querySelector(query);
     if (div != null) {
         var tbody = div.querySelector("tbody");
         var rows = tbody.querySelectorAll("tr");

         for (var i=0; i < rows.length; i++) {
            var tr = rows[i];
            if (tr.classList.contains('ui-expanded-row-content')) {
                var style = window.getComputedStyle(tr);
                if (style.display !== 'none' && style.display !== 'hidden') {
                        tr.parentNode.removeChild(tr);
                }
            }
         }
     }
}



function onContractLoadStatus(data) {
   var status = data.status;
       if (status === "success") {
            var height = window.screen.availHeight - 10;
            var width = window.screen.availWidth - 10;
            var props = "toolbar=0,location=1,directories=1,status=0,menubar=1,scrollbars=1,resizable=1,fullscreen=0,width="+width+",height="+height+",top=10,left=10";
            var orderWindow = pop=window.open('contract','',props);
            try {
                orderWindow.focus();
            } catch (e){
                console.log("Can't open PopUp. Please Check PopUp Blocker!");
            }
       }
}

function disableContractHistory(data){
   var status = data.status;
   if (status === "success"){
        disableTopBar();
        var inputTags = jQuery("span[id$=':templForm1:currentForm'] input");
        for (i = 0; i < inputTags.length; i++) {
            try {
                     var inputTag = inputTags[i];
                     if (inputTag.className == 'hstView') {
                         console.log("do not disable hstView button");
                     } else if (inputTags[i].type == 'submit' ){
                         var buttonId = inputTag.id;
                         document.getElementById(buttonId).remove();
                     } else {
                         inputTag.setAttribute("disabled","true");
                     }
                } catch (e){
                   console.log("disabled Input Tags failt");
            }
        }

        var selectTags = jQuery("span[id$=':templForm1:currentForm'] select");
        for (i = 0; i < selectTags.length; i++) {
            try {
                   selectTags[i].setAttribute("disabled","true");
                } catch (e){
                   console.log("disabled select Tags failt!");
            }
        }

        var textareaTags = jQuery("span[id$=':templForm1:currentForm'] textarea");
        for (i = 0; i < textareaTags.length; i++) {
             try {
                  textareaTags[i].setAttribute("disabled","true");
                 } catch (e){
                   console.log("disabled textarea Tags failt!");
                 }
         }
   }
}


function disableTopBar(){
    var aLinks = jQuery("li[id*='layout_'] a");
    for (i = 0; i < aLinks.length; i++) {
        try {
            var aLink = aLinks[i];
             aLink.href = "javascript:void(0)";
        } catch (e) {
             console.log("disabled A Link Tag failt");
        }
    }
}


