/* Popup plugin */
;(function($JQ) {

    var popup = function(el, options) {
        
        $JQ.extend(this.options, this.defaults,  options);

        this.el = $JQ(el);

        this.viewport = $JQ('html');

        $JQ.when(this.decorate()).done(function() {
            this.initEvents();
			if (undefined !== this.options.url) {
                var scope = this;
				$JQ.when($JQ.get(this.options.url)).done(function(html) {
					scope.el.append(html);
					scope.show();
				});
			} else {
				this.show();
			}
        });

        this.el.data('popup', this);
    }

    popup.prototype = {

        defaults: {
            width: 625
        },

        centered: false,

        options: {},

        closeBtnTpl: '<div class="close-btn"></div>',

        decorate: function() {
            var popup = this;
            return $JQ.Deferred(function(dfd) {
                if (popup.el.parent().hasClass('popup-wrapper')) {
                    popup.centered = true;
                } else {
                    popup.wnd = $JQ('<div class="popup-wrapper"></div>').append(popup.el).appendTo('body');
                    popup.closeBtn = $JQ(popup.closeBtnTpl);
                    popup.el.css(popup.options).append(popup.closeBtn);
                }

                dfd.resolveWith(popup);
            }).promise();
        },

        addOverlay: function() {
            this.overlay = $JQ('<div></div>')
            .css({
                height: $JQ('body').height(),
                width: '100%',
                'z-index': 1002,
                opacity: 0.7,
                background: '#e6e7e8',
                position: 'absolute',
                top: 0,
                left: 0
            })
            .appendTo('body');
        },

        removeOverlay: function() {
            this.overlay.remove();
        },

        center: function(force) {
            var popup = this;
            return $JQ.Deferred(function(dfd) {
                if (!popup.centered || force) {
                    popup.wnd.css({
//                        top: (popup.viewport.height() / 2) - (popup.el.height() / 1),
                        top: document.body.scrollTop + document.documentElement.scrollTop + 50,
                        left: (popup.viewport.width() / 2)- (popup.el.width() / 2),
                        position: 'absolute',
                        'z-index': 1003
                    });
                    popup.centered = true;
                }
                dfd.resolveWith(popup);
            }).promise();
        },

        initEvents: function() {
            var popup = this;
            this.closeBtn.click(function() {
                popup.hide.call(popup);
            });
        },

        hide: function() {
            this.el.addClass('hidden');
            this.removeOverlay();
            $JQ(window).unbind('popup');
        },

        show: function() {
			$JQ.when(this.center()).done(function() {
				var popup = this;
				popup.addOverlay();
				popup.el.removeClass('hidden');
				$JQ(window).bind({
					'keydown.popup': function(e) {
						if (e.keyCode == 27) {
							popup.hide();
						}
					},
					'resize.popup': function() {
						popup.center(true);
					}
				});
			});
        }
    }

    $JQ.fn.popup = function(options) {
        return this.each(function() {
            var el = $JQ(this);
            if (!el.data('popup')) {
                new popup(el, options);
            } else {
                el.data('popup').show();
            }
        });
    }
})(jQuery);

/* Round corners */
(function($JQ) {
    $JQ.fn.roundCorners = function() {
        return this.each(function() {
            $JQ(this).append('<em class="ctl"></em><em class="ctr"></em><em class="cbl"></em><em class="cbr"></em>');
        });
    }
})(jQuery);

/* Labeled text input */
(function($JQ) {

    function setLabelPos(input) {
        input = $JQ(input);
        var lbl = input.prev('label');
        if (lbl) {
            var pos = input.position()
                marginTop = parseInt(input.css('marginTop'), 10);

            input.data('label', lbl);
            lbl.css({
                position: 'absolute',
                top: (pos.top - lbl.height()) + ((input.outerHeight() - lbl.height()) / 2) + marginTop ,
                left: pos.left + 5
            });
        }
    }

    $JQ.fn.labeledInput = function() {
        this.parent().css('position', 'relative');

        this.focus(function() {
            $JQ(this).data('label').hide();
        })
        .focusout(function() {
            if (!$JQ(this).val()) {
                $JQ(this).data('label').show();
            }
        });

        return this.each(function(index) {
            if (index) {
                $JQ(this).css('marginTop', 10);
            }
            setLabelPos(this);
        });
    }
})(jQuery);

/* Custom checkbox/radio */
(function($JQ) {

    function setChecked(el) {
        var el = $JQ(el),
            input = el.data('input'),
            checked = input.is(':radio') ? input.is(':checked') : !input.is(':checked');

        if (!checked && el.attr('radio-group')) {
            $JQ('span[radio-group="' + el.attr('radio-group') + '"]').removeClass('checked');
            checked = true;
        }

        el.toggleClass('checked', checked);

        checked ? input.attr('checked', 'checked') : input.removeAttr('checked');
    }

    function decorate() {
        var input = $JQ(this),
            likeRadio = input.is(':checkbox') && input.hasClass('like-radio'),
            target = input, removeTarget = false,
            decorator = $JQ('<span class="tommy-' + (likeRadio ? 'radio' : input.attr('type')) + '"></span>');

        if (likeRadio || input.is(':radio')) {
            target = input.parent('label');
            removeTarget = !!target;
        }

        decorator
        .addClass(target.attr('class'))
        .data('input', input)
        .click(function() {
            setChecked(decorator);
        });

        if (input.is(':checkbox')) {
            input.prev('.btn').click(function() {
                if(decorator.data('input')[0].checked == false)
                setChecked(decorator);
                return false;
            });
        } else {
            decorator.attr('radio-group', input.attr('name'));
        }

        if (likeRadio || input.is(':radio')) {
            if (removeTarget) {
                input.addClass('hidden').insertBefore(target);
            }
            decorator.html(target.html());
        }

        decorator
        .toggleClass('checked', input.is(':checked'))
        .insertAfter(target.addClass('hidden'));

        if (removeTarget) {
            target.remove();
        }
    }

    $JQ.fn.tommyCheckbox = $JQ.fn.tommyRadio = function() {
        this.each(decorate);
    }
})(jQuery);


/* form data*/

(function($JQ) {

    function markInvalid(obj, flag, frompop){
        obj.each(function(){
            var el = $JQ(this);
            if(flag){
                if(!frompop){
                    var validbox = el.attr('validbox');
                    if(validbox != ''){
                        $JQ('#' + validbox).remove();
                        el.attr('validbox','');
                    }
                }
                el.removeClass('validation-failed');
            }else{
                var validbox = el.attr('validbox');
                if(!el.hasClass('selectBox-disabled') && (!validbox || validbox == '')){
                    if(!frompop){
                        var newDate = new Date;
                        var r = newDate.getTime();
                        el.after('<div style="" id="' + r + '" class="validation-advice">Kies optie</div>');
                        el.attr('validbox', r);
                    }
                    el.addClass('validation-failed');
                }
            }
        });
    }

    function checkSelect(select, productId, flag){
        var atId = $JQ(select).attr('atid');
        if(atId){
            var selector = productId + atId;
        }else{
            var selector = productId;
        }
        
        if($JQ(select).val() == ''){
            if($JQ(select).hasClass('super-attribute-select' + productId)){
                var obj = $JQ('#product_addtocart_form' + productId + ' a.' + selector);
                if(obj.length > 0){
                    markInvalid(obj, false, flag);
                }
            }else if($JQ(select).hasClass('qty' + productId)){
                var obj = $JQ('#product_addtocart_form' + productId + ' a.qty' + productId);
                if(obj.length > 0){
                    markInvalid(obj, false, flag);
                }
            }
            return false;
        }else{
            if($JQ(select).hasClass('super-attribute-select' + productId)){
                var obj = $JQ('#product_addtocart_form' + productId + ' a.' + selector);
                if(obj.length > 0){
                    markInvalid(obj, true, flag);
                }
            }else if($JQ(select).hasClass('qty' + productId)){
                var obj = $JQ('#product_addtocart_form' + productId + ' a.qty' + productId);
                if(obj.length > 0){
                    markInvalid(obj, true, flag);
                }
            }
            return true;
        }
    }

    $JQ.fn.tommyValidateProduct = function(productId, flag) {
        var result = true;
        this.each(function(){
            if(!checkSelect(this, productId, flag) && result){
                result = false;
            }
        });
        return result;
    }

})(jQuery);

(function($JQ) {

    function initTooltip(obj){
        var forId = $JQ(obj).attr('forid');

        var html = $JQ('#' + forId).html()
        if(html == null) return;
        $JQ('#' + forId).remove();
        $JQ('body').append('<div class="review-box" style="display: none;" id="' + forId + '">' + html + '</div>');

        $JQ(obj).mouseover(function(e){
            var forId = $JQ(this).attr('forid');
            $JQ('#' + forId).css('top',e.pageY + 2);
            $JQ('#' + forId).css('left',e.pageX + 2);
            $JQ('#' + forId).fadeIn(400);
        });

        $JQ(obj).mousemove(function(e){
            var forId = $JQ(this).attr('forid');
            $JQ('#' + forId).css('top',e.pageY + 2);
            $JQ('#' + forId).css('left',e.pageX + 2);
        });

        $JQ(obj).mouseout(function(e){
            var forId = $JQ(this).attr('forid');
            $JQ('#' + forId).css('top',e.pageY + 2);
            $JQ('#' + forId).css('left',e.pageX + 2);
            $JQ('#' + forId).fadeOut(400);
        });

    }

    $JQ.fn.tooltip = function() {
        var result = true;
        this.each(function(){
            initTooltip(this);
        });
        return result;
    }

})(jQuery);
