dojo.provide("custom.PageFunc");
/**
 * openHide => opens / hides the given element using CSS
 * @author: Jakub Wrona
 * @param String elementId
 * @return void
 */
var openHide = function(elementId) {
	if (dojo.byId(elementId).style.display == 'none') {
		dojo.byId(elementId).style.display = 'block';
	} else {
		dojo.byId(elementId).style.display = 'none';
	}
	return;
};
/**
 * showHideFullNews => opens / hides the the full content of a news by the given id
 * using the @openHide() function
 * @author: Jakub Wrona
 * @param Numeric id
 * @return void
 */
var showHideFullNews = function(id) {
	openHide('fullContent_'+id);
	return;
};
/**
 * openHideSubMenu => iterates through left menu items and
 * opens / hides submenu items of a given parent element
 * @author: Jakub Wrona
 * @param String elementPrefix
 * @return void
 */
var openHideSubMenu = function(elementPrefix) {
	items = dojo.byId('leftMenuItems').children;
	dojo.forEach(items, function(single) {
		if (single.id.match(elementPrefix+'_')) {
			if (single.style.display == 'none') {
				single.style.display = 'block';
			} else {
				single.style.display = 'none';
			}
		}
	});
	return;
};
/**
 * makes a request for searching resolutions using dojo.xhr
 * calls handleResults() for rendering hits
 * @author: Jakub Wrona
 * @return void
 */
var searchResolutions = function() {
	dojo.byId('formStatusContainerSearchResolutionForm').style.display = 'block';
	dojo.byId('formStatusContainerSearchResolutionForm').innerHTML = '<img src="'+baseUrl+'/images/page/searching.gif" alt="Wyszukiwanie" title="Wyszukiwanie" align="left" /> &nbsp;&nbsp;&nbsp;&nbsp; Wyszukiwanie...';
	var theDojoForm = dijit.byId('SearchResolutionForm');
	if (theDojoForm.isValid()) {
		dojo.xhrPost ({
	          url: baseUrl+'/view/resolutions/',
	          form: 'SearchResolutionForm',
	          handleAs: "json",
	          load: function (data) {
	          		 handleResults(data, 'searchFormPane');
	          },
	          error: function (error) {
	                  console.log('Error: ', error);
	          }
	    });
	} else {
		console.log('form not valid...');
	}
};
/**
 * Makes a request for getting all resolutions that belong to 
 * a given category
 * Calls handleResults() for rendering hits
 * @author: Jakub Wrona
 * @param Numeric cid
 * @return void
 */
var getResolutionsByCategory = function(cid) {
	dojo.xhrGet ({
          url: baseUrl+'/view/resolutions/cid/'+cid,
          handleAs: "json",
          load: function (data) {
          		 handleResults(data, 'categoryTreePane');
          },
          error: function (error) {
                  console.log('Error: ', error);
          }
    });
};
/**
 * Renders resolution list
 * @author Jakub Wrona
 * @param JSON		data
 * @param String	paneID
 * @return void
 */
var handleResults = function(data, paneID) {
	if (data.status == 'OK') {
		dojo.byId('formStatusContainerSearchResolutionForm').innerHTML = '';
		try {
			var theTable = dojo.byId('theResultTable');
			for (var i=theTable.rows.length-1; i>=0; i--) {
				theTable.deleteRow(i);
			}
		}
		catch(e)
		{}
		foundRows = data.data.length;
		if (foundRows > 0) {	
			dojo.byId('resultsContainer').innerHTML = '';
			var theResultTable = document.createElement('table');
			theResultTable.id = 'theResultTable';
			var theRow = theResultTable.insertRow(0);
			var theCell = theRow.insertCell(0);
			theCell.innerHTML = '<b>Data uchwalenia</b>';
			var theCell = theRow.insertCell(1);
			theCell.innerHTML = '<b>Numer uchwały</b>';

			var rowToInsert = 1;			
			for (var i=0; i<foundRows; i++) {
				try {
					theCurrentRow = data.data[i];
				}
				catch(e) {
					continue;
				}
				
				var passedOn = theCurrentRow.resolutionPassedOn;
				var theRow = theResultTable.insertRow(rowToInsert);
				rowToInsert++;
				var theCell = theRow.insertCell(0);
				theCell.innerHTML = '<span style="font-weight: bold;">'+passedOn.substr(8, 2)+'.'+passedOn.substr(5, 2)+'.'+passedOn.substr(0, 4)+'</span>';
				var theCell = theRow.insertCell(1);
				theCell.innerHTML = '<span style="font-weight: bold;">'+theCurrentRow.resolutionNumber+'</span>';
				var theRow2 = theResultTable.insertRow(rowToInsert);
				var theCell2 = theRow2.insertCell(0);
				theCell2.colSpan = '2';
				theCell2.style.paddingBottom = '10px';
				theCell2.style.borderBottom = '1px solid gray';
				theCell2.innerHTML = '';
				theCell2.innerHTML+=theCurrentRow.resolutionContent;
				if (theCurrentRow.attachments.length >0) {
					var attachmentsContent = '<br/><span class="files">Dokumenty:</span><ul class="attachments">';
					for (var att=0; att<theCurrentRow.attachments.length; att++) {
						attachmentsContent+='<li><a href="'+baseUrl+'/download/'+theCurrentRow.attachments[att].file.fileID+'">'+theCurrentRow.attachments[att].file.origName+'</a></li>';
					}
					attachmentsContent+='</ul>';
					theCell2.innerHTML+=attachmentsContent;
				}
				rowToInsert++;
			}
			dojo.byId('resultsContainer').appendChild(theResultTable);
			dojo.byId('resultsPane').style.display = 'block';
			dijit.byId(paneID).toggle();
			if (!dijit.byId('resultsPane').open) {
				dijit.byId('resultsPane').toggle();
			}
		} else {
			dojo.byId('resultsContainer').innerHTML = 'Nie odnaleziono uchwał spełniających podane kryteria...';
			dojo.byId('resultsPane').style.display = 'block';
			dijit.byId(paneID).toggle();
			if (!dijit.byId('resultsPane').open) {
				dijit.byId('resultsPane').toggle();
			}
		}
	} else {
		errors = data.message;
		if (typeof(errors) == 'string') {
			dojo.byId('formStatusContainerSearchResolutionForm').innerHTML=errors;
		}
		else {
			for (var i in errors) {
				try {
					errorContainer = dojo.byId('error-'+errors[i].fieldName);
					errorContainer.innerHTML = errors[i].errorMsg;
					errorLabel = dojo.byId('label-'+errors[i].fieldName);
					errorLabel.style.color = 'red';
				}
				catch(e){}
			}
		}
	}
};
/**
 * Shows a competition dialog with information
 * @author Jakub Wrona
 * @param String id
 * @return void
 */
var showCompetition = function(id) {
	try {
		dojo.byId('gMapContainer').parentNode.removeChild(dojo.byId('gMapContainer'));
	} catch(e) {}
	var theContent = '<table class="richList" style="width: 650px; margin-right: 100px; float: left;">';
	theContent+='<tr><td>Data</td><td>'+dojo.byId('date_'+id).innerHTML+' ('+dojo.byId('dayName_'+id).innerHTML+')</td></tr>';
	theContent+='<tr><td>Miasto</td><td>'+dojo.byId('city_'+id).innerHTML+'</td></tr>';
	theContent+='<tr><td>Organizator</td><td>'+dojo.byId('organizer_'+id).innerHTML+'</td></tr>';
	theContent+='<tr><td>Ranga wydarzenia</td><td>'+dojo.byId('rank_'+id).innerHTML+' <span style="background: '+dojo.byId('rankColor_'+id).innerHTML+';">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td></tr>';
	if (dojo.byId('notes_'+id)!=null) {
		theContent+='<tr><td>Uwagi</td><td>'+dojo.byId('notes_'+id).innerHTML+'</td></tr>';
	}
	theContent+='<tr><td>Informacje zew.</td><td>'+dojo.byId('www_'+id).innerHTML+'</td></tr>';
	theContent+='<tr><td>Adres hali</td><td>'+dojo.byId('arena_'+id).innerHTML+'<br/><div id="gMapContainer" style="width: 500px; height: 220px;"></div></td></tr>';
	theContent+='</table><br/><br/>';
	var dijitDialog = new dijit.Dialog({
		 title: dojo.byId('name_'+id).innerHTML,
	     content: theContent,
	     style: "width: 670px"});
	dijitDialog.show();
	if (dojo.byId('arena_'+id).innerHTML!='') {
		showAddressEmbed(dojo.byId('gMapContainer'), dojo.byId('arena_'+id).innerHTML);
	}
};

/**
 * Runs a GoogleMaps widget within a specyfied container
 * @author Jakub Wrona
 * @param String container
 * @param String address
 * @return void
 */
var showAddressEmbed = function(container, address) {
	if (GBrowserIsCompatible()) {
		if (GBrowserIsCompatible()) {
	      var map = new GMap2(container);
	      map.addControl(new GSmallMapControl());
	      map.addControl(new GMapTypeControl());
	      var geocoder = new GClientGeocoder();
	      geocoder.getLatLng(address, function(point) {
	      	if (!point) {
	        	console.log(address + " not found");
	      	} else {
		        map.setCenter(point, 15);
		        var marker = new GMarker(point);
		        map.addOverlay(marker);
		        marker.openInfoWindowHtml(address);
	      	}
	      });
	    }
	} else {
		console.log('Browser not supported...');
		return;
	}
};
/**
 * Selects text of a given container
 * @author: Jakub Wrona
 * @param String container
 * @return void
 */
var selectTheText = function(container) {
	dojo.byId(container).select();
	return;
};
