swfobject.addDomLoadEvent(function(){
    if(document.getElementById('banner_mysamsung'))swfobject.embedSWF( K_WEB_PATH+'public/swf/top-banner-mysamsung.swf', 'banner_mysamsung', '728', '90', '9.0.0', {}, {}, {wmode: 'transparent'});
    if(document.getElementById('banner'))swfobject.embedSWF( K_WEB_PATH+'public/swf/top-banner.swf', 'banner', '728', '90', '9.0.0', {}, {}, {wmode: 'transparent'});
});


jQuery.fn.extend({
    check: function(){
        return jQuery(this).attr('checked',true);
    },
    uncheck: function(){
        return jQuery(this).attr('checked',false);
    },
    select: function(){
        return jQuery(this).attr('selected','selected');
    },
    deselect: function(){
        return jQuery(this).rmoveAttr('selected');
    },
    disable: function(){
        return jQuery(this).attr('disabled','disabled').removeAttr('enabled');
    },
    enable: function(){
        return jQuery(this).attr('enabled','enabled').removeAttr('disabled');
    },
    clearInputs: function(df){
        var $inp = $(this);
        $inp.addClass('defValued');
        if(df)$inp.val(df);
        var defaultValue = df || $inp.val();
        
        return $inp.focus(function(){
            var $t = $(this);
            if ($t.val() == defaultValue) {
                $t.val('').removeClass('defValued');
            }
        }).blur(function(){
            var $t = $(this);
            if ($t.val() == defaultValue || $t.val() == '') {
                $t.val(defaultValue).addClass('defValued');
            }
        });
        
        // Ha nincs kliens oldali validáció akkor ez is kell hogy töröljük a default értékeket
        /*$inp.parents('form').submit(function(){
            if($inp.val()==defaultValue)$inp.val('');
        });*/
    }
});

jQuery.extend({
    beginsWith: function(what,withWhat){
        return (what.match("^"+withWhat)==withWhat)
    }
});

var ajaxCheckRun=false;

function replaceSubmitBtns(){
    var $sbmts = $('input[type="submit"]').filter(function(){
        return !$(this).hasClass('replaced');
    }); 
    if($sbmts.length){
        $sbmts.each(function(){
            
            var $sbmt = $(this).wrap('<span style="position:relative;float:left;"></span>');
            
            var $btn = $('<a href="#" class="arrow replacedSubmit"></a>').addClass($sbmt.attr('class')).css({
                position: 'relative',
                zIndex: 1
            }).append($('<strong>').html($sbmt.val()));
            
            $sbmt.after($btn).css({
                position: 'absolute',
                zIndex: 2,
                width: $btn.outerWidth(),
                height: $btn.outerHeight(),
                top: 0,
                left: 0,
                border: 0,
                padding: 0,
                margin: 0,
                opacity: 0,
                overflow: 'visible',
                cursor: 'pointer'
            }).addClass('replaced');
            
            if ($(this).hasClass('withCancel')) $btn.after('<a class="cancel" href=\"#\"><strong>Mégsem</strong></a>');
        });
    }
}

function historyBackButtons(){
    $('.cancel, .back').click(function(e){
        history.back();
        e.preventDefault();
    })
}

// formValidation custom methods

jQuery.validator.addMethod("notDefault", function(value, element, param) { 
 return this.optional(element) || value != param; 
}, jQuery.format("Please enter a value"));

jQuery.validator.addMethod('urlWithoutHttp', function(url, element){
    var reg = new RegExp(/^(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i);
    return this.optional(element) || reg.test(url);
}, '');

jQuery.validator.addMethod('lettersonly', function(number, element){
    var reg = new RegExp(/^['.\-\sa-zA-ZÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóŐőŰűúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]+$/);
    return this.optional(element) || reg.test(number);
}, 'Letters only');

jQuery.validator.addMethod('zipnum', function(number, element){
    var reg = new RegExp(/^[0-9]{4}$/);
    return this.optional(element) || reg.test(number);
}, 'Incorrect ZIP');

jQuery.validator.addMethod('cityname', function(number, element){
    var reg = new RegExp(/^[a-záéíóöőúüű\-\s]+$/);
    return this.optional(element) || reg.test(number);
}, 'Incorrect city name');

jQuery.validator.addMethod('mobileOrPhoneNum', function(number, element){
    var reg = new RegExp(/^(((20|30|70)[0-9]{7})|([1-9][0-9]{7}))$/);
    return this.optional(element) || reg.test(number);
}, 'Incorrect mibile num');

jQuery.validator.addMethod('mobilenum', function(number, element){
    var reg = new RegExp(/^[0-9]{7}$/);
    return this.optional(element) || reg.test(number);
}, 'Incorrect mibile num');

jQuery.validator.addMethod('telnum', function(number, element){
    var reg = new RegExp(/^[1-9][0-9]{7,8}$/);
    return this.optional(element) || reg.test(number);
}, 'Incorrect mibile num');

jQuery.validator.addMethod('ajaxcheck', function(number, element){
    return !ajaxCheckRun;
}, '');

// validator constructor function

function formValidation(form,rules,messages,invalidHandler,groups){
    
    if(form.length){

        form.validate({
            onfocusout: false,
            onkeyup: false,
            onclick: false,
            errorClass: 'inputError',
            wrapper: 'li',
            errorPlacement: function(error, element){
                var par=element.parent();
                var errorCnt=$('<ul class="formErrors client"></ul>').append(error);
                if (par.is('td')) element.parents('table').after(errorCnt);
                else if (element.attr('name') == 'city' ) element.prev().find('.inputBox').append(errorCnt);
                else if (element.attr('name')=='login_name' || element.attr('name')=='password') errorCnt.insertAfter($('#password'))
                else element.parent().append(errorCnt);
                
            },
            groups: groups,
            rules: rules,
            messages: messages,
            invalidHandler: invalidHandler
        });
        
        if($('#regFormProductMore').length){
            $('#regFormProductMore').bind('submit', function(e){
                var $t = $(this),
                    $box = $('#purchase_date_year').parent(),
                    fdate = new Date(),
                    date = new Date(),
                    fyear = $t.find('#purchase_date_year').val(),
                    fmonth = new Number($t.find('#purchase_date_month').val()-1),
                    fday = $t.find('#purchase_date_day').val();
                    
                    fdate.setFullYear(fyear,fmonth,fday);

                    if(fdate!='Invalid Date' && date<fdate){
                        $box.append('<ul class="formErrors"><li>Vásárlási dátum nem lehet a mai napnál frissebb!</li></ul>');
                        e.preventDefault();
                    }
            });
        }
        
    }
}

function ajaxEmailAddrChecker(userMail){
    var $mail = $('.defaultForm #email'),
        $loader = $('<img class="dib ajaxLoader ml10" src="' + K_WEB_PATH + 'public/img/ajax-loader.gif" width="16" height="16" alt="ajax loading" title="" />'),
        curMail,origMail
        go = true;
    if($mail.val()!='') origMail = $mail.val();
    if ($mail.length) {
        $mail.blur(function(){
            
            if ($mail.next('ul').length && $mail.val() != curMail) $mail.next('ul').remove();
            if ($mail.val() != curMail && $mail.val() != origMail && $mail.val() != '') {
                
                if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($mail.val())) {
                    
                    if(!$mail.next('img').length)$loader.insertAfter($mail);
                    ajaxCheckRun=true;
                    $.post(K_QUERY_PATH + 'user/emailexists' + K_QUERY_SEPARATOR + 'email=' + encodeURIComponent($mail.val()), function(data){
                        curMail = $mail.val();
                        $loader.remove();
                        ajaxCheckRun=false;
                        
                        if (data) {
                            go = false;
                            var $ul = $('<ul class="formErrors"></ul>').html('<li class="error">Ezt az e-mail címet már valaki regisztrálta. <br />Ha Öné az e-mail cím, <a href="'+K_QUERY_PATH+'">jelentkezzen be</a> vele,<br /> vagy <a href="'+K_QUERY_PATH+'uj-jelszo">kérjen új jelszót</a>.</li>');
                            if ($mail.parents('#emailModifyForm').length) {
                                if(curMail==userMail)$ul.find('.error').html('Ez a jelenlegi e-mail címe.');
                                else $ul.find('.error').html('Ezt az e-mail címet már valaki regisztrálta.<br /> Válasszon másikat!');
                            }
                            if($mail.parents('#regFormProduct').length || $mail.parents('#subscribeForm').length)$ul.find('.error').html('Ezzel az e-mail címmel már valaki regisztrált egy My Samsung profilt.<br /> Ha az Öné az e-mail cím, kérjük jelentkezzen be vele a jobb oldalon!');
                            if(!$mail.next('ul').length)$ul.appendTo($mail.parent());
                            $mail.parents('form').submit(function(){
                                return go;
                            });
                        }
                        else {
                            go = true;
                        }
                    });
                }
            }
            $mail.parents('form').submit(function(){
               return go; 
            });
        });
    }
}

function ajaxZipList(){
    var $zip = $('#zip').attr('maxlength',4),
        $errors = $zip.parents('.formRow').find('ul.formErrors'),
        $loader = $('<img class="ajaxLoader ml5 di fl" src="' + K_WEB_PATH + 'public/img/ajax-loader.gif" width="16" height="16" alt="ajax loading" title="" />'),
        $city = $('#city'),
        $sel = [], $a = [], $span = [], $ul = [], zipVal = '', pageLoad=false;
        
    if ($zip.length) {
        
        function getZip(){
            $loader.insertAfter($zip);
            $.get(K_QUERY_PATH + 'user/getcitiesbyzip/' + $zip.val(), function(data){
                $loader.remove();
                data = eval(data);
                $zip.nextAll().remove();
                if($errors.length)$errors.remove();
                if (data) {
                    
                    function appendElem(elem){
                        $zip.parent().css('position', 'relative').append(elem);
                    }
                    
                    if (data.length > 1) {
                        
                        $sel = $('<select class="citySelector frmSelect"><option value=""> - Válasszon - </option></select>');
                        
                        if(pageLoad)$sel.hide();
                        
                        appendElem($sel);
                        
                        $.each(data, function(){
                            $('<option value="'+this.toString()+'"></option>').html(this.toString()).appendTo($sel);
                        });
                        
                        if ($.inArray($city.val(), data) > -1) {
                            $sel.find('option').filter(function(){
                                return $(this).html()==$city.val();
                            }).select();
                        } else {
                            $sel.find('option:first').select();
                        }
                        
                        $a = $('<a class="lnk cityText" href="#">'+$sel.find('option:selected').html()+'</a>');
                        
                        $sel.before($a);
                        
                        if(!pageLoad)$a.hide();
                        
                        $a.click(function(e){
                            var $l = $(this);//.hide();
                            $sel.show().find('option:first').select();
                            e.preventDefault();
                        });
                        
                        $sel.change(function(){
                            var $s = $(this).hide();
                            var value = $s.find('option:selected').html(); 
                            $a.html(value).show();
                            $city.val(value);
                            if($s.nextAll('ul').length)$s.nextAll('ul').remove();
                        }).keydown(function(e){
                            if (e.keyCode == 13) {
                                var $s = $(this).hide();
                                var value = $s.find('option:selected').html();
                                $a.html($s.val()).show();
                                $city.val($s.val());
                            }
                        });
                        
                        var cityValue = ($sel.val()=='') ? '': $sel.find('option:selected').html();  
                        
                        $city.val(cityValue);
                    }
                    else {
                        if (data.length) {
                            
                            $span = $('<span class="cityText"></span>').html(data[0]);
                            
                            appendElem($span);
                            
                            $city.val(data[0]);
                        }
                        else {
                            var msg = (pageLoad) ? 'Kérjük ellenőrizze az irányítószámát, majd mentse el adatait!' : 'Nem létező irányítószám!';
                            $ul = $('<ul class="formErrors"></ul>').html('<li class="error">'+msg+'</li>').appendTo($zip.parent());
                            $city.val('');
                        }
                    }
                }
                pageLoad = false;
            });
        }
        
        if($zip.val().length>3){
            pageLoad = true;
            getZip();
            zipVal = $zip.val();
        }
        
        $zip.keyup(function(){
            if ($(this).val().length > 3) {
                if ($zip.next().length && zipVal!=$(this).val())$zip.next().remove();
                if(zipVal!=$(this).val())getZip();
                zipVal = $(this).val();
            }
            if($(this).val().length < 4) {
                $(this).next().remove();
                $city.val('');
                zipVal = '';
            }
        }).blur(function(){
            if($(this).val()=='' || $(this).val()<4){
                if($sel.length)$sel.remove();
                if($ul.length)$ul.remove();
                if($span.length)$span.remove();
                $city.val('');
                zipVal = '';
            } else {
                if(zipVal!=$(this).val())getZip();
            }
        });
    }
}

function modifyEmailLayer(){
    var $btn = $('#modifyEmailBtn'),
        $loader = $('<div style="text-align:center;"><img src="' + K_WEB_PATH + 'public/img/ajax-loader-dialog.gif" width="48" height="48" alt="ajax loading" title="" /></div>'),
        userMail = '';
    if($btn.length){
        $('<div id="modifyEmailDialog" class="dialogBox"></div>').appendTo($('body'));
        $btn.click(function(e){
            var $modDialog = $('#modifyEmailDialog').dialog({
                buttons: {
                    "Mégse": function(){
                        $(this).dialog('destroy').empty();
                    }
                },
                title: 'E-mail cím módosítás',
                minHeight: 0,
                width: 500,
                bgiframe: true,
                modal: true,
                close: function(event, ui){
                    $(this).dialog('destroy').empty();
                }
            });
            
            $modDialog.html($loader).find('form').live('submit',function(e){
                var pendingMail = $(this).find('#email').val();
                if (pendingMail != userMail) {
                    $.post($(this).attr('action'), $(this).serialize(), function(data){
                        $modDialog.html(data);
                        if ($modDialog.find('.emailModSucc').length) {
                            $modDialog.dialog('option', 'buttons', {
                                'Bezárás': function(){
                                    $(this).dialog('destroy').empty();
                                    var $pendingMail = $('<div class="formRow clearfix pendingMail">' +
                                    '<div class="labelBox">&nbsp;</div>' +
                                    '<div class="inputBox">Kezdeményezte az e-mail cím módosítását a következőre: <br /><strong>' +
                                    pendingMail +
                                    '</strong><br/>' +
                                    'A módosítást 3 napon belül érvényesítheti az aktivációs link segítségével,<br /> amit elküldtünk erre a címre.' +
                                    '</div>' +
                                    '</div>');
                                    if ($btn.parents('.formRow').next('.pendingMail').length) 
                                        $btn.parents('.formRow').next('.pendingMail').remove();
                                    $btn.parents('.formRow').after($pendingMail);
                                    
                                }
                            });
                        }
                        replaceSubmitBtns();
                        ajaxEmailAddrChecker(userMail);
                        modifyEmailValidation();
                    });
                }
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
            
            $.get($btn.attr('href'),function(data){
                    if(data.error=='session_timeout'){
                        $modDialog.dialog('option','close',function(){
                            window.location.href = K_WEB_PATH;
                        });
                        $modDialog.dialog('option','buttons',{
                            'Ok': function(){
                            window.location.href = K_WEB_PATH;
                        }
                        }).html('<p><strong>A weboldal biztonsági okokból kijelentkeztette.</strong><br><br>Ez olyankor fordul elő, ha 15 percnél hosszabb ideig nem használja a weboldalt.<br><br>Kérjük, jelentkezzen be újra.</p>');
                    }
                    else{
                        $modDialog.html(data);
                        userMail = $('#email').val();
                        $('#email').val('');
                        replaceSubmitBtns();
                        ajaxEmailAddrChecker(userMail);
                        modifyEmailValidation();
                    }
                });
            
//            $modDialog.load($btn.attr('href'),function(data){
//                userMail = $('#email').val();
//                $('#email').val('');
//                replaceSubmitBtns();
//                ajaxEmailAddrChecker(userMail);
//                modifyEmailValidation();
//                
//            });
            
            e.preventDefault();
            e.stopPropagation();
        });
    }
}

function modifyPasswordLayer(){
    var $btn = $('#modifyPassworBtn'),
        $loader = $('<div style="text-align:center;"><img src="' + K_WEB_PATH + 'public/img/ajax-loader-dialog.gif" width="48" height="48" alt="ajax loading" title="" /></div>');
    if($btn.length){
        $('<div id="modifyPasswordDialog" class="dialogBox"></div>').appendTo($('body'));
        $btn.click(function(e){
            var $modDialog = $('#modifyPasswordDialog').dialog({
                buttons: {
                    "Mégse": function(){
                        $(this).dialog('destroy').empty();
                    }
                },
                title: 'Jelszó módosítás',
                minHeight: 0,
                bgiframe: true,
                width: 500,
                modal: true,
                close: function(event, ui){
                    $(this).dialog('destroy').empty();
                }
            });
            
            $modDialog.html($loader).find('form').live('submit',function(e){
                    $.post($(this).attr('action'), $(this).serialize(), function(data){
                        $modDialog.html(data);
                        if ($modDialog.find('.passwordModSucc').length) {
                            $modDialog.dialog('option','buttons', {
                                'Bezárás': function(){
                                    $(this).dialog('destroy').empty();
                                }
                            });
                        }
                        replaceSubmitBtns();
                        ajaxEmailAddrChecker();
                        modifyPasswordValidation();
                      });
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
                
                $.get($btn.attr('href'),function(data){
                    if(data.error=='session_timeout'){
                        $modDialog.dialog('option','close',function(){
                            window.location.href = K_WEB_PATH;
                        });
                        $modDialog.dialog('option','buttons',{
                            'Ok': function(){
                            window.location.href = K_WEB_PATH;
                        }
                        }).html('<p><strong>A weboldal biztonsági okokból kijelentkeztette.</strong><br><br>Ez olyankor fordul elő, ha 15 percnél hosszabb ideig nem használja a weboldalt.<br><br>Kérjük, jelentkezzen be újra.</p>');
                    }
                    else{
                        $modDialog.html(data);
                        replaceSubmitBtns();
                        ajaxEmailAddrChecker();
                        modifyPasswordValidation();
                    }
                });
                
//            $modDialog.load($btn.attr('href'),function(){
//                replaceSubmitBtns();
//                ajaxEmailAddrChecker();
//                modifyPasswordValidation();
//            });
            
            e.preventDefault();
            e.stopPropagation();
        });
    }
}

function deleteProfileLayer(){
    var $btn = $('#myProfDel'),
        $loader = $('<div style="text-align:center;"><img src="' + K_WEB_PATH + 'public/img/ajax-loader-dialog.gif" width="48" height="48" alt="ajax loading" title="" /></div>');
    if($btn.length){
        $('<div id="profileDeleteDialog" class="dialogBox"></div>').appendTo($('body'));
        $btn.click(function(e){
            var $modDialog = $('#profileDeleteDialog').dialog({
                buttons: {
                    "Mégse": function(){
                        $(this).dialog('destroy').empty();
                    }
                },
                title: 'Regisztráció törlése',
                minHeight: 0,
                width: 500,
                bgiframe: true,
                modal: true,
                close: function(event, ui){
                    $(this).dialog('destroy').empty();
                }
            });
            
            $modDialog.html($loader).find('form').live('submit',function(e){
                    $.post($(this).attr('action'), $(this).serialize(),
                      function(data){
                        $modDialog.html(data);
                        if ($modDialog.find('.passwordModSucc').length) {
                            $modDialog.dialog('option','buttons', {
                                'Bezár': function(){
                                    $(this).dialog('destroy').empty();
                                    $('.logout').trigger('click');
                                }
                            });
                        }
                        modifyPasswordValidation();
                        replaceSubmitBtns();
                        ajaxEmailAddrChecker();
                      });
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
            
            $.get($btn.attr('href'),function(data){
            	if(data.error=='session_timeout'){
                    $modDialog.dialog('option','close',function(){
                            window.location.href = K_WEB_PATH;
                        });
            		$modDialog.dialog('option','buttons',{
            			'Ok': function(){
            			window.location.href = K_WEB_PATH;
            		}
            		}).html('<p><strong>A weboldal biztonsági okokból kijelentkeztette.</strong><br><br>Ez olyankor fordul elő, ha 15 percnél hosszabb ideig nem használja a weboldalt.<br><br>Kérjük, jelentkezzen be újra.</p>');
            	}
            	else{
	            	$modDialog.html(data);
	                modifyPasswordValidation();
	                replaceSubmitBtns();
	                ajaxEmailAddrChecker();
            	}
            });
            
            e.preventDefault();
            e.stopPropagation();
        });
    }
}

function voteBoxes(){
    
    var $databoxes=$('.dataBox');
    
    $databoxes.each(function(i){
        
        var $box=$(this),
            $modButton = $box.find('.modLink'),
            $rateButton = $box.find('.rateLink'),
            $mod = $box.find('.modify').hide(),
            $form = $box.find('form'),
            $cancel = $form.find('.cncl'),
            $radios = $box.find('.stars table').hide().find('.frmRadio'),
            $textarea =  $form.find('.opinion'),
            //curRateText = $mod.find('.ratingText').html(),
            $stars = [],
            $formStars = [],
            oldText = '',
            oldRating = 0,
            rating = 0;
            
        
            
        if($box.find('.voted').length){
            rating = $box.find('.rating').hide().html();
            oldRating = $box.find('.rating').hide().html();
            oldText = $textarea.val();
            $stars = $box.find('.voted .stars .star');
            $stars.filter(':lt('+(rating)+')').addClass('hovered');
        }
        
        $radios.each(function(i){
            var $star=$('<span class="star"></span>');
            if(i+1<=rating)$star.addClass('hovered');
            $box.find('form .stars').append($star);
        });
        
        $formStars = $form.find('.star');
        
        $modButton.live('click',function(e){
            $box.find('.voted').hide();
            $mod.find('.ratingText').html('Értékelés módosítása:');
            $mod.find('.ratingLabel').html('Vélemény módosítása:');
            $mod.find('.replacedSubmit').html('<strong>Módosítások mentése</strong>');
                $mod.show();
                $radios.eq(rating-1).check();
            e.preventDefault();
        });
        
        $rateButton.addClass('opened').click(function(e){
            $mod.show();
            $(this).hide();
            e.preventDefault();
        });
        
        $cancel.click(function(e){
            $mod.hide();
            $box.find('.voted').show();
            $mod.find('.errorbox').remove();
            $rateButton.show();
            $rateButton.toggleClass('opened');
            e.preventDefault();
            rating = oldRating;
            $textarea.val(oldText);
            $formStars.removeClass('hovered').filter(':lt(' + (rating) + ')').addClass('hovered');
        });
        
        $formStars.mouseover(function(){
            var x = $.inArray(this, $formStars);
            $formStars.removeClass('hovered').filter(':lt('+(x+1)+')').addClass('hovered');
        }).click(function(){
            var x = $.inArray(this, $formStars);
            $radios.eq(x).check();
        }).parent().mouseleave(function(){
            var x = $.inArray($radios.filter(':checked')[0], $radios);
            $formStars.removeClass('hovered').filter(':lt('+(x+1)+')').addClass('hovered');
        });
        
        $form.submit(function(e){
            var $f = $(this);
            rating = $f.find('input:checked').val();
            if (rating) {
                
                if (rating != oldRating || $textarea.val() != oldText) {
                    
                    $.ajax({
                        url: K_QUERY_PATH + 'user/rate',
                        data: $(this).serialize(),
                        type: 'post',
                        success: function(data){
                            if (data.error == 'session_timeout') {
                                $('<div id="voteDialog" class="dialogBox"></div>').appendTo($('body'));
                                var $modDialog = $('#voteDialog').dialog({
                                    buttons: {
                                        'Ok': function(){
                                            window.location.href = K_WEB_PATH;
                                        }
                                    },
                                    title: 'Termék értékelése',
                                    minHeight: 0,
                                    width: 500,
                                    bgiframe: true,
                                    modal: true,
                                    close: function(event, ui){
                                        window.location.href = K_WEB_PATH;
                                    }
                                }).html('<p><strong>A weboldal biztonsági okokból kijelentkeztette.</strong><br><br>Ez olyankor fordul elő, ha 15 percnél hosszabb ideig nem használja a weboldalt.<br><br>Kérjük, jelentkezzen be újra.</p>');
                            }
                            else if (data) {
                                if (!$box.find('.voted').length) {
                                    var $votedBox = $('<div class="voted">' +
                                    '<div>' +
                                    '<strong>A termék értékelése: <var class="rating dn">' +
                                    rating +
                                    '</var></strong>' +
                                    '<div class="stars">' +
                                    '<span class="star s_1"></span>' +
                                    '<span class="star s_2"></span>' +
                                    '<span class="star s_3"></span>' +
                                    '<span class="star s_4"></span>' +
                                    '<span class="star s_5"></span>' +
                                    '</div>' +
                                    '<a class="modLink" href="#">módosít</a>' +
                                    '</div>' +
                                    '</div>');
                                    
                                    $rateButton.replaceWith($votedBox);
                                    $stars = $box.find('.voted .stars .star');
                                    $stars.filter(':lt(' + (rating) + ')').addClass('hovered');
                                    
                                }
                                else {
                                    $stars.removeClass('hovered').filter(':lt(' + (rating) + ')').addClass('hovered');
                                }
                                
                                $mod.hide();
                                $box.find('.voted').show();
                                $box.find('.errorbox').remove();
                            }
                            
                            oldRating = rating;
                            oldText = $textarea.val();
                            
                        }
                    });
                } else {
                    $mod.hide();
                    $box.find('.voted').show();
                    $box.find('.errorbox').remove();
                }
            }
            else{
                $mod.find('.errorbox').remove();
                $textarea.after('<div class="errorbox cb mb10"><strong class="error">Értékeléshez kattintson a csillagokra!</strong></div>');
            }
            e.preventDefault();
        });
        
    });
}

function imeiNum(){
    
    var $imeiNumRow = $('.imeiNumRow');
    
    if($imeiNumRow.length){
        
        var $prodGroup = $('#product_group'),
            $prodCat = $('#product_cat'),
            $prodNum = $('#product_num'),
            $imei = $('#imei').disable(),
            $label = $imei.parents('.formRow').find('label');
            
        if ($prodGroup.val() == '1') {
            $imeiNumRow.slideDown('fast');
            $imei.enable();
        }
        
        $prodGroup.change(function(){
            if ($(this).val() == '1') {
                $imei.enable();
                $imeiNumRow.slideDown('fast');
            }
            else{
                $imei.disable();
                $imeiNumRow.slideUp('fast');
            }
            $label.find('span').remove();
        });
        
        $prodCat.change(function(){
            if ($prodGroup.val() == '1') {
                if ($(this).find('option:selected').attr('parent') != 8) {
                    $imei.enable();
                    $imeiNumRow.slideDown('fast');
                }
                else {
                    $imei.disable();
                    $imeiNumRow.slideUp('fast');
                }
            }
            $label.find('span').remove();
        });
        
//        $prodNum.change(function(){
//            if( $(this).find('option:selected').html() == 'GT-S5620' )$label.append('<span>*</span>');
//            else $label.find('span').remove();
//        });
        
    }
}

function purchasePlace(){
    
    var $sel=$('#purchase_place'),
        $url=$('.purchaseUrlInput'),
        $citySel = $('#purchase_city'),
        citySelVal = $('var#' + $citySel.attr('id') + '_data').html() || '',
        $addrSel = $('#purchase_address_id'),
        addrSelVal = $('var#' + $addrSel.attr('id') + '_data').html() || '',
        pageLoaded = (citySelVal)?true:false,
        $otherPpi = $('.formRow.otherPurchasePlaceInputs'),
        $pop = $otherPpi.find('#purchase_other_place'),
        $poc = $otherPpi.find('#purchase_other_city'),
        $poa = $otherPpi.find('#purchase_other_address'),
        $aloader = $('<div />').addClass('aloader').css({
            opacity: 0.5
        });
        
        function handleSessionTimeout(){
            var $modDialog = $('<div />').appendTo('body').dialog();
            $modDialog.dialog('option','close',function(){
                            window.location.href = K_WEB_PATH;
                        });
                    $modDialog.dialog('option','buttons',{
                        'Ok': function(){
                        window.location.href = K_WEB_PATH;
                    }
                    }).html('<p><strong>A weboldal biztonsági okokból kijelentkeztette.</strong><br><br>Ez olyankor fordul elő, ha 15 percnél hosszabb ideig nem használja a weboldalt.<br><br>Kérjük, jelentkezzen be újra.</p>');
        }
        
    $addrSel.change(function(){
        $(this).parent().find('.formErrors').remove();
    });
        
    $citySel.change(function(){
        
        $addrSel.hide().find('option.ajaxLoaded').remove();
        $otherPpi.hide().find('.formErrors').remove();
        
        var $t = $(this);
        $t.parent().find('.formErrors').remove();
        $t.parent().append($aloader);
        $aloader.css({
            width: $t.outerWidth() + 'px',
            height: $t.outerHeight() + 'px',
            left: $t.position().left
        }).show();
        
        $.getJSON(K_QUERY_PATH + 'product/getpurchaseaddresslist&purchase_place=' + encodeURIComponent($sel.val()) + '&purchase_city=' + encodeURIComponent($t.val()), function(data){
            if (data != null) {
                if (data.length != 0) {
                    $.each(data, function(i, item){
                        $("<option/>").addClass('ajaxLoaded').attr("value", i).text(item).appendTo($addrSel);
                    });
                    $addrSel.show();
                    if (pageLoaded) {
                        $addrSel.find('option[value="' + addrSelVal + '"]').select();
                    }
                }
            }
            else{
                sessionTimeoutHandler();
            }
            $aloader.remove();
        });
    });
    
    $sel.change(function(){
        
        $citySel.hide().find('option.ajaxLoaded').remove();
        $addrSel.hide().find('option.ajaxLoaded').remove();
        $otherPpi.hide().find('.formErrors').remove();
        
        var $t = $(this),
            thisVal = $t.find('option:selected').html(),
            mobile = ($('#product_group option:selected').html()=='Mobiltelefonok')?true:false;
            
        $t.parent().find('.formErrors').remove();
        
        if (thisVal == 'Online vásárlás'){
            $otherPpi.hide().find('.formErrors').remove();
            $url.find('label').removeClass('dn');
            $url.slideDown('fast');
        }   
        else {
            $('#purchase_url').val('');
            $url.hide().find('.formErrors').remove();
            if(mobile || citySelVal){
                if(thisVal=='Egyéb'){
                    $otherPpi.slideDown('fast');
                }
                else{
                    $t.parent().append($aloader);
                    $aloader.css({
                        width: $t.outerWidth() + 'px',
                        height: $t.outerHeight() + 'px',
                        left: $t.position().left
                    }).show();
                    $.getJSON(K_QUERY_PATH + 'product/getpurchaseaddresslist&purchase_place=' + encodeURIComponent($t.val()), function(data){
                        if (data != null) {
                            if (data.length != 0) {
                                $.each(data, function(i, item){
                                    $("<option/>").addClass('ajaxLoaded').attr("value", i).text(item).appendTo($citySel);
                                });
                                $citySel.show();
                                if (pageLoaded) {
                                
                                    $citySel.find('option[value="' + citySelVal + '"]').select();
                                    $citySel.trigger('change');
                                }
                            }
                        }
                        else{
                            sessionTimeoutHandler();
                        }
                        $aloader.remove();
                    });
                }
            }
        }
         
    });
    
    if ($sel.find('option:selected').html()=='Online vásárlás'){
        $url.find('label').removeClass('dn');
        $url.slideDown();
    }
    else if ($sel.find('option:selected').html()=='Egyéb' ){
        $otherPpi.show();
    }
    else {
        $sel.trigger('change');
    }        
    
    $('#purchase_url').blur(function(){
        var u = $(this).val();
        if($.beginsWith(u,'http://'))u=u.replace('http://','');
        if($.beginsWith(u,'https://'))u=u.replace('https://','');
        $(this).val(u);
    });
    
    $('#product_group').change(function(){
        if($(this).find('option:selected').html()!='Mobiltelefonok'){
            $citySel.hide().find('option.ajaxLoaded').remove();
            $addrSel.hide().find('option.ajaxLoaded').remove();
            $otherPpi.hide().find('.formErrors').remove();
        }
        else {
            if ($sel.find('option:selected').html()=='Online vásárlás'){
                $url.find('label').removeClass('dn');
                $url.slideDown();
            }
            else if ($sel.find('option:selected').html()=='Egyéb' ){
                $otherPpi.show();
            }
            else {
                $sel.trigger('change');
            }
        }
    });
    
    $('body').click(function(){
        pageLoaded = false;
    })
    
}

function showCompanyData(){
    var $comp=$('#company_data_section');
    var $felements=$comp.find('input, select, textarea');
    
    if(!$('#type-2').is(':checked')){
        $comp.slideUp();
        $felements.disable();
    } else {
        $comp.slideDown();
        $felements.enable();
    }
    
    
    $('#type-1').click(function(){
        $comp.slideUp();
        $felements.disable();
    });
    
    $('#type-2').click(function(){
        $comp.slideDown();
        $felements.enable();
    })
}

function changeNewsLetterForms(){
    var $s = $('#subscribe-form').hide(),
        $sr = $('#subscribe'),
        $u = $('#unsubscribe-form').hide(),
        $ur = $('#unsubscribe');
        
    if ($s.is('.visible')) {
        $s.show();
        $('.subscribe').show();
        $('.unsubscribe').hide();
        $sr.attr('checked','checked');
        $.cookie('form_type', 'feliratkozas');
    }
    
    if($u.is('.visible')){
        $u.show();
        $('.subscribe').hide();
        $('.unsubscribe').show();
        $ur.attr('checked','checked');
        $.cookie('form_type', 'leiratkozas');
    }
    
    $sr.click(function(){
        $s.show();
        $u.hide();
        $('.subscribe').show();
        $('.unsubscribe').hide();
        $.cookie('form_type', 'feliratkozas');
    });
    
    $ur.click(function(){
        $s.hide();
        $u.show();
        $('.subscribe').hide();
        $('.unsubscribe').show();
        $.cookie('form_type', 'leiratkozas');
    });
}


function productGroups(){
    
    var loadedPage = ($('#product_group_data').length)?1:0;
    
    if (loadedPage){
        var pGroup = $('#product_group_data').html(),
            pCat = $('#product_cat_data').html(),
            pNum = $('#product_num_data').html(); 
    }
    
    if ($('.product_filter_campaign_product_category').length) {
        
        var $aloader_1 = $('<div />').addClass('aloader').css({
            opacity: 0.5
        });
        
        var $sel = $('#product_group');
        
        $sel.parent().append($aloader_1);
        $aloader_1.css({
            width: $sel.parent().outerWidth() + 'px',
            height: $sel.parent().outerHeight() + 'px'
        }).show();
        $.getJSON(K_QUERY_PATH + 'product/getcategorylist&type=1', function(data){
            if(data!=null){
                $.each(data, function(i, item){
                    if (i != '_empty_' || (!$.beginsWith(item.name, 'Egyéb') && !$.beginsWith(item.name, 'egyéb'))) 
                        $("<option/>").addClass('ajaxLoaded').attr("value", i).text(item).appendTo($sel);
                });
            }
            else{
                sessionTimeoutHandler();
            }
            if (loadedPage){
                
                $sel.find('option').filter(function(){
                    return $(this).attr('value')==pGroup;
                }).select();
                
                $('.product_filter_campaign_product_category').trigger('change');
                
            }
            $aloader_1.hide().remove();
        });
        
        
        
        
        $('.product_filter_campaign_product_category').change(function(){
        
            var $sel = $(this);
            
            var val = encodeURIComponent($sel.val());
            var $nextSel = $sel.parents('td').next().find('select');
            var $nextAllSel = $sel.parents('td').nextAll().find('select');
            $nextAllSel.find('.ajaxLoaded').remove();
            
            $nextAllSel.enable();
            $nextSel.parent().append($aloader_1);
            $aloader_1.css({
                width: $nextSel.parent().outerWidth() + 'px',
                height: $nextSel.parent().outerHeight() + 'px'
            }).show();
            $.getJSON(K_QUERY_PATH + 'product/gettypelist&type=1&category_id=' + val, function(data){
                if (data != null) {
                    $.each(data, function(i, item){
                        var lvl = (item.level == 2) ? 'level_2' : 'level_1';
                        var parent = item.parent;
                        var txt = (item.level == 2) ? '&nbsp;&nbsp;&nbsp;' + item.name : item.name;
                        $('<option/>').addClass('ajaxLoaded ' + lvl).attr({
                            'value': i,
                            'parent': parent
                        }).html(txt).appendTo($nextSel);
                    });
                    
                    $('.ajaxLoaded').each(function(){
                        var $opt = $(this);
                        var $nxt = $opt.next();
                        if ($.beginsWith($opt.html(), '&nbsp;&nbsp;&nbsp;Egyéb') || $.beginsWith($opt.html(), '&nbsp;&nbsp;&nbsp;egyéb')) {
                            $opt.remove();
                        }
                        else 
                            if ($.beginsWith($opt.html(), 'Egyéb') || $.beginsWith($opt.html(), 'egyéb')) {
                                $opt.nextUntil('.level_1').remove();
                                $opt.remove();
                            }
                        if ($opt.hasClass('level_1') && $nxt.hasClass('level_2')) {
                            var text = $opt.html();
                            $opt.replaceWith('<optgroup class="ajaxLoaded level_1" label="' + text + '"></optgroup>');
                        }
                        
                    });
                }
                else{
                    sessionTimeoutHandler();
                }
                
                if (loadedPage) {
                
                    $('.product_filter_campaign_product_type').trigger('change');
                    
                }
                $aloader_1.hide().remove();
            });
            
        }).append('<option value=""> - Termékcsoport - </option>');
        
        $('.product_filter_campaign_product_type').change(function(){
            var $sel = $(this);
            
            if (loadedPage){
                
                $sel.find('option').filter(function(){
                    return $(this).attr('value')==pCat;
                }).select();
                
            }
            
            var val = encodeURIComponent($sel.val());
            var $nextSel = $sel.parents('td').next().find('select');
            var $nextAllSel = $sel.parents('td').nextAll().find('select');
            $nextAllSel.find('.ajaxLoaded').remove();
            
            $nextAllSel.enable();
            $nextSel.parent().append($aloader_1);
            $aloader_1.css({
                width: $nextSel.parent().outerWidth() + 'px',
                height: $nextSel.parent().outerHeight() + 'px'
            }).show();
            $.getJSON(K_QUERY_PATH + 'product/getmodellist&type=1&type_id=' + val, function(data){
                if (data != null) {
                    $.each(data, function(i, item){
                        if (!$.beginsWith(item, 'Egyéb')) 
                            $('<option/>').addClass('ajaxLoaded').attr('value', i).text(item).appendTo($nextSel);
                    });
                    if ($nextSel.find('.ajaxLoaded').length) 
                        $nextSel.find('option:first').before('<option value=""> - Modellkód - </option>').remove();
                    else 
                        $nextSel.html('').append('<option value=""> Ebben a típusban nincs modell. Válasszon másikat! </option>');
                }
                else{
                    sessionTimeoutHandler();
                }
                if (loadedPage){
                    
                    $('.product_filter_campaign_product_model').find('option').filter(function(){
                        return $(this).html()==pNum || $(this).val()==pNum;
                    }).select();
                    
                    loadedPage = 0;
                    
                }
                $aloader_1.hide().remove();
            });
            
        }).append('<option value=""> - Terméktípus - </option>');
        
        $('.product_filter_campaign_product_model').append('<option> - Modellkód - </option>');
    }
    
    var $all = $('select.prodgroup');
        
    $all.click(function(){
        $all.next('ul.formErrors').remove();
    });
    
}

function deleteProdConfirm(){
    $('<div id="productDeleteDialog" class="dialogBox"></div>').appendTo($('body'));
    $('.delete').click(function(e){
        var $btn = $(this),
            $modDialog = $('#productDeleteDialog').dialog({
            buttons: {
                "Mégse": function(){
                    $(this).dialog('destroy').empty();
                },
                "Ok": function(){
                    window.location.href = $btn.attr('href');
                    //$(this).dialog('destroy').empty();
                }
            },
            title: 'Termék törlése',
            minHeight: 0,
            width: 300,
            bgiframe: true,
            modal: true,
            close: function(event, ui){
                $(this).dialog('destroy').empty();
            }
        }).html('Biztosan törölni szeretné ezt a terméket?');
        e.preventDefault();
    });
}

function linkInLabel () {
    // label-en belüli a tagek kattintása ne váltsa ki a label kattintást
    $('label').filter(function(){
        return $(this).children('a').length>0;
    }).click(function(e){
        if(e.target.nodeName=='A'){
            e.stopPropagation();
            e.preventDefault();
            if(e.target.target=='_blank')window.open(e.target.href);
            else window.location.href = e.target.href;
        }
    });
}

function guaranteeTooltips(){
    $('<div id="guaranteeDialog" class="dialogBox"></div>').appendTo($('body'));
    var $tt = [];
    $('.guaranteeTip').each(function(){
        var $t = $(this);
        $t.click(function(e){
            $tt = $('#guaranteeDialog').dialog({
                buttons: {
                    "Bezár": function(){
                        $(this).dialog('destroy').empty();
                    }
                },
                title: 'Garanciaidő',
                minHeight: 0,
                width: 500,
                bgiframe: true,
                modal: true,
                close: function(event, ui){
                    $(this).dialog('destroy').empty();
                }
            }).html('<p><strong>A garanciaidő lejárati dátuma tájékoztató jellegű!</strong><br /><br />Az itt megjelenített dátum az Ön által megadott vásárlási dátum, illetve online vásárlás esetén a rendelés leadásának időpontja alapján számított. A tényleges lejárati dátumról a termék garanciajegye és az esetleges garanciahosszabbítást igazoló lap együttesen nyújt pontos információt.<br />Különösen valószínű az eltérés abban az esetben, ha a termék regisztrációja során nem adta meg a modellnevet.<br /><br />Bizonyos termékek egyes alkatrészeire eltérő hosszúságú a garanciaidő, illetve egyes termékekre a garanciaidő lejárata után további jótállást vállalunk.<br /><br /> <strong>A 2010. március 31. után szolgáltatónál vásárolt (nem kártyafüggetlen) mobiltelefonokra</strong> a gyártói garancia itt feltüntetett lejárati dátuma után további 1 év Samsung teljes körű garanciát biztosítunk.</p>');
            e.preventDefault();
        });
    });
}

function printButtons(){
    $('.printBtn').click(function(e){
        window.print();
        e.preventDefault();
    });
}

function showWarrantyCardSample(){
    var $btn = $('#warrantyCard');
    if($btn.length){
        $('<div id="showWarrantyCardSample" class="dialogBox"></div>').appendTo($('body'));
        $btn.click(function(e){
            var $modDialog = $('#showWarrantyCardSample').dialog({
                buttons: {
                    "Bezár": function(){
                        $(this).dialog('destroy').empty();
                    }
                },
                title: 'Jótállási jegy minta',
                height: 400,
                width: 630,
                bgiframe: true,
                modal: true,
                close: function(event, ui){
                    $(this).dialog('destroy').empty();
                }
            }).html('<img src="'+K_WEB_PATH+'public/img/jotallasi-jegy-minta.gif" width="600" height="831" alt="Jótállási jegy minta" title="" />');
            e.preventDefault();
        });
    }
}

function sessionTimeoutHandler(){
    var $modDialog = $('<div id="sessionTimeOut" class="dialogBox"></div>').appendTo($('body')).dialog({
        buttons: {
            "Ok": function(){
                window.location.href = (K_WEB_PATH);
                $(this).dialog('destroy');
            }
        },
        title: 'Hiba',
        minHeight: 0,
        width: 500,
        bgiframe: true,
        modal: true,
        close: function(event, ui){
            window.location.href = (K_WEB_PATH);
        }
    }).html('<p><strong>A weboldal biztonsági okokból kijelentkeztette.</strong><br><br>Ez olyankor fordul elő, ha 15 percnél hosszabb ideig nem használja a weboldalt.<br><br>Kérjük, jelentkezzen be újra.</p>');
}

jQuery(function($){
    linkInLabel();
    replaceSubmitBtns();
    ajaxEmailAddrChecker();
    ajaxZipList();
    modifyEmailLayer();
    modifyPasswordLayer();
    deleteProfileLayer();
    voteBoxes();
    showCompanyData();
    purchasePlace();
    imeiNum();
    changeNewsLetterForms();
    productGroups();
    deleteProdConfirm();
    guaranteeTooltips();
    printButtons();
    historyBackButtons();
    showWarrantyCardSample();
});



