Import('myLib/http/ParamUrl.js');
Import('myLib/events/CreatorEvents.js');
Import('myLib/html/DisplayFlash.js');
Import('myLib/util/BoxObjects.js');
Import('myLib/html/Background.js');
//Import('myLib/native/String.js');
Import('myLib/text/Crypt.js');
Import('myLib/html/TagEdit.js');
Import('myLib/form/CheckForm.js');

function Service(){};

Service.SEARCH_PHRASE_LENGTH = 2;

Service.onLoad = function(newFunc){
	var evname = 'onload';
	if(typeof(window[evname]) == 'function')
		var oldFunc = window[evname];
	else
		var oldFunc = function(){};
	window[evname] = function(){
		oldFunc();
		newFunc();
	};
};

Service.createTargetBlank = function(){
	var items = document.getElementsByTagName('a');
	for(var i = 0; i < items.length; i++){
		if(items[i].target == '_blank'){
			items[i].target = '_self';
			items[i].href = "javascript:void(window.open('" + items[i].href + "'))";
		}
	}
};

Service.openPage = function(href, target){
	var href = href.replaceAll('@', '&');
	if(target == '_self')
		document.location.href = href;
	else
		window.open(href);
};


Service.showMail = function(mail, label){
	//document.write(Service.decodeText(label));
	//return;
	//var mail = account.reverse() + '@' + host.reverse();
	mail = Crypt.decode(mail);
	if(typeof(label) == 'undefined')
		label = mail;
	else
		label = Crypt.decode(label);
	document.write('<a href="mailto:' + mail + '">' + label + '</a>');
};

/*
Service.decodeText = function(text){
	var result = '';
	var t = text.split('#');
	for(var i = 0; i < t.length; i++){
		//$r .= ($hexes [(ord($s{$i}) >> 4)] . $hexes [(ord($s{$i}) & 0xf)]);
		result += t[i].charCodeAt();
	}
	return result;
};
*/

/*
Service.showMail = function(user, label){
	var mail = user + '@' + Config.MAIL_HOST;
	if(typeof(label) == 'undefined'){
		label = mail;
	}
	document.write('<a href="mailto:' + mail + '">' + label + '</a>');
};
*/

/*
Service.loadSelectPage = function(field, isEmpty, link){
	if(field.options[field.selectedIndex].value != '' || isEmpty){
		link = link.replace('{value}', field.options[field.selectedIndex].value);
		document.location.href = link;
	}
};
*/

/*
Service.insertSelectedValue = function(fieldSelect, fieldInput){
	if(this.value != ''){
		this.form.language.value = this.value;
	}
};
*/

Service.sendSearchForm = function(field, message){
	fieldsTab = new Array(field) ;

	if(field.value == ''){
		//alert('Podaj szukane wyrażenie.');
		if(typeof(message) == 'undefined'){
			var message = 'Podaj szukane wyrażenie.';
		}
		alert(message);
		field.focus();
	}
	else{
		if(Service.checkSearchPhrasesLength(fieldsTab, Service.SEARCH_PHRASE_LENGTH))
			field.form.submit();
		else
			field.focus();
	}
	return false;
};

Service.sendAdvancedSearchForm = function(form, message){

	textFieldsTab = new Array(
		form.allKeywords,
		form.withoutKeywords
	);

	var emptyFieldCounter = 0;
	isOk = true ;

	if((form.date_from.value == '' && form.date_to.value == '')) {
		for(var i = 0 ; i < textFieldsTab.length ; i++) {
			if(textFieldsTab[i].value == '') {
				emptyFieldCounter++ ;
			}
		}
		if(emptyFieldCounter == i) {
			isOk = false ;
			alert('Podaj szukane wyrażenie.');
			textFieldsTab[0].focus() ;
		}else {
			if(!Service.checkSearchPhrasesLength(textFieldsTab, Service.SEARCH_PHRASE_LENGTH)) {
				isOk = false ;
			}
		}
	}else {

	}

	if(isOk == true) {
		form.submit() ;
	}

	return false;
};

Service.checkSearchPhrasesLength = function(valueTab, phraseLength) {
	for(var i = 0 ; i < valueTab.length ; i++){
		if(valueTab[i].value.length < phraseLength && valueTab[i].value != ''){
			alert('Fraza musi posiadać conajmniej ' + phraseLength + ' znaki/znaków.');
			valueTab[i].value = '' ;
			valueTab[i].focus();
			return false;
		}
	}
	return true ;
}

Service.addTooltip = function(element, text){
	element.alt = text;
};

Service.changeBackground = function(itemId, isInit){
	var bgColor = '#efefef';
	if(isInit)
		BoxObjects.getObject(itemId, new Background(itemId)).setColor(bgColor);
	else
		BoxObjects.getObject(itemId).setColor();
};

Service.getOpener = function(){
	if(document.opener)
		return document.opener;
	else
		return opener;
};

Service.refreshOpener = function(){
	var doc = Service.getOpener();
	//doc.history.go();
	doc.location.href = doc.location.href;
	window.close();
};

Service.refreshOpenerFrame = function(frameName){
	/*
	  if (iframe.contentDocument) { // For NS6
	    iframeDocument = iframe.contentDocument;
	  } else if (iframe.contentWindow) { // For IE5.5 and IE6
	    iframeDocument = iframe.contentWindow.document;
	  } else if (iframe.document) { // For IE5
	    iframeDocument = iframe.document;
	  } else { // damn!
	    alert("Error: could not find IFRAME document");
	  }
	*/
	var frame = opener.document.getElementById(frameName);
	var src = frame.src;
	var win = frame.contentWindow;
	win.document.location.href = src;
	window.close();
	//var win = opener.document.getElementById(frameName).contentWindow;
	//win.history.go();
	//window.close();
};

Service.loadFilter = function(field){
	//field.title = 'Wprowadz pierwsze litery szukanego elementu i wcisnij enter';
	var f = function(e){
		Service.initFilter(field, e);
	};
	field.onchange = f;
	field.onkeydown = f;
};

Service.initFilter = function(field, e){
	var key = CreatorEvents.getKey(e);
	if(key == 0 || key == 13){
		location.href = new ParamUrl().toString({offset: 0, filter: field.value});
	}
};

Service.checkField = function(field){
	if(field.value == ''){
		alert('Proszę wypełnić wskazane pole.');
		field.select();
		return false;
	}
	else{
		return true;
	}
};

Service.activateField = function(field, isActive){
	field.disabled = !isActive;
	field.style.backgroundColor = isActive ? 'white' : '#ededed';
};

/**
 * Zwraca rozszerzenie pliku.
 */
Service.getSuffix = function(fileName){
	var fileName = fileName.toLowerCase();
	var pos = fileName.lastIndexOf('.');
	return fileName.substring(pos + 1);
};

/**
 * Wyswietla banery w formatach: swf, jpg, gif, png.
 */
Service.dispalyBanner = function(params){
	var suffix = Service.getSuffix(params['src']);
	if(suffix == 'swf'){
		DisplayFlash.init(params);
	}
	else{
		var img = '<img src="' + params['src'] + '" width="' +
		params['width'] + '" height="' + params['height'] + '" border="0" />';

		if(typeof(params['href']) != 'undefined' && params['href'] != ''){
			img = '<a href="' + params['href'] + '" target="' + params['target']
		+ '">' + img + '</a>';
		}

		document.write(img);
	}
};

Service.confirmDelete = function(href, text){
	if(typeof(text) == 'undefined'){
		var text = "Czy jesteś pewien?";
	}
	text += "\nJeżeli tak kliknij [OK], jeżli nie kliknij [Anuluj].";

	if(confirm(text)){
		document.location.href = href;
	}
};

Service.confirmOpenWindow = function(href, text){
	if(confirm(text)){
		window.open(href);
	}
};

Service.checkPassword = function(field1, field2){
	if(field1.value != field2.value){
		alert('Wprowadzone hasła muszą być identyczne');
		field1.value = field2.value = '';
		field1.focus();
		return false;
	}
	else{
		return true;
	}
};

Service.openSubEditor = function(href, params){
	var p = {
		width:	600,
		top:	200,
		left:	100
	};
	if(typeof(params) == 'object'){
		for(var i in params){
			p[i] = params[i];
		}
	}
	Service.openWindow(href, p);
};

Service.openWindow = function(href, params){
	var p = '';
	var name = '';
	if(typeof(params) == 'object'){
		for(var i in params){
			if(i == 'name')
				name = params[i];
			else
				p += i + '=' + params[i] + ',';
		}
	}
	window.open(href, name, p);
};

Service.showPanel = function(fieldName){
	var params = [TagEdit.B, TagEdit.BR, TagEdit.LI, TagEdit.A, TagEdit.A_MAILTO]; //TagEdit.CENTERSystem.getValue(params, [TagEdit.B, TagEdit.BR]); //, TagEdit.LI
	var t = new TagEdit(params);
	t.styleClass = 'button1';
	t.addElement({label: 'edytuj', action: 'Service.showHTMLEditor(\'' + fieldName + '\')'});
	t.showMenu(fieldName);
	/*
	document.write('<div style="margin: 5px 0 5px 0; text-align: center;">' +
	'<div><input type="button" value="Edytor" class="bMain" onclick="Service.showHTMLEditor(\''
	+ filedName + '\');"></div>' +
	'<div><input type="button" value="Edytor" class="bMain" onclick="Service.showHTMLEditor(\''
	+ filedName + '\');"></div>' +
	'</div>');
	*/
};

Service.showHTMLEditor = function(filedName){
	var href = Config.getPathToCommon() + 'editor.php?field=' + filedName;
	//alert(href);
	window.open(href, '', 'width=700, height=500');
};

//---

Service.openResizer = function(key, value){
	var path = Config.getPathToCommon() + Config.file.RESIZER + '?' + key + '=' + value;
	var params = {
		name:	'newWindow',
		left:	100,
		top:	100,
		width:	100,
		height:	100
	};
	Service.openWindow(path, params);
};

Service.openViewer = function(key, value){
	var path = Config.getPathToCommon() + Config.file.VIEWER + '?' + key + '=' + value;
	var params = {
		name: 'newWindow'
	};
	Service.openWindow(path, params);
};

Service.openResource = function(pathFile){
	if(Service.isImage(pathFile))
		Service.openImage(pathFile);
	else
		Service.openFile(pathFile);
};

/*
Service.checkImage = function(pathFile){
	if(!Service.isImage(pathFile)){
		alert('Podany plik musi byÄ formatu: jpg, gif, png.');
		return false;
	}
	return true;
};
*/

Service.isImage = function(pathFile){
	var suffix = Service.getSuffix(pathFile);
	return (suffix == 'jpg' || suffix == 'gif' || suffix == 'png');
};

Service.openImage = function(pathFile){
	Service.openResizer('file', pathFile);
};

Service.openImageById = function(id){
	Service.openResizer('id', id);
};

Service.openFile = function(pathFile){
	var path = Config.getPathToData() + pathFile;
	window.open(path);
};

Service.openFileById = function(id){
	Service.openViewer('id', id);
};

/*
Service.openImageByModuleId = function(moduleId, itemId, offset){
	//var pathFile = Config.file.VIEWER + '?id=' + id;
	//alert(pathFile);
	Service.openResizableWindow('id', id);

};
*/

//---

Service.insertString = function(field, text){
	if(typeof(text) != 'string'){
		var text = 'http://';
	}

	if(field.value == ''){
		field.value = text;
		field.select();
		field.onblur = function(){
			if(field.value == text){
				field.value = '';
			}
		}
	}
};

Service.addFavorite = function(){
	var l = document.location;
	var link = l.protocol + '//' + l.hostname; // l.href - full address
	var title = l.hostname;

	var t = document.getElementsByTagName('title');

	if(document.all){ // for IE
		if(t[0].innerText != ''){
			title = t[0].innerText;
		}
		window.external.AddFavorite(link, title);
	}
	else{
		var title = t[0].firstChild.nodeValue;
		window.sidebar.addPanel(title, link, '');
	}
};

/*

Service.bg = '';

Service.changeBg = function(id, x, color){
    var element = document.getElementById(id);
    if(x){
        Service.bg = element.bgColor;
        if(!color){
            var color = "#eeeeee";
		}
		element.bgColor = color;
    }
	else{
		element.bgColor = Service.bg;
	}
};

Service.insertString = function(field, text){
	if(typeof(text) != 'string'){
		var text = 'http://';
	}

	if(field.value == ''){
		field.value = text;
		field.select();
		field.onblur = function(){
			if(field.value == text){
				field.value = '';
			}
		}
	}
};

Service.insertDefaultValue = function(field, selectInput){
	var isInsert = false;

	if(field.value == ''){
		isInsert = true;
	}
	else{
		for(var i = 0; i < selectInput.options.length; i++){
			if(selectInput.options[i].text == field.value){
				isInsert = true;
				break;
			}
		}
	}

	if(isInsert){
		var x = selectInput.options[selectInput.selectedIndex];
		if(x.value == ''){
			field.value = x.value;
		}
		else{
			field.value = x.text;
			field.focus();
			field.select();
		}
	}

	return isInsert;
};
*/
