document.onmousemove = getMouseXY;
document.onmousedown = getMouseButtonDown;
document.onmouseup = getMouseButtonUp;

var mouseX = 0;
var mouseY = 0;
var mouseR = false;
var mouseC = false;
var mouseL = false;

function getMouseButtonUp(e)
{
	if (!e)
		var e = window.event;
	
	if (e.which)
	{
		if (e.which == 1) 	   mouseL = false;
		else if (e.which == 2) mouseC = false;
		else if (e.which == 3) mouseR = false;
	}
	else if (e.button)
	{
		if (e.button == 0) 		mouseL = false;
		else if (e.button == 1) mouseC = false;
		else if (e.button == 2) mouseR = false;
	}	
}

function getMouseButtonDown(e)
{
	if (!e)
		var e = window.event;
	
	if (e.which)
	{
		if (e.which == 1) 	   mouseL = true;
		else if (e.which == 2) mouseC = true;
		else if (e.which == 3) mouseR = true;
	}
	else if (e.button)
	{
		if (e.button == 0) 		mouseL = true;
		else if (e.button == 1) mouseC = true;
		else if (e.button == 2) mouseR = true;
	}
}

function getMouseXY(e)
{
  if (!e || e == null)
  	e = window.event; 

  if (document.all ? true : false)
  {
    mouseX = e.clientX + document.documentElement.scrollLeft;
    mouseY = e.clientY + document.documentElement.scrollTop;
  }
  else
  {
    mouseX = e.pageX;
    mouseY = e.pageY;
  }  

  if (mouseX < 0) mouseX = 0;
  if (mouseY < 0) mouseY = 0;

  return true;
}

function getById(id)
{
	var elem;
	if (document.getElementById) // this is the way the standards work
		elem = document.getElementById(id);
	else if (document.all) // this is the way old msie versions work
		elem = document.all[id];
	else if (document.layers) // this is the way nn4 works
		elem = document.layers[id];
	return elem;
}

function getOpenerById(id)
{
	var elem;
	if (window.top.opener.document.getElementById) // this is the way the standards work
		elem = window.top.opener.document.getElementById(id);
	else if (window.top.opener.document.all) // this is the way old msie versions work
		elem = window.top.opener.document.all[id];
	else if (window.top.opener.document.layers) // this is the way nn4 works
		elem = window.top.opener.document.layers[id];
		
	return elem;
}

function doCommand(formName, command, value)
{
	var objDoCommand = getById("command");
	var objDoCommandValue = getById("commandValue");
	var objForm = getById(formName);

	objDoCommand.value = command;
	objDoCommandValue.value = value;
	objForm.submit();
}

function doNothing()
{
}

function Size(width, height)
{
    this.width = width;
    this.height = height;
}

function addEvent(obj, ev, fn)
{
	if(obj.addEventListener)
		obj.addEventListener(ev, fn, false);
	else if(obj.attachEvent)
		obj.attachEvent('on'+ev, fn);
	else
	{
		if (typeof(obj['on'+ev]) == 'function')
		{
			var f = obj['on'+ev];
			obj['on'+ev] = function(){if(f)f();fn()}
		}
		else obj['on'+ev]=fn;
	}
}

// Form function
var TYPE_STRING        = 0;
var TYPE_NUMBER        = 1;
var TYPE_SELECT        = 2;
var TYPE_EMAIL         = 3;
var TYPE_DATE          = 4;
var TYPE_DATE_CHILD    = 5;
var TYPE_DATE_SENIOR   = 6;
var TYPE_MOBILE        = 7;
var TYPE_DATE_YOUTH	   = 8;
var TYPE_VOID    	   = 9;
var TYPE_RADIO    	   = 10;
var TYPE_CHECKBOX      = 11;
var TYPE_BUSINNESS_DATE= 12;
//var fmMandatoryColor = "yellow";
//var fmMandatoryBorder = "";
//var fmErrorColor = "red";
//var fmErrorBorder = ""; 

function FormItem(form, fieldName, dataType, required, groupId, armed, styleId)
{
    this.fieldName = fieldName;
    this.dataType = dataType;
    this.isEnabled = true;
    this.required = required;
    this.groupId = groupId;
    this.armed = armed;
    this.styleId = styleId;
    this.element = form.elements[fieldName];
    
	var obj = null;
	if (this.styleId != null)
		obj = getById(this.styleId);
	else if (this.dataType != TYPE_RADIO)
		obj = this.element;
	
	if (obj != null)
		this.className = obj.className;
	else
		this.className = null;
}

function FormManager(formName)
{
    this.formName = formName;
    this.formItems = new Array(1024);
    for (i = 0; i < this.formItems.length; i++)
	    this.formItems[i] = null;

    this.mandatoryClass = null;
    this.errorClass = null;

    try
    {
		var styleSheet = document.styleSheets[0];
		
		var rulesList = null;
		if (styleSheet.cssRules)
			rulesList = styleSheet.cssRules
		else if (styleSheet.rules)
			rulesList = styleSheet.rules

		this.fmMandatoryColor = "yellow";
		this.fmMandatoryBorder = "";
    	for (i = 0; i < rulesList.length; i++)
    	{
    		if (rulesList[i].selectorText == ".fmMandatoryColor")
    		{
    			this.fmMandatoryColor = rulesList[i].style.backgroundColor;
    			this.fmMandatoryBorder = rulesList[i].style.border;
    			break;
    		}
    	}

		this.fmErrorColor = "red"; 
		this.fmErrorBorder = "";
    	for (i = 0; i < rulesList.length; i++)
    	{
    		if (rulesList[i].selectorText == ".fmErrorColor")
    		{
    			this.fmErrorColor = rulesList[i].style.backgroundColor; 
    			this.fmErrorBorder = rulesList[i].style.border;
    			break;
    		}
    	}
    }
    catch (e)
    {
    }
}

FormManager.prototype.refresh = function()
{
	var thisForm = document.forms[this.formName];
	for (i = 0; i < this.formItems.length; i++)
	{
		formItem = this.formItems[i];
		if (formItem != null)
		{
		    var thisElement = thisForm.elements[formItem.fieldName];
		    if (thisElement.type == "hidden")
		        continue;

		    try
		    {
			    if (formItem.dataType == TYPE_VOID || !formItem.armed || !formItem.required)
			    	this.applyNormalStyle(formItem);
			    else
			    	this.applyMandatoryStyle(formItem);
		    }
		    catch (e)
		    {
		    }
		}
	}
}

FormManager.prototype.applyNormalStyle = function(formItem)
{
	var obj = null;
	if (formItem.styleId != null)
		obj = getById(formItem.styleId);
	else if (formItem.dataType != TYPE_RADIO)
		obj = formItem.element;

	if (obj != null)
	{
		obj.style.border = "";
		obj.className = formItem.className;
	}
}

FormManager.prototype.applyErrorStyle = function(formItem)
{
	var obj = null;
	if (formItem.styleId != null)
		obj = getById(formItem.styleId);
	else if (formItem.dataType != TYPE_RADIO)
		obj = formItem.element;

	if (obj != null)
	{
		if (this.errorClass != null)
			obj.className = (formItem.className == null ? "" : formItem.className + " ") + this.errorClass;
		else
		{
			obj.style.backgroundColor = this.fmErrorColor;
			obj.style.border = this.fmErrorBorder;
		}
	}
}

FormManager.prototype.applyMandatoryStyle = function(formItem)
{
	var obj = null;
	if (formItem.styleId != null)
		obj = getById(formItem.styleId);
	else if (formItem.dataType != TYPE_RADIO)
		obj = formItem.element;

	if (obj != null)
	{
		if (this.mandatoryClass != null)
			obj.className = (formItem.className == null ? "" : formItem.className + " ") + this.mandatoryClass;
		else
		{
			obj.style.backgroundColor = this.fmMandatoryColor;
			obj.style.border = this.fmMandatoryBorder;
		}
	}
}

FormManager.prototype.add = function(fieldName, dataType, required, groupId, armed, styleId)
{
	if (required == undefined)
	{
		if (dataType == TYPE_VOID)
			required = false;
		else
			required = true;
	}

	if (groupId == undefined)
		groupId = null;

	if (armed == undefined)
		armed = true;

	if (styleId == undefined)
		styleId = null;
	
	this.remove(fieldName);
	freeSlot = this.getFreeSlot();
    if (freeSlot == -1)
        alert("No More Slot Available for FormItem.");
	var thisForm = document.forms[this.formName];
    var formItem = new FormItem(thisForm, fieldName, dataType, required, groupId, armed, styleId);
	this.formItems[freeSlot] = formItem;
    var thisElement = thisForm.elements[formItem.fieldName];
    if (thisElement.type == "hidden" || dataType == TYPE_VOID || !formItem.armed)
        return;

    // Set the color
    try
    {
    	this.applyMandatoryStyle(formItem);
    }
    catch (e)
    {
    }
    
    return formItem;
}

FormManager.prototype.remove = function(fieldName)
{
	for (i = 0; i < this.formItems.length; i++)
	{
		formItem = this.formItems[i];
		if (formItem != null && formItem.fieldName == fieldName)
		{
			this.formItems[i] = null;
			return;
		}
	}
}

FormManager.prototype.setDataType = function(fieldName, dataType)
{
	for (i = 0; i < this.formItems.length; i++)
	{
		formItem = this.formItems[i];
		if (formItem != null && formItem.fieldName == fieldName)
		{
			this.formItems[i].dataType = dataType;
			return;
		}
	}
}

FormManager.prototype.setEnabled = function(fieldName, isEnabled)
{
	for (i = 0; i < this.formItems.length; i++)
	{
		formItem = this.formItems[i];
		if (formItem != null && formItem.fieldName == fieldName)
		{
			this.formItems[i].isEnabled = isEnabled;
			return;
		}
	}
}

FormManager.prototype.setArmedByGroupId = function(groupId, armed)
{
	for (i = 0; i < this.formItems.length; i++)
	{
		formItem = this.formItems[i];
		if (formItem != null && formItem.groupId == groupId)
			this.formItems[i].armed = armed;
	}
}

FormManager.prototype.getFreeSlot = function()
{
	for (i = 0; i < this.formItems.length; i++)
		if (this.formItems[i] == null)
			return i;
}

FormManager.prototype.validate = function()
{
    var i;
    var formItem;
    var thisForm;
    var thisElement;
    var isError = false;
    
    try
    {
        thisForm = document.forms[this.formName];
        for (i = 0; i < this.formItems.length; i++)
        {
            formItem = this.formItems[i];
            if (formItem == null || !formItem.isEnabled)
            	continue;
            
            thisElement = thisForm.elements[formItem.fieldName];
            if (thisElement.type == "hidden")
                continue;
                
			if (formItem.dataType == TYPE_VOID)
            {
				continue;
            }
			else if (formItem.dataType == TYPE_STRING)
            {
				if (formItem.required && formItem.armed)
				{
	                value = String(thisElement.value);
	                if (value.length == 0)
	                {
	                	this.applyErrorStyle(formItem);
	                    isError = true;
	                }
	                else
	                	this.applyMandatoryStyle(formItem);
				}
            }
            else if (formItem.dataType == TYPE_NUMBER)
            {
                value = String(thisElement.value);
                if (value.length == 0 && (formItem.required && formItem.armed))
                {
                	this.applyErrorStyle(formItem);
                    isError = true;
                }
                else if (value.length > 0 && isNaN(value))
                {
                	this.applyErrorStyle(formItem);
                    isError = true;
                }
                else if (formItem.required && formItem.armed)
                	this.applyMandatoryStyle(formItem);
            }
            else if (formItem.dataType == TYPE_SELECT)
            {
                value = String(thisElement.options[thisElement.selectedIndex].value);
                if (value.length == 0 && (formItem.required && formItem.armed))
                {
                	this.applyErrorStyle(formItem);
                    isError = true;
                }
                else if (formItem.required && formItem.armed)
                	this.applyMandatoryStyle(formItem);
            }
            else if (formItem.dataType == TYPE_EMAIL)
            {
                value = String(thisElement.value);
                if (value.length == 0 && (formItem.required && formItem.armed))
                {
                	this.applyErrorStyle(formItem);
                    isError = true;
                }
                else if (value.length > 0 && !isValidEMail(value))
                {
                	this.applyErrorStyle(formItem);
                    isError = true;
                }
                else if (formItem.required && formItem.armed)
                	this.applyMandatoryStyle(formItem);
            }
            else if (formItem.dataType == TYPE_DATE)
            {
                value = String(thisElement.value);
                if (value.length == 0 && (formItem.required && formItem.armed))
                {
                	this.applyErrorStyle(formItem);
                    isError = true;
                }
                else if (value.length > 0 && !isValidDate(value))
                {
                	this.applyErrorStyle(formItem);
                	isError = true;
                }
                else if (formItem.required && formItem.armed)
                {
                	thisElement.value = formatDate(value);
                	this.applyMandatoryStyle(formItem);
                }
            }
            else if (formItem.dataType == TYPE_RADIO)
            {
            	isChecked = false;
            	for (nRadios = 0; nRadios < thisElement.length; nRadios++)
            	{
            		if (thisElement[nRadios].checked)
            		{
            			isChecked = true;
            			break;
            		}
            	}

            	if (!isChecked)
            	{
                	this.applyErrorStyle(formItem);
	                isError = true;
            	}
            	else
                	this.applyMandatoryStyle(formItem);
            }
            else if (formItem.dataType == TYPE_CHECKBOX)
            {
            	isChecked = false;
            	
            	for (nCheckboxes = 0; nCheckboxes < thisElement.length; nCheckboxes++)
            	{
            		if (thisElement[nCheckboxes].checked)
            		{
            			isChecked = true;
            			break;
            		}
            	}

            	if (!isChecked)
            	{
                	this.applyErrorStyle(formItem);
	                isError = true;
            	}
            	else
                	this.applyMandatoryStyle(formItem);
            }
            else if (formItem.dataType == TYPE_BUSINNESS_DATE)
            {
                value = String(thisElement.value);
                if (value.length == 0 && (formItem.required && formItem.armed))
                {
                	this.applyErrorStyle(formItem);
                    isError = true;
                }
                else if (value.length > 0 && !isValidDate(value))
                {
                	this.applyErrorStyle(formItem);
                	isError = true;
                }
                else if (value.length > 0 && !isBusinessDate(value))
                {
                	this.applyErrorStyle(formItem);
                	isError = true;
                }
                else if (formItem.required && formItem.armed)
                {
                	thisElement.value = formatDate(value);
                	this.applyMandatoryStyle(formItem);
                }
            }
/*
            else if (formItem.dataType == TYPE_DATE_CHILD)
            {
                value = String(thisElement.value);
                
                if(!isValidDate(value))
                {
                	isError = true;
					thisElement.style.backgroundColor = fmErrorColor;
					thisElement.style.border = fmErrorBorder;
                }
                else
                {
                	if (!isYearBetween(1994, 2009, value))
                	{
	                	isError = true;
						thisElement.style.backgroundColor = fmErrorColor;
						thisElement.style.border = fmErrorBorder;
						alert(labels.get("InvalidBirthDate"));
                	}
                	else
                	{
	                	thisElement.value = formatDate(value);
                    	thisElement.style.backgroundColor = fmMandatoryColor;
                    	thisElement.style.border = fmMandatoryBorder;
                    }
                }
            }
            else if (formItem.dataType == TYPE_DATE_SENIOR)
            {
                value = String(thisElement.value);
                
                if(!isValidDate(value))
                {
                	isError = true;
					thisElement.style.backgroundColor = fmErrorColor;
					thisElement.style.border = fmErrorBorder;
                }
                else
                {
                	if(!isYearBetween(1800, 1945, value))
                	{
	                	isError = true;
						thisElement.style.backgroundColor = fmErrorColor;
						thisElement.style.border = fmErrorBorder;
						alert(labels.get("InvalidBirthDate"));
                	}
                	else
                	{
	                	thisElement.value = formatDate(value);
                    	thisElement.style.backgroundColor = fmMandatoryColor;
                    	thisElement.style.border = fmMandatoryBorder;
                    }
                }
            }
            else if (formItem.dataType == TYPE_MOBILE)
            {
                value = String(thisElement.value);
                if (value.length < 11 || isNaN(value))
                {
                    thisElement.style.backgroundColor = fmErrorColor;
                    thisElement.style.border = fmErrorBorder;
                    isError = true;
                }
                else
                {
                    thisElement.style.backgroundColor = fmMandatoryColor;
                    thisElement.style.border = fmMandatoryBorder;
                }
            }
			else if (formItem.dataType == TYPE_DATE_YOUTH)
            {
                value = String(thisElement.value);
                
                if(!isValidDate(value))
                {
                	isError = true;
					thisElement.style.backgroundColor = fmErrorColor;
					thisElement.style.border = fmErrorBorder;
                }
                else
                {
                	if(!isYearBetween(1984, 1995, value))
                	{
	                	isError = true;
						thisElement.style.backgroundColor = fmErrorColor;
						thisElement.style.border = fmErrorBorder;
						alert(labels.get("InvalidBirthDate"));
                	}
                	else
                	{
	                	thisElement.value = formatDate(value);
                    	thisElement.style.backgroundColor = fmMandatoryColor;
                    	thisElement.style.border = fmMandatoryBorder;
                    }
                }
            }
*/
            else
            {
                alert("Invalid formItem.dataType = " + formItem.dataType);
                isError = true;
            }
        }
    }
    catch (e)
    {
        alert(
        		"Name = " + e.name + 
        		"\r\nMessage = " + e.message);
        isError = true;
    }

    if (isError)
    {
		alert(labels.get("checkRedFields"));
        return false;
    }

    return true;
}

function isValidEMail(email)
{
	if (email == null || email == "")
		return false;
	var parts = email.split("@");
	if (parts.length != 2)
		return false;

	if (!isValidEmailPart(parts[0]) ||
		!isValidEmailPart(parts[1]))
		return false;

	parts = parts[1].split(".");
	if (parts.length < 2)
		return false;
	if (parts[parts.length - 1].length < 2)
		return false;

	return true;
}

function isValidEmailPart(emailPart)
{
	if (emailPart == null || emailPart.length == 0)
		return false;

	for (i = 0; i < emailPart.length; i++)
	{
		c = emailPart.charAt(i);
		if ((c >= '0' && c <= '9') ||
			(c >= 'a' && c <= 'z') ||
			(c >= 'A' && c <= 'Z') ||
			(c == '-') ||
			(c == '_') ||
			(c == '.'))
			continue;
		return false;
	}
	return true;
}

// XOption 
function XOption(keyParent, key, value)
{
	this.keyParent = keyParent;
    this.key = key;
    this.value = value;
}

function fillListBox(listbox, xoptionList, keyParent, key, emptyOption, emptyText)
{
	if (listbox.type != "select-one")
		return;

	for (i = listbox.options.length - 1; i >= 0; i--)
		listbox.remove(i);

	if (emptyOption)
	{
		var option = document.createElement("OPTION");
		option.value = "";
		option.text = emptyText;
		listbox.options.add(option);
	}

	for (i = 0; i < xoptionList.length; i++)
	{
		if (xoptionList[i].keyParent == keyParent)
		{
			var option = document.createElement("OPTION");
			option.value = xoptionList[i].key;
			option.text = xoptionList[i].value;
			if (xoptionList[i].key == key)
				option.selected = true;
			listbox.options.add(option);
		}
	}
}

// Label
function Label(key, value)
{
    this.key = key;
    this.value = value;
}

function Labels()
{
	this.labelList = new Array(256);
	this.numLabels = 0;
}

Labels.prototype.add = function(key, value)
{
    if (this.numLabels >= this.labelList.length)
        alert("No more space for Label.");
    else
        this.labelList[this.numLabels++] = new Label(key, value);
}

Labels.prototype.get = function(key)
{
    for (i = 0; i < this.numLabels; i++)
    	if (this.labelList[i].key == key)
        	return this.labelList[i].value;
	return "Label " + key + " not found.";
}

var labels = new Labels();

// AJAX
function Ajax()
{
    var ajaxInitialized= false;
    this.xmlHttp = null;

    try
    {
        this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        ajaxInitialized = true;
    }
    catch (e)
    {
        try
        {
            this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            ajaxInitialized = true;
        }
        catch (e)
        {
        }
    }
    if (!ajaxInitialized && typeof XMLHttpRequest != 'undefined')
    {
        try
        {
            this.xmlHttp = new XMLHttpRequest();
            ajaxInitialized = true;
        }
        catch (e)
        {
        }
    }
    if (!ajaxInitialized)
    {
        try
        {
            this.xmlHttp = window.createRequest();
            ajaxInitialized = true;
        }
        catch (e)
        {
        }
    }

    if (!ajaxInitialized)
        alert("Unable to initialize AJAX.");
}

Ajax.prototype.getStatus = function()
{
    return this.xmlHttp.status;
}

Ajax.prototype.getDataAsync = function(url)
{
    var data;

    var url_ts = url;
    if (url.indexOf("?") != -1)
        url_ts += "&ts=";
    else
        url_ts += "?ts=";
    url_ts += new Date();

    try
    {
        this.xmlHttp.open(
            "GET",
            url_ts,
            true);
        this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.xmlHttp.send(null);
    }
    catch (e)
    {
        alert(e.description);
    }
}

Ajax.prototype.getData = function(url)
{
    var data;

    var url_ts = url;
    if (url.indexOf("?") != -1)
        url_ts += "&ts=";
    else
        url_ts += "?ts=";
    url_ts += new Date();

    try
    {
        this.xmlHttp.open(
            "GET",
            url_ts,
            false);
        this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        this.xmlHttp.send(null);

        data = this.xmlHttp.responseText;

        if (this.xmlHttp.status == 200)
            return data;
        else
        {
            alert("Unable to get data from " + url + " error " + this.xmlHttp.status);
            return null;
        }
    }
    catch (e)
    {
        alert(e.description);
    }
}

// Date
function isValidDate(data)
{
    aData = data.split(" ");

    if (aData.length > 1)
    {
        sDate = aData[0];
        sTime = aData[1];
    }
    else
    {
        sDate = aData[0];
        sTime = "00:00:00";
    }

	if (sDate.indexOf("-") != -1)
	{
	    sYMD = sDate.split("-");
    	if (sYMD.length != 3)
    		return false;
    	if (sYMD[0].lenght != 4)
    	{
    		year = sYMD[2];
    		month = sYMD[0];
    		day = sYMD[1];
    	}
    	else
    	{
    		year = sYMD[0];
    		month = sYMD[1];
    		day = sYMD[2];
    	}
    }
    else if (sDate.indexOf("/") != -1)
    {
	    sYMD = sDate.split("/");
		if (sYMD.length != 3)    	
			return false;
   		year = sYMD[2];
   		month = sYMD[1];
   		day = sYMD[0];
    }
    else
    	return false;

    sTime = sTime.replace(".", ":");
    if (sTime.length < 8)
    	sTime += "00:00:00".substring(sTime.length);

    sHMS = sTime.split(":");
    if (sHMS.length != 3)
		return false;

    date = new Date(
        Number(year),
        Number(month) - 1,
        Number(day),
        Number(sHMS[0]),
        Number(sHMS[1]),
        Number(sHMS[2]));

    inDate =
        year + "-" +
        (month.length == 1 ? "0" + month : month) + "-" +
        (day.length == 1 ? "0" + day : day) + " " +
        (sHMS[0].length == 1 ? "0" + sHMS[0] : sHMS[0]) + ":" +
        (sHMS[1].length == 1 ? "0" + sHMS[1] : sHMS[1]) + ":" +
        (sHMS[2].length == 1 ? "0" + sHMS[2] : sHMS[2]);

    outDate =
        date.getFullYear().toString() + "-" +
        ((date.getMonth() + 1).toString().length == 1 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString()) + "-" +
        (date.getDate().toString().length == 1 ? "0" + date.getDate().toString() : date.getDate().toString()) + " " +
        (date.getHours().toString().length == 1 ? "0" + date.getHours().toString() : date.getHours().toString()) + ":" +
        (date.getMinutes().toString().length == 1 ? "0" + date.getMinutes().toString() : date.getMinutes().toString()) + ":" +
        (date.getSeconds().toString().length == 1 ? "0" + date.getSeconds().toString() : date.getSeconds().toString());

    return (inDate == outDate);
}


//Date
function isBusinessDate(data)
{
	aData = data.split(" ");

	if (aData.length > 1)
	{
	    sDate = aData[0];
	    sTime = aData[1];
	}
	else
	{
	    sDate = aData[0];
	    sTime = "00:00:00";
	}
	
	if (sDate.indexOf("-") != -1)
	{
		sYMD = sDate.split("-");
		if (sYMD.length != 3)
			return false;
		if (sYMD[0].lenght != 4)
		{
			year = sYMD[2];
			month = sYMD[0];
			day = sYMD[1];
		}
		else
		{
			year = sYMD[0];
			month = sYMD[1];
			day = sYMD[2];
		}
	}
	else if (sDate.indexOf("/") != -1)
	{
		sYMD = sDate.split("/");
		if (sYMD.length != 3)    	
			return false;
		year = sYMD[2];
		month = sYMD[1];
		day = sYMD[0];
	}
	else
		return false;
	
	sTime = sTime.replace(".", ":");
	if (sTime.length < 8)
		sTime += "00:00:00".substring(sTime.length);
	
	sHMS = sTime.split(":");
	if (sHMS.length != 3)
			return false;
	
	date = new Date(
	    Number(year),
	    Number(month) - 1,
	    Number(day),
	    Number(sHMS[0]),
	    Number(sHMS[1]),
	    Number(sHMS[2]));
	
	var dayOfWeek = date.getDay();
	
	if (dayOfWeek == 0 || dayOfWeek == 6)
		return false;
	
	return true;
}


function formatDate(value)
{
	var sOut = "";
	var aDate = value.split("/");
	var token_day = new String(aDate[0]);
	var token_month = new String(aDate[1]);
	var token_year = new String(aDate[2]);
	
	if(token_day.length == 1)
	{
		token_day = "0" + token_day;
	}
	if(token_month.length == 1)
	{
		token_month = "0" + token_month;
	}
	return token_day + "/" + token_month + "/" + token_year;
}

function isYearBetween(iStart, iEnd, value)
{
	var myDate = value.substring(0,10)
	var aDate = myDate.split("/");
	if(aDate[2] > iStart && aDate[2] < iEnd)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// Numeri & C.
function format_number(p, d, ds)
{
  var r;
  if (p < 0)
  {
      	p=-p;
		r = format_number2(p, d, ds);
		r = "-" + r;
  }
  else
  {
		r=format_number2(p , d, ds);
  }
  return r;
}

function format_number2(pnumber, decimals, decimalsSeparator)
{
  var strNumber = new String(pnumber);
  var arrParts = strNumber.split('.');
  var intWholePart = parseInt(arrParts[0],10);
  var strResult = '';
  if (isNaN(intWholePart))
    intWholePart = '0';
  if(arrParts.length > 1)
  {
    var decDecimalPart = new String(arrParts[1]);
    var i = 0;
    var intZeroCount = 0;
     while ( i < String(arrParts[1]).length )
     {
       if( parseInt(String(arrParts[1]).charAt(i),10) == 0 )
       {
         intZeroCount += 1;
         i += 1;
       }
       else
         break;
    }
    decDecimalPart = parseInt(decDecimalPart,10)/Math.pow(10,parseInt(decDecimalPart.length-decimals-1));
    Math.round(decDecimalPart);
    decDecimalPart = parseInt(decDecimalPart)/10;
    decDecimalPart = Math.round(decDecimalPart);

    if(decDecimalPart==Math.pow(10, parseInt(decimals)))
    {
      intWholePart+=1;
      decDecimalPart="0";
    }
    var stringOfZeros = new String('');
    i=0;
    if( decDecimalPart > 0 )
    {
      while( i < intZeroCount)
      {
        stringOfZeros += '0';
        i += 1;
      }
    }
    decDecimalPart = String(intWholePart) + decimalsSeparator + stringOfZeros + String(decDecimalPart);
    var dot = decDecimalPart.indexOf(decimalsSeparator);
    if(dot == -1)
    {
      decDecimalPart += decimalsSeparator;
      dot = decDecimalPart.indexOf(decimalsSeparator);
    }
    var l=parseInt(dot)+parseInt(decimals);
    while(decDecimalPart.length <= l)
    {
      decDecimalPart += '0';
    }
    strResult = decDecimalPart;
  }
  else
  {
    var dot;
    var decDecimalPart = new String(intWholePart);

    decDecimalPart += decimalsSeparator;
    dot = decDecimalPart.indexOf(decimalsSeparator);
    var l=parseInt(dot)+parseInt(decimals);
    while(decDecimalPart.length <= l)
    {
      decDecimalPart += '0';
    }
    strResult = decDecimalPart;
  }
  return strResult;
}

function blankUrl(url)
{
    window.open(url);
}

function plusMinusLayer(imgObj, id)
{
    var divObj = document.getElementById(id);

    if (divObj.style.display == "block")
    {
        imgObj.src = imgObj.src.replace("Minus.gif", "Plus.gif");
        divObj.style.display = "";
    }
    else
    {
        imgObj.src = imgObj.src.replace("Plus.gif", "Minus.gif");
        divObj.style.display = "block";
    }
}

function isVisible(id)
{
    var divObj = getById(id);
    if (divObj != null)
        return !(divObj.style.display == "none"); 
	return false;
}

function show(id)
{
    var divObj = getById(id);
    if (divObj != null)
    	divObj.style.display = "block";
}

function hide(id)
{
    var divObj = getById(id);
    if (divObj != null)
    	divObj.style.display = "none";
}

function showHide(id)
{
    divObj = getById(id);
    if (divObj == null)
	    return;
	if (divObj.style.display == "none")
		divObj.style.display = "block";
	else
		divObj.style.display = "none";
}

function selectTab(tabPrefix, position)
{
    var tabsId;
    var cntId;
    var countId;
    var numTabs;

    tabId = tabPrefix + "_tab_";
    cntId = tabPrefix + "_cnt_";
    countId = tabPrefix + "_count";

    countObj = document.getElementById(countId);
    numTabs = Number(countObj.value);

    for (i = 1; i <= numTabs; i++)
    {
        tabObj = document.getElementById(tabId + i);
        cntObj = document.getElementById(cntId + i);

        if (position == i)
        {
            tabObj.className = "on";
            cntObj.style.display = "block";
        }
        else
        {
            tabObj.className = "off";
            cntObj.style.display = "none";
        }
    }
}

function newsFormOnChange(selectObject, idNewsTypeMultimediaType)
{
    alert(selectObject.options[selectObject.selectedIndex].value);
}

var lastFocusElement = null;

function onloadPage()
{
	loadMap();

 	var inputs = document.getElementsByTagName("input");  
 	for( var i = 0; i < inputs.length; i++ )
 		if (inputs[i].type == 'text' || inputs[i].type == 'password')
 			if (typeof inputs[i].onblur != "function")
				inputs[i].onblur = function() {lastFocusElement = this;};
}

function jumpToSite(selectObject)
{
	var url = selectObject.value;
	if (url != "")
		document.location = url;
}

function onLevelOver(position)
{
    countObj = document.getElementById("firstLevel_count");
    numTabs = Number(countObj.value);

	for (i = 1; i <= numTabs; i++)
	{
		id1Obj = document.getElementById("firstLevel_" + i);
		id2Obj = document.getElementById("secondLevel_" + i);
		if (id1Obj != undefined && id2Obj != undefined)
		{
	        if (position == i)
	        {
				id2Obj.style.display = "block";
				x = id1Obj.offsetLeft + (id1Obj.offsetWidth / 2);
				x -= (id2Obj.offsetWidth / 2);
				if ((x + id2Obj.offsetWidth) > 760) 
					x = 760 - id2Obj.offsetWidth;
				else if (x < 0)
					x = 0;
	        	id2Obj.style.left = x + "px";
			}
			else
				id2Obj.style.display = "none";
		}
	}
}

function moveOption(fromSelect, toSelect, all)
{
	fromSelectObj = document.getElementById(fromSelect);
	toSelectObj = document.getElementById(toSelect);

	dst = toSelectObj.options.length;
	for (src = fromSelectObj.options.length - 1; src >= 0 ; src--)
	{
		if (all == true || fromSelectObj.options[src].selected)
		{
			opt = new Option(fromSelectObj.options[src].text, fromSelectObj.options[src].value);
			toSelectObj.options[dst++] = opt;
			fromSelectObj.options[src] = null;
		}
	}
}

function selectAllOption(select)
{
	selectObj = document.getElementById(select);
	for (i = 0; i < selectObj.options.length; i++)
		selectObj.options[i].selected = true;
}

var type = '';
var days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
var dateFieldObj;

function showCalendar(dateFieldId)
{
	var container = document.getElementById('calendarcontainer');
	var header = document.getElementById('calendartop');
	header.innerHTML = "Calendar"; 
	if (document.all)
	{
		var entries = document.getElementsByTagName('select');
		for (var i = 0; i < entries.length; i++)
			if (entries[i].className == 'cal_hide')
				entries[i].style.display = 'none';
	}
	
	var today = new Date();
	document.getElementById('calendaryear').value = today.getFullYear();

	var monthObj = getById('calendarmonth');
	if (monthObj.options.length == 0)
	{
		monthObj.options[0] = new Option("Jan", "0");
		monthObj.options[1] = new Option("Feb", "1");
		monthObj.options[2] = new Option("Mar", "2");
		monthObj.options[3] = new Option("Apr", "3");
		monthObj.options[4] = new Option("May", "4");
		monthObj.options[5] = new Option("Jun", "5");
		monthObj.options[6] = new Option("Jul", "6");
		monthObj.options[7] = new Option("Aug", "7");
		monthObj.options[8] = new Option("Sep", "8");
		monthObj.options[9] = new Option("Oct", "9");
		monthObj.options[10] = new Option("Nov", "10");
		monthObj.options[11] = new Option("Dec", "11");
	}
	monthObj.selectedIndex = today.getMonth();

	var hourObj = getById('calendarhour');
	if (hourObj.options.length == 0)
		for (h = 0; h < 24; h++)
			hourObj.options[h] = new Option(h, h);

	var minuteObj = getById('calendarminutes');
	if (minuteObj.options.length == 0)
		for (m = 0; m < 60; m++)
			minuteObj.options[m] = new Option(m, m);

	updateMonth();

	dateFieldObj = document.getElementById(dateFieldId);

	container.style.left = mouseX + "px";
	container.style.top = mouseY + "px";
	container.style.display = "block";
}

function fill(day, month, hour, minutes)
{
	var date = "";
	closeCalendar();

	if (day < 10)
		date += "0"
	date += String(day) + "/";

	month++;
	if (month < 10)
		date += "0"
	date += String(month) + "/";
	
	date += document.getElementById('calendaryear').value + " ";
	if (document.getElementById('calendarhour').options.selectedIndex < 10)
		date+= "0"
	date += document.getElementById('calendarhour').options.selectedIndex + ":";
	if (document.getElementById('calendarminutes').options.selectedIndex < 10)
		date+= "0"
	date += document.getElementById('calendarminutes').options.selectedIndex + ":00";
	
	dateFieldObj.value = date;	
}

function closeCalendar ()
{
	var container = document.getElementById('calendarcontainer');
	if (document.all)
	{
		var entries = document.getElementsByTagName('select');
		for (var i = 0; i < entries.length; i++)
			if (entries[i].className == 'cal_hide')
				entries[i].style.display = 'block';
	}
	container.style.display = 'none';
}

function updateMonth()
{
	year = Number (document.getElementById('calendaryear').value);
	month = document.getElementById('calendarmonth').options.selectedIndex;
	selection = month;
	month += 1;
	var noOfDays = getNumberOfDays(month, year);
	var firstDay = getFirstDay(month, year);
	fillMonth(month, firstDay, noOfDays, selection);
}

function getNumberOfDays(m, y)
{
	var days = 31;
	switch (parseInt(m))
	{
		case 4: case 6: case 9: case 11:
			days = 30;
			break;
		case 2:
		  if ((y % 4 == 0) ^ (y % 100 == 0) ^ (y % 400 == 0))
			days = 29;
		  else
			days = 28;
		  break;
	}
	return days;
}

function prevYear()
{
	today = new Date();
	yearObj = document.getElementById('calendaryear');
	year = Number(yearObj.value) - 1;
	yearObj.value = String(year);
	updateMonth();
}

function nextYear()
{
	yearObj = document.getElementById('calendaryear');
	year = Number(yearObj.value) + 1;
	yearObj.value = String(year);
	updateMonth();
}

function getFirstDay(m, y)
{
	d = new Date(y, m-1, 1);
	d.setHours(12);
	return (d.getDay() - 1 >= 0 ? d.getDay() - 1 : d.getDay() + 6);
}

function fillMonth(month, firstDay, noOfDays, monthIndex)
{
	var firstSet = false;
	var dayCounter = 1;
	var today = new Date();
	dateToday = today.getDate();
	monthToday = today.getMonth() + 1;
	var sHTML = '<table cellspacing="0" border=\"0\"><tr class="head">'
	for (var i = 0; i < days.length; i ++)
		sHTML += '<td>' + days[i] + '</td>\n';

	sHTML += '</tr>';
	while (dayCounter <= noOfDays)
	{
		sHTML += '<tr>';
		for (i = 0; i < 7; i++)
		{
			if (!firstSet && i < firstDay)
			{
				sHTML += '<td>&nbsp;</td>\n';
			}
			else
			{
				firstSet = true;
				if (dayCounter <= noOfDays)
					sHTML += '<td><a alt="" href="javascript:fill(' + dayCounter + ' , ' + monthIndex + ');">' + dayCounter + '</a></td>\n';
				else
					sHTML += '<td>&nbsp;</td>\n';
				dayCounter++;
			}
		}
		sHTML += '</tr>'
	}
	sHTML += '</table>';
	document.getElementById('monthtable').innerHTML = sHTML;
}

function onlyNumbers(id)
{
     var valore=document.getElementById(id).value
     valore=valore.replace (/[^\d]/g,'')
     document.getElementById(id).value=valore;
     updateMonth();
}

function onChangeCdModel(objSelect)
{
	objImg = document.getElementById("cdModelImg");
	objImg.src = "/mm?id=" + idMultimediaModel[objSelect.selectedIndex];
}

function onChooseMultimediaType(id)
{
	var size = mtSizes[id];
	objAdvisedSize = document.getElementById("advisedSize");
	if (size != null)
	{
		msg = "";
		if (size.width == -1) msg += "any x ";
		else				  msg += size.width + " x ";
		if (size.height == -1) msg += "any";
		else				  msg += size.height;
		
		objAdvisedSize.innerHTML = msg;
	}
	else
		objAdvisedSize.innerHTML = " ";
}

// Show Product Function
var showProductTotQty = 0;
var showProductMaxQty = 0;

function spSubQty(idObj)
{
	var obj = getById(idObj);
	var qty = Number(obj.value);
	if (isNaN(qty))
		qty = 0;
	else
	{
		qty--;
		if (qty < 0) 
			qty = 0;
		else
			showProductTotQty--;
		try
		{
			if (packageManager)
			{
				var parts = idObj.split("_");
				var idProductItem = Number(parts[parts.length - 1]);
				packageManager.subQty(idProductItem);
			}
		}
		catch (e)
		{
		}
		
	}
	obj.value = qty;
}

function spAddQty(idObj, maxTicket)
{
	var obj = getById(idObj);
	var qty = Number(obj.value);
	if (isNaN(qty))
		qty = 1;
	else
	{
		qty++;
		if (qty > maxTicket) 
			qty = maxTicket;
		else
		{
			if (showProductMaxQty > 0 && showProductTotQty >= showProductMaxQty)
				return;
			showProductTotQty++;
			try
			{
				if (packageManager)
				{
					var parts = idObj.split("_");
					var idProductItem = Number(parts[parts.length - 1]);
					packageManager.addQty(idProductItem);
				}
			}
			catch (e)
			{
			}
		}
	}
	obj.value = qty;
}

var isSubmit = false;
function validatePayment()
{
	if (isSubmit)
		return false;
	
	var obj;
	obj = getById("PaymentInfo.cdCreditCard");
	if (obj != null)
	{
		if (obj.value.length == 0 || !isValidLuhn(obj.value))
		{
			alert(labels.get("spInvalidCreditCard"));
			return false;
		}
	}

	obj = getById("PaymentInfo.cdCvv2");
	if (obj != null)
	{
		if (obj.value.length != 3 || isNaN(obj.value))
		{
			alert(labels.get("spInvalidCvv2"));
			return false;
		}
	}

	if (showPaymentFormJs.validate())
	{
		var objMsg = getById("waitMessage");
		objMsg.innerHTML = "<p class='waitMessage'>Please Wait!!!!</p>";
		isSubmit = true;
		return true;
	}
	return false;
}

function goToHttps(page)
{
	var url = new String(window.location);
	var urlparts = url.split('/');
	var newUrl = "https:";
	for (i = 1; i < urlparts.length - 1; i++)
		newUrl += "/" + urlparts[i];
	newUrl += "/" + page;
	document.location = newUrl;
}

function goToHttp(page)
{
	var url = new String(window.location);
	var urlparts = url.split('/');
	var newUrl = "http:";
	for (i = 1; i < urlparts.length - 1; i++)
		newUrl += "/" + urlparts[i];
	newUrl += "/" + page;
	document.location = newUrl;
}

function activateActiveX()
{
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		var arrElements = new Array(3);
		arrElements[0] = "object";
		arrElements[1] = "embed";
		arrElements[2] = "applet";
        for (n = 0; n < arrElements.length; n++)
        {
			replaceObj = document.getElementsByTagName(arrElements[n]);
            for (i = 0; i < replaceObj.length; i++)
			{
				parentObj = replaceObj[i].parentNode;
				newHTML = parentObj.innerHTML;
				parentObj.removeChild(replaceObj[i]);
				parentObj.innerHTML = newHTML;
			}
		}
	}
}

// Show/Hide Menu
var isMenuOpen = false;
var slideSpeed = 10;
var menuObj = null;
var acc = 1.3;

function setMenu(objectID)
{
	menuObj = document.getElementById(objectID);
	if (isMenuOpen)
	{
		fX = 40 - (menuObj.offsetWidth);
		cX = 0;
		isMenuOpen = false;
	}
	else
	{
		fX = 0;
		cX = 40 - (menuObj.offsetWidth);
		isMenuOpen = true;
	}
	slideMenu(cX, fX);
}

function slideMenu(cX, fX) 
{
	if (!isMenuOpen && (cX > fX))
	{
		cX -= slideSpeed;
		menuObj.style.left = cX + 'px';
		setTimeout('slideMenu(' + cX + ',' + fX + ')', 0);
	}
	else if(isMenuOpen && (cX < fX))
	{
		cX += slideSpeed;
		menuObj.style.left = cX + 'px';
		setTimeout('slideMenu(' + cX + ',' + fX + ')', 0);
	}
	else
		return;
}

// Functions For Touchscreen Keyboard
function addIt(cKey)
{
	if (lastFocusElement == null)
	{
		alert("Click on desired field first");
		return;
	}
	
	if (cKey.value == 'backspace' || cKey.id == 'backspace')
		lastFocusElement.value = lastFocusElement.value.slice(0, -1);
	else if (cKey.value == 'space' || cKey.id == 'space')
		lastFocusElement.value += ' ';
	else
		lastFocusElement.value += cKey.value;
		
	lastFocusElement.focus();
}

function toggle(div)
{
	var option=['part1','part2'];

	for(var i=0; i<option.length; i++)
	{ 
		obj=document.getElementById(option[i]);
		obj.style.display=(option[i]==div) && !(obj.style.display=="block")? "block" : "none"; 
	}
}

// Functions For Popup
function newWindow(url, myname, w , h, scroll)
{
	if (w == null)
		w = screen.width;
	if (h == null)
		h = screen.height;

	leftPosition = (screen.width) ? (screen.width - w) / 2 : 0;
	topPosition = (screen.height) ? (screen.height - h) / 2 : 0;
	settings = 'height='+h+',width='+w+',top='+topPosition+',left='+leftPosition+',scrollbars='+scroll+',resizable';

	if (url.indexOf("?") != -1)
		url += "&nohistory=true";
	else 
		url += "?nohistory=true";

	var win = window.open(url, myname, settings)
	if (win.window.focus)
		win.window.focus();
}

function showPriceSection(cdPriceSection)
{
	var el = document.getElementsByTagName("tr");
	for (var i = 0; i < el.length; i++)
	{
  		if (el[i].id.substring(0, 3) == "ps_")
  		{
			if (el[i].id == "ps_" + cdPriceSection)
				el[i].className = "hl";
			else
				el[i].className = "";
		}
	}
}

function selectSection(cdSection)
{
	document.showProductForm.cdSection.value = cdSection;
	document.showProductForm.submit();
}

function syncMsCheckBox(obj)
{
	var el = document.getElementsByName("ms");
	for (var i = 0; i < el.length; i++)
	{
		el[i].checked = false;
		if (obj.value.length == 0)
			continue;

		pos = obj.value.indexOf(el[i].value);
		if (pos == -1)
			continue;
		if (pos > 0 && obj.value.charAt(pos - 1) != ',')
			continue;
		pos += el[i].value.length;
		if (pos == obj.value.length || obj.value.charAt(pos) == ',')
			el[i].checked = true;
	}
}

function resetProductSelection(obj)
{
	var el = document.getElementsByTagName("input");
	for (var i = 0; i < el.length; i++)
	{
		if (el[i].type != "radio" || el[i].name == obj.name)
			continue;
			
  		if (el[i].id == "idProductItemQta")
  			el[i].checked = false;
	}
}

function getDigitsOnly(s)
{
	var digitsOnly = "";
	for (i = 0; i < s.length; i++)
	{
		c = s.charAt(i);
		if (c >= '0' && c <= '9')
			digitsOnly += c;
	}
	return digitsOnly;
}

function isValidLuhn(cardNumber)
{
	var digitsOnly = getDigitsOnly(cardNumber);
	var sum = 0;
	var digit = 0;
	var addend = 0;
	var timesTwo = false;
	for (i = digitsOnly.length - 1; i >= 0; i--)
	{
		digit = digitsOnly.charAt(i) - '0';
		if (timesTwo)
		{
			addend = digit * 2;
			if (addend > 9)
				addend -= 9;
		}
		else
			addend = digit;

		sum += addend;
		timesTwo = !timesTwo;
	}

	var modulus = sum % 10;
	return (modulus == 0);
}

function getImageLink(id, name, width, maxwidth)
{
	var img = "<img src='/mm?id=" + id + "' alt='" + name + "'";
	if (width > 0)
	{
		if (maxwidth > 0 && width > maxwidth)
			img += " width='" + maxwidth + "'";
		else
			img += " width='" + width + "'";
	}
	img += "/>";
	return img;
}

function wbGoTo(
	url,
	idDay,
	idMonth,
	idYear,
	idEvent,
	nmEvent,
	idEventType,
	idSpace,
	idVenue,
	idEventCategory)
{
	if (idDay == null)
		idDay = document.winbankForm.idDay.value;
	if (idMonth == null)
		idMonth = document.winbankForm.idMonth.value;
	if (idYear == null)
		idYear = document.winbankForm.idYear.value;
	if (idEvent == null)
		idEvent = document.winbankForm.idEvent.value;
	if (nmEvent == null)
		nmEvent = document.winbankForm.nmEvent.value;
	if (idEventType == null)
		idEventType = document.winbankForm.idEventType.value;
	if (idSpace == null)
		idSpace = document.winbankForm.idSpace.value;
	if (idVenue == null)
		idVenue = document.winbankForm.idVenue.value;
	if (idEventCategory == null)
		idEventCategory = document.winbankForm.idEventCategory.value;
		
	url = addUrlParam(url, "idDay", idDay);
	url = addUrlParam(url, "idMonth", idMonth);
	url = addUrlParam(url, "idYear", idYear);
	url = addUrlParam(url, "idEvent", idEvent);
	url = addUrlParam(url, "nmEvent", nmEvent);
	url = addUrlParam(url, "idEventType", idEventType);
	url = addUrlParam(url, "idSpace", idSpace);
	url = addUrlParam(url, "idVenue", idVenue);
	url = addUrlParam(url, "idEventCategory", idEventCategory);
	
	document.location = url;
}

function addUrlParam(url, name, value)
{
	if (value != null && String(value).length > 0)
	{
		if (url.indexOf('?') == -1)
			url += "?";
		else 
			url += "&";
		
		url += name + "=" + value;
	}
	
	return url;
}

function moveDiv(id, step)
{
	document.getElementById(id).scrollTop += step;
}

function calcMod11(value)
{
	var sum = 0;
	var len = value.length;
	for (k = 1; k <= len; k++)
	    sum += (11 - k) * (value.charCodeAt(k - 1) - 48);
	    
	var rem = sum % 11;

	if (rem == 0)
		return "0";
	else if (rem == 1)
		return "X";
	return (11 - rem);
}

function calcMod11(value)
{
	var sum = 0;
	var len = value.length;
	for (k = 1; k <= len; k++)
	    sum += (11 - k) * (value.charCodeAt(k - 1) - 48);
	    
	var rem = sum % 11;

	if (rem == 0)
		return "0";
	else if (rem == 1)
		return "X";
	return (11 - rem);
}

//alert(calcMod10(169509));
function calcMod10(value)
{
    var sumOdd = 0;
    var sumEven = 0;
    var len = value.length;
    for (i = (len - 1); i >= 0; --i)
    {
    	if ((i & 0x01) == 0x00)
    		sumOdd += (value.charCodeAt(i) - 48);
    	else
    		sumEven += (value.charCodeAt(i) - 48);
    }
    sumOdd *= 3;
    res =  10 - ((sumOdd + sumEven) % 10);
    if (res == 10)
    	res = 0;
    return res;
}

function focusById(id)
{
	var obj = getById(id);
	if (obj != null)
		obj.focus();
}

//Google functions
var _gaq = _gaq || []; 
var gmarkers;
var infoTabs;
var map;

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function trackEvent(category, action)
{
	try
	{
		_gaq.push(["_trackEvent", category, action]);
	}
	catch (e)
	{
	}
	return true;
}

function trackPageView(fakeLink)
{
	try
	{
		_gaq.push(["_trackPageview", fakeLink]);
	}
	catch (e)
	{
	}
	return true;
}

function Location(
	id,
    nmName, 
    noPhone, 
    noFax, 
    ulEmail,
    ulWebSite, 
    txAddress, 
    cdStreetNumber,
    cdPostal, 
    nmCity, 
    cdArea,
    cdCountry, 
    txNotes,
    dgLat, 
    dgLon)
{
	this.id = id;
    this.nmName = nmName;
    this.noPhone = noPhone;
    this.noFax = noFax;
    this.ulEmail = ulEmail;
    this.ulWebSite = ulWebSite;
    this.txAddress = txAddress;
    this.cdStreetNumber = cdStreetNumber;
    this.cdPostal = cdPostal;
    this.nmCity = nmCity;
    this.cdArea = cdArea;
    this.cdCountry = cdCountry;
    this.txNotes = txNotes;
    this.dgLat = dgLat;
    this.dgLon = dgLon;
}

function loadMap()
{
	try
	{
		if (locationList == null || locationList.length == 0)
			return;
	}
	catch (e)
	{
		return;
	}

    if (GBrowserIsCompatible())
    {
        mapObj = document.getElementById("googleMap");
        if (mapObj != null)
        {
            map = new GMap2(mapObj);

            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            map.addControl(new GScaleControl());
            map.addControl(new GOverviewMapControl());
            //map.setCenter(new GLatLng(42.588907, 11.517371), 5);

        	if (locationList.length > 0)
        	{
        		map.setCenter(new GLatLng(locationList[0].dgLat, locationList[0].dgLon), 15);	
            	renderMap(locationList, null); //"/img/bpm360_maps.gif");
        	}
        	else
        		map.setCenter(new GLatLng(42.588907, 11.517371), 5);
        }
    }
}

function panTo(idLocation)
{
	map.setZoom(15);
	map.panTo(
		new GLatLng(
			locationList[idLocation].dgLat, 
			locationList[idLocation].dgLon));
}

function renderMap(locationList, iconUri)
{
    var i, x1, x2, xm, y1, y2, ym;
    var icon = getIcon(iconUri, 48, 34, 24, 34, 24, 17);

    if (locationList.length == 0)
    {
        map.setZoom(5);
        map.panTo(new GLatLng(42.588907, 11.517371));
        return;
    }

    gmarkers = new Array(locationList.length);
    infoTabs = new Array(locationList.length);

    for (i = 0; i < locationList.length; i++)
    {
        if (i == 0)
        {
            x1 = locationList[i].dgLat;
            x2 = locationList[i].dgLat;
            xm = locationList[i].dgLat;
            y1 = locationList[i].dgLon;
            y2 = locationList[i].dgLon;
            ym = locationList[i].dgLon;
        }
        else
        {
            if (x1 > locationList[i].dgLat)
                x1 = locationList[i].dgLat;

            if (x2 < locationList[i].dgLat)
                x2 = locationList[i].dgLat;

            xm += locationList[i].dgLat;

            if (y1 > locationList[i].dgLon)
                y1 = locationList[i].dgLon;

            if (y2 < locationList[i].dgLon)
                y2 = locationList[i].dgLon;

            ym += locationList[i].dgLon;
        }

        point = new GLatLng(locationList[i].dgLat, locationList[i].dgLon);
        html =
            "<table border='0' width='300' class='googleBaloon'>" +
            "<tr><td><b>" + locationList[i].nmName + "</b></td></tr>" +
            "<tr><td>" + locationList[i].txAddress + ", " + locationList[i].cdStreetNumber + "</td></tr>" +
            "<tr><td>" + locationList[i].cdPostal + " " + locationList[i].nmCity + " " + locationList[i].cdArea + " " + locationList[i].cdCountry  + "</td></tr>";

        if (locationList[i].noPhone.trim().length > 0)
            html += "<tr><td>Tel: " + locationList[i].noPhone + "</td></tr>";
        if (locationList[i].noFax.trim().length > 0)
            html += "<tr><td>Fax: " + locationList[i].noFax + "</td></tr>";
        if (locationList[i].ulEmail.trim().length > 0)
            html += "<tr><td>Email: <a href='mailto:" + locationList[i].ulEmail + "'>" + locationList[i].ulEmail + "</a></td></tr>";
        if (locationList[i].ulWebSite.trim().length > 0)
            html += "<tr><td>Web: <a href='" + locationList[i].ulWebSite + "' target='_new'>" + locationList[i].ulWebSite + "</a></td></tr>";
        if (locationList[i].txNotes.trim().length > 0)
            html += "<tr><td>" + locationList[i].txNotes + "</td></tr>";
        html += "</table>";

        gmarkers[i] = createMarker(point, icon, html);
        infoTabs[i] = html;

        map.addOverlay(gmarkers[i]);
    }

    xm /= locationList.length;
    ym /= locationList.length;

    var centromappa = new GLatLng(xm, ym);
    var point_min = new GLatLng(x1, y1);
    var point_max = new GLatLng(x2, y2);
    var rectBounds = new GLatLngBounds(point_min, point_max);
    var zoom = map.getBoundsZoomLevel(rectBounds);
    map.setZoom(zoom - 1);
    map.panTo(centromappa);
}

function createMarker(point, icon, html)
{
    var marker = new GMarker(point, icon);
    GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
    return marker;
}

function writeLink(id, icon)
{
     for (i = 0; i < locationList.length; i++)
     {
         if (locationList[i].id == id)
         {
            document.write("<a title='Clicca qui per visualizzare la località sulla mappa.' href=\"#map\" onclick=\"openBaloon(" + i + ");\"><img alt='' src='" + icon + "' border='0'/></a>");
            break;
         }
    }
}

function openBaloon(i)
{
    gmarkers[i].openInfoWindowHtml(infoTabs[i]);
}

function getIcon(
		uri, 
		w, 
		h, 
		anchorX, 
		anchorY, 
		infoWindowX, 
		infoWindowY)
{
	if (!uri)
		return null;

	var icon = new GIcon();
	icon.image = uri;
	icon.iconSize = new GSize(w, h);
	icon.iconAnchor = new GPoint(anchorX, anchorY);
	icon.infoWindowAnchor = new GPoint(infoWindowX, infoWindowY);

	return icon;
}

function chooseMultimedia(
		idField, 
		dsField, 
		prwField,
		cdMultimediaType)
{
	newWindow(
		'chooseMultimedia.html' +
		'?nohistory=true' +
		'&idField=' + idField + 
		'&dsField=' + dsField + 
		'&prwField=' + prwField +
		'&lockMultimediaType=True' +
		'&cdMultimediaType=' + cdMultimediaType,
		'ChooseMultimedia', 
		'1008', 
		'600', 
		'yes');
}

function removeMultimedia(
		idField, 
		dsField, 
		prwField)
{
	var obj;
	
	obj = getById(idField);
	if (obj != null)
		obj.value = '';

	obj = getById(dsField);
	if (obj != null)
		obj.value = '';

	obj = getById(prwField);
	if (obj != null)
		obj.innerHTML = '';
}

function parseXML(xml)
{
	var xmlDoc;
	try 
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = "false";
		xmlDoc.loadXML(xml);
	}
	catch(e)
	{
		parser = new DOMParser();
		xmlDoc = parser.parseFromString(xml, "text/xml");
	}
	
	return xmlDoc;
}

function showGlossaryTerm(
	cdApplication,
	cdLanguage,
	idGlossaryTerm)
{
	var ajax = new Ajax();
	var xml = ajax.getData("/glossaryTerm.xml?cdApplication=" + cdApplication + "&cdLanguage=" + cdLanguage + "&idGlossaryTerm=" + idGlossaryTerm);
	var xmlDoc = parseXML(xml);
	var root = xmlDoc.getElementsByTagName("GlossaryTerm")[0];
	var title = root.getAttribute("nmGlossaryTerm");
	var text = root.getAttribute("dsGlossaryTerm");
	
	var container = document.getElementById('gtContainer');
	var gtHdr = document.getElementById('gtHdr');
	var gtCnt = document.getElementById('gtCnt');
	gtHdr.innerHTML = title;
	gtCnt.innerHTML = text;
	
	container.style.left = mouseX + "px";
	container.style.top = mouseY+12 + "px";
	container.style.display = "block";
}

function closeGlossaryTerm()
{
	var container = document.getElementById('gtContainer');
	container.style.display = "none";	
}

function formatNumber(val, dec)
{
	var decSep = ".";
	var grpSep = ",";
	var mul = Math.pow(10, dec);	
	val = Math.round(val * mul) / mul;
	val = val.toString();
	x = val.split('.');
	x1 = x[0];

	if (x.length > 1 && dec > 0)
		x2 = decSep + x[1];
	else
		x2 = "";

	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1))
		x1 = x1.replace(rgx, '$1' + grpSep + '$2');

	return x1 + x2;
}

