/**
 * 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 = 'http://betar-illit.muni.il/';
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...');
}

/****************************************************************************************************
 * Methods & Examples                                                                               *
 *                                                                                                  *
 * Cookie.Read("cookie_name");                                                                      *
 * Cookie.Write("cookie_name", "cookie_value", [4]); //The brackets ([ ]) signifies optional value. *
 * Cookie.Remove("cookie_name");                                                                    *
 ****************************************************************************************************/
var Cookie = {
	//Read the cookie -
	// @param sName {type: string} The cookie name. [required]
	Read: function(sName){
		//Split all the cookies to a 'name=value' pair {return: array}.
		if(typeof sGetNames == "undefined" || sGetNames != document.cookie) sGetNames = document.cookie.split("; ");
		//Loop through every cookie from the recieved array.
		for(var i=0; i<sGetNames.length; i++){
			//If the the name matches, return the value of the cookie {return: string}.
			if((sGetNames[i].search(sName+"=") == 0)){
				return sGetNames[i].substring(sGetNames[i].search("=")+1, sGetNames[i].length);
			}
		}
		//return false, if match was not made.
		return false;
	},
	//Write the cookie -
	// @param sName {type: string} The cookie name. [required]
	// @param sValue {type: string} The cookie value. [required]
	// @param iDays {type: integer} The cookie lifespan in days. [optional]
	Write: function(sName, sValue, iDays){
		if(iDays){
			//Get the current date
			var dCurrent = new Date();
			//Set the date to the 'iDays' defined lifespan. {return: date object}
			dCurrent.setTime(dCurrent.getTime()+(iDays*24*60*60*1000));
			var sExp = "; expires="+dCurrent.toGMTString();
		}else sExp = ""; //If 'iDays' was not defined, do not set an expiry date
		//Concatenate the cookie.
		document.cookie = sName.concat("=", sValue, sExp, "; path=/");
	},
	//Remove the cookie -
	// @param sName {type: string} The cookie name. [required]
	Remove: function(sName){
		//Using the Cookie.Write method, set the cookie to expire yesterday.
		this.Write(sName, "", -1);
	}
};

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

	try{
		if(window.XMLHttpRequest){
			xmlHttp = new XMLHttpRequest();
		}else if(window.ActiveXObject){
			try{
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(e){
				try{
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){}
			}
		}

		if(xmlHttp){
			xmlHttp.onreadystatechange = function(){
				if(this.readyState==4 && this.status==200)
					handler();
			};

			xmlHttp.open(method, url, true);

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

			xmlHttp.send(postData);

			return xmlHttp;
		}
	}catch(e){
		alert(e.message);
	}

	return false;
}


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;
	}
}


// 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;
}


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 mailingList(){
	try{
		email = /^[a-z0-9\-]+(\.[a-z0-9\-]+)*(\+[a-z0-9\-]+)?(\.[a-z0-9\-]+)*?\@[a-z0-9]((\.|-)?[a-z0-9])*\.[a-z]+$/i;

		if(!$("mailingList_email").value){
			alert('חובה לציין כתובת דוא"ל');
			$("mailingList_email").focus();
			return false;
		}
		else if(!email.test($("mailingList_email").value)){
			alert('כתובת הדוא"ל אינה תקינה');
			$("mailingList_email").focus();
			return false;
		}

		return true;
	}catch(e){
		alert("אירעה שגיאה\n\n" + e.message);
	}

	return false;
}


function _search(){
	try{
		location.href = "/search/" + $("search").value;
	}catch(e){
		alert("אירעה שגיאה\n\n" + e.message);
	}

	return false;
}


var survey_vote_XMLHTTP = false;
var survey_vote_sId = false;
function survey_vote(sId, id){
	if(Cookie.Read("surveyVote_"+sId))
		return false;

	if(survey_vote_XMLHTTP){
		alert("נא המתן להשלמת הבחירה הקודמת");
		return false;
	}

	survey_vote_sId = sId;

	survey_vote_XMLHTTP = getXmlHttpSend(BASE_URL+"survey/vote/"+id, function(){
		try{
			var XMLDOC = survey_vote_XMLHTTP;
			var home_survey = $('home_survey').firstChild.nextSibling;
			var sumOfVotes=0, votes=[], ul="";

			if(XMLDOC.status != 200)
				throw {message: 'XMLHTTP.status = ' + XMLDOC.status};
			if(!XMLDOC.responseText)
				throw {message: 'XMLHTTP.responseText is NULL'};
			if(!(XMLDOC = XMLDOC.responseXML))
				throw {message: 'XMLDOC / XMLHTTP.responseXML is not XML Documnent'};

			if(XMLDOC.getElementsByTagName('ok')[0].firstChild.data != 1)
				throw {message: 'אירעה שגיאה, נסה שוב מאוחר יותר\nok=false'};
			else{
				try{
				//	Cookie.Write("surveyVote_"+survey_vote_sId, true, 90);

					XMLDOC = XMLDOC.getElementsByTagName('body')[0];
					sumOfVotes = XMLDOC.getElementsByTagName("sumOfVotes")[0].getAttribute("sum");
					votes = XMLDOC.getElementsByTagName("votes");

					home_survey.getElementsByTagName('div')[0].innerHTML = 'סה&quot;כ ' + sumOfVotes + ' הצבעות';
					for(i=0; i<votes.length; ++i)
						ul += '<li><div>' + Math.round(votes[i].getAttribute("votes")/(sumOfVotes/100)) + "%</div><div>" + votes[i].getAttribute("selectOption") + "</div></li>";
					home_survey.getElementsByTagName('ul')[0].innerHTML = ul;

				}catch(e){
					throw {message: 'הצבעת נקלטה, אך אירעה שגיאה בהצגת פרטי הסקר, יש לרענן את הדף על מנת להציג את תוצאות הסקר.\n'+e.message};
				}
			}
		}catch(e){
			alert(e.message);
		}

		survey_vote_XMLHTTP = false;
	});
}



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;
}
