var agt = navigator.userAgent.toLowerCase();
var browserid = agt.match(/(firefox|chrome|safari|opera|msie)/)[1];
var appVer = (agt.match(new RegExp('.+(?:version)[\/: ]([\\d.]+)')) || agt.match(new RegExp('.+(?:'+browserid+')[\/: ]([\\d.]+)')) || [0,'0'])[1];
var is_opera = (agt.indexOf("opera") != -1);
var is_chrome = (agt.indexOf("chrome") != -1);
var is_safari = (agt.indexOf("safari") != -1 && agt.indexOf("chrome") == -1);
var is_ie = (agt.indexOf('msie') != -1);
var is_firefox = (agt.indexOf('firefox') != -1);
var is_ie6 = (agt.indexOf('msie 6') != -1);
var is_ie8 = (agt.indexOf('msie 8') != -1);

$(document).ready(function() {

    if($('.lang_en').length) {
        $.extend($.validator.messages, {
            required: "Kérjük töltse ki ezt a mezőt!",
            email: "Kérjük valós e-mail címet adjon meg!",
            equalTo: "A megadott adatok nem egyeznek!",
            required_valuealabel: "Kérjük töltse ki ezt a mezőt!"
        });
    }

    $('a[rel^=ajaxsubmit]').ajaxSubmit();

	$('a[href=#]').attr('href', 'javascript:;');

	$('.valuelabel').valueLabel();
	
	$('a[rel=submit]').formSubmit();

    if($('.home_banner > *').length > 1)
        bannerRotator.create().start(5000);

    if($("a[rel^='prettyPhoto']").length)
        $("a[rel^='prettyPhoto']").prettyPhoto();

    $('img.overpic').each(function() {
        var img = $(this);
        $('<img src="/images/0/photo_icon.png" alt="" />').prependTo($(this).prev('a'));
        $(this).prev('a').addClass('imagehover').hover(function() {
            img.stop(true,true).show().css({opacity:0}).animate({opacity:1}, 200);
        },function() {
            img.stop(true,true).fadeOut(200);
        }).mousemove(function(e) {
            extramargin = 10;
            if(img.parent().hasClass('right_prods_name'))
                var x = e.pageX - $('.sub_container').position().left - img.outerWidth() - extramargin;
            else
                var x = e.pageX - $('.sub_container').position().left + extramargin;
	        var y = e.pageY - $('.sub_container').position().top + extramargin;
            var diff = e.pageY + img.outerHeight() - $(window).height()-$(window).scrollTop() + extramargin;
            if (diff > 0)
                y = y - diff;
            img.css({left: x, top: y});
        });
    });

    // megegyezik a szamlazasi adatokkal
	var inputs = Array('name', 'street', 'zip', 'city');
	$('#same_data').click(function() {
		if($(this).attr('checked')) {
			for (var i in inputs) {
				$('#shipping_'+inputs[i]).val($('#billing_'+inputs[i]).val());
            }
		}
		else {
			for (var i in inputs)
				$('#shipping_'+inputs[i]).val("");
		}
	});
	for (var i in inputs) {
		$('#billing_'+inputs[i]).keyup(function() {
			if($('#same_data').attr('checked') == true) {
				for (var i in inputs)
					$('#shipping_'+inputs[i]).val($('#billing_'+inputs[i]).val());
			}
		});
	}

    $('.onlynumber').keydown(function(event) {
        if (event.shiftKey == true)
            event.preventDefault();
        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
        } else
            event.preventDefault();
    });

    $('.cart_next, .cart_prev').click(function() {
        var curr = parseInt($(this).parent().find('input[name^=volume]').val().replace(/[^\d]/g,''));
        if($(this).hasClass('cart_next'))
            $(this).parent().find('input[name^=volume]').val(curr+1);
        else if(curr > 1)
            $(this).parent().find('input[name^=volume]').val(curr-1);
    });

    $('.ral2hex').each(function() {
        var color_text = $(this).html().split(' | ');
        if(typeof(color_text[1]) != "undefined") {
            var _color = color_text[1];
            var _color_text = color_text[0];
            var double = true;
        }
        else {
            var _color = _color_text = color_text[0];
            var double = false;
        }
        $(this).html(_color_text);
        var hex_pattern = /^#?(([a-fA-F0-9]){3}){1,2}$/;
        var text_pattern = /^[a-zA-Z]+$/;
        if(hex_pattern.test(_color) || text_pattern.test(_color))
            var color = _color;
        else {
            var ral_pattern = /^[a-zA-Z0-9]+$/;
            if(ral_pattern.test(_color)) {
                var color = ral2hex(_color);
            }
            else {
                var color = '';
                if(double)
                    $(this).html(color_text[1]);
                return true;
            }
        }
        $(this).css({backgroundColor: color});
        var currentBackground = $(this).css("background-color");
         if(currentBackground == "rgba(0, 0, 0, 0)" || currentBackground == "transparent" || typeof(currentBackground) == "undefined")
            return true;

         currentBackground  = rgb2hex(currentBackground);
         var newColor = getContrastYIQ(currentBackground);
         $(this).css("color",newColor);
    });

    $('.prod_desc_bigpic a:first').show();
    $('.prod_desc_subpic_scroll').scrollLeft(0);
    subimage_pages = Math.ceil($('.prod_desc_subpic_scroll_sub img').length/3);
	subimage_page = 1;
	$('.right_arrow').click(function() {
		if(subimage_pages <= subimage_page)
			return false;
		subimage_page = subimage_page+1;
	 	$('.prod_desc_subpic_scroll').stop(true,true).animate({scrollLeft: $('.prod_desc_subpic_scroll').scrollLeft()+120}, 300, 'easeOutCubic');
	});
	$('.left_arrow').click(function() {
		if(subimage_page <= 1)
			return false;
		subimage_page = subimage_page-1;
	 	$('.prod_desc_subpic_scroll').stop(true,true).animate({scrollLeft: $('.prod_desc_subpic_scroll').scrollLeft()-120}, 300, 'easeOutCubic');
	});
    $('.prod_desc_subpic_scroll_sub a').live("click", function() {
        var _this = $(this);
        $('.prod_desc_bigpic a:visible').animate({opacity:0}, 100, 'easeOutCubic', function() {
            $(this).hide();
            $('.prod_desc_bigpic .'+_this.attr('rel')).show().css({opacity:0}).animate({opacity:1}, 100, 'easeInCubic');
        });
    });

    $('.facebook_right').html('<fb:like-box href="http://www.facebook.com/pages/P%C3%A1ko-Kft/144161642322681" width="200" height="323" show_faces="true" stream="false" header="true"></fb:like-box>');

    $('.centerpic').each(function() {
        var width = $(this).width();
        var table = $('<table class="imagecenter" style="width:'+$(this).width()+'px;height:'+$(this).height()+'px;line-height:'+$(this).height()+'px"><tr><td></td></tr></table>');
        var html = $(this).html();
        $('td', table).html(html);
        table.insertAfter(this);
        $(this).remove();
    });

    $('.reload_captcha').click(function() {
        var url = $(this).prev().attr("src");
        $(this).prev().attr("src", '/felhasznalo/captcha/'+Math.floor(Math.random()*999999+1000));
    });

    if($('.validateme').length)
        $('.validateme').validate();

});

var bannerRotator = {
    create: function() {
        var _this = this;
        $('.current_banner').live({
            mouseover: function() {
                _this.stop();
            },
            mouseout: function() {
                _this.stop();
                _this.next();
                _this.start();
            }
        }).not(':first').hide();
        $('.home_banner > *').not(':first').hide();
        $('.home_banner > *:first').addClass("current_banner");
        return _this;
    },
    start: function(_speed) {
        var _this = this;
        if(typeof(_this._speed) != "undefined")
            _speed = _this._speed;
        if(typeof(_speed) == "undefined")
            _speed = 1200;
        if(_speed < 1000)
            _speed = 1200;
        _this._speed = _speed;
        _this.rotate_timer = setInterval(_this.next, _this._speed);
    },
    stop: function() {
        var _this = this;
        clearInterval(_this.rotate_timer);
    },
    next: function() {
        var _this = this;
        var current = $('.home_banner > *.current_banner');
        var next = current.next();
        if(next.length < 1)
            next = $('.home_banner > *:first');
        if(next.length < 1)
            next = $('.home_banner > *:first');
        current.stop(true,true).animate({opacity:0}, 1000, 'easeOutCubic', function(){$(this).hide()}).removeClass('current_banner');
        next.addClass('current_banner').stop(true,true).show().css({opacity:0}).animate({opacity:1}, 1000, 'easeOutCubic');
    }
}

$(window).resize(function() {
    if(is_ie8 || is_opera) { // ie8 and opera resize bug fix
        $('.container').css({height:'100%'});
        if($('.container').height() < (parseInt($('.sub_container').css('min-height'))+parseInt($('.sub_container').css('padding-bottom'))+$('.header').height()))
            $('.container').height(parseInt($('.sub_container').css('min-height'))+parseInt($('.sub_container').css('padding-bottom'))+$('.header').height())
    }
});

$.fn.valueLabel = function() {
	$(this).each(function() {
    	$(this).attr('fvalue', $(this).val());
		$(this).focus(function() {
			if($(this).val() == $(this).attr('fvalue') || $(this).val() == "")
				$(this).val('');
		}).blur(function() {
			if($(this).val() == $(this).attr('fvalue') || $(this).val() == "")
				$(this).val($(this).attr('fvalue'));
		});
	});
};

$.fn.formSubmit = function() {
	$(this).each(function() {
		$('<input type="submit" name="submit" value="submit" />').css('display', 'none').insertAfter($(this));
		$(this).click(function() {
			$(this).next().click();
			return false;
		});
	});
};

$.fn.ajaxSubmit = function() {

	$(this).parents("form").find('input[type=text], input[type=password]').live("keydown", function(e) {
		if (e.keyCode == '13') {
     		e.preventDefault();
			$(this).parents("form").find('[submit=submit]').click();
   		}
	}).keydown(function(e) {
		if (e.keyCode == '13') {
     		e.preventDefault();
			$(this).parents("form").find('[submit=submit]').click();
   		}
	});

	$(this).each(function () {
		$(this).attr("submit", "submit");
		var method = $(this).parents("form").attr('method');
		$(this).click(function() {
			if($(this).hasClass("wait"))
				return false;
			var katt = $(this);
			var link = $(this).parents("form").attr('action');
			if(link == "") link = document.location.href;
			$.ajax({
				url: link,
				type: method,
				dataType: "json",
				data: $(this).parents("form").serialize(),
				success: function(data){
					if(data.reload) {
						if(data.reload == "this")
							window.location.href=window.location.href.split('#')[0];
						else
							window.location.href=data.reload;
						return false;
					}
					else if(data.error) {
						popupInfo(data.error);
					}
					else if(data.assembler) {
						popupInfo(data.assembler+'<div class="clear4"></div><div class="button" style="margin-left:100px;margin-right:40px;float:left"><a class="assembler_add_cart btn1" title="Kosárba rakom" href="javascript:;"><span>Megrendelem</span></a></div> <div class="button" style="float:left"><a title="Mégsem" onclick="$(\'.cartaction2\').remove();" href="javascript:;" class="btn1"><span>Mégsem</span></a></div>', 'btn');
						$(".assembler_add_cart").click(function() {
							var posts = katt.parents("form").serialize();
							$.post(katt.parents("form").attr('action')+"/1", posts, function(data){
                                window.location.href=window.location.href+"/2";
						    }, "json");
						});
					}
					else if(data.info) {
						popupInfo(data.info);
					}
					if(data.callback) {
						eval(data.callback+"(data.data);");
					}
				}
			});
			return false;
		});
		$('<input type="submit" name="submit" value="submit" />').css('display', 'none').insertAfter($(this));
		$(this).parents("form").submit(function () {
			$(this).find('[submit=submit]').click();
			return false;
		});
	});
};

function popupInfo(msg, close)
{
	if(typeof(close) == "undefined")
		var close = 2000;
	if(close != "btn") {
	   	setTimeout("$('.cartaction2').remove();", close);
	}
	$('.cartaction2').remove();
	var Xwidth = 400;
	var Yheight = 150;
	if( self.pageYOffset ) {
		scrolledX = self.pageXOffset;
		scrolledY = self.pageYOffset;
	} else if( document.documentElement && document.documentElement.scrollTop ) {
		scrolledX = document.documentElement.scrollLeft;
		scrolledY = document.documentElement.scrollTop;
	} else if( document.body ) {
		scrolledX = document.body.scrollLeft;
		scrolledY = document.body.scrollTop;
	}

	if( self.innerHeight ) {
		centerX = self.innerWidth;
		centerY = self.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight ) {
		centerX = document.documentElement.clientWidth;
		centerY = document.documentElement.clientHeight;
	} else if( document.body ) {
		centerX = document.body.clientWidth;
		centerY = document.body.clientHeight;
	}

	var leftOffset = scrolledX + (centerX - Xwidth) / 2;
	var topOffset = scrolledY + (centerY - Yheight) / 2;
	// The initial width and height of the div can be set in the
	// style sheet with display:none; divid is passed as an argument to // the function

	var divToOpen1 = $("<div/>").addClass("cartaction2").css("width", Xwidth).css("position", "absolute").css("top", topOffset).css("left", leftOffset).css("padding", "10px").css("textAlign", "center").css("z-index", "201").css("color", "#fff").html(msg);
	var divToOpen2 = $("<div/>").addClass("cartaction2").css("width", Xwidth).css("position", "absolute").css("top", topOffset).css("left", leftOffset).css("backgroundColor", "#000").css("padding", "10px").css("textAlign", "center").css("opacity", 0.8).css("z-index", "200").css("color", "#fff").css("fontWeight", "bold");


	$("#body").append(divToOpen1);
	$("#body").append(divToOpen2);
	divToOpen2.height(divToOpen1.height());

	$('.cartaction2').goCenter();

}

$.fn.getCenter = function() {
	var winH = $(window).height();
	var winW = $(window).width();
	var winSL = $(window).scrollLeft();
	var winST = $(window).scrollTop();
	var width = $(this).outerWidth();
	var height = $(this).outerHeight();
	var x = (winW/2 - width/2)+winSL;
	var y = (winH/2 - height/2)+winST;
	var center = Object();
	center.left = x;
	center.top = y;
	return center;
}

$.fn.goCenter = function() {
	var _center = $(this).getCenter();
	$(this).css({
		left: _center.left,
		top: _center.top,
		marginTop: 0
	});
}


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
