var VerMSIE;
var IsMSIE = GetMSIE(VerMSIE);

function openPopupInfoBox(div) {
	GetControlByID('divInfoBoxContent').innerHTML = GetControlByID(div).innerHTML;
	showPopup('InfoBox',closePopupInfoBox);
	return;
}

function closePopupInfoBox() {
	return;
}

function openPopupSearchBox() { 
	showPopup('SearchBox',closePopupSearchBox);
	return;
}

function closePopupSearchBox() {
	return;
}

function openPopupZoomBox(obj) {
	var image = GetControlByID(obj).src;
	var title = GetControlByID(obj).title;
	GetControlByID('imgZoomBox').src = SetImageFilename(image,'_zoom');
	GetControlByID('imgZoomBox').alt = GetControlByID('imgZoomBox').title;
	GetControlByID('imgZoomBox').title = title;
	showPopup('ZoomBox',closePopupZoomBox);
	return;
}

function SetImageFilename(image,suffix) {
	if(image.indexOf('.jpg')>=0) image = image.replace('.jpg',suffix+'.jpg');
	if(image.indexOf('.png')>=0) image = image.replace('.png',suffix+'.png');
	if(image.indexOf('.gif')>=0) image = image.replace('.gif',suffix+'.gif');
	return image;
}

function closePopupZoomBox() {
	GetControlByID('imgZoomBox').src = 'images/layout/zoom_loading.jpg';
	GetControlByID('imgZoomBox').title = GetControlByID('imgZoomBox').alt;
	return;
}

function GetImageFilename(src) {
	var tkns = src.split('/');
	var ntkn = tkns.length;
	return ((ntkn>=1)?tkns[ntkn-1]:'');
}

function DoSubmit(action,checked) {	
	if(checked) {
		GetControlByID('frmAction').value = action;
		document.forms[0].submit();
	}
	return false;
}

function DoLogout() {	
	GoPage('index.php?logout=1');
}

function GoIndex() {	
	GoPage('index.php');
}

function SetLanguage(userid) {
	var lng = GetControlByID('frmUserLanguage').value;
	var flg = GetControlByID('divLanguageFlag');	
	var url = location.href;
	flg.src = 'images/layout/language_'+lng+'.jpg';
	if(userid)
		ajaxCallPhpScriptSync('setLanguage','action=setlanguage&key='+userid,lng);
	GoPage(url);
}

function GoPage(url) {
	var url = SetUrl(url);
	window.location = url;
}

function GoBookmark(url,bookmark) {
	var url = SetUrl(url);
	window.location = url+'#'+bookmark;
}

function SetUrl(url) {
	var lng = GetControlByID('frmUserLanguage').value;
	var pnew = "lang="+lng;	
	var x = url.indexOf("&lang");
	if(x==-1) {
		x = url.indexOf("?lang");
		if(x==-1) url = url + ((url.indexOf("?")==-1)?'?':'&') + pnew;
	}
	if(x!=-1) {
		pold = url.substr(x+1,7);
		if(pold!=pnew) url = url.replace(pold,pnew);
	}
	return url;
}

function showPopup(div,fn_name) { 
	var mdl = GetControlByID('modal'+div);
	var shd = GetControlByID('shade'+div);
	var cls = GetControlByID('btnClose'+div);	
	mdl.style.display = 'block';
	shd.style.display = 'block';
	cls.onclick=function() {
		mdl.style.display='none';
		shd.style.display='none';
		if(fn_name!='') fn_name();
	}
}

function GetSexFromCF(cf) {
	var sex = 'M';
	var age = cf.substr(9,2)*1;
	if(age>40) sex = 'F';
	return sex;
}

function ParseXML(text) {
	if(IsMSIE) {
		xmldoc = new ActiveXObject("Microsoft.XMLDOM");
		xmldoc.async="false";
		xmldoc.loadXML(text); 
	} else {
		parser = new DOMParser();
		xmldoc = parser.parseFromString(text,"text/xml");
	}
	return xmldoc;
}

function GetXMLValue(response,attribute) { 
	var xml = ParseXML(response);
	var val = "";
	if(xml) {
		var nod = xml.getElementsByTagName('response')[0];
		if(nod) { 
			val = ""+nod.getAttribute(attribute);
		}
	}
	return val;
}

function GetXMLDetailValue(response,attribute) {
	var xml = ParseXML(response);
	var val = "";
	if(xml) {		
		var nod = xml.getElementsByTagName("response")[0].childNodes;
		if(nod.length>0) {
			for(var n=0;n<nod.length;n++) { 
				if(nod[n].getAttribute('id')==attribute) {
					val = ""+nod[n].getAttribute('value');
					break;
				}
			}
		}
	}
	return val;
}

function GetMSIE(VerMSIE) {
	var nuag = navigator.userAgent;
	var idx = nuag.indexOf('MSIE');
	if(idx>=0) {
		VerMSIE = nuag.substring(idx+5,idx+6);
		return true;
	} else {
		VerMSIE = '0';
		return false;
	}
}

function GetControlByID(id) {
	if (document.all)
		return document.all[id];
    else
		return document.getElementById(id);
}

function CriptaPassword(id1,id2) {
	var old_pwd = GetControlByID(id1);
	var new_pwd = GetControlByID(id2);
	new_pwd.value = hex_md5(old_pwd.value);
	old_pwd.value = '';
}

function SetCurrentRow(rowid) {
	var old_rowid = GetControlByID('frmCurrentOldRow').value;
	if(old_rowid>0)
		GetControlByID('tableRow'+old_rowid).bgColor = GetControlByID('frmOldColor').bgColor;	
	GetControlByID('frmCurrentRow').value = rowid;
	GetControlByID('frmCurrentOldRow').value = rowid;	
	GetControlByID('frmOldColor').bgColor = GetControlByID('tableRow'+rowid).bgColor;
	GetControlByID('tableRow'+rowid).bgColor = '#644646';
}

function SetCurrentRowGraphic(rowid) {
	var old_rowid = GetControlByID('frmCurrentOldRow').value;
	if(old_rowid>0)
		GetControlByID('tableRow'+old_rowid).className = "graphic_notselected";
	GetControlByID('tableRow'+rowid).className = "graphic_selected";
	GetControlByID('frmCurrentRow').value = rowid;
	GetControlByID('frmCurrentOldRow').value = rowid;
}

function T(text) {
	text = text.replace(/’/g,'\u00B4');
	text = text.replace(/°/g,'\u00BA');
	return text;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function number(val,dec) {
	var num = new Number(val);
	num = num.toFixed(dec);
	return num.toString().replace(".",",");
}

function euro(val,dec) {
	return '€ '+number(val,dec);
}

function str2number(str) {
	if(str=='') str = '0';
	str = str.replace(".","");
	str = str.replace(",",".");
	return parseFloat(str);
}

function GetDateTime() { 
  return NormalizeDate(new Date()); 
}

function NormalizeDate(date) {
  var day = date.getDate();
  var month = (date.getMonth()+1);
  var year = date.getFullYear();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  return ((day<10)?'0':'')+day+'-'+((month<10)?'0':'')+month+'-'+year+' '+((hours<10)?'0':'')+hours+':'+((minutes<10)?'0':'')+minutes+':'+((seconds<10)?'0':'')+seconds; 
}

String.prototype.replaceAll = function(stringToFind,stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);
	while(index != -1){
		temp = temp.replace(stringToFind,stringToReplace);
		index = temp.indexOf(stringToFind);
	}
	return temp;
}

// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
}

Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return (((this.getFullYear()%4==0)&&(this.getFullYear()%100 != 0)) || (this.getFullYear()%400==0)) ? '1' : '0'; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); },
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
}

function SetThumb(thumb,tipo,onoff,lng) {
	var div = GetControlByID(thumb);
	if(onoff) div.style.backgroundImage = 'url(images/layout/thumb_'+tipo+'_sharp_'+lng+'.png)';
	else div.style.backgroundImage = 'url(images/layout/thumb_'+tipo+'_'+lng+'.png)';
}

function SetPhoto(obj,idx,path,titles,images,zooms,verso) {
	var img = GetControlByID(obj);
	var zom = GetControlByID('btnPhotoZoom');
	var jpg =  GetImageFilename(img.src);
	var imgs = images.split('#');
	var tits = titles.split('#');
	var zoms = zooms.split('#');
	var nimg = imgs.length;
	var tit = '';	
	if(nimg>0) {
		for(i=0;i<nimg;i++) {
			if(zoms[i]=='0') { zom.style.display = 'none'; } else { zom.style.display = 'inline'; }
			if(imgs[i]==jpg) {				
				if(verso=='current') { jpg = imgs[i]; tit = tits[i]; break; }
				if(verso=='prev') { i = ((i==0)?(nimg):(i)); jpg = imgs[i-1]; tit = tits[i-1]; break; }
				if(verso=='next') { i = ((i==(nimg-1))?(-1):(i)); jpg = imgs[i+1]; tit = tits[i+1]; break; }
				break;
			}
		}
		img.src = path+'/'+idx+'/'+jpg;
		img.title = tit;
	}
}
