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


var hibaLogSzint = 10;
var hibaHalalSzint = 10;


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

Element.implement({
    show: function()
    {
        this.set('styles', {
            'display': 'block'
        });
    },
    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'
            });
        };
    }
});

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


var AjaxUpdater = new Class({

    Implements: [Options, Events],

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

    initialize: function(options) {
        this.setOptions(options);
        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 {
            this.processObj = new AjaxUpdaterGeneric(this.options);
        }
    },

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

    success: function(json, text) {
        fut_tovabb = true;
        if (json.status) {
            logger = new AjaxLogger({data: json.status, requestData: this.request.options});
            fut_tovabb=logger.log();
        }
        if (fut_tovabb) {
            this.processObj.process(json, text);
            this.options.frissitendoElement.removeProperty('disabled');
            this.fireEvent('success',[json, this.options.frissitendoElement]);
        } else {
            this.fireEvent('failure',[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 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) {
    if (!$('currency_setup_panel')) {
        return;
    }
    size=$(this).getCoordinates();
    var posx = 0;
    var posy = 0;
    if (!e) var e = window.event;
    e = new Event(e);
    $('currency_setup_panel').style.top = (size.top+10) + 'px';
    $('currency_setup_panel').style.left = size.left + 'px';

    //new Effect.BlindDown($('currency_setup_panel'));
    $('currency_setup_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.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 confirmwindow(string)
{
    if ( self.confirm(string) ) {
        return true;
    } else {
        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 formatInt( field )
{
    document.getElementById(field).style.color='#333';

    if ( document.getElementById(field).value.length < 1 ) {
        return;
    }
    var object = document.getElementById(field);
    var str = object.value;
    var d = document.getElementById('debugtext');

    str = str.replace(/(\s){2,}/g, ' ');
    str = str.replace(/(\d)(\ )+(\d)/g, '$1$3');
    str = str.replace(/(\d)([a-zA-Z])/g, '$1 $2');
    str = str.replace(/([a-zA-Z])(\d)/g, '$1 $2');

    var str_arr = str.split(' ');

    for (i=0; i<str_arr.length; i++) {
        if ( str_arr[i].match(/\d/) > 0 ) {
            str_arr[i] = str_arr[i].replace(/(?=(\d\d\d)+$)/g, ' ');
            str_arr[i] = str_arr[i].replace(/^\s/, '');
        }
    }

    object.value = str_arr.join(' ');
}


function submitFormatInt( field )
{
        var object = document.getElementById(field);
        var szam = object.value.replace( /\D/g, '' );
        object.value = szam;
}

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