function disableEnterKey(e)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     return (key != 13);
}


function mouseOverSpreadsheetCell(cellID){		
	row = cellID.split("__FLAG__")[1];
	column = cellID.split("__FLAG__")[2];
	selected_row = -10;
	
	//get selected_row
	var chkboxes = document.getElements('input[id^=rowSelector__FLAG__]');
	chkboxes.each(function(checkbox){
		if (checkbox.checked == true){
			selected_row = checkbox.id.toString().split('__FLAG__')[1];
		}
	});
	
	//paint vertical line  and horizontal line cells
	var cells = document.getElements('div[id^=cell__FLAG__]').filter(function(item,index){
		item.setStyles({
			'background-color':  'transparent'
		});
		
		//check cell if it belongs on a selected row
		if ((item.get("id").toString().split('__FLAG__')[1] == selected_row) && (item.get("id").toString().split('__FLAG__')[2] != -1)){
			item.setStyles({
				'background-color':  '#9999FF'
			});
		}
		
		else
		
		// match vertical line cells
		if ((item.get("id").toString().split('__FLAG__')[2] == column) && (item.get("id").toString().split('__FLAG__')[2] != -1)){
			item.setStyles({
				'background-color':  '#F0F0F0'
			});	
		}
		
		else
		
		// match horizontal line cells
		if ((item.get("id").toString().split('__FLAG__')[1] == row) && (item.get("id").toString().split('__FLAG__')[2] != -1)){
			item.setStyles({
				'background-color':  '#F0F0F0'
			});	
		}
		return false;
	});
	
	/*/ paint current cell
	if ( $(cellID).get("id").toString().split('__FLAG__')[1] != selected_row){
		$(cellID).setStyles({ //set('class', 'currentCell');
				'background-color':  '#F0F0F0'
		});
	}*/
}

function mouseOutSpreadsheetCell(cellID){
	// get selected row
	var row = -10;
	var chkboxes = document.getElements('input[id^=rowSelector__FLAG__]');
	chkboxes.each(function(checkbox){
		if (checkbox.checked == true){
			row = checkbox.id.toString().split('__FLAG__')[1];
		}
	});
	
	var cells = document.getElements('div[id^=cell__FLAG__]');
	cells.each(function(cell){
		if (cell.get("id").toString().split('__FLAG__')[1] != row){
			cell.setStyles({
				'background-color':  'transparent'
			});
		} 
	});
}

function selectRow(row, spreadsheetName){

	var wasChecked = false;
	var chkboxes = document.getElements('input[id^=rowSelector__FLAG__]');
	chkboxes.each(function(checkbox){
		// change color to transparent on privious row
		if (checkbox.checked == true){
			wasChecked = true;
			var	privious_row = checkbox.id.toString().split('__FLAG__')[1];
			var priviousRowCells = document.getElements('div[id^=cell__FLAG__]').filter(function(item,index){
				if (item.get("id").toString().split('__FLAG__')[1] == privious_row){
					item.setStyles({
						'background-color':  'transparent'
					});
				}
				return false;
			});
		}
		checkbox.checked = false;
	});
	
	$('rowSelector__FLAG__' + row.toString()).set('checked', 'checked');
	
	var header_row_cells_values = new Array();
	//change color of selected row and also fill array of header row cells values
	var currentRowCells = document.getElements('div[id^=cell__FLAG__]').filter(function(item,index){
		if ((item.get("id").toString().split('__FLAG__')[1] == row) && (item.get("id").toString().split('__FLAG__')[2] != -1)){
			item.setStyles({
				'background-color':  '#9999FF'
			});
			header_row_cells_values[parseInt(item.get("id").toString().split('__FLAG__')[2])] = item.get("html").toString();
		}
		return false;
	});
	
	//alert($("headerRow__FLAG__" + spreadsheetName.toString()).get("value"));
	//alert(row.toString());
	//alert(wasChecked);
	
	// refill selections with heaser row cell values(only if header row was changed)
	if  (/*(!wasChecked) ||*/ (ltrim(rtrim($("headerRow__FLAG__" + spreadsheetName.toString()).get("value"))) != rtrim(ltrim(row.toString()))))
	{
	  //these are selections in tabbed pane that need to be re-filled
	  var tabSelectionsMapping = document.getElements('select[class=tab_selection_mapping]').filter(function(item,index){
	  	return (item.get("id").toString().split("__FLAG__")[1] == spreadsheetName);
	  });
		
		tabSelectionsMapping.each(function(tabSelectionMapping)
		{
			//alert(tabSelectionMapping.id/*options[tabSelectionMapping.selectedIndex].value.toString()*/);
			
			var col = -5;
			
			var spreadsheetSelectionMapping = document.getElements('select[class=spreadsheet_selection_mapping]').filter(function(item,index){
				return item.options[item.selectedIndex].value==tabSelectionMapping.id;
			})[0];
			
			if(typeof(spreadsheetSelectionMapping) != "undefined"){
				//alert('spreadsheetSelectionMapping.id=' + spreadsheetSelectionMapping.id);
				col = parseInt(spreadsheetSelectionMapping.id.toString().split('__FLAG__')[1]);
				//alert('col=' + col);
			}
			
			clearOptions(tabSelectionMapping);
			addOption(tabSelectionMapping, 'Select...', '', false);
			for (var i = 0; i < header_row_cells_values.length; i++) {
	    	addOption(tabSelectionMapping, ltrim(rtrim(header_row_cells_values[i])), i.toString() + '__FLAG__' + ltrim(rtrim(header_row_cells_values[i])), col == i);
	    }
	  });
	}
	
	//change value on input header_row
	$("headerRow__FLAG__" + spreadsheetName.toString()).set("value", rtrim(ltrim(row.toString())));
}

function selectRowPreviewMode(row, spreadsheetName){
	
	var chkboxes = document.getElements('input[id^=rowSelector__FLAG__]');
	chkboxes.each(function(checkbox){
		// change color to transparent on privious row
		if (checkbox.checked == true){
			var	privious_row = checkbox.id.toString().split('__FLAG__')[1];
			var priviousRowCells = document.getElements('div[id^=cell__FLAG__]').filter(function(item,index){
				if (item.get("id").toString().split('__FLAG__')[1] == privious_row){
					item.setStyles({
						'background-color':  'transparent'
					});
				}
				return false;
			});
		}
		checkbox.checked = false;
	});
	
	$('rowSelector__FLAG__' + row.toString()).set('checked', 'checked');
	
	var header_row_cells_values = new Array();
	//change color of selected row and also fill array of header row cells values
	var currentRowCells = document.getElements('div[id^=cell__FLAG__]').filter(function(item,index){
		if ((item.get("id").toString().split('__FLAG__')[1] == row) && (item.get("id").toString().split('__FLAG__')[2] != -1)){
			item.setStyles({
				'background-color':  '#9999FF'
			});
			header_row_cells_values[parseInt(item.get("id").toString().split('__FLAG__')[2])] = item.get("html").toString();
		}
		return false;
	});
}


function tabbedPaneSellectionChange(selection){
	//alert(selection);
	curentSpreadsheet =  selection.id.toString().split("__FLAG__")[1];
	//get checked row
	var inputHeaderRow = $("headerRow__FLAG__" + curentSpreadsheet);
	
	var row = parseInt(inputHeaderRow.value);
	
	//alert(row);
	
	chkbox =  document.getElements('input[type=checkbox]').filter(function(el){return (el.id == ('rowSelector__FLAG__' + row.toString()))})[0];
	
	if (typeof(chkbox) == 'undefined'){
		alert('Canot locate chkbox with id = ' + row.toString());
		return false;
	}
	
	if (chkbox.checked == false){
		alert('Different values for checkbox and textbox ');
		return false;
	}
	  
	if (selection.options[selection.selectedIndex].value.toString() != "")
	{
		// get colum number for selected tab selection
		var cell = document.getElements('div[id^=cell__FLAG__' + row.toString() +'__FLAG__' + ']').filter(function(el){
			return (ltrim(rtrim(el.innerHTML))  == ltrim(rtrim(selection.options[selection.selectedIndex].text)));
		})[0];
		if (typeof(cell) == 'undefined'){
			alert('Canot locate cell with text = ' + selection.options[selection.selectedIndex].text.toString());
			return false;
		}
	
		col = parseInt(cell.id.toString().split('__FLAG__')[2]);
	
		spreadsheetSelectionMapping = $("mapfield__FLAG__" + col.toString());
		if (typeof(spreadsheetSelectionMapping) == 'undefined'){
			alert('Canot locate spreadsheetSelectionMapping with id = ' + "mapfield__FLAG__" + col.toString());
			return false;
		}
	
		//alert(spreadsheetSelectionMapping);
	
		for (var i = 0; i < spreadsheetSelectionMapping.length; i++) {
    	if (spreadsheetSelectionMapping[i].value == selection.id){
				spreadsheetSelectionMapping[i].selected = true;
				spreadsheetSelectionMapping.set("title", spreadsheetSelectionMapping.options[spreadsheetSelectionMapping.selectedIndex].text.toString());
			}
			else{
				spreadsheetSelectionMapping[i].selected = false;
			}
  	}
  }
}

function spreadsheetSellectionChange(selection){
	
	curentSpreadsheet =  selection.options[selection.selectedIndex].value.toString().split("__FLAG__")[1];
	//
	//get checked row
	var inputHeaderRow = $("headerRow__FLAG__" + curentSpreadsheet);
	
	if (inputHeaderRow.get("value") == ""){
		return false;
	}
	
	var row = parseInt(inputHeaderRow.value);
	
	//alert(row);
	
	var chkbox =  $("rowSelector__FLAG__" + row.toString());
	if ((typeof(chkbox) == 'undefined') ||(chkbox == null)) {
		alert('Canot locate chkbox with id = ' + row.toString());
		return false;
	}
	
	if (chkbox.checked == false){
		//alert(chkbox.id);
		alert('Different values for checkbox and textbox ');
		return false;
	}
	
	// get current col
	var col = parseInt(selection.id.toString().split('__FLAG__')[1]);
	//alert(col);
	 
	// get cell text forom cell[row, col]
	var cell = $("cell__FLAG__" + row.toString() + "__FLAG__" + col.toString());
	if (typeof(cell) == 'undefined'){
		alert('Canot locate cell with id = ' + "cell__FLAG__' + row.toString() +'__FLAG__' + col.toString()");
		return false;
	}
	
	var cellText = ltrim(rtrim(cell.innerHTML.toString()));
	
	//alert(selection.options[selection.selectedIndex].value.toString());
	// get tab selection	
	tabSelectionMapping = $(selection.options[selection.selectedIndex].value.toString());
	if (typeof(tabSelectionMapping) == 'undefined'){
		alert('Canot locate tabSelectionMapping with id = ' + selection.options[selection.selectedIndex].value.toString());
		return false;
	}
	
	
	for (var i = 0; i < tabSelectionMapping.length; i++) {
    if (tabSelectionMapping[i].text == cellText){
			tabSelectionMapping[i].selected = true;
		}
		else{
			tabSelectionMapping[i].selected = false;
		}
  }
  
  selection.set("title", selection.options[selection.selectedIndex].text.toString());
}


function importRadioClick(radio){
	if (radio.id.toString().split("__FLAG__")[1] == '0'){
		//spreadsheetTabs.removeTab(radio.id.toString().split("__FLAG__")[0]);
		// not removeing, only disable	
		//alert(radio.id.toString());
		disableDiv(radio.id.toString().split("__FLAG__")[0]);
	}
	else if (radio.id.toString().split("__FLAG__")[1] == '1'){ 
		//spreadsheetTabs.addRemovedTab(radio.id.toString().split("__FLAG__")[0]);
		// not adding, only dimmoff
		enableDiv(radio.id.toString().split("__FLAG__")[0]);	
	}
}

function spreadsheetsValidation()
{
	var res = true;
	
	// first validate id_distributor!
	var selectionDistributor = $("distributor_id");
	if (typeof(selectionDistributor) == 'undefined'){
		return false;
	}
	//check existance of error element for selectionDistributor
	var existsErrorDistributor = true;
	if ((typeof($("errorDistributor")) == 'undefined') || ($("errorDistributor") == null)){
		existsErrorDistributor = false;
	}
	if (selectionDistributor.options[selectionDistributor.selectedIndex].value == ""){
		if (!existsErrorDistributor){
			// add error element for error
			var errorDistributor = new Element('span', {'id': 'errorDistributor', 'class': 'error', 'styles': {'white-space': 'nowrap'}}).set('html','&nbsp;*').injectAfter(selectionDistributor);
		}	
		res = false;	
	}
	else if (existsErrorDistributor){
		$("errorDistributor").dispose();	
	}

	
	//validate spreadsheets!
	var spreadsheets = document.getElements('div[class=spreadsheets]');
	spreadsheets.each(function(spreadsheet){
		name_spreadsheet = spreadsheet.id.toString().split("__FLAG__")[1];
		
		//check existance of error element for spreadsheets
		var existsErrorSpreadsheet = true;
		if ((typeof($("errorSpreadsheet__FLAG__" + name_spreadsheet.toString())) == 'undefined') || ($("errorSpreadsheet__FLAG__" + name_spreadsheet.toString()) == null)){
			existsErrorSpreadsheet = false;
		}
		if (!($(name_spreadsheet + "__FLAG__1").checked) && !($(name_spreadsheet + "__FLAG__0").checked)){
			if (!existsErrorSpreadsheet){
				var errorSpreadsheet = new Element('span', {'id': 'errorSpreadsheet__FLAG__' + name_spreadsheet.toString(), 'class': 'error', 'styles': {'white-space': 'nowrap'}}).set('html','&nbsp;*').injectAfter(spreadsheet);
			}	
			res = false;	
		}
		else if (existsErrorSpreadsheet){
			$("errorSpreadsheet__FLAG__" + name_spreadsheet.toString()).dispose();	
		}
		
		document.getElements('select[id^=' + name_spreadsheet + '__FLAG__]').filter(function(el){return (el.get("class") == 'tab_selection_mapping');}).each(function(field){
			//check existance of error element for current field
			var existsErrorField = true;
			if ((typeof($("errorField__FLAG__" + field.id.toString())) == 'undefined') || ($("errorField__FLAG__" + field.id.toString()) == null)){
				existsErrorField = false;
			}
			required = Boolean(field.id.toString().split("__FLAG__")[3]);
			if ((required) && (field.options[field.selectedIndex].value == "")){
				if (!existsErrorField){
					var existsErrorField = new Element('span', {'id': 'errorField__FLAG__' + field.id.toString(), 'class': 'error', 'styles': {'white-space': 'nowrap'}}).set('html','&nbsp;*').injectAfter(field);
				}	
				res = false;	
			}
			else if (existsErrorField){
				$("errorField__FLAG__" + field.id.toString()).dispose();	
			}
		});
	});
	return res;
}

function setCurentSheet(nameSheet){
	//alert('ke setiram: ' + nameSheet);
	$("curentSheet").set("html", ltrim(rtrim(nameSheet)));
	spreadsheetTabs.activate(nameSheet.toString());
}

function spreadsheetPreview(filename, curentSheet, forseHeaderRow){
	
	$("curentSheet").set("value", ltrim(rtrim(curentSheet)));
	spreadsheetTabs.activate(curentSheet.toString());
	var curentHeaderRow = 0;
	if ((forseHeaderRow == 'undefined') || (forseHeaderRow == null) || (forseHeaderRow == 0)){
		if (($("headerRow__FLAG__" + curentSheet.toString()) != null) && ($("headerRow__FLAG__" + curentSheet.toString()) != "undefined")){
			if (($("headerRow__FLAG__" + curentSheet.toString()).value != 0) || ($("headerRow__FLAG__" + curentSheet.toString()).value != "")){
				curentHeaderRow = $("headerRow__FLAG__" + curentSheet.toString()).value;
			}
		} 
		else{
			alert("Can't locate header row!");
		}
	}
	else curentHeaderRow = forseHeaderRow;
	
	var serverName = ltrim(rtrim($('serverName').innerHTML.toString()));
	document.body.style.cursor = 'wait';
	gyiAjax.dimOnDiv("spreadsheetView", true/*show animation*/);
  	//$("spreadsheetView").set("html", "");
	var req = new Request({			  
		method: 'get',  
		url: serverName + "/PHPExcelHelpers/spreadsheet.php/filename/" + filename + "/curentSheet/" + curentSheet + "/curentHeaderRow/" + curentHeaderRow,    
		onRequest: function() {},  
		evalScripts: true,
		onSuccess : function(responseText, responseXML){			
			var response = new String(responseText);
    	$("spreadsheetView").set("html", response);
			document.body.style.cursor = 'default';
			gyiAjax.dimOffDiv("spreadsheetView");
			if (curentHeaderRow > 0){
      	selectRow(curentHeaderRow, curentSheet);
      }
  	},
		onException : function(headerName, value){
			alert('Exception:' + headerName + '; ' + value)
		}, 
		onFailure : function(xhr){
			alert('Failure:' + xhr.responseText)
		}  
	}).send();              
}

function disableDiv(div){
	//alert(div);
	var elements = $(div).getElements('');
	elements.each(function(element){
		if (element.get("tag") == "select"){
			element.set("disabled", "disabled");
		}
		else if((element.get("tag") == "input") && (element.getStyle("display") != "none")){
			element.set("disabled", "disabled");
			//element.setStyles({
			//	'background-color':  'gray'
			//});
		}
		else if ((element.get("tag") == "span") && (element.get("class") == "error")){
			element.dispose();
		}
	});
}

function enableDiv(div){
	var elements = $(div).getElements('');
	elements.each(function(element){
		if (element.get("tag") == "select"){
			element.erase("disabled");
		}
		else if (element.get("tag") == "input"){
			element.removeProperty("disabled");
		}
	});
}

function popupSpreadsheet(filename, Sheet, HeaderRow){
	// open the window
	sprPreview = window.open("/PHPExcelHelpers/spreadsheetPreview.php/filename/" + filename + "/curentSheet/" + Sheet + "/curentHeaderRow/" + HeaderRow.toString(), "SpreadsheetPreview", "width=1024, height=768, scrollbars=yes");
	/* var serverName = ltrim(rtrim($('serverName').innerHTML.toString()));
	sprPreview.document.body.style.cursor = 'wait';
	var req = new Request({			  
		method: 'get',  
		url: serverName + "/admin/spreadsheet.php/filename/" + filename + "/curentSheet/" + Sheet + "/curentHeaderRow/" + HeaderRow,    
		onRequest: function() {},  
		evalScripts: true,
		onSuccess : function(responseText, responseXML){			
			var response = new String(responseText);
    	// write to window
			sprPreview.document.body.innerHTML = response;
			sprPreview.document.body.style.cursor = 'default';
			if (HeaderRow > 0){
      	selectRow(HeaderRow, Sheet);
      }
  	},
		onException : function(headerName, value){
			alert('Exception:' + headerName + '; ' + value)
		}, 
		onFailure : function(xhr){
			alert('Failure:' + xhr.responseText)
		}  
	}).send();  */            
}
