/**
 * 3 code blocks: CONSTANTS, Specific Code, Generic Code
 * each section is separated by "/* -------------- [SECTION_NAME] -------------- *" + "/"
 * each block begins with the variables from this section and afterwards his classes and functions.
 **/


/* -------------- CONSTANTS -------------- */

//var BASE_URL = '/keilotYakov/';
var SHOW_TECHNICAL_ERROR_DETAILS = true;

/* -------------- Generic Code -------------- */

var d = document;

var ErrorHandler = function(msg,url,l)
{
	thisObj = this;
	this.errors = new Array();
	this.onError = new Array();

	this.addError = function(msg, url, line)
	{
		this.errors.push([msg, url, line]);
		thisObj.popAlert(msg, url, line);
	}

	this.popAlert = function(msg, url, line)
	{
		if(SHOW_TECHNICAL_ERROR_DETAILS)
		{
			alert(
				'Error occur.\n\
				\n\
				Error details:\n\
				Error: '+msg+'\n\
				URL: '+url+'\n\
				Line: '+l+'\n\
				\n\
				Click OK to continue.');
		}
		else
		{
			alert('Error occur');
		}

		if(thisObj.onError.length > 0)
		{
			for(x in thisObj.onError)
			{
				if(thisObj.onError[x])
					thisObj.onError[x]();
			}
		}
	}

	this.addEvent = function(eventFunction)
	{
		return thisObj.onError.push(eventFunction) - 1;
	}

	this.removeEvent = function(eventKey)
	{
		thisObj.onError[eventKey] = false;
	}
};

//onerror = ErrorHandler.addError;



function $(id)
{
	return d.getElementById(id);
}

function go(url)
{
	d.location.href = url;
}

function getStyle(element, style)
{
	if(document.defaultView && document.defaultView.getComputedStyle)
		return eval("d.defaultView.getComputedStyle(element, '')." + style);
	else if(element.currentStyle)
		return eval("element.currentStyle." + style);
}

function addEventsAction(element, event, action, useCapture)
{
	if(!action)
		action = function(){};

	if(element.addEventListener)
		element.addEventListener(event, action, useCapture);
	else if(element.attachEvent)
		element.attachEvent('on' + event, action);
	else
		alert('Error Occur...');
}

function form_checkbox_checkAll(form, check)
{
	if(form.nodeName.toLowerCase() != 'form')
	{
		form = form.form;

		while(form.nodeName.toLowerCase() != 'form')
			form = form.parentNode;
	}

	var inputs = form.getElementsByTagName('input');
	for(i=0; i<inputs.length; ++i)
	{
		if(inputs[i].type == 'checkbox')
			inputs[i].checked = check;
	}

	return false;
}

function get_html_translation_table(table, quote_style)
{
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
 
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
 
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38']  = '&amp;';
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

function htmlspecialchars(string, quote_style)
{
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
 
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function htmlspecialchars_decode(string, quote_style)
{
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki
    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
 
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }
 
    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';
 
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function encodeHebrewText(text)
{
	var letters = [
		'א',
		'ב',
		'ג',
		'ד',
		'ה',
		'ו',
		'ז',
		'ח',
		'ט',
		'י',
		'ך',
		'כ',
		'ל',
		'ם',
		'מ',
		'ן',
		'נ',
		'ס',
		'ע',
		'ף',
		'פ',
		'ץ',
		'צ',
		'ק',
		'ר',
		'ש',
		'ת'
	]

	var codes = [
		'%E0',
		'%E1',
		'%E2',
		'%E3',
		'%E4',
		'%E5',
		'%E6',
		'%E7',
		'%E8',
		'%E9',
		'%EA',
		'%EB',
		'%EC',
		'%ED',
		'%EE',
		'%EF',
		'%F0',
		'%F1',
		'%F2',
		'%F3',
		'%F4',
		'%F5',
		'%F6',
		'%F7',
		'%F8',
		'%F9',
		'%FA'
	]

	for(x in codes)
		text = eval('text.replace(/'+letters[x]+'/g, "'+codes[x]+'")');

	return text;
}

function convertNum(inputElement, integer, positive)
{
	var val = inputElement.value;

	if(!val) return;
	if(val=='-' && !positive) return;
	if(!integer && (val.substr(val.length-1)=='.' || val.substr(val.length-1)=='0')) return;
	if(isNaN(val = integer ? parseInt(val) : parseFloat(val))) val = '';
	if(positive && val<0) val = val-val*2;

	inputElement.value = val;
}

function getXmlHttpSend(url, handler, postData)
{
	var method = postData ? 'POST' : 'GET';

	var xmlHttp;

	if(navigator.userAgent.indexOf('Gecko') > 0)
	{
		xmlHttp = new XMLHttpRequest();
		xmlHttp.onload = handler;
		xmlHttp.onerror = function() {
				//alert("error occur '.__LINE__.'");
		}
	}
	else if(navigator.userAgent.indexOf('MSIE'))
	{
		var strName = 'Msxml2.XMLHTTP';

		if(navigator.appVersion.indexOf('MSIE 5.5'))
		{
			strName = 'Microsoft.XMLHTTP';
		}
		try
		{
			xmlHttp = new ActiveXObject(strName);
			xmlHttp.onreadystatechange = handler;
		}
		catch(e)
		{
			alert('Error. Scripting for ActiveX might be disabled');
		}
	}
	else
	{
		alert("This Action doesn't work in your Browser");
		return false;
	}

	xmlHttp.open(method, url, true);

	if(method == 'POST')
		xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	xmlHttp.send(postData);

	return xmlHttp;
}


function range(textObj, from, to)
{
	if(!textObj.value)
		return false;
	else if(!from){
		from = 0;
		to = textObj.value.length;
	}
	else if(from >= to)
		return false;

	if(textObj.setSelectionRange)
	{
		textObj.setSelectionRange(from, to);
	}
	else if(textObj.createTextRange)
	{
		var range = textObj.createTextRange();
		range.collapse(true);
		range.moveEnd('character', to);
		range.moveStart('character', from);
		range.select();
	}
}


function createElement(name, attr, val, text, _alert_)
{
	var element, i;

	if(!d.all)
	{
		element = d.createElement(name);

		if(attr)
		{
			for(i=0; i<attr.length; ++i)
			{
				if(attr[i].substr(0, 2) == 'on')
					eval('element.' + attr[i] + '=' + val[i]);
				else
					element.setAttribute(attr[i], val[i]);
			}
		}
	}
	else
	{
		if(name == 'input')
		{
			for(i=0; i<attr.length; ++i)
			{
				if(attr[i] == 'name')
				{
					element = d.createElement('<input name="' + val[i] + '">');
					attr.splice(i, 1);
					attr.splice(i, 1);
					break;
				}
			}
		}
		else
		{
			element = d.createElement(name);
		}

		if(attr)
		{
			for(i=0; i<attr.length; ++i)
			{
				switch(attr[i])
				{
					case 'class':
						attr[i] = 'className';
						break;
					case 'for':
						attr[i] = 'htmlFor';
						break;
					case 'maxlength':
						attr[i] = 'maxLength';
						break;
					case 'colspan':
						attr[i] = 'colSpan';
						break;
					case 'style':
						continue;
						break;
					case 'name':
						//need to check for not input elements
						continue;
					case '':
						continue;
				}

				element.setAttribute(attr[i], val[i]);
/*				if(attr[i].substr(0,2) != 'on')
					eval('element.' + attr[i] + "='" + val[i] + "'");
//				else if(val[i].substr(0,11) != 'function(){')
//					eval('element.' + attr[i] + '=' + val[i]);
				else
					eval('element.' + attr[i] + '=function(){' + val[i] + '}');
-*/			}
		}
	}

	if(text)
		element.appendChild(d.createTextNode(text));

	return element;
}

function unique_id(id)
{
	var i, temp;

	if(!id)
		id = 'unique_id';

	temp = id;
	for(i=0; $(temp); ++i)
		temp = id + '__' + i;

	return temp;
}


/**
 * 
 **/

function __check_form()
{
	try{
		if(!$('un').value)
		{
			alert('חובה לציין שם משתמש');
			$('un').focus();
			return false;
		}
		else if(!$('pass').value)
		{
			alert('חובה לבחור סיסמה');
			$('pass').focus();
			return false;
		}
		else if(!$('fName').value && !$('lName').value)
		{
			alert('חובה לציין שם פרטי או שם משפחה');
			$('fName').focus();
			return false;
		}

		return true;
	}catch(e){
		alert('אירעה שגיאה. נא פנא לתמיכה הטכנית בצירוף הפרטים אותם נסית להוסיף');
		return false;
	}
}

function _checkAndRewriteForm()
{
	try
	{
		var actionAddress, formFields=[], theForm=$('clients_search_fName').form;

		if	(
			!$('clients_search_fName').value
			&& !$('clients_search_lName').value
			&& !$('clients_search_street').value
			&& !$('clients_search_city').value
			&& !$('clients_search_zip').value
			&& !$('clients_search_phone').value
			&& !$('clients_search_mobile').value
			)
		{
			alert('חובה לבחור לפחות בערך אחד לחיפוש. שם פרטי, משפחה, רחוב, עיר, מיקוד, טלפון או טלפון נייד.');
			return false;
		}


		actionAddress = new String('/');

		if($('clients_search_fName').value)
			actionAddress = actionAddress.concat('fName,' + encodeHebrewText($('clients_search_fName').value) + '/');

		if($('clients_search_lName').value)
			actionAddress = actionAddress.concat('lName,' + encodeHebrewText($('clients_search_lName').value) + '/');

		if($('clients_search_street').value)
			actionAddress = actionAddress.concat('street,' + encodeHebrewText($('clients_search_street').value) + '/');

		if($('clients_search_city').value)
			actionAddress = actionAddress.concat('city,' + encodeHebrewText($('clients_search_city').value) + '/');

		if($('clients_search_zip').value)
			actionAddress = actionAddress.concat('zip,' + $('clients_search_zip').value + '/');

		if($('clients_search_phone').value)
			actionAddress = actionAddress.concat('phone,' + $('clients_search_phone').value + '/');

		if($('clients_search_mobile').value)
			actionAddress = actionAddress.concat('mobile,' + $('clients_search_mobile').value + '/');

		actionAddress = actionAddress.concat('AndOrOperator,' + ($('clients_search_operatorAnd').checked ? 'and' : 'or') + '/');

		theForm.action += actionAddress;


		// disabled all inputs elements, in order to prevent from the browser to add the "?' character and field's value's in the address string
		formFields = theForm.getElementsByTagName('input');
		if(formFields.length)
		{
			for(x in formFields)
				formFields[x].disabled = true;
		}

		formFields = theForm.getElementsByTagName('select');
		if(formFields.length)
		{
			for(x in formFields)
				formFields[x].disabled = true;
		}

		formFields = theForm.getElementsByTagName('textarea');
		if(formFields.length)
		{
			for(x in formFields)
				formFields[x].disabled = true;
		}



		return true;
	}catch(e){
		alert('אירעה שגיאה, מומלץ לרענן את הדף באמצעות ctrl+f5\n\nמידע טכני:\n' + e);
		return false;
	}
}


var completionText_XMLHTTP;
var completionText_clientName_obj;
var completionText_clientNamesList_obj;
function completionUserDeatils(e)
{
	try{
		e = e || window.event;

		if(!completionText_clientName_obj)
		{
			completionText_clientName_obj = $('orders_add_clientName');
			completionText_clientNamesList_obj = $('orders_add_clientNamesList');
		}

		//invalid user input; 46=DEL, 8=BACKSPACE, 37-40=Arrows
		if(completionText_clientName_obj.value=='' || e.keyCode==46 || e.keyCode==8 || (e.keyCode>36 && e.keyCode<41))
			return;

		completionText_XMLHTTP = getXmlHttpSend('/tovllajax/completionUserDeatils/name=' + completionText_clientName_obj.value, function(){
			if(completionText_XMLHTTP.status!=200 || !completionText_XMLHTTP.responseText)
				return false;
//alert('status: ' + completionText_XMLHTTP.status + "\n\n" + completionText_XMLHTTP.responseText);return
//alert(completionText_XMLHTTP + "\n\n" + completionText_XMLHTTP.responseText);
//return
			var clients = completionText_XMLHTTP.responseXML.getElementsByTagName('c');

			completionText_clientNamesList_obj.style.display = 'block';
			completionText_clientNamesList_obj.innerHTML = '';

			for(var i=0; i<clients.length; i++)
				completionText_clientNamesList_obj.innerHTML += '<div onclick="alert(' + clients[i].getAttribute('id') + ')">' + clients[i].getAttribute('lName') + ' ' + clients[i].getAttribute('fName') + '</div>';
		});
	}catch(e){
		alert(e);
	}
}


// chek if an object is an array or not.
// returns true if it is an array
function isArray(obj)
{
	if(!obj)
		return false;

	return (obj.constructor.toString().indexOf('Array') == -1)
		 ? false
			: true;
}

/**
 *
 * Variables:
 *		thisObj - internal reference
 *		(date - Global Date object)
 *		(selectedDate - the selected date)
 *		yearsPlusMinus - How many years to show in years list after in before this year
 *		monthNames - array that contain all name of month
 *		monthDays - array that contain how many days of each month
 *		input - reference to input object. if it set, the value of this object is set to the selected date (i.e. 30/03/2009) when the date is selected
 *		onSet - you can set this to a function that runs when the date is selected. if this function is returned a boolean false the selected date is canceled.
 *		onReset - you can set this to a function that runs when the date is reset by resetSelectedDate method. if this function is returned a boolean false the reset action is canceled.
 *
 * Methods:
 *		(newDate - intended for internal use)
 *		(show - internal function that create the html code of the calendar)
 *		pop - pop the calendar "window" [you must pass the Event object to the function, i.e. "objectName.pop(event)"]
 *		hide - hide the calendar "window"
 *		(setDate - intended for internal use)
 *		setFromStr - set the selected date from string in format d/m/yyyy or dd/mm/yyyy, i.e. "30/3/2009".
 *		(showMonth - for internal use)
 *		(showYear - for internal use)
 *		setTitle - set the title that shown in the head of calendar
 *		getTitle - get the title that shown in the head of calendar
 *		getSelectedDate - get the selected date in dd/mm/yyyy, dd/mm/yyyy, i.e. "30/3/2009" format or in number format (according to the returnInNumberFormat parameter)
 *		resetSelectedDate - set selected date to '';
 *
 *
 * Example 1:
 *	js code:
 *		var someVarName = new Calendar();
 *
 *	html code:
 *		<img src="objects/calendar.png" alt="calendar" onclick="someVarName.pop(event)" />
 *
 *
 * Example 2:
 *	js code:
 *		var date2close = new Calendar();
 *		date2close.input = $('orders_dateToSupply');
 *		date2close.setTitle('some Title');
 *
 *	html code:
 *		<img src="objects/calendar.png" alt="calendar" onclick="someVarName.pop(event)" />
 *
 *
 * Example 3:
 *	js code:
 *		var date2close = new Calendar();
 *		date2close.input = document.getElementById('closeDate');
 *		date2close.setTitle('תאריך סיום');
 *		date2close.onSet = function()
 *		{
 *			if(this.getSelectedDate(true) < this.newDate().getTime()) // Please care that "this" is work, if not, replace this in the object name like "date2close"
 *			{
 *				alert('לא ניתן לבחור תאריך המוקדם מהיום');
 *				return false;
 *			}	
 *		};
 *		date2close.setFromStr(document.getElementById('closeDate').value);
 *
 *	html code:
 *		<img src="objects/calendar.png" alt="calendar" onclick="someVarName.pop(event)" />
 **/
function Calendar(obj)
{
	var thisObj = this;

	if(!obj)
	{
		obj = createElement('div', ['class'], ['Calendar']);
		d.body.appendChild(obj);
	}

	this.obj = obj;
	obj.style.display = 'none';
	obj.style.position = 'absolute';

	this.date; // Global Date object
	this.selectedDate = 0;
	this.yearsPlusMinus = 10; // How many years to show in years list after in before this year
	this.monthNames = ['ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'];
	this.monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

	this.input = false;
	this.onSet = false;


	// Create an head title
	this.obj.appendChild(createElement('div', ['class'], ['CalendarHead']));


	// Return Date object that set hours, minutes, seconds and milliseconds to 0
	this.newDate = function()
	{
		var date = new Date;
		date.setHours(0);
		date.setMinutes(0);
		date.setSeconds(0);
		date.setMilliseconds(0);

		return date;
	}

	this.show = function(M, Y)
	{
		var date = this.date;

		date.setDate(1);
		if((M!==undefined) && (M!==false)) date.setMonth(M-1);
		if((Y!==undefined) && (Y!==false)) date.setYear(Y);

		var today = this.newDate().getTime();
		var month = date.getMonth();
		var year = date.getFullYear();
		var i, day, dayPtr, table, tr, td, div, temp, option;


		// Delete previous display
		while(this.obj.childNodes.length > 1)
			this.obj.removeChild(this.obj.lastChild);

		table = createElement('div', ['class'], ['year_month_list']);
		this.obj.appendChild(table);


		// Build the month list area
		div = createElement('div', ['class'], ['month_list']);
		table.appendChild(div);

		if(month != 0){
			if(d.all){
				temp = createElement('span', ['class', 'onclick'], ['button', function(){thisObj.showMonth(this.nextSibling.value*1-1);}], '«');
			}else{
				temp = createElement('span', ['class'], ['button'], '«');
				temp.onclick = function(){thisObj.showMonth(this.nextSibling.value*1-1);};
			}

			div.appendChild(temp);
		}

		temp = d.createElement('select');
		temp.onchange = function(){thisObj.showMonth(this.value);};
		div.appendChild(temp);

		for(i=0; i<12; i++)
		{
			option = createElement('option', ['value'], [i+1], this.monthNames[i]);
			temp.appendChild(option);

			if(i==month)
				option.setAttribute('selected', 'selected');
		}

		if(month != 11){
			if(d.all){
				temp = createElement('span', ['class', 'onclick'], ['button', function(){thisObj.showMonth(this.previousSibling.value*1+1);}], '»');
			}else{
				temp = createElement('span', ['class'], ['button'], '»');
				temp.onclick = function(){thisObj.showMonth(this.previousSibling.value*1+1);};
			}

			div.appendChild(temp);
		}


		// Build the year list area
		div = createElement('div', ['class'], ['year_list']);
		table.appendChild(div);

		temp = d.createElement('span');
		temp.className = 'button';
		temp.onclick = function(){thisObj.showYear(this.nextSibling.value*1-1);};
		temp.appendChild(d.createTextNode('«'));
		div.appendChild(temp);

		temp = d.createElement('select');
		temp.onchange = function(){thisObj.showYear(this.value);};
		div.appendChild(temp);

		for(i=year-this.yearsPlusMinus; i<year+this.yearsPlusMinus; i++)
		{
			if(i==year)
				temp.appendChild(createElement('option', ['value', 'selected'], [i, 'selected'], i));
			else
				temp.appendChild(createElement('option', ['value'], [i], i));
		}

		if(year != 1)
		{
			temp = d.createElement('span');
			temp.className = 'button';
			temp.onclick = function(){thisObj.showYear(this.previousSibling.value*1+1);};
			temp.appendChild(d.createTextNode('»'));
			div.appendChild(temp);
		}


		// Build the title of week days
		table = d.createElement('table');
		table.setAttribute('cellspacing', 5);
		this.obj.appendChild(table);

		temp = d.createElement('tbody');
		table.appendChild(temp);
		table = temp;

		tr = d.createElement('tr');
		table.appendChild(tr);
		td = createElement('th', [], [], "א'");
		tr.appendChild(td);
		td = createElement('th', [], [], "ב'");
		tr.appendChild(td);
		td = createElement('th', [], [], "ג'");
		tr.appendChild(td);
		td = createElement('th', [], [], "ד'");
		tr.appendChild(td);
		td = createElement('th', [], [], "ה'");
		tr.appendChild(td);
		td = createElement('th', [], [], "ו'");
		tr.appendChild(td);
		td = createElement('th', [], [], "ז'");
		tr.appendChild(td);


		// Build the month days cells
		date.setDate(1);
		day = date.getDay();

		tr = d.createElement('tr');
		table.appendChild(tr);
		for(dayPtr=0; dayPtr<day; dayPtr++)
		{
			td = createElement('td', ['class'], ['null']);
			tr.appendChild(td);
		}

		for(i=1; i<this.monthDays[month]+1; i++,dayPtr++)
		{
			if(dayPtr%7 == 0)
			{
				tr = d.createElement('tr');
				table.appendChild(tr);
			}

			temp = date.setDate(i);
			td = d.createElement('td');
			td.className = (temp==this.selectedDate ? 'select' : (temp==today ? 'today' : ''));
			td.onclick = function(){thisObj.setDate(this.innerHTML*1)};
			td.appendChild(d.createTextNode(i));
			tr.appendChild(td)
		}
	}

	this.pop = function(event)
	{
		if(this.obj.style.display == 'block')
		{
			this.hide();
		}
		else
		{
			// Reset thh display to the selected date or to the current date
			if(this.selectedDate)
				this.date.setTime(this.selectedDate);
			else
				this.date.setTime(this.newDate().getTime());

			this.obj.style.display = 'block';
			this.obj.style.top = (event.clientY + d.body.scrollTop + d.documentElement.scrollTop + 10) + 'px';
			this.obj.style.left = (event.clientX + d.body.scrollLeft + d.documentElement.scrollLeft + 10) + 'px';

			this.show();
		}
	}

	this.hide = function(day)
	{
		this.obj.style.display = 'none';
	}

	this.setDate = function(day, month, fullYear)
	{
		if(!day) return false;

		var previousSelectedDate = this.selectedDate;
		this.date.setDate(day);
		if(month) this.date.setMonth(month-1);
		if(fullYear) this.date.setFullYear(fullYear);
		this.selectedDate = this.date.getTime();

		if(this.onSet && this.onSet()===false)
		{
			this.selectedDate = previousSelectedDate;
			return false;
		}

		if(this.input)
			this.input.value = this.getSelectedDate();

		this.hide();
		
		return true;
	}

	this.setFromStr = function(str)
	{
		var datePattern = new RegExp(/^(\d{1,2}\D){2}\d{1,4}$/);
		if(!datePattern.test(str))
			return false;

		str = str.split('/');

		if(str[0]>31 || str[1]>12)
			return false;

		if(str[2] < 10)
			str[2] = '200'+str[2];
		else if(str[2] < 100)
			str[2] = '20'+str[2];
		else if(str[2] < 1000)
			str[2] = '2'+str[2];

		return this.setDate(str[0], str[1], str[2]);
	}

	this.showMonth = function(month)
	{
		this.show(month);
	}

	this.showYear = function(year)
	{
		this.show(false, year);
	}

	this.setTitle = function(title)
	{
		this.obj.firstChild.innerHTML = title;
	}

	this.getTitle = function()
	{
		return this.obj.firstChild.innerHTML;
	}

	// Return the selected date in dd/mm/yyyy format or in number format (according to the returnInNumberFormat parameter)
	this.getSelectedDate = function(returnInNumberFormat)
	{
		if(returnInNumberFormat)
			return this.selectedDate;

		var date = new Date();
		var temp = '';

		date.setTime(this.selectedDate);
		return temp.concat(date.getDate(), '/', (date.getMonth()+1) + '/', date.getFullYear());
	}

	// Return the selected date in dd/mm/yyyy format or in number format (according to the returnInNumberFormat parameter)
	this.resetSelectedDate = function()
	{
		var previousSelectedDate = this.selectedDate;
		this.selectedDate = '';

		if(this.onReset && this.onReset()===false)
		{
			this.selectedDate = previousSelectedDate;
			return false;
		}

		if(this.input)
			this.input.value = '';

		return true;
	}


	this.date = this.newDate();
}

function Scroller(object, objectWrapper, direction, tempo)
{
	var thisObj 		= this;
	this.xCoordinate 	= 0;
	this.yCoordinate 	= 0;
	this.offset			= 0;
	this.tempo			= tempo;
	this.strDirection	= direction;
	this.scrollerStatus	= true;
	this.htmlObj		= object;
	this.htmlObjWrapper	= objectWrapper;
	this.interval;

	this.htmlObj.style.position = "relative";
	this.htmlObjWrapper.style.position = "relative"; // needed to fix an overflow bug in IE7
	this.htmlObjWrapper.style.overflow = "hidden";

	this.move = function()
	{
		if(this.scrollerStatus)
		{
			switch(this.strDirection)
			{
				case 'u':	// moving up
					this.htmlObj.style.top = --this.yCoordinate + "px";

					if ((0-this.yCoordinate) > this.offset)
						this.yCoordinate = this.offset;

					break;
				case 'd':	// moving down
					this.yCoordinate++;
					this.htmlObj.style.top = this.yCoordinate+"px";

					if (this.yCoordinate > this.offset)
						this.yCoordinate = -this.offset;

					break;
				case 'r':	// moving right
					this.xCoordinate++;
					this.htmlObj.style.left = this.xCoordinate+"px";

					if (this.xCoordinate > this.offset)
						this.xCoordinate = -this.offset;

					break;
				case 'l':	// moving left
					this.xCoordinate--;
					this.htmlObj.style.left = this.xCoordinate+"px";

					if ((0-this.xCoordinate) > this.offset)
						this.xCoordinate = this.offset;
			}
		}
	}

	this.changeDir = function(dir)
	{
		thisObj.strDirection = dir;

		if(thisObj.scrollerStatus)
		{
			thisObj.stopScroll();
			thisObj.startScroll();
		}
		else
		{
			thisObj.startScroll();
			thisObj.stopScroll();
		}
	}

	this.start = function()
	{
		thisObj.offset = (thisObj.strDirection=='u' || thisObj.strDirection=='d')
			? thisObj.htmlObjWrapper.offsetHeight
				: thisObj.htmlObjWrapper.offsetWidth; // need to check this line code, maybe it's not "width"

		addEventsAction(thisObj.htmlObj, 'mouseover', function(){
			thisObj.interval = clearInterval(thisObj.interval);
		});

		addEventsAction(thisObj.htmlObj, 'mouseout', function(){
			thisObj.interval = setInterval(function() { thisObj.move(); }, thisObj.tempo);
		});

		thisObj.interval = setInterval(function() { thisObj.move(); }, thisObj.tempo);
	}

	this.stop = function()
	{
		thisObj.interval = clearInterval(thisObj.interval);
		//addEventsAction(thisObj.htmlObj, 'mouseout', function(){});
		//addEventsAction(thisObj.htmlObj, 'mouseover', function(){});
		thisObj.htmlObj.onmouseout = function(){};
		thisObj.htmlObj.onmouseover = function(){};
	}
}
/*
var sideFlashes = new Scroller($("sideFlashesMarquee"), $("sideFlashesMarqueeWrap"), 'u', 100);
sideFlashes.start()
sideFlashes.stop()
sideFlashes.changeDir('l')
*/
function disableForum()
{
}


/* -------------- Specific Code -------------- */



/**
 * User interface
 **/
/*
ErrorHandler.addEvent(function(){
	GlobalMessage.writeError('אירעה שגיאה, נסה שנית מאוחר יותר.\nנא פנה לתמיכה הטכנית במידה והבעיה נמשכת');
});
*/
GlobalMessage = {
	init: false,
	globalMessage: null,
	successMessage: null,
	errorMessage: null,

	load: function(){
		GlobalMessage.globalMessage = $('GlobalMessage');
		GlobalMessage.successMessage = $('SuccessMessage');
		GlobalMessage.errorMessage = $('ErrorMessage');
		GlobalMessage.init = true;
	},



	writeGloabl: function(msg, duration, add2exists){
		if(!GlobalMessage.init) GlobalMessage.load();

		if(add2exists)
			msg = GlobalMessage.globalMessage.innerHTML + '\n<br >\n' + msg;

		GlobalMessage.globalMessage.innerHTML = msg;
		GlobalMessage.globalMessage.style.display = 'block';
	},

	cleanGloabl: function(){
		if(!GlobalMessage.init) GlobalMessage.load();

		GlobalMessage.globalMessage.innerHTML = '';
	},

	hideGloabl: function(){
		if(!GlobalMessage.init) GlobalMessage.load();

		GlobalMessage.globalMessage.style.display = 'none';
	},

	// Clean the content message and hide the element
	delGloabl: function(){
		GlobalMessage.cleanGloabl();
		GlobalMessage.hideGloabl();
	},



	writeSuccess: function(msg, duration, add2exists){
		if(!GlobalMessage.init) GlobalMessage.load();

		if(add2exists)
			msg = GlobalMessage.globalMessage.innerHTML + '\n<br >\n' + msg;

		GlobalMessage.successMessage.innerHTML = msg;
		GlobalMessage.successMessage.style.display = 'block';
	},

	cleanSuccess: function(){
		if(!GlobalMessage.init) GlobalMessage.load();

		GlobalMessage.successMessage.innerHTML = '';
	},

	hideSuccess: function(){
		if(!GlobalMessage.init) GlobalMessage.load();

		GlobalMessage.successMessage.style.display = 'none';
	},

	// Clean the content message and hide the element
	delSuccess: function(){
		GlobalMessage.cleanSuccess();
		GlobalMessage.hideSuccess();
	},



	writeError: function(msg, duration, add2exists){
		if(!GlobalMessage.init) GlobalMessage.load();

		if(add2exists)
			msg = GlobalMessage.globalMessage.innerHTML + '\n<br >\n' + msg;

		GlobalMessage.errorMessage.innerHTML = msg;
		GlobalMessage.errorMessage.style.display = 'block';
	},

	cleanError: function(){
		if(!GlobalMessage.init) GlobalMessage.load();

		GlobalMessage.errorMessage.innerHTML = '';
	},

	hideError: function(){
		if(!GlobalMessage.init) GlobalMessage.load();

		GlobalMessage.errorMessage.style.display = 'none';
	},

	// Clean the content message and hide the element
	delError: function(){
		GlobalMessage.cleanError();
		GlobalMessage.hideError();
	}
}



/**
 * 
 **/


function add2bookmark(url, title)
{
	if(window.sidebar){ // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
	}else if(window.external){ // IE Favorite
		window.external.AddFavorite(url, title);
	}else if(window.opera && window.print){ // Opera Hotlist
		return true;
	}
}


onerror = function(msg,url,l)
{
	txt = "There was an error on this page.\n\n";
	txt += "Error: " + msg + "\n";
	txt += "URL: " + url + "\n";
	txt += "Line: " + l + "\n\n";
	txt += "Click OK to continue.\n\n";

	alert(txt);

	return true;
}
