$(document).ready(function(){
	a_co_il.popup_height = parseInt($('#popup').css('top').replace('px', ''));

	// jquery sortable
	var banner_pos;

	set_banner_pos();
	$("#main_subjects").sortable({
		handle : 'div.dragger',
		placeholder: "ui-state-highlight gray_bright",
		items: 'li.group',
		change: function (event, ui) {
			$(banner_pos).each( function() {
				var cur_index = $(this.obj).prevAll("li.group:not(.ui-sortable-helper), li.ui-state-highlight").length;
				if (cur_index > this.index){
					$(this.obj).after($(this.obj).prevAll("li.group:not(.ui-sortable-helper), li.ui-state-highlight").eq(cur_index-this.index).nextUntil(".banner").remove());
				}
				else if (cur_index < this.index){
					$(this.obj).before($(this.obj).nextAll("li.group:not(.ui-sortable-helper), li.ui-state-highlight").eq(this.index-cur_index).prevUntil(".banner").remove());
				}
			});
		},
		update : function(){
			updateSortCookie();
		}
	});
	$("#main_subjects").disableSelection();
	
	var sorting_cookie_name = PAGE + '_sort_' + CATEGORY;
	if (PAGE == 'apps'){
		// this data is used in the apps page
		var CC = a_co_il.readCookie('cc');
		var PRICE = a_co_il.readCookie('paid') ? 'paid' : 'free';
	}

	$('#sort .option').disableSelection();
	if (PAGE == 'web') {
		$('#abc').click(function () { sortRows('alphabet'); updateSortCookie(); } );
		$('#popular').click(function () { sortRows('popularity'); } );
	} else if(PAGE =='apps') {
		$('#popular_il').click(function () {
			a_co_il.createCookie('cc', 'il');
			a_co_il.createCookie('paid', '1');
			$('#sort .option').removeClass('bold');
			$(this).addClass('bold');
			sortRows('popularity');
		});
		$('#popular_il_free').click(function () {
			a_co_il.createCookie('cc', 'il');
			a_co_il.eraseCookie('paid');
			$('#sort .option').removeClass('bold');
			$(this).addClass('bold');
			sortRows('popularity');
		});
		$('#popular_us').click(function () {
			a_co_il.createCookie('cc', 'us');
			a_co_il.createCookie('paid', '1');
			$('#sort .option').removeClass('bold');
			$(this).addClass('bold');
			sortRows('popularity');
		});
		$('#popular_us_free').click(function () {
			a_co_il.createCookie('cc', 'us');
			a_co_il.eraseCookie('paid', '1');
			$('#sort .option').removeClass('bold');
			$(this).addClass('bold');
			sortRows('popularity');
		});
	}

	// corrent categories return false on click
	$('#nav ul#categories li.current a').click(function(){
		return false;
	});
	
	// grabbing cursor
	if(BrowserDetect.browser == 'Firefox'){
		$('ul.websites div.dragger').mouseup(function(){
			$('ul.websites div.dragger').css('cursor', '-moz-grab');
		});

		$('ul.websites div.dragger').mousedown(function(){
			$('ul.websites div.dragger').css('cursor', '-moz-grabbing');
		});
	}
	
	// set as homepage
	$('.set_as_homepage').click(function(){
		var title = 'A אינדקס אתרים';
		var url = window.location.href;
		
		if (BrowserDetect.browser == 'Explorer'){
			this.style.behavior = 'url(#default#homepage)';
			this.setHomePage(url);
		}
		else if (BrowserDetect.browser == 'Firefox'){
			showPopupMessage('גרור את הקישור של <a href="'+ BASE_URL +'" title="a.co.il">a.co.il</a> ל-<a href="' + BASE_URL + '"><img src="' + BASE_URL + 'images/ui/popup/ff-homepage.png" class="inline_icon ff-homepage" /></a> שבחלקו העליון של הדפדפן');
		}
		else if (BrowserDetect.browser == 'Chrome') {
			showPopupMessage('לחץ על <img src="' + BASE_URL + 'images/ui/popup/chrome-settings.png" class="inline_icon" />, בחר באפשרויות > דף הבית > בחר "פתח דף זה" ורשום a.co.il.');
		}
		else if (BrowserDetect.browser == 'Safari') {
			showPopupMessage('לחץ בדפדפן על <img src="' + BASE_URL + 'images/ui/popup/safari-settings.png" class="inline_icon" />, בחר Preferences, גש ללשונית General, לחץ על כפתור Set&#160;to&#160;Current&#160;Page והקלק OK');
		}
		else if (BrowserDetect.browser == 'Opera'){
			showPopupMessage('הקש Ctrl+12 במקלדת, גש ללשונית General, לחץ על כפתור Use&#160;current והקלק OK');
		}
		return false;
	});

	// add to bookmark
	$('.add_to_fav').click(function(){
		var title = 'A אינדקס אתרים'; 
		var url = window.location.href;
		
		if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url, "");
		}
		else if (navigator.appName == 'Microsoft Internet Explorer'){ // IE Favorite
			window.external.AddFavorite(url, title);
		}
		else { // chrome / opera
			var popup_message;
			if (/mac/i.test(navigator.platform)){ // mac
				popup_message = 'Command+D';
			}
			else { // win & others
				popup_message = 'Ctrl+D';
			}
			$('popup_message_text').html(':השתמש בצירוף המקשים ' + popup_message);
			
			showPopupMessage('על מנת לשמור את האתר למועדפים<br />לחץ על <img src="' + BASE_URL + 'images/ui/popup/fav_icon_chrome.png" class="fav_icon_chrome" /> בחלק העליון של הדפדפן');
		}
        return false;
	});

	// google search focus / blur / submit / +keydown user might press ESC and reset the value of the input + stays focus)
	$('form.google_search input.query').focus(function(){
		if($(this).val() == SEARCH_FIELD_WORD){
			$(this).val('');
		}
	});
	$('form.google_search input.query').blur(function(){
		if($(this).val() == ''){
			$(this).val(SEARCH_FIELD_WORD);
		}
	});
	$('form.google_search input.query').keydown(function(e){
		if (e.which == 27){ // user pressed esc
			$(this).blur();
			return false;
		}
	});
	$('form.google_search').submit(function() {
		if ($(this).find('input.query').val() == SEARCH_FIELD_WORD){
			return false;
		} else {
			google_search_helper($(this).find('input.query').val(), $(this).find('input[name=cx]').val());
		}
	});

	// get radio stations from the radio controller and populate the available radios in our nice list
	$.getJSON(BASE_URL + 'radio.php?ajax', function(data){
		$('#radio select').html(data['radio_stations']);
	});

	// activate a new radio popup window when selecting a station
	$('#radio select').change( function(){
		var radio_url = $('#radio select option:selected').val();
		if (radio_url != '') {
			window.open(BASE_URL + 'radio.php?radio_url=' + encodeURIComponent(radio_url), 'a_co_il_radio', 'width=300,height=70');
		}
	});
	
	// onclick site link (index.php) - add to site history
	$('ul#main_subjects a.webs').live('click', function(){
		var href = $(this).attr('href');
		var title = $(this).attr('title');

		var classes = $(this).parent('li').attr('class');
		var regex;

		// extract link column number
		regex = /column_([0-9])/;
		matches = regex.exec(classes);
		var column_id = matches[1];

		// extract link category
		regex = /cat_([a-zA-Z0-9-_]+)/;
		matches = regex.exec(classes);
		var category = matches[1];

		// create/update the cookie
		var to_add = { 
					   "href":  encodeURIComponent(href),
					   "category": encodeURIComponent(category),
					   "column_id": encodeURIComponent(column_id),
					   "title": encodeURIComponent(title)
					 };

		var history = a_co_il.readCookie('sites_history');
		try {
			if (!history) throw 'No history object';
			history = $.secureEvalJSON(history);
		} catch( e ) {
			history = {};
		}

		if (!history.links) {
			history.links = [];
		}

        // make sure we don't duplicate an href
        var href_list = [];
        for (x in history.links) {
            href_list.push(history.links[x].href);
        }
        if ($.inArray(to_add.href, href_list) == -1) {
            // not found, add it
            history.links.push(to_add);

            // manipulate some dom
            $('#history ul.slots li').first().before('<li class="cat_' + category + ' column_' + column_id + '"><a href="' + href + '" title="' + title + '"></a></li>');
            $('#history ul.slots li').last().remove();
        }

		// limit number of sites history
		while (history.links.length > MAX_SITE_HISTORY) history.links.shift(); // in case we got more than MAX entries for some reason

		// history object is ready, build JSON for cookie
		var json = $.toJSON(history)
		a_co_il.createCookie('sites_history', json, 30);


	});
		
	// onclick app (app.php) - open popup window
	$('ul#main_subjects').delegate('a.apps', 'click', function(){
		// handle content
		var title = $(this).attr('title');

		// TODO add loading gif
		$('#popup h1').text('loading...');
		$('#popup .info img').attr('src', '').attr('alt', '');
		$('#popup .info .description').text('');
		$('#popup .qr_download img').attr('src', '');

		// get the data
		if (PAGE == 'apps') {
			var CC = a_co_il.readCookie('cc');
			if (!CC) CC = 'il';
			var PRICE = a_co_il.readCookie('paid') ? 'paid' : 'free';
			var CATEGORY_APPS_DATA = CATEGORY + '_' + CC + '_' + PRICE;
		} else {
			var CATEGORY_APPS_DATA = CATEGORY;
		}
		$.getJSON(BASE_URL + 'appsdata.php', { c: encodeURIComponent(CATEGORY_APPS_DATA), w: encodeURIComponent(title) }, function(data) {
			var TITLE_MAX_LENGTH = 30;
			if (title.length > TITLE_MAX_LENGTH) title = title.substring(0, TITLE_MAX_LENGTH - 3) + '...';

			$('#popup h1').filter(':first').text(title);
			$('#popup .info img').attr('alt', title).attr('src', data['big_img']);
			$('#popup .info .description').html(data['description']);
			$('#popup .sms_download .link a').attr('href', a_co_il.url_to(data['href'])).text(data['href']);

			setTimeout(function(){ // needed to wait a bit for some reason on firefox
				$('#popup .info .description').scrollTop(0);
			}, 0);

			// qr image stuff
			$.get(BASE_URL + 'url_md5.php', {q : encodeURIComponent(data['href'])}, function(data) {
				$('#popup .qr_download img').attr('src', BASE_URL + 'cache/qr/' + data);
			});

		});

		showPopupApp();
		return false;
	});

    var row_group_orig_background = $('#mainContent ul li.group').first().css('background');
    $('#mainContent ul li.group').hover(function() {
        $(this).css('background', 'url(' + BASE_URL + 'images/ui/frame_gray_hover.png)');
    }, function()
    {
        $(this).css('background', row_group_orig_background);
    });
	
	// contact us popup
	$('a#contact_us_link').click(function(e){
		showPopupContact();
		e.preventDefault();
		return false;
	});

	// close popup
	$('#opacity_curtain, #popup .x_btn2, #popup .close').click(function(){
		$('#opacity_curtain, #popup').hide();
	});
	
	// ajax updates
	// clearing all site history list and cookie
	$('#delete_history').click(function(){
		a_co_il.eraseCookie('sites_history');

		// clear list
		$('#history ul.slots li').text('').attr('class', '');
	});

	// get news from google or wherever
	var params = null;
	if (CATEGORY == 'business') params = { 'section' : 'business' };
	if (CATEGORY == 'students') params = { 'section' : 'students' };
	if (CATEGORY == 'sports') params = { 'section' : 'sports' };
	if (PAGE == 'apps') params = { 'section' : 'apps' };
	$.getJSON(BASE_URL + 'news.php', params, function(data){
		var news = '';
		for (x in data.items){
			var item = data.items[x];

            // set time text
            var d = new Date(item.pubDate);

            var year = (d.getFullYear()).toString();
            var date = (d.getDate()).toString();
            var month = (d.getMonth()+1).toString();
            if (d.getMonth()+1 < 10) month = '0' + month;
            var hours = d.getHours();
            if (d.getHours() < 10) hours = '0' + hours;
            var minutes = d.getMinutes();
            if (d.getMinutes() < 10) minutes = '0' + minutes;

            var time_text = hours + ':' + minutes + ', ' + date + '.' + month + '.' + year;
            time_text = '<span dir="ltr">' + time_text + '</span>';

			// we remove the " - news_source" text and put it OUTSIDE the <a>
			item.title = item.title.replace(/- ?([^-]*)$/, '</a><span> - $1</span>').replace('&apos;', '&#039');
			news = news + '<div>' + time_text + ' <a href="' + item.link + '">' + item.title + '</div>';
		}

		$('#news .marquee .inner').html(news);
		$('#news .marquee').marquee();
		
		setTimeout( function(){
			$('.marquee').css('visibility', 'visible')
		} , 100 );
	});
	
	// get weather
	update_weather();

	$('#weather .change_city').click(function(){
		$('#weather .cities').slideDown('fast').mouseenter(function(){
			// mouse enters, remove document click
			$('body').unbind('click');
		}).mouseleave(function (){
			// mouse leaves, set document click again
			$('body').click( function() {
				$('#weather .cities').hide();
			});
		});
	});

	$('#weather').delegate('.cities li' ,'click', function(){
		
		a_co_il.createCookie('weather_city', $(this).children('li.city_data .english').text(), 30);

		$('#weather .city').first().text( $(this).children('li.city_data .hebrew').text() );
		$('#weather .min').first().text( $(this).children('li.city_data .min').text());
		$('#weather .max').first().text( $(this).children('li.city_data .max').text());

		update_weather_condition();

		$('#weather .cities').hide();
	});

	// get currencies
	$.getJSON(BASE_URL + 'currency.php', { 'get_currency': '1' }, function(data) {
		if (!data) return;

		// build HTML to output
		var output = '';
		output = output + '<a href="' + a_co_il.url_to('http://www.bankisrael.gov.il/heb.shearim/index.php') + '">€' + data.EUR.rate;
		if (data.EUR.change > 0) output = output + '<span class="green">&uarr;</span>';
		else output = output + '<span class="red">&darr;</span>';
		output = output + '</a>';

		output = output + '&nbsp;';

		output = output + '<a href="' + a_co_il.url_to('http://www.bankisrael.gov.il/heb.shearim/index.php') + '">$' + data.USD.rate;
		if (data.USD.change > 0) output = output + '<span class="green">&uarr;</span>';
		else output = output + '<span class="red">&darr;</span>';
		output = output + '</a>';

		// html ready
		$('#header .dollar_rate').html(output);
	});

	// contact form
	$("form#contact_us").submit(function(e){
		if (!contact_validate()) return false;

		$("#popup").hide();

		$.post(
			BASE_URL + "contactussend.php",
			{
				"name": $("#contact_name").val(),
				"email": $("#contact_email").val(),
				"phone1": $("#contact_phone1").val(),
				"phone2": $("#contact_phone2").val(),
				"subject": {"eng": $("#contact_subject").val(), "heb": $("#contact_subject option:selected").text()},
				"message": $("#contact_message").val()
			},
			function(data){
				if (!data) return;

				var message = '';
				if (data == 'success'){
					message = 'נשלח בהצלחה!';

					// clear form fields
					$('#contact_us *:not(input#contact_submit)').val('');

				} else {
					// an error has occured
					if (data.hebrew_error){
						// only one error
						message = data.hebrew_error
					}
				}
                // show message if we have something to show
                if (message) showPopupMessage(message);

				// init form errors
				$('form#contact_us *').removeClass('error');
				$('form#contact_us .error_message').hide();
			},
			"json"
		);

		e.preventDefault();
		return false;
	});

	// handle position of popup window by scroll
	$(window).scroll(function(){
		$('#popup').css('top', $(window).scrollTop() + a_co_il.popup_height);
	});

    // banner loading hack
    $('div#hidden_banners').removeClass('hide').children('div.banner').each(function() // get all hidden banners loaded before the </body> tag
    //$('div#hidden_banners div.banner').each(function() // get all hidden banners loaded before the </body> tag
    {
		var offset_elem_id = $(this).attr('id').replace('_hidden', '_offset'); // get id of offset element
		var position = $("#" + offset_elem_id).offset(); // get the offset

		if (position)
		{
			// Show the banner directly on the placeholder
			$(this).css({
				"position": "absolute",
				"left": position.left + "px",
				"top":  position.top  + "px"
			});
		}
    });

    $('#categories li.general a').click(function() {
        // reset the web category/section
        a_co_il.eraseCookie('web_section');
    });

    $('#categories li.iphone a').click(function() {
        // reset the apps category/section
        a_co_il.eraseCookie('apps_section');
    });

	function set_banner_pos(){
		banner_pos = [];
		$("#main_subjects li.banner").each( function() {
			banner_pos.push( { index:$(this).prevAll("li.group").length, obj:this } );
		});
	}
	function updateSortCookie(){
	/**
	 *	Call it when you want to set cookie that 'remembers' the current
	 *	position of the subjects rows.
	 */
		// get current web sort
		var current_order = [];
		var regex = /row_([a-zA-Z0-9-_]+)/; // for extracting row identifier (news, sports, news2, etc)

		$('#main_subjects li:not(li[class^=column], li.banner)').each(function(){
			var classes = $(this).attr('class');
			var matches = regex.exec(classes);
			var row = matches[1];

			current_order.push(row);
		});

		//set cookie
		a_co_il.createCookie(sorting_cookie_name, encodeURIComponent(current_order.join(',')), 30);
	}
	function sortRows(method){ // auto-sort functions (i.e. by name/popularity)
		// ask user that already changed the order of subjects whether to continue.
		if (PAGE != 'apps') {
			var sort_cookie = a_co_il.readCookie(sorting_cookie_name); // if cookie is present, the user changed the order of items
			if (sort_cookie && !confirm('השינויים שביצעת בסדר הנושאים יימחקו. האם ברצונך להמשיך?'))
			{
				return;
			}
		}
		var elements_to_sort = $('#main_subjects li:not(li[class^=column], li.banner)');
		switch (method)
		{
		case 'alphabet':
			function comparator(a, b)
			{
				// h2 has the hebrew title
				return $(a).find('h2').text() > $(b).find('h2').text() ? 1 : -1;
			}
			elements_to_sort.sortElements(comparator);

			break;

		case 'popularity':
			a_co_il.eraseCookie(sorting_cookie_name);

            URL_PAGE = PAGE + '/';
            if (URL_PAGE == 'web/') URL_PAGE = '';
			$.getJSON(BASE_URL +  URL_PAGE + CATEGORY, { ajax: 1 }, function(data) {
				if (!data) return;

				$(data.main_subjects_ajax).first().children().filter('li:not(li[class^=column], li.banner)').each (function (index) {
					var li_html = $(this).html();
					$('#main_subjects li:not(li[class^=column], li.banner)').eq(index).html(li_html);
				});
			});

			break;

		default:
			break;
		}
	}
	function popupToggle(toShow){ // hide all popup contents and show only `toShow`
		if (toShow) toShow = ', ' + toShow; // will extend jQuery selector
		
		$('#popup').css('top', $(window).scrollTop() + a_co_il.popup_height); // handle the case when the user opens the popup for the first time and his scroll is in the middle of the page. without this like the popup will apeare on the top of the page (cause the user didn't scroll yet)
		
		$('#popup .popup_content').hide();
		$('#opacity_curtain, #popup' + toShow).show();
	}
	function showPopupApp(){
		$('#popup').removeClass('message'); // default sized popup
		$('#popup').removeClass('rtl');
		popupToggle('#app_info');
	}
	function showPopupMessage(m, t){ // m - message, t - title
		if (typeof(t) == 'undefined'){
			t = 'הודעה';
		}

		$('#popup h1').html(t);
		$('#popup .popup_message_text').html(m);
	
		$('#popup').addClass('message rtl'); // message sized popup
		popupToggle('#popup_message');
	}
	function showPopupContact(){
		$('#popup h1').html('צור קשר');
		$('#popup').removeClass('message'); // default sized popup
		$('#popup').addClass('rtl');
		popupToggle('form#contact_us');
	}
	function update_weather(){
		// update cities and their weather data
		// set weather for current city (stored in a cookie)
		var curr_city = a_co_il.readCookie('weather_city');

		$.getJSON(BASE_URL + 'weather.php', { "get_weather": "1" }, function(data){
			if (!data) return;

			var list = '';
			for (x in data){
				list = list + '<li class="city_data">' +
							  '<span class="hebrew">' + data[x].name_heb + '</span> - ' +
							  '<span class="degrees min">' + data[x].min + '°</span>/' +
							  '<span class="degress max">' + data[x].max +'°</span>' +
							  '<span class="english hide">' + x + '</span>' +
							  '<span class="cond_class hide">' + data[x].cond['cond_class'] + '</span>' +
							  '<span class="cond_hebrew hide">' + data[x].cond['heb_condition'] + '</span>' +
							  '</li>';

				// if current
				if (x == curr_city) {
					$('#weather .city').first().text( data[x].name_heb );
					$('#weather .min').first().text( data[x].min + '°' );
					$('#weather .max').first().text( data[x].max + '°' );
				}
			}

			$('#weather .cities .white_frame_content').html( '<ul>' + list + '</ul>');

			update_weather_condition(); // to all cities, I think
		});
	}
	// update weather
	setInterval(update_weather, 1000*60*5); // every 5 minutes in case the user likes to keep his a.co.il opened

	// helper function to change the old weather condition class to a new one
	function update_weather_condition(){
		// remove previous condition class and condition image
		var classes = $('#weather').attr('class');
		var regex = /cond_[a-zA-Z0-9-]+/;
		var curr_weather = regex.exec(classes);
		if (curr_weather){
			curr_weather = curr_weather[0];
			$('#weather').removeClass(curr_weather);
		}
		// empty previous condition desciption
		$('#weather .description .condition').text('');

		// iterate on cities and update their condition
		$('#weather .cities li').each(function(){
			var city = $(this).find('.english').text();
			// TODO update for other cities as well (with small icons etc...)
			if (city == a_co_il.readCookie('weather_city')){
				var new_weather_cond = $(this).find('.cond_class').text().toLowerCase();
				var new_weather_hebrew = $(this).find('.cond_hebrew').text();

				// update condition class
				$('#weather').addClass('cond_' + new_weather_cond);

				// update condition description
                if (new_weather_hebrew != 'undefined') {
                    $('#weather .description .condition').text(new_weather_hebrew);
                }
			}
		});

	}
	function google_search_helper(search_string, cx){ // google search stuff
		var src = 'http://www.google.com/cse?cx=' + cx + '&q=' + encodeURIComponent(search_string);

		window.location.href = src;
	}
	function contact_validate(){ // this function first checks all required fields then it goes through other things
		var error_type_message = false;
		
		if (checkAndMarkRequireds()){ // check required fields first
			error_type_message = 'required_fields';
		} else { // required are ok, now check other things
			error_type_message = checkOtherThings();
		}

		function checkAndMarkRequireds(){
			var err = false;
			// phone required fields
			$('form#contact_us .required').each(function(){
				if ($(this).val() == ''){
					$(this).addClass('error');
					err = true;
				}
			});
			
			if ($('form#contact_us #contact_phone1').val() == '' && $('form#contact_us #contact_phone2').val() == ''){
				$('form#contact_us #contact_phone1').addClass('error');
				err = true;
			}
			
			// check select subject
			if ($('form#contact_us #contact_subject').val() == $('form#contact_us #contact_subject option').eq(0).val()){
				$('form#contact_us #contact_subject').addClass('error');
				err = true;
			}

			return err;
		}

		function checkOtherThings(){
			// check name NaN
			if(!isNaN($('form#contact_us #contact_name').val()[0])){ // if first char is numeric
				$('form#contact_us #contact_name').addClass('error');
				return 'numeric_name';
			}

			// check valid email
			if(!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($('form#contact_us #contact_email').val())){
				$('form#contact_us #contact_email').addClass('error');
				return 'email';
			}

			// check phone1 NaN
			if (isNaN($('form#contact_us #contact_phone1').val())){ // is char
				$('form#contact_us #contact_phone1').addClass('error');
				return 'unnumeric';
			}

			// check phone2 NaN
			if (isNaN($('form#contact_us #contact_phone2').val())){ // is char
				$('form#contact_us #contact_phone2').addClass('error');
				return 'unnumeric';
			}

			return false;
		}
		
		if (error_type_message){
			//set message
			switch(error_type_message){
				case 'required_fields':
					$('form#contact_us .error_message').html('יש להתייחס לכל שדות החובה המסומנים');
					break;

				case 'numeric_name':
					$('form#contact_us .error_message').html('השם שהזנת אינו תקין');
					break;

				case 'email':
					$('form#contact_us .error_message').html('כתובת האימייל שהזנת אינה תקינה');
					break;

				case 'unnumeric':
					$('form#contact_us .error_message').html('יש להזין מספרים בלבד בשדות הטלפון');
					break;

				case 'select_subject':
					$('form#contact_us .error_message').html('יש לבחור נושא');
					break;
			}

			$('form#contact_us .error_message').show(500);
			
			// handle things after user got errors - clean the red borders while he fixes his mistakes
			$('form#contact input, form#contact select, form#contact textarea').unbind(); // reseting events
			
			// remove error class to element on keypress / change
			$('form#contact_us input.error, form#contact_us textarea.error').each(function(){
				$(this).keypress(function(){
					$(this).removeClass('error');
				});
			});
			$('form#contact_us #contact_subject').change(function(){
				if ($(this).val() != $(this).find('option').eq(0).val()){
					$(this).removeClass('error');
				}
			});
			return false;
		} else { // no errors
			return true;
		}
	}
}); // document ready

