(function( $ ){
	$.fn.clean = function() {
		return this.filter( function(v) {
			switch (v) {
				case undefined:
				case null:
				case 0:
				case "":
					return false;

				default:
					return true;
			}
		});
	};

	$.fn.last = function(n) {
		n = n ? n : 0;
		return $(this[this.length-(1+n)]);
	};

	if ($.validator) {
		$.validator.addMethod('formatted-number', function(value, element, param) {
			return /^[0-9 ,]*$/.test(value);
		}, STR_VALIDATE_NUMBER);

		$.validator.addMethod('req-select', function(value, element, param) {
			return value.length > 0 && value != '0' && value != INET_ANY;
		}, STR_VALIDATE_SELECT);

		$.validator.addClassRules('formatted-number', {
			'formatted-number': true
		});

		jQuery.extend(jQuery.validator.messages, {
			required: STR_VALIDATE_REQUIRED,
			email: STR_VALIDATE_EMAIL,
			number: STR_VALIDATE_NUMBER
		});
	}
})( jQuery );

//////////////////////
////JAVASCRIPT FGV////
//////////////////////


// E-mail címet <a href="mailto:info#kukac#jox#pont#hu" onClick="defendSpam(this);">info@jox.hu</a> -ba tehetjük
function defendSpam(x) {
    x.href=x.href.replace("#kukac#", "@");
    x.href=x.href.replace("#pont#", ".");
    return true;
}

Array.prototype.last = function() {
	return this[this.length-1];
};

Array.prototype.remove = function(e) {
	var t, _ref;
	if ((t = this.indexOf(e)) > -1) {
		return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
	}
};

//
// szám konvertálása más számrendszerbe
//
Number.prototype.toBase = function(b, c){
    var s = "", n = this;
    if(b > (c = (c || "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").split("")).length || b < 2) return "";
    while(n)
        s = c[n % b] + s, n = Math.floor(n / b);
    return s;
};
//
// a string-ként megadott hexadecimális jegyekből
// álló sorozatot ascii text-é alakítja
//
function hex2text(hex)
{
    var text = '';
    for(var i=0 ; i<hex.length ; i+=2) {
        text = text + String.fromCharCode(  parseInt(hex.charAt(i),16)*16 + parseInt(hex.charAt(i+1),16) );
    }
    return text;
}

//
// a string-ként megadott ascii text-t
// hexadecimális számjegyekké alakítja
//
function text2hex(text)
{
    var hex = '';
    for(var i=0; i<text.length; i++) {
        var chr = text.charCodeAt(i).toBase(16);
        hex = hex + chr;
    }
    return hex.toLowerCase();
}

/**
 * Cookie-ba elmenti a kivalasztott penznemet
 *
 * @param reference->object obj a SELECT, amiben kivalasztottuk a 3 karakteres penznem kodot
 */
function save_currency(code)
{
    createCookie('currency', code, 31536000);
    document.location.reload();
}


/**
 * Cookie-t csinal
 *
 * @param string name a cookie valtozo neve
 * @param string value a cookie erteke
 * @param integer hours hany oraig legyen ervenyes
 */
function createCookie(name, value, hours) {
    if (hours) {
        var date = new Date();
        date.setTime(date.getTime()+(hours*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}


/**
 * Handle properties onclick event
 * Open anchor's locatoion in a new window, named by properties id
 *
 * @param Object oAnchor
 * @return Boolean false not open link in original window
 */
function inet_popup_ingatlan(oAnchor) {
    var height = parseInt(screen.height) - 160;
    var width = 980;

    var regexp_only_id = /^.*\/([\d]*)-.*$/gi;
    var popupname = 'ingatlan_' + oAnchor.href.replace(regexp_only_id, "$1");
    popupname = 'ingatlan_ek_popup';
    window.open(oAnchor.href + '&popup=true', popupname, 'width=' + width + ',height=' + height + ',scrollbars=yes,resizable=yes,toolbar=no,location=yes,directories=no,status=no,menubar=no');

    return false;
}

function inet_popup_ingatlan_gmap(oAnchor) {
    var regexp_only_id = /^.*kod\=([\d]*).*$/gi;

    var height = parseInt(screen.height) - 160;
    var width = 980;

    window.open(oAnchor+ '&popup=true', 'ingatlan_' + oAnchor.replace(regexp_only_id, "$1"), 'width=' + width + ',height=' + height + ',scrollbars=yes,resizable=yes,toolbar=no,location=yes,directories=no,status=no,menubar=no');

    return false;
}

function inparent( uri )
{
    if (window.opener && !window.opener.closed) {
        // a hivatkozo oldalban nyitjuk meg az ingatlan reszletes adatlapjat (a lista helyett)
        window.opener.location.href = uri;
        // atadjuk a fokuszt, de nem zarjuk be a kis ablakot a talalatokkal
        window.opener.focus();
    } else {
        window.location.href = uri;
    }
}

function newpopup ( popupurl, popupname, popupfeatures )
{
    newwindow = window.open(popupurl, popupname, popupfeatures);
    newwindow.focus();
    return false;
}

function delete_default_from_input( field, defval )
{
    if ( field.value == defval ) {
        field.value='';
        field.style.color='#333';
    } else if ( field.value == '' ) {
        field.value=defval;
        field.style.color='#bbb';
    }
}

function evCheck( field )
{
        if ( field.value.match(/^\d{4}$/) || field.value.length == 0 ) {
                field.style.background = '#fff';
                return TRUE;
        } else {
                field.style.background = '#c00';
                return FALSE;
        }
}

function ucfirst (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ucfirst('kevin van zonneveld');
    // *     returns 1: 'Kevin van zonneveld'
 
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}


//////////////////////////
///FORMCHECK VALIDACIOK///
//////////////////////////

function check_eula(el)
{
    if(!el.checked) {
        el.errors=new Array();
        el.errors.push("Az oldal használatához el kell fogadnia a felhasználási feltételeket.");
    }
    return el.checked;
}
function check_aszf(el)
{
    if(!el.checked) {
        el.errors=new Array();
        el.errors.push("A regisztrációhoz el kell fogadnia a szerződési feltételeket.");
    }
    return el.checked;
}
function return_true(el)
{
    return true;
}

////////////////////////
///                  ///
////////////////////////

var currency_panel_close = function(){
	$('#currency_setup_panel').hide();
}
$('a.currency_exchange').live('click', function(){
	var $panel = $('#currency_setup_panel');
	if ($panel.length < 1) {
		return;
	}

	if (typeof(_gaq) != 'undefined') {
		_gaq.push(['_trackEvent', 'currency', 'currency_show']);
	}

	var pos = $(this).offset();
	$panel.css({
		top: pos.top + $(this).height() + 3
		, left: pos.left
	}).show();

	setTimeout(function(){
		$(document).one('click', currency_panel_close);
	}, 200);
});


function change_status_event( elem )
{
	$('input[name=' + elem + ']').click( function(){
		change_status('#ing_status_change', $(this).val());
	});

	change_status('#ing_status_change', $('input[name=' + elem + ']:checked').val());
}

function change_status(elem, statusz)
{
	$(elem).html(statusz == 1 ? 'millió Ft' : 'ezer Ft/hó');
}


function is_authenticated()
{
	return $.ajax({
		url:		'/user/index.html?ajax=is_authenticated&light=1',
		type:		'GET',
		async:		false
	}).responseText == 'true';
}

function updateCounters(counts)
{
	var selectors = {
		'ingatlanok':	'#kedvenc_ingatlanok_count',
		'keresesek':	'#kedvenc_keresesek_count',
		'arfigyelok':	'#arfigyelok_count'
	};

	for (c in counts) {
		if (selectors[c]) $(selectors[c]).html(counts[c] > 0 ? ' ('+counts[c]+')' : '');
	}
}

/*
function js_login()
{
	if (is_authenticated()) {
		return true;
	}

	$.facebox({
		ajax:	'/user/index.html'
	});
}
*/

