$(document).ready(function() {
    $('.cat-link a').click(function () {
        $.cookie('opencat', $(this).attr('id').replace('cat-', ''), {path: '/'});
    });

    $('.middle-cat-link a').click(function () {
        cid = $(this).attr('id').replace('middle-cat1-link-', '');
        cid = $(this).attr('id').replace('middle-cat2-link-', '');
        cid = $(this).attr('id').replace('middle-cat3-link-', '');
        $.cookie('opencat', cid, {path: '/'});
    });

    $('#categories .leveltwo ul').addClass('levelthree');
    var cats = $('#categories').find('#cat-'+$.cookie('opencat'));
    cats.parents('ul').addClass('selected').show();
    cats.parents('li').addClass('selected');
    $('#categories ul:not(.selected)').hide();
    
    var cats = $('#categories .cat-link-folder').find('#cat-'+$.cookie('opencat'));
    cats.next().show();

    $('div#open-company').css('opacity', 0.85);
    $('div#open-form').css('opacity', 1.5);
    
    $('div.action-menu div.action-menu-list').hide();
    
    $('#cms-cat-select').change(function () {
    	var url = document.location.href;
    	url = url.replace(/\/category\/[0-9]+/, '');
    	document.location.href = url + '/category/' + $(this).val();;
    });
     
    $('div#tabs div.tab-caption:first').addClass('tab-active');
    $('form.tabbed-form fieldset').parent().hide();
    $('form.tabbed-form fieldset').parent().prev().hide();
    $('form.tabbed-form fieldset#fieldset-general').parent().show();
    $('form.tabbed-form fieldset#fieldset-save').parent().show();
    $('form.line-sub-form .element-label').hide();
    
    jQuery.fn.setActiveStep(0);
    
    $(':text, input[type=password], textarea').focus(function() {
    	$(':text, input[type=password], textarea').removeClass('highlight');
    	$(this).addClass('highlight');
    });
    
    $('fieldset#fieldset-newaddress').hide();
    
    $('div#product-gallery div#pictures div.picture').click(function() {
    	link = $(this).find('img').next('div').text();
    	$('div#product-gallery div#actual-picture').find('img').attr('src', link);
    });
    
    $('.photobox').each(function (i) {
    	id = $(this).attr('id').substring(9);
    	$(this).refreshPhotobox(id); 
    });
    
    $('div#header').everyTime(10000, function(i) {
    	set = $('.photobox');
    	set.each(function (i) {
    		id = $(this).attr('id').substring(9);
    		$(this).refreshPhotobox(id);
    	});
    });
    
    $('div#product-gallery div#actual-picture img').resizeElem(500);
    $('div#product-gallery div#actual-picture img').show();
    
    currDate = new Date();
    var currYear = currDate.getFullYear() + 10;
    
    $.datepicker.setDefaults($.extend({
    		showMonthAfterYear: false, 
            minDate: 1,
    		constrainInput: true,
    		yearRange: '1920:' + currYear,
    		showOtherMonths: false,
            numberOfMonths: 2,
            showWeek: true, 
            firstDay: 1
    	}, $.datepicker.regional[mbPortal.currLang])
	);
    
    if ($('#ship-method-form input#date').length > 0) {
        $('#ship-method-form input#date').parents('.element-form').css('margin-top', '10px');
        
	    $('#ship-method-form input#date').parent().datepicker({
            onSelect: function(dateText, inst) {
                $('input#date').val(dateText);
            }
        });
    }
    
	/*$('#item-list tr .item-list-description').hover(
	    function () {
    	    var jq = $(this).find('.product-info-bubble');
    	    if (jq.css('display') == 'none') {
    	       jq.fadeIn('slow');
    	    }
    	    $().mousemove(function (e) {
                jq.css('top', e.pageY + 'px').css('left', e.pageX + 'px');
            });
        },
        function () {
            $(this).find('.product-info-bubble').fadeOut('fast');
        }
    );*/
    
    $('.product-picture-fk').hover(
        function () {
            var jq = $(this).find('.product-info-bubble');
            if (jq.css('display') == 'none') {
               jq.fadeIn('slow');
            }
            $(this).mousemove(function (e) {
                jq.css('top', e.pageY + 'px').css('left', e.pageX + 'px');
            });
        },
        function () {
            $(this).find('.product-info-bubble').fadeOut('fast');
        }
    );    
    
    $('#language-change-hu').click(function () {
        $.cookie('language', 'hu', { path: '/'});
        document.location.reload(true);
    });

    $('#language-change-en').click(function () {
        $.cookie('language', 'en', { path: '/'});
        document.location.reload(true);
    });   
    
    $('#language-change-de').click(function () {
        $.cookie('language', 'de', { path: '/'});
        document.location.reload(true);
    });
    
    $('a#registerBtn').hover(function() {
        $(this).addClass('ui-state-highlight');
    },function () {
        $(this).removeClass('ui-state-highlight');
    });
    
    $('#shopping-cart-form .order-qty').checkOrderQty();
    
    if (mbPortal.itemBoxChangeInterval > 0) {
        $('div#itembox-new').everyTime(mbPortal.itemBoxChangeInterval, function(i) {
            $.fn.refreshItembox('new');
        });
    }
    
    if (mbPortal.itemBoxChangeInterval > 0) {
        $('div#itembox-offer').everyTime(mbPortal.itemBoxChangeInterval, function(i) {
            $.fn.refreshItembox('offer');
        });
    }
    
    $('#select-abc-list').change(function () {
        if ($(this).val.length > 0)
            document.location.href='/products/index/Category_Id/'+$(this).val();
    });
    
    $('#shopping-cart-create').validateCartCreateForm();
    $('#shopping-cart-create').submit(function () {
        var no = $('#shopping-cart-create #itemno');
        var desc = $('#shopping-cart-create #itemdesc');
        var qty = $('#shopping-cart-create #orderqty');
        
        if (no.val().length == 0) {
            alert('Kérem adjon meg cikkszámot!');
            no.focus();
            return false;
        }
        
        var val = parseFloat($(this).find('.order-qty').val());
        var minVal = parseFloat($(this).find('.min-order-qty').html());
        var inv = parseFloat($(this).find('.inventory').text());
        
        val = (isNaN(val) ? 0 : val);
        minVal = (isNaN(minVal) ? 1 : minVal);
        minVal = (minVal == 0 ? 1 : minVal);
        inv = (isNaN(inv) ? 0 : inv);
        
        if (val < minVal) {
            if (confirm('A legkisebb rendelhető mennyiség: '+ minVal+'. Elfogadja?')) {
                val = minVal;
                $(this).find('.order-qty').val(minVal);
            } else {
                return false;
            }
        }
        
        if (val > inv) {
            var mul = Math.floor(inv / minVal);
            var newVal = mul * minVal;

            if (inv == 0) {
                if (confirm('Jelenleg nincs raktáron a termék. Mégis megrendeli?')) {
                    return true;
                } else {
                    return false;
                }
            } else {
                if (confirm('Az elérhető készlet ' + newVal + '. Elfogadja ' + val + ' helyett?')) {
                    $(this).find('.order-qty').val(newVal);
                } else {
                    return false;
                }
            }
        } else {
            if (val % minVal != 0) {
                var mul = Math.ceil(val / minVal);
                var newVal = mul * minVal;

                if (confirm('Az egységcsomag '+minVal+', így a helyes érték '+newVal+'. Elfogadja?')) {
                    $(this).find('.order-qty').val(newVal);
                } else {
                    return false;
                }
            }
        }   
        
        return true;
    });
    
    $('#blind-change, #wcag-view').click(function () {
        if ($.cookie('wcag')) {
            $.cookie('wcag', null, {path: '/'});
        } else {
            $.cookie('wcag', 1, {path: '/'});
        }
        document.location.reload(true);
    });
    
    if ($('#shopping-progress').length > 0) {
	    $('.shopping-step').each (function () {
	    	$(this).keypress(function (e) {
		    	var elem = $(this);
		        var code = (e.keyCode ? e.keyCode : e.which);
		        switch(code) {
		        	case 13:
		        		$(this).find('form').submit();
		        		return false;
		        		break;
		        }
	    	});
	    });
    }
    
    $('.language-change').click(function () {
    	lang = $(this).attr('id').replace('language-', '');
        $.cookie('language', lang, { path: '/'});
        document.location.reload(true);
    });    
    

    if ($("#popup-dialog").length > 0) {
        $("#popup-dialog").dialog({
            bgiframe: true,
            height: mbPortal.popupHeight,
            width: mbPortal.popupWidth,
            modal: true,
            show: mbPortal.popupAnimation,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                /*Ok: function() {
                    $(this).dialog('destroy');
                }*/
            },
            close: function(event, ui) {
                $(this).dialog('destroy');
            }
        }); 
    }    
    
    $('#offer_select-label').hide();
    $('#offer_select').change(function () {
        document.location.href = 'http://fehervarkerekpar.hu/products/offer/kategoria/'+$(this).val();
    });
    
    if ($('#inv-btn').length > 0) {
        if ($.cookie('onlyinv') == 1) {
            $('#inv-btn').val(mbPortal.lang[mbPortal.currLang].All_Prod);
        } else {
            $('#inv-btn').val(mbPortal.lang[mbPortal.currLang].Only_Inv);
        }
        
        $('#inv-btn').click(function () {
            if ($.cookie('onlyinv') == 1) {
                $.cookie('onlyinv', null, {path: '/'});
            } else {
                $.cookie('onlyinv', 1, {path: '/'});
            }
            document.location.reload(true);
        });
    }    
});

jQuery.fn.extend({ 
	ajaxSendForm: function() {
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(msg) {
				msg = jQuery.trim(msg);
				alert(msg);
			}
		});
		return false;
	},
	ajaxSendRegisterForm: function() {
		$('.ajax-loader').show();
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(msg) {
				msg = jQuery.trim(msg);
				$('.ajax-loader').hide();
				if (msg == 'Success') {
					//jQuery.fn.setActiveStep(3);
					document.location.reload();
				} else {
					$('#registerForm').html(msg);
					$('#registerForm').show();
				}
			}
		});
		return false;
	},
	ajaxSendBillingAddressForm: function() {
		$('.ajax-loader').show();
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(msg) {
				msg = jQuery.trim(msg);
				$('.ajax-loader').hide();
				if (msg == 'Success') {
					jQuery.fn.setActiveStep(2);
				} else if (msg == 'SuccessOver') {
					jQuery.fn.setActiveStep(3);
				} else {
					$('#billing-address').html(msg);
					$('#billing-address').show();
				}
			}
		});
		return false;
	},
	ajaxSendShipAddressForm: function() {
		$('.ajax-loader').show();
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(msg) {
				msg = jQuery.trim(msg);
				$('.ajax-loader').hide();
				if (msg == 'Success') {
					jQuery.fn.setActiveStep(3);
				} else {
					$('#ship-address').html(msg);
					$('#ship-address').show();
				}
			}
		});
		return false;
	},	
    lookup: function(url, where) {
		offset = $(this).offset();
		$('#lookup-form').css('top', offset.top);
		$('#lookup-form').css('left', offset.left);
		$('#lookup-form').html('<div id="list"><img src="/themes/images/admin/progress.gif" alt="Loading.." /></div>');
		$('#lookup-form').show();
		value = '';
		if (where != '')
		{
			value = $('#' + where).val();
		}
		$.ajax({
			type: "POST",
			url: url,
			data: { field: value },
			success: function(msg) {
				$('#lookup-form').hide();
				$('#lookup-form').html(msg);
				$('#lookup-form').show('normal');
			}
		});		
	},
	ajaxSendShipMethodForm: function() {
		$('.ajax-loader').show();
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(msg) {
				msg = jQuery.trim(msg);
				$('.ajax-loader').hide();
				if (msg == 'Success') {
                    jQuery.fn.setActiveStep(5);
                    $('.ajax-loader').show();
                    $('#order-review').hide();
                    $.ajax({
                        type: "POST",
                        url: '/user/cart/ajaxcheckorder',
                        data: $(this).serialize(),
                        success: function(msg) {
                            msg = jQuery.trim(msg);
                            $('.ajax-loader').hide();
                            $('#order-review').html(msg);
                            $('#order-review').slideDown(500);
                            $('#order-review').parent().hide().fadeIn(1000);
                            $('#accept-form #submit').click(function () {
                                $('#step5').addClass('ui-state-disabled');
                                var w = $('#step5').width();
                                var h = $('#step5').height();
                                elem = $('#order-progressbar-container');
                                elem.css('margin-top', 0 - 50 - (h / 2 - elem.height() / 2) + 'px');
                                elem.css('margin-left', (w / 2 - elem.width() / 2) + 'px');
                                elem.show();
                            });                            
                        }
                    });
				} else {
					$('#ship-method').html(msg);
					$('#ship-method').show();
				}
			}
		});
		return false;
	},
	ajaxSendPaymentMethodForm: function() {
		$('.ajax-loader').show();
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(msg) {
				msg = jQuery.trim(msg);
				$('.ajax-loader').hide();
				if (msg == 'Success') {
					jQuery.fn.setActiveStep(5);
					$('.ajax-loader').show();
					$('#order-review').hide();
					$.ajax({
						type: "POST",
						url: '/user/cart/ajaxcheckorder',
						data: $(this).serialize(),
						success: function(msg) {
							msg = jQuery.trim(msg);
							$('.ajax-loader').hide();
							$('#order-review').html(msg);
							$('#order-review').slideDown('normal');
						}
					});
				} else {
					$('#payment-method').html(msg);
					$('#payment-method').show();
				}
			}
		});
		return false;
	},
	markRow: function() {
		$(this).parent().find('td').removeClass('marked');
		$(this).find('td').addClass('marked');
    	value = $(this).find('.lookup-no').text();
    	$('#lookup-value').val(value);
	},
	closeLookup: function(field) {
		value = $('#lookup-value').val();
		if (field != '')
		{
			if (value == '')
			{
				$('#lookup-form').hide();
				return false;
			}
			$('#' + field).val(value);
		}
		$('#lookup-form').hide();
	},
	showFormTab: function(tab) {
		$('div#tabs div.tab-caption').removeClass('tab-active');
		$(this).addClass('tab-active');
		$('form.tabbed-form fieldset').parent().prev().hide();
		$('form.tabbed-form fieldset').parent().hide();
		$('form.tabbed-form fieldset#fieldset-' + tab).parent().show();
		$('form.tabbed-form fieldset#fieldset-save').parent().show();
	},
	insertSalesLine: function() {
		$('#sales-line-subform').fadeTo('normal', 0.3);
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(msg) {
				msg = jQuery.trim(msg);
				$('#sales-line-subform').html(msg);
				$('form.line-sub-form .element-label').hide();
				$('#sales-line-subform').fadeTo('normal', 1);
			}
		});
		return false;
	},
	setActiveStep: function(step) {
		$('#shopping-progress div.shopping-step-header').addClass('ui-state-active');
        if (step == 0)
            $('#shopping-progress div.shopping-step-content').hide();
        else
		    $('#shopping-progress div.shopping-step-content').slideUp('fast');
            
		$('#step' + step).find('div.shopping-step-header').removeClass('ui-state-active');
        if (step > 0 && step < 5)
		    $('#step' + step).find('div.shopping-step-content').slideDown('normal');
        else
            $('#step' + step).find('div.shopping-step-content').show();
		
        //$.scrollTo('#step' + step);
		return false;
	},
	showAddressForm: function() {
		if ($(this).val() == 'new') {
			$('.element-form div.errors').hide();
			$('.element-form div.errors').prev('.element-label').hide();
			$('fieldset#fieldset-newaddress').show();
		} else {
			$('fieldset#fieldset-newaddress').hide();
		}
	},
	refreshPhotobox: function(id) {
		$.ajax({
			type: 'post',
			url: '/core/cms/index/photo',
			data: {photobox : id},
			success: function(msg) {
				msg = jQuery.trim(msg);
				elem = $('#photobox-' + id + ' .photos');
				elem.html(msg);
				
				/*img = elem.find('.photobox-image');
				if (img.width() > img.height()) {
					img.css('width', '190px');
				}
				if (img.height() > img.width()) {
					img.css('height', '190px');
				}*/
				elem.fadeTo(0, 0.1);
				elem.fadeTo(1500, 1.0);
			}
		});
	},
    refreshItembox: function(boxType) {
        $.ajax({
            type: 'post',
            url: '/core/cms/index/ajaxitem',
            data: {type : boxType},
            success: function(msg) {
                msg = jQuery.trim(msg);
                elem = $('#itembox-'+boxType);
                elem.html(msg);
                //elem.fadeTo(0, 0.1);
                //elem.fadeTo(500, 1.0);
            }
        });
    },    
	resizeElem: function(width) {
		if ($(this).width() > width) {
			$(this).width(width);
		}
	},
    checkOrderQty: function () {
        $(this).blur(function () {
            var val = parseFloat($(this).val());
            var minVal = parseFloat($(this).parent().find('.min-order-qty').html());
            var inv = parseFloat($(this).parent().find('.inventory').text());
            var oldqty = parseFloat($(this).parent().find('.old-qty').val());
    
            val = (isNaN(val) ? 0 : val);
            minVal = (isNaN(minVal) ? 1 : minVal);
            minVal = (minVal == 0 ? 1 : minVal);
            inv = (isNaN(inv) ? 0 : inv);

            if (val < minVal) {
                if (confirm('A legkisebb rendelhető mennyiség: '+ minVal+'. Elfogadja?')) {
                    val = minVal;
                    $(this).val(minVal);
                } else {
                    $(this).val(oldqty);
                    return false;
                }
            }
            
            if (val > inv) {
                var mul = Math.floor(inv / minVal);
                var newVal = mul * minVal;

                if (inv == 0) {
                    return true;
                } else {                
                    if (confirm('Az elérhető készlet ' + newVal + '. Elfogadja ' + val + ' helyett?')) {
                        $(this).val(newVal);
                    } else {
                        $(this).val(oldqty);
                        return false;
                    }
                }
            } else {
                if (val % minVal != 0) {
                    var mul = Math.ceil(val / minVal);
                    var newVal = mul * minVal;

                    if (confirm('Az egységcsomag '+minVal+', így a helyes érték '+newVal+'. Elfogadja?')) {
                        $(this).val(newVal);
                    } else {
                        $(this).val(oldqty);
                        return false;
                    }
                }
            }
        });
    },
    validateCartFormSubmitButton: function () {
        var form = $(this).parents('form');
        var val = parseFloat(form.find('.order-qty').val());
        var minVal = parseFloat(form.find('.min-order-qty').html());
        var inv = parseFloat(form.find('.inventory').text());
        
        val = (isNaN(val) ? 0 : val);
        minVal = (isNaN(minVal) ? 1 : minVal);
        minVal = (minVal == 0 ? 1 : minVal);
        inv = (isNaN(inv) ? 0 : inv);

        if (val < minVal) {
            if (confirm('A legkisebb rendelhető mennyiség: '+ minVal+'. Elfogadja?')) {
                val = minVal;
                $(this).val(minVal);
            } else {
                return false;
            }
        }

        if (val > inv) {
            var mul = Math.floor(inv / minVal);
            var newVal = mul * minVal;

            if (inv == 0) {
                return true;
            } else {                
                if (confirm('Az elérhető készlet ' + newVal + '. Elfogadja ' + val + ' helyett?')) {
                    $(this).val(newVal);
                } else {
                    return false;
                }
            }
        } else {
            if (val % minVal != 0) {
                var mul = Math.ceil(val / minVal);
                var newVal = mul * minVal;

                if (confirm('Az egységcsomag '+minVal+', így a helyes érték '+newVal+'. Elfogadja?')) {
                    $(this).val(newVal);
                } else {
                    return false;
                }
            }
        }
    },
    validateCartCreateForm: function () {
        var no = $('#shopping-cart-create #itemno');
        var desc = $('#shopping-cart-create #itemdesc');
        var qty = $('#shopping-cart-create #orderqty');
        var alerted = false;
        qty.focus(function() {
            $(this).select();
            if ($('#field-No').html() != no.val()) {
                $('#field-No').html(no.val());
                qty.focus();
                $.ajax({
                    type: "POST",
                    url: '/core/catalog/order/getbycode',
                    data: {code: no.val()},
                    success: function (data) {
                        obj = JSON.parse(data);
                        
                        switch (obj.message) {
                            case 'notfound':
                                $('#ajax-item-info').html('');
                                desc.val('');
                                qty.val(0);
                                no.val('');
                                $('#itemid').val('');
                                if (!alerted)
                                    alert('Termék nem található!');
                                alerted = true;
                                no.focus();
                                break;
                            default:
                            case 'success':
                                $('#orderqty').val(obj.qty);
                                $('#shopping-cart-create #itemid').val(obj.itemid);
                                $('#shopping-cart-create .min-order-qty').html(obj.minqty);
                                $('#shopping-cart-create #itemdesc').val(obj.desc);
                                $.ajax({
                                    type: "POST",
                                    url: '/core/catalog/list/ajaxcard',
                                    data: {itemid: $('#itemid').val()},
                                    success: function (data) {
                                        $('#ajax-item-info').html(data);
                                        qty.focus();
                                    }
                                });
                                break;
                        }
                    }
                });
            }            
        });
        
        no.autocomplete({
            source: '/core/catalog/order/autocomplete/field/No/desc/No,Description/limit/50/plusfield/Description/applyfilter/1',
            minLength: 1,
            select: function(event, ui) {
                $('#ajax-item-info').html('');
                desc.val(ui.item.Description);
            },
            close: function(event, ui) {
                qty.focus();
            }
        })
        .blur(function () {
            var elem = $(this);
            if (elem.val().length == 0) {
                $('#ajax-item-info').html('');
                return true;
            }
        })
        .keyup(function () {
            alerted = false;
        });
        
        desc.autocomplete({
            source: '/core/catalog/item/autocomplete/field/Description/desc/No,Description/limit/50/plusfield/No/applyfilter/1',
            minLength: 1,
            select: function(event, ui) {
                no.val(ui.item.No);
                /*if ($('#field-Description').html() != desc.val()) {
                    $('#field-Description').html(desc.val());
                    $.ajax({
                        type: "POST",
                        url: '/core/catalog/order/getbycode',
                        data: {code: no.val()},
                        success: function (data) {
                            obj = JSON.parse(data);
                            
                            switch (obj.message) {
                                case 'notfound':
                                    $('#ajax-item-info').html('');
                                    desc.val('');
                                    qty.val(0);
                                    no.val('');
                                    $('#itemid').val('');
                                    alert('Termék nem található!');
                                    no.focus();
                                    break;
                                default:
                                case 'success':
                                    $('#orderqty').val(obj.qty);
                                    $('#shopping-cart-create #itemid').val(obj.itemid);
                                    $('#shopping-cart-create .min-order-qty').html(obj.minqty);
                                    $.ajax({
                                        type: "POST",
                                        url: '/core/catalog/list/ajaxcard',
                                        data: {itemid: $('#itemid').val()},
                                        success: function (data) {
                                            $('#ajax-item-info').html(data);
                                            qty.focus();
                                        }
                                    });                                    
                                    break;
                            }
                        }
                    });
                }*/
            },
            close: function(event, ui) {
                qty.focus();
            }            
        })
        .blur(function () {
            var elem = $(this);
            if (elem.val().length == 0) {
                return true;
            }
        });        
    },
    savecatcookie: function () {
        cid = $(this).attr('id').replace('middle-cat2-link-', '');
        $.cookie('opencat', cid, {path: '/'});
        return true;
    }
});

