///////////////////
////"KONSTANSOK////
///////////////////


var hibaLogSzint = 10;
var hibaHalalSzint = 10;


////////////////////////////
////MOOTOOLS VARAZSLATOK////
////////////////////////////

Element.implement({
    show: function()
    {
        this.set('styles', {
            'display': ''
        });
    },
    hide: function()
    {
        this.set('styles', {
            'display': 'none'
        });
    },
    toggle: function()
    {
        if(this.getStyle('display')=='none') {
            this.set('styles', {
                'display': 'block'
            });
        } else {
            this.set('styles', {
                'display': 'none'
            });
        };
    },
    isHidden: function()
    {
        return (this.getStyle('display') == 'none');
    },
    isVisible: function()
    {
        return !this.isHidden();
    }
});

//////////////////////////
////MOOTOOLS OSZTALYOK////
//////////////////////////


var AjaxUpdater = new Class({

    Implements: [Options, Events],

    options: {
        frissitendoElement: '',
        postData: '',
        url: ''
    },

    initialize: function(options) {
        this.setOptions(options);
        if (!this.options.frissitendoElement) {
            this.options.frissitendoElement= new Element('div');
        }
        if (this.options.frissitendoElement.get('tag')=='input' && this.options.frissitendoElement.get('type')=='text') {
            this.processObj= new AjaxUpdaterText(this.options);
        } else if (this.options.frissitendoElement.get('tag')=='select') {
            this.processObj= new AjaxUpdaterSelect(this.options);
        } else if (this.options.frissitendoElement.hasClass('MultiSelect')) {
            this.processObj= new AjaxUpdaterMultiSelect(this.options);
        } else {
            this.processObj = new AjaxUpdaterGeneric(this.options);
        }
    },

    update: function() {
        this.request = new Request.JSON({url: this.options.url, data: this.options.postData, onSuccess: this.success.bind(this)}).post();
    },

    success: function(json, text) {
        this.options.frissitendoElement.set('disabled', 'disabled');
        this.options.frissitendoElement.set('html', '...');
        this.processObj.process(json, text);
        this.options.frissitendoElement.removeProperty('disabled');
        this.fireEvent('success',[json, this.options.frissitendoElement]);
    }

});

var AjaxUpdaterText = new Class({

    Implements: Options,

    options: {
        frissitendoElement: '',
        postData: '',
        url: ''
    },

    initialize: function(options) {
        this.setOptions(options);
    },

    process: function(json, text) {
        this.options.frissitendoElement.set({'value' : json.data});
    }

});

var AjaxUpdaterSelect = new Class({

    Implements: Options,

    options: {
        frissitendoElement: '',
        postData: '',
        url: ''
    },

    initialize: function(options) {
        this.setOptions(options);
    },

    process: function(json, text) {
        voltLegalabbEgy=false;
        this.options.frissitendoElement.set({'html' : ''});
        $H(json.data).each(function (value, key) {
            voltLegalabbEgy=true;
            if (json.selected_value==key) {
                this.options.frissitendoElement.adopt(new Element('option', {
                    'value': key,
                    'text': value,
                    'selected': 'selected'
                }));
            } else {
                this.options.frissitendoElement.adopt(new Element('option', {
                    'value': key,
                    'text': value
                }));
            }
        }.bind(this));
        if (!voltLegalabbEgy) {
            this.options.frissitendoElement.adopt(new Element('option', {
                'value': 0,
                'text': json.data
            }))
        }
    }

});

var AjaxUpdaterMultiSelect = new Class({

    Implements: Options,

    options: {
        frissitendoElement: '',
        postData: '',
        url: '',
        baseName: ''
    },

    initialize: function(options) {
        options.baseName = options.frissitendoElement.get('rel');
        this.setOptions(options);
    },

    process: function(json, text) {
        var voltLegalabbEgy = false;
        this.options.frissitendoElement.set({'html' : ''});
        $H(json.data).each(function (value, key) {
            voltLegalabbEgy = true;

			if (this.options.csak_int) {
				key = parseInt( key );
			}

            var id       = this.options.baseName + '_' + key;
            var checked  = json.selected_value == key || json.empty ? 'checked' : false;
            var disabled = json.empty ? 'disabled' : false;
			var inp = new Element('input', {
                'type':     'checkbox',
                'value':    key,
                'title':    value,
                'id':       id,
                'name':     this.options.baseName + '[]',
                'disabled': disabled
            });
			if (checked) {
				inp.checked = true;
			}
            this.options.frissitendoElement.adopt(inp, new Element('label', {
                'class':    'checkbox',
                'for':      id,
                'text':     value
            }));
        }.bind(this));

        if (!voltLegalabbEgy) {
            this.options.frissitendoElement.adopt(new Element('input', {
                'type':     'checkbox',
                'value':    0,
                'title':    'nincs',
                'id':       this.options.baseName + '_nodata',
                'name':     this.options.baseName + '_nodata',
                'checked':  'checked',
                'disabled': 'disabled'
            }), new Element('label', {
                'class':    'checkbox',
                'for':      '',
                'text':     'no data'
            }))
        }
        if (typeof(MultiSelect) != undefined) {
            new MultiSelect('#'+this.options.frissitendoElement.get('id'));
        }
    }

});


var AjaxUpdaterGeneric = new Class({

    Implements: Options,

    options: {
        frissitendoElement: '',
        postData: '',
        url: ''
    },

    initialize: function(options) {
        this.setOptions(options);
    },

    process: function(json, text) {
        this.options.frissitendoElement.set({'html' : json.data});
    }

});

var AjaxLogger = new Class({

    Implements: Options,

    options: {
        logSzint: hibaLogSzint,
        halalSzint: hibaHalalSzint,
        data: '',
        requestData: ''
    },

    initialize: function(options) {
        this.setOptions(options);
        this.loggerObj = new AjaxLoggerConsole;
    },

    log: function() {
        return_val = true;
        this.options.data.error.each(function(value) {
            if (value.error_level >= this.options.logSzint) {
                this.loggerObj.log(value, this.options.requestData);
            }
            if (value.error_level >= this.options.halalSzint) {
                return_val = false;
            }
        }.bind(this));
        return return_val;
    }

});

var AjaxLoggerConsole = new Class({
    log: function (data, requestData) {
        console.log("Hibaszint: "+data.error_level+" - Hiba: "+data.error_desc+" - Request: "+JSON.encode(requestData));
    }
});

var AjaxLoggerAlert = new Class({
    log: function (data, requestData) {
        alert("Hibaszint: "+data.error_level+" - Hiba: "+data.error_desc+" - Request: "+JSON.encode(requestData));
    }
});



////////////////////
////MOOTOOLS FGV////
////////////////////

var lng_panel_show = function(e) {
    if (!$('lng_setup_panel')) {
        return;
    }
    if (!e) var e = window.event;
    e = new Event(e);
    $('lng_setup_panel').style.display = 'block';
    document.addEvent('click', lng_panel_close);
    e.stop();
}

var lng_panel_close = function(e) {
    if (!e) var e = window.event;
    e = new Event(e);
    $('lng_setup_panel').style.display = 'none';
    e.stop();
    document.removeEvent('click', lng_panel_close);
}


var currency_panel_show = function(e) {
	var $panel = $('currency_setup_panel');
    if (!$panel) {
        return;
    }
    var size = $(this).getCoordinates();
    if (!e) var e = window.event;
    e = new Event(e);
    $panel.setStyles({top: (size.top+10) + 'px', left: size.left + 'px'});

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

    //new Effect.BlindDown($('currency_setup_panel'));
    $panel.style.display = 'block';
    document.addEvent('click', currency_panel_close);
    e.stop();
}


/**
 * Penzvalto ablak bezarasa es a hozza tartozo esemenyfigyelo megszuntetese
 */
var currency_panel_close = function(e) {
    if (!e) var e = window.event;
    e = new Event(e);
    $('currency_setup_panel').style.display = 'none';
    e.stop();
    document.removeEvent('click', currency_panel_close);
}




/**
 *  irsz: irányítószám (int)
 *  hova: ELEMENT (input type='text', amibe injektáljuk a település nevét
 */
var irszToTelepules = function(irsz, hova) {
    var ajaxaa = new Request.JSONP({
        'url': 'http://ws.geonames.org/postalCodeLookupJSON',
        'timeout': 3000,
        'method': 'get',
        'data': {
            'maxRows': 2,
            'country': 'HU',
            'postalcode': irsz
        }
    });
    ajaxaa.addEvent('request', function() {
        //hova.set('value', '');
        hova.set('readonly', true);
    });
    ajaxaa.addEvent('complete', function() {
        hova.set('readonly', false);
    });
    ajaxaa.addEvent('timeout', function() {
        hova.set('readonly', false);
    });
    ajaxaa.addEvent('failure', function() {
        hova.set('readonly', false);
    });
    ajaxaa.addEvent('success', function(resp) {
        if (resp.postalcodes.length == 1 && hova.get('value') == '') {
            hova.set('value', resp.postalcodes[0].placeName);
        }
    });
    ajaxaa.send();
}

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

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

/*
 * Megmutatja az adott elemet
 */
function show_by_id(id) {
    document.getElementById(id).style.display = 'block';
}


/*
 * Elrejti az adott elemet
 */
function hide_by_id(id) {
    document.getElementById(id).style.display = 'none';
}

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

//////////////////////////////////
////MOOTOOLS AZ UPDATELIST-HEZ////
//////////////////////////////////


//
// Az updateList() függvény által kért és a szerveroldali fájl által szolgáltatott
// XML fájlt elemzi
// Mindig a függőségi fában legmagasabban elhelyezkedő, még feltöltetlen <select> -t update-eli
// Egyelőre még csak <select> van támogatva
// TO DO : <input> <textarea>, stb. támogatása
//
function handleHttpResponse( responseText, response )
{
    var xmlList = response.getElementsByTagName(nowUpdateing);
    var Object = $(nowUpdateing);
    Object.disabled = false;

    // Betöltés... kiszedése
    Object.removeChild(Object.childNodes[0]);
    var option = null;
    // A <xmlresult> -ba egy h="0|1" attributum jelzi, hogy megjelenhet-e a hozzaadas gomb
    var xmlHeader = response.getElementsByTagName('xmlresult');
    hozzaadas = xmlHeader[0].attributes.getNamedItem("h").nodeValue;
    for (var j=0; j<xmlList.length; j++) {
        option = document.createElement("option");
        // Az orszag/regio/telepules/varosresz adatbazisbeli azonositoja
        option.setAttribute('value', xmlList[j].attributes.getNamedItem("kod").nodeValue);
        option.appendChild(document.createTextNode(xmlList[j].firstChild.nodeValue));
        $(nowUpdateing).appendChild(option);
    }

    // Megnézzük, kérvényeztük-e az új hozzáadásának engedélyezését
    for(var key in addlist) {
        if(nowUpdateing == key && hozzaadas == 1) {
            // ha nem üres a lista
            if(($(nowUpdateing).options.length > 1)) {
                $(addlist[nowUpdateing]['toggle']).value = addlist[nowUpdateing]['toggleOn'];
                $(addlist[nowUpdateing]['toggle']).show();
            } else {
                $(addlist[nowUpdateing]['select']).hide();
                $(addlist[nowUpdateing]['input']).show();
                $(addlist[nowUpdateing]['input']).value = '';
            }
        }
    }
}

//
// Egy dropdownlist elemeit tölti fel XML-es kommunikációval
// A kiváltó <select> alatt elhelyezkedő <select> -t frissíti
// - az adott <select> onchange eventjéhez kell hozzáadni onchange=updateList(this.id); formában
//
// Szükséges változók : xmlhandler, selectlist, addlist
// var selectlist = new Array('orszag','regio','telepules','varosresz'); formában (függőségi fa)
// var xmlhandler = 'ajax_update.php'; formájában.
function updateList(id,kereso_mod,help_felirat)
{
    if (!isWorking) {
        if (help_felirat == 'Új település felvétele') {
            kereso_mod = false;
        }
        isWorking = true;
        // A hívó select indexét megkeressük
        var i;
        for(i=0; i<selectlist.length; i++) {
            if( id == selectlist[i] ) {
                break;
            }
        }
        // Ha üresre állították a hívó select-t, töröljük az alatta lévőek tartalmát
        if( !kereso_mod && ($(id).selectedIndex == 0)) {
            for(var j=i+1; j<selectlist.length; j++) {
                clearList(selectlist[j]);
                disableList(selectlist[j]);
                if(addlist[selectlist[j]]) {
                    selectInputAddHide(addlist[selectlist[j]]);
                    $(addlist[selectlist[j]]['toggle']).hide();
                }
            }
            isWorking = false;
            return;
        }
        // A módosítandó select indexét megkeressük
        i++;

        nowUpdateing = selectlist[i];
        // Az alatta lévő select-k törlése

        for(var j=i+1;j<selectlist.length; j++){
            clearList(selectlist[j]);
            if(!kereso_mod) {
                // ha nem keresés van, akkor disable
                disableList(selectlist[j]);
            } else {
                // ha keresés van, akkor a mindegy -t visszatesszük, és nincs disabled
                option = document.createElement("option");
                option.appendChild(document.createTextNode(STR_MINDEGY));
                option.set('value', 0);
                $(selectlist[j]).appendChild(option);
            }
            if(addlist[selectlist[j]]) {
                selectInputAddHide(addlist[selectlist[j]]);
                $(addlist[selectlist[j]]['toggle']).hide();
            }
        }

        clearList(nowUpdateing);

        var option = document.createElement("option");
        option.appendChild(document.createTextNode(STR_BETOLTES+'...'));
        option.setAttribute('value', 0);
        $(nowUpdateing).appendChild(option);

        if(addlist[nowUpdateing]) {
            selectInputAddHide(addlist[nowUpdateing]);
            $(addlist[nowUpdateing]['toggle']).hide();
        }

        // A POST adatok beállítása
        var query = '';
        if(kereso_mod) {
            query = "mode=1&update=" + escape(nowUpdateing);
        }
        else {
            query = query + "update=" + escape(nowUpdateing);
        }
        for(var j=i-1;j>=0; j--) {
            query = query + "&" + escape(selectlist[j]) + "=" + escape($(selectlist[j]).getSelected().get('value'));
        }
        query = query + "&request_uri=" + escape(window.location.href);
        // Request options beállítása
        var options = {
            method: 'get',
            url: xmlhandler + ((xmlhandler.indexOf("?") > 0) ? "&" : "?") + query,
            onSuccess: handleHttpResponse,
            onFailure: function(t) {
                alert('Az oldal frissítése közben hiba történt. Kérjük próbálja meg újra!');
            }
        }
        new Request(options).send();
  
        isWorking = false;
    }
}


//
// Egy dropdownlist elemeit kitörli
// @param : a dropdownlist id mezője
//
function clearList(list)
{
    var listObject = $(list);
    while(listObject.childNodes.length > 0) {
        listObject.removeChild(listObject.childNodes[0]);
    }
}

function disableList(list)
{
    var listObject = $(list);
    var option = null;
    option = document.createElement("option");
    option.appendChild(document.createTextNode(STR_VALASSZON_FENTEBB));
    listObject.appendChild(option);
    listObject.disabled = true;
}
var nowUpdateing = "";
var isWorking = false;


//
// Egy adatbázisból feltöltött <select> -hez új elem felvételének támogatása <input> al.
// @param : array, asszociatív tömb:
//
// var parameter_array = {
//      depend: 'telepules',
//      select: 'varosresz',
//      input: 'varosresz_add',
//      toggle: 'varosresz_toggle',
//      emptyDepend: 'Válassza ki a települést!',
//      toggleOn: 'Új településrész felvétele',
//      toggleOff: 'Vissza'
//  };
// Leírás:
// depend: a <select> -ünk melyik select-től függ
// select: a <select> -ünk id-je
// input: az <input> mezőnk neve (eredetileg rejtett)
// submit: az input elküldéséhez használt submit-gomb(eredetileg rejtett)
// toggle: az új megadása/selectből kiválasztás kapcsológomb (eredetileg látható)
// emptyInput: ha az input mezőt üresen küldené el
// emptyDepend: ha még a függőséget sem választotta ki
// toggleOn, toggleOff: gomb-feliratok
//
// Szükséges változók : xmlhandler, selectlist, array
//
//
function selectInputAddToggle(array)
{
    if($(array['select']).isVisible()) {
        selectInputAddShow(array);
    } else {
        selectInputAddHide(array);
    }
}

function selectInputAddShow(array)
{
    $(array['select']).hide();
    $(array['input']).show();
    $(array['input']).value = '';
    $(array['toggle']).value = array['toggleOff'];
}
function selectInputAddHide(array)
{
    $(array['select']).show();
    $(array['input']).hide();
    $(array['toggle']).value = array['toggleOn'];
}

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

	change_status('ing_status_change', $$('input[name=' + elem + ']:checked').get('value')[0]);
}

function change_status(elem, statusz)
{
	$(elem).set('html', (statusz == 1 ? STR_MILLIO + ' Ft' : STR_EZER + ' Ft/hó'));
}


////////////////////////////////
//// SUBCHECKLIST //////////////
////////////////////////////////

window.addEvent('domready', function(){
	$$('a.currency_exchange').addEvent('click', currency_panel_show);

	if ($$('div.subchecklist').length == 0) return;

	$$('div.subchecklist .sub').each(function(e){
		if (e.getElements('div input:checked').length == 0) {
			e.removeClass('active');
		} else {
			e.addClass('active');
		}

		var chks = e.getElements('div input');
		e.getElements('div input').addEvent('click', function(){
			_gaq.push(['_trackEvent', 'kereseslista', 'subchecklist', 'sub', this.get('value'), (this.get('checked') ? 'on' : 'off')]);

			e.getElement('input').set('checked', (e.getElements('div input:checked').length == chks.length));
		});
	});

	$$('div.subchecklist .sub > label > input').addEvent('click', function(){
		_gaq.push(['_trackEvent', 'kereseslista', 'subchecklist', this.get('value'), (this.get('checked') ? 'on' : 'off')]);

		var sub_div = this.getParent().getNext('div');
		if (sub_div) {
			if (this.get('checked')) {
				sub_div.getParent('.sub').addClass('active');
			} else {
				sub_div.getParent('.sub').removeClass('active');
			}
			sub_div.getElements('input').set('checked', this.get('checked'));
		}
	});

	$$('.header_lnk').addEvent('click', function(){
		var parent = this.getParent('.sub');
		_gaq.push(['_trackEvent', 'kereseslista', 'subchecklist', 'link', this.get('href'), (parent.hasClass('active') ? 'off' : 'on')]);

		parent.toggleClass('active');
		return false;
	});
});

