if (!window.console) {
    window.console = function () { }
}

if (typeof Migros === 'undefined') {
    Migros = {};
}
if (typeof Migros.HochHaus === 'undefined') {
    Migros.HochHaus = {};
}


// jQuery Custom Plugins

; (function ($) {
    // overlay
    var 
	_ns = 'modalWindow',
	_doc = null,
	_win = null,
	_content = null,
    _ticketOverlay = false,
	_settings = {
	    'modalHeight': 0,
	    'modalWidth': 0,
	    'opacity': '.8',
	    'fxSpeed': 'fast'
	},

	methods = {
	    init: function (options, callback) {
	        return this.each(function () {
	            var $this = $(this),
					data = $this.data(_ns);

	            if (options) {
	                $.extend(_settings, options);
	            }

	            _doc = $(document);
	            _win = $(window);

	            // If the plugin hasn't been initialized yet
	            if (!data) {
	                $(this).data(_ns, {});
	            }

	            $this.click(function (e) {
	                e.preventDefault();

	                markup = initMarkup(); // public element

	                $.ajax({
	                    url: $this.attr('href'),
	                    dataType: 'html',
	                    success: function (data) {
                            $data = $(data).find('#ajaxContent');

                            var _ticketOverlay = $data.data('partial-render');

                            markup.modal.contentInner.html($data).appendTo($('body'));
                         

	                        buildOverlay();
	                        resizeModalContent(markup.modal.contentInner.outerHeight(true), markup.modal.contentInner.outerWidth());

	                        markup.modal.closerHolder.append(markup.modal.closer);
	                        markup.modal.content.append(markup.modal.closerHolder, markup.modal.contentInner);
	                        markup.modal.contentInner.css('display', 'block');
	                        positionModalContent();

                            if(_ticketOverlay)
                            {
                                ticketOverlayScript();
                            }
                            
	                        methods.open(function () {
	                            //alert(999);alert('hh = ' + markup.modal.contentInner.height() + ', ww = ' + markup.modal.contentInner.width())
	                            resizeModalContent(markup.modal.contentInner.outerHeight(true), markup.modal.contentInner.outerWidth());
	                            positionModalContent();
	                        });
	                    }
	                });
	            });
	        });
	    },
	    open: function (cb) {
	        markup.modal.overlay.fadeIn(_settings.fxSpeed, function () {
	            markup.modal.content.fadeIn(_settings.fxSpeed, function () {
	                if (cb && typeof cb === 'function') {
	                    cb();
	                }
	            });
	        });
	    },
	    close: function () {
	        markup.modal.content.fadeOut(_settings.fxSpeed, function () {
	            markup.modal.overlay.fadeOut(_settings.fxSpeed, function () {
	                removeOverlay();
	            });
	        });
	    },
	    resize: function () {
	        _doc = $(document);
	        _win = $(window);
	    },
	    loadContent: function (_href, cb) {
	        $.ajax({
	            url: _href,
	            dataType: 'html',
	            success: function (data) {
	                data = $(data).find('#ajaxContent');
	                markup.modal.contentInner.html(data);
	                resizeModalContent(markup.modal.contentInner.outerHeight(true), markup.modal.contentInner.width());
	                if (cb && typeof cb === 'function') {
	                    cb();
	                }
	            }
	        });
	    }
	},
    ticketOverlayScript = function()
        {
            $.validator.setDefaults({
                submitHandler2: function () { alert("submitted!"); return true; },
                highlight: function (input) {
                    $(input).addClass("highlight");
                },
                unhighlight: function (input) {
                    $(input).removeClass("highlight");
                }
            });

            $.validator.addMethod("newscheck", function(value, element) { 
                var $e = $(element);

                if($e.attr('id') == 'news') {
                    if($e.is(':checked')) {
                        if($('#post').is(':checked') == false && $('#mail').is(':checked') == false) {
                            return false;
                        }
                    }
                }

                return true; 
            }, "Bitte geben Sie mindestens eine Option an");

            $(function () {
                //alert('ready');
                $('#news').click(function () {
                    if ($('#news').is(':checked')) {

                        $("#post_method").css('visibility', 'visible');
                        if ($('#post').is(':checked')) {
                            $("#address").css('visibility', 'visible');
                            $("#signupForm").validate().settings.rules.Street = { required: true };
                            $("#signupForm").validate().settings.rules.Build = { required: true };
                            $("#signupForm").validate().settings.rules.City = { required: true };
                            $("#signupForm").validate().settings.rules.Zip = { required: true };
                        }
                    }
                    else {

                        //  custom validate
                        $("#signupForm").validate().settings.rules

                        $("#post_method").css('visibility', 'hidden');
                        $("#address").css('visibility', 'hidden');
                        $("#signupForm").validate().settings.rules.Street = { required: false };
                        $("#signupForm").validate().settings.rules.Build = { required: false };
                        $("#signupForm").validate().settings.rules.City = { required: false };
                        $("#signupForm").validate().settings.rules.Zip = { required: false };
                    }
                });

                $('#post').click(function () {
                    if ($('#post').is(':checked')) {
                        $("#address").css('visibility', 'visible');
                        $("#signupForm").validate().settings.rules.Street = { required: true };
                        $("#signupForm").validate().settings.rules.Build = { required: true };
                        $("#signupForm").validate().settings.rules.City = { required: true };
                        $("#signupForm").validate().settings.rules.Zip = { required: true };
                    }
                    else {
                        $("#address").css('visibility', 'hidden');
                        $("#signupForm").validate().settings.rules.Street = { required: false };
                        $("#signupForm").validate().settings.rules.Build = { required: false };
                        $("#signupForm").validate().settings.rules.City = { required: false };
                        $("#signupForm").validate().settings.rules.Zip = { required: false };
                    }
                });


                // validate signup form on keyup and submit

                $("#signupForm").validate({
                    rules: {
                        Prefix: "required",
                        FirstName: "required",
                        LastName: "required",
                        Email: {
                            required: true,
                            email: true
                        },
                        Amount: "required",
                        Dates: "required",
                        SendNews: { required: false, newscheck: '' }

                        //Street: "required",
                        //Build: "required"//,
                        //City: "required",
                        //Zip: "required"
                    },
                    messages: {
                        Prefix: "Bitte waehlen Sie Ihr Geschlecht aus!",
                        FirstName: "Bitte Vornamen eingeben!",
                        LastName: "Bitte Nachnamen eingeben!",
                        Email: { 
                                    required: "Bitte gueltige E-Mail-Adresse eingeben!",
                                    email:  "Bitte gueltige E-Mail-Adresse eingeben!" 
                                },
                        Dates: "Bitte waehlen Sie ein Datum aus!",
                        Amount: "Bitte Anzahl eingeben!",
                        Street: "",
                        Build: "",
                        City: "",
                        Zip: ""
                    },
                    errorPlacement: function(error, element)
                    {
                        if(element.parent().attr('id') !== 'address')
                        {
                            error.insertAfter(element);
                        }

                        if(element.attr('id') == 'news')
                        {
                            error.insertBefore($('#post_method'));
                        }
                    }
                });

            });
        },
    // markup methods
	initMarkup = function () {
	    var _markup = {
	        modal: {
	            overlay: $('<div />', { 'id': 'modalOverlay' }).css({
	                'background-color': '#f9401c',
	                'display': 'none',
	                'height': '100%',
	                'left': 0,
	                'opacity': _settings.opacity,
	                'position': 'absolute',
	                'top': 0,
	                'width': '100%',
	                'z-index': 1000
	            }),
	            content: $('<div />', { 'id': 'modalContent', 'class': 'modalWindow' }).css({
	                'display': 'none',
	                'overflow': 'hidden',
	                'position': 'absolute',
	                'z-index': 1100
	            }),
	            contentInner: $('<div />', { 'id': 'modalContentInner' }).css({
	                'display': 'none'
	            }),
	            closerHolder: $('<div />', { 'id': 'modalCloserHolder', 'class': 'modalCloserHolder' }),
	            closer: $('<a />', { 'href': '#', 'id': 'modalCloser', 'class': 'modalCloser' }).html('X').click(function (e) {
	                e.preventDefault();
	                methods.close();
	            })
	        }
	    };

	    return _markup;
	},
	buildOverlay = function () {
	    //console.log('buildOverlay');
	    markup.modal.overlay.css({
	        'height': _doc.height(),
	        'width': _doc.width()
	    });
	    $('body').append(markup.modal.overlay, markup.modal.content);

	    // capture ESC key to close modal
	    $(document.documentElement).bind('keyup', function (e) {
	        var code = (e.keyCode ? e.keyCode : e.which);
	        if (code === 27) {
	            methods.close();
	        }
	    });
	},
	removeOverlay = function () {
	    //console.log('removeOverlay');
	    markup.modal.content.remove();
	    markup.modal.overlay.remove();
	},

    // helpers
	resizeModalContent = function (h, w) {
	    //console.log('resizeModalContent');
	    //var h = parseInt(markup.modal.contentInner.css('padding-top'), 10) + parseInt(markup.modal.contentInner.css('padding-bottom'), 10) + h + markup.modal.closerHolder.height() + 10;
	    //var w = parseInt(markup.modal.contentInner.css('padding-left'), 10) + parseInt(markup.modal.contentInner.css('padding-right'), 10) + w;
	    //alert('h = ' + h);
	    //alert('w = ' + w);
	    markup.modal.content.height(h);
	    markup.modal.content.width(w);
	},
	positionModalContent = function () {
	    //console.log('positionModalContent');
	    var _left = (_doc.width() - markup.modal.content.width()) / 2,
			_top = (_win.height() - markup.modal.content.height()) / 2;

		if( markup.modal.content.height() > _win.height() ) {
			markup.modal.content.height(_win.height());
			markup.modal.content.find('#scrollableContainer').height( markup.modal.content.height() - markup.modal.content.find('.ticketHeader').outerHeight(true) - 18 ).css('overflow-y','scroll');
			_top = 0;
		}

	    markup.modal.content.css({
	        'left': _left,
	        'top': _top
	    });

        $(window).scrollTop(_top);
	},
	optionsFromRel = function (str) {
	    var arr = $.grep(str.split(' '), function (n, i) {
	        return (n);
	    });
	    return (arr.length > 0) ? arr : false;
	}
	;

    $.fn.modalWindow = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + _ns);
        }
    };
})(jQuery);


; (function ($) {
    // toolTip
    var 
	_ns = 'toolTip',
	_content = null,

	_settings = {
	    'fxSpeed': 'fast',
	    'tooltipClass': 'tooltipWrapper'
	},

	_tooltip = $('<span />'),

	methods = {
	    init: function (options, callback) {
	        return this.each(function () {
	            var $this = $(this);

	            if (options) {
	                $.extend(_settings, options);
	            }
	            _tooltip.addClass(_settings.tooltipClass);
	            $this.hover(
					function () {
					    if (!$this.data('toolTipTitle')) {
					        $.data(this, 'toolTipTitle', $this.attr('title'));
					    }
					    showTooltip($this);
					    $this.removeAttr('title');
					},
					function () {
					    $this.attr('title', $this.data('toolTipTitle'));
					    hideTooltip($this);
					}
				);
	        });
	    }
	},

	showTooltip = function ($o) {
	    var _offset = $o.position();
	    _tooltip
			.html($o.data('toolTipTitle'))
			.insertAfter($o)
			.css({
			    'left': _offset.left + parseInt($o.css('padding-left'), 10),
			    'top': _offset.top - _tooltip.outerHeight()
			});
	    if (_tooltip.width() > 200) {
	        _tooltip.width(200);
	    }
	    _tooltip.show();
	},

	hideTooltip = function ($o) {
	    $o.next('.' + _settings.tooltipClass).remove();
	};

    $.fn.toolTip = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + _ns);
        }
    };
})(jQuery);


; (function ($) {
    // toggleComments
    var 
	_ns = 'toggleComments',
	_content = null,

	_settings = {},

	methods = {
	    init: function (options, callback) {
	        return this.each(function () {
	            var $this = $(this),
					$form = $this.find('.comment-form'),
					$list = $this.next('.comments-list').eq(0);

	            if (options) {
	                $.extend(_settings, options);
	            }

	            $this.delegate('a', 'click', function (e) {
	                e.preventDefault();
	                var $target = $(e.target);

	                // toggle comments-list
	                if ($target.is('.comments')) {
	                    if ($list.is(':hidden')) {
	                        $list.show();
	                        if ($('.PlaceHolder', $list).length > 0) {
	                            Migros.HochHaus.Comment.GetComments($this.parents('.comments').first());
	                        }
	                    }
	                    else {
	                        $list.hide();
	                    }
	                }

	                // toggle comment form
	                if ($target.is('.comment-add')) {
	                    if ($form.is(':hidden')) {
	                        if ($('.PlaceHolder', $form).length > 0) {
	                            Migros.HochHaus.Comment.GetCommentForm($this.parents('.comments').first());
	                        }
	                        $form.show();
	                    }
	                    else {
	                        $form.hide();
	                    }
	                }
	            });
	        });
	    }
	};

    $.fn.toggleComments = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + _ns);
        }
    };
})(jQuery);

; (function ($) {
    // placeholder:
    // provides support for new html5 placeholder attribute to older browsers
    var 
	_ns = 'placeholder',

	methods = {
	    init: function (options, callback) {
	        return this.each(function () {
	            if (!$.support.placeholder) {
	                var _i = $(this).find('input:text');
	                // don't execute if attribute has not been set
	                if (typeof _i.attr('placeholder') != 'undefined') {
	                    _i.each(function () {
	                        var obj = $(this);

	                        // preserve default input values on page load
	                        if (this.value.length === 0) {
	                            this.value = obj.attr('placeholder');
	                        }
	                    })
							.end()
						.delegate('input[type=text]', 'focus blur', function (e) {
						    var obj = jQuery(this),
								eType = e.type;

						    if (eType == 'focusin') {
						        if (this.value == obj.attr('placeholder')) {
						            this.value = '';
						        }
						    }
						    else if (eType == 'focusout') {
						        if (this.value.length === 0) {
						            this.value = obj.attr('placeholder');
						        }
						    }
						});
	                    $(this).find('input:submit, button:submit').click(function () {
	                        _i.each(function () {
	                            if (this.value == $(this).attr('placeholder')) {
	                                this.value = '';
	                            }
	                        });
	                    });
	                }
	            }
	        });
	    }
	};

    $.fn.placeholder = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + _ns);
        }
    };
})(jQuery);

; (function ($) {
    // expandAsset:
    // show more <p> of asset in asset listing
    var 
	_ns = 'expandAsset',

	methods = {
	    init: function (options, callback) {
	        return this.each(function () {
	            var $this = $(this),
					$parent = $this.parent(),
					$p = $parent.find('.showMoreContent').hide();

	            $this.click(function (e) {
	                e.preventDefault();
	                var _text = $this.data('showmoretext');
	                if ($p.is(':hidden')) {
	                    $p.show();
	                }
	                else {
	                    $p.hide();
	                }
	                $this.data('showmoretext', $this.html()).html(_text);
	            });
	        });
	    }
	};

    $.fn.expandAsset = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.' + _ns);
        }
    };
})(jQuery);

// Comment functionality
Migros.HochHaus.Comment = function () {
    function update(data) {
        var commentsArea = $('#' + data.AreaId);
        if (data.CommentFormMarkup) {
            $('.CommentFormArea', commentsArea).html(data.CommentFormMarkup);
        }
        if (data.CommentsMarkup) {
            $('.CommentsArea', commentsArea).html(data.CommentsMarkup);
        }
        if (data.ShowCommentsTitle) {
            $('.icn.comments', commentsArea).html(data.ShowCommentsTitle);
        }
        if (data.CommentFormOpen !== null) {
            var showCommentsForm = $('.comment-form', commentsArea);
            if (data.CommentFormOpen) {
                showCommentsForm.show();
            }
            else {
                showCommentsForm.hide();
            }
        }
        if (data.ShowCommentsVisible !== null) {
            var showCommentsListItem = $('.icn.comments', commentsArea).parent();
            if (data.ShowCommentsVisible) {
                showCommentsListItem.show();
            }
            else {
                showCommentsListItem.hide();
            }
        }
    }

    function getCommentForm(commentsElement) {
        $.getJSON(getUrl(commentsElement, 'GetCommentForm'), function (data) {
            update(data);
        });
    }

    function getComments(commentsElement) {
        getJson(getUrl(commentsElement, 'GetComments'),
                                          function (data) {
                                              update(data);
                                          });
    }

    function getUrl(commentsElement, command) {
        var areaId = commentsElement.attr('id');
        var articleId = $("[name='ArticleId']", commentsElement).val();
        var languageCode = $("[name='LanguageCode']", commentsElement).val();
        return '/' + 'Comment/' + command + '?ArticleId=' + articleId + '&AreaId=' + areaId + '&Lng=' + languageCode;
    }

    function getJson(url, handler) {
        $.ajax({
            url: url,
            cache: false,
            dataType: "json",
            success: handler
        });
    }

    function init() {
        $('.comments-sorting-desc').live('click', function (e) {
            e.preventDefault();
            var commentsElement = $(e.target).parents('.comments').first();
            getJson(getUrl(commentsElement, 'SortComments') + '&SortOrder=desc',
                                          function (data) {
                                              update(data);
                                          });
        });
        $('.comments-sorting-asc').live('click', function (e) {
            e.preventDefault();
            var commentsElement = $(e.target).parents('.comments').first();
            getJson(getUrl(commentsElement, 'SortComments') + '&SortOrder=asc',
                                          function (data) {
                                              update(data);
                                          });
        });
    }

    return {
        Init: function () {
            init();
        },
        Update: function (e) {
            update(e);
        },
        GetCommentForm: function (commentsElement) {
            getCommentForm(commentsElement);
        },
        GetComments: function (commentsElement) {
            getComments(commentsElement);
        }
    };
} ();

(function () {
    $('textarea[maxlength]').live('keyup', function () {
        var $this = $(this);
        var max = parseInt($this.attr('maxlength'), 10);
        if ($this.val().length > max) {
            $this.val($this.val().substr(0, $this.attr('maxlength')));
        }
    });
} ());

Migros.HochHaus.Gallery = (function () {
    var 
	_ns = 'modalWindow',
	_doc = null,
	_win = null,
	_content = null,

	_elements = {
	    root: null,
	    handler: null,
	    controls: {
	        wrapper: $('<div />', { 'class': 'modalControlWrapper cf' }).css({ 'position': 'relative' }),
	        left: $('<a />', { 'class': 'modalPrev modalControl', 'href': '#' }).html('Zurueck'),
	        right: $('<a />', { 'class': 'modalNext modalControl', 'href': '#' }).html('Weiter'),
	        download: $('<a />', { 'class': 'modalDownload modalControl', 'href': '#' }).html('Download')
	    }
	},

	_gallery = {
	    count: 0,
	    current: 0,
	    items: $([]),
	    height: 0
	},

	_settings = {
	    'modalHeight': 0,
	    'modalWidth': 0,
	    'opacity': '.8',
	    'fxSpeed': 'fast'
	},

	init = function ($root, handler) {
	    _doc = $(document);
	    _win = $(window);

	    _elements.root = $root;
	    _elements.handler = _elements.root.find(handler);

	    _elements.handler.click(function (e) {
	        var $this = $(this);
	        e.preventDefault();
	        markup = initMarkup();

	        $.ajax({
	            url: $this.attr('href'),
	            dataType: 'html',
	            success: function (data) {
	                markup.modal.contentInner.html(data).appendTo($('body'));
	                buildOverlay();
	                markup.modal.content.css({ 'width': 'auto', 'height': 'auto' }).append(markup.modal.closer, markup.modal.contentInner);
	                markup.modal.contentInner.css('display', 'block').append(_elements.controls.wrapper.append(_elements.controls.left, _elements.controls.right, _elements.controls.download));
	                markup.modal.contentInner.find('img').eq(0).load(function () {
	                    resizeModalContent(0);
	                    _gallery.items = markup.modal.contentInner.find('.gallery-item');
	                    _gallery.count = _gallery.items.length;

	                    // add counter to items
	                    _gallery.items.find('h2').each(function (index) {
	                        var _s = $('<span />').html('Bild ' + (index + 1) + ' von ' + _gallery.count);
	                        $(this).append(_s);
	                    });

	                    open(function () {
	                        markup.modal.contentInner.delegate('a', 'click', function (e) {
	                            e.preventDefault();
	                            var _$this = $(this);

	                            if (_$this.hasClass('modalPrev')) {
	                                showItem(-1);
	                            }
	                            else if (_$this.hasClass('modalNext')) {
	                                showItem(1);
	                            }
	                            else if (_$this.hasClass('modalControl')) {
	                                window.open(markup.modal.contentInner.find('img').filter(':visible').attr('src'));
	                            }
	                        });
	                    });
	                });
	            }
	        });
	    });
	},

	showItem = function (i) {
	    var _next = _gallery.current + i;

	    // left boundary
	    if (_next < 0) {
	        _next = _gallery.count - 1;
	    }
	    // right boundary
	    else if (_next > _gallery.count - 1) {
	        _next = 0;
	    }
	    _gallery.items.eq(_gallery.current).fadeOut(_settings.fxSpeed, function () {
	        _gallery.items.eq(_next).fadeIn(_settings.fxSpeed, function () {
	            _gallery.current = _next;
	        });
	    });
	},

	open = function (cb) {
	    markup.modal.overlay.fadeIn(_settings.fxSpeed, function () {
	        markup.modal.content.css({ 'visibility': 'visible', 'display': 'none' }).fadeIn(_settings.fxSpeed, function () {
	            if (cb && typeof cb === 'function') {
	                cb();
	            }
	        });
	    });
	},

	close = function () {
	    markup.modal.content.fadeOut(_settings.fxSpeed, function () {
	        markup.modal.overlay.fadeOut(_settings.fxSpeed, function () {
	            removeOverlay();
	        });
	    });

	    // reset widget to default
	    _gallery.count = 0;
	    _gallery.current = 0;
	    _gallery.items = $([]);
	    _gallery.height = 0;
	},

    // markup methods
	initMarkup = function () {
	    var _markup = {
	        modal: {
	            overlay: $('<div />', { 'id': 'modalOverlay' }).css({
	                'background-color': '#000000',
	                'display': 'none',
	                'height': '100%',
	                'left': 0,
	                'opacity': _settings.opacity,
	                'position': 'absolute',
	                'top': 0,
	                'width': '100%',
	                'z-index': 1000
	            }),
	            content: $('<div />', { 'id': 'modalContent', 'class': 'modalWindow' }).css({
	                'visibility': 'hidden',
	                'position': 'fixed',
	                'z-index': 1100
	            }),
	            contentInner: $('<div />', { 'id': 'modalContentInner' }),
	            closer: $('<a />', { 'href': '#', 'id': 'modalCloser', 'class': 'modalCloser' }).html('X').click(function (e) {
	                e.preventDefault();
	                close();
	            })
	        }
	    };

	    return _markup;
	},
	buildOverlay = function () {
	    markup.modal.overlay.css({
	        'height': _doc.height(),
	        'width': _doc.width()
	    });
	    $('body').append(markup.modal.overlay, markup.modal.content);

	    // capture ESC key to close modal
	    $(document.documentElement).bind('keyup', function (e) {
	        var code = (e.keyCode ? e.keyCode : e.which);
	        if (code === 27) {
	            close();
	        }
	    });
	},
	removeOverlay = function () {
	    markup.modal.content.remove();
	    markup.modal.overlay.remove();
	},

    // helpers
	resizeModalContent = function (i) {
	    var _ch = markup.modal.content.height(),
			_wh = _win.height(),
			_ratio = parseFloat(_wh / _ch),
			_img = markup.modal.contentInner.find('img');


	    if (_ratio < 1) {
	        _gallery.height = (_img.height() - 100) * _ratio;
	        _img.css({ 'height': _gallery.height });
	    }

	    positionModalContent();
	},
	positionModalContent = function () {
	    var _left = (_doc.width() - markup.modal.content.width()) / 2,
			_top = (_win.height() - markup.modal.content.height()) / 2;

	    markup.modal.content.css({
	        'left': _left,
	        'top': _top
	    });
	}

	;

    return {
        init: init
    };
})();

Migros.HochHaus.Homepage = (function () {
    var 
	_ns = 'modalWindow',
	_doc = null,
	_win = null,
	_content = null,

	_settings = {
	    'modalHeight': 0,
	    'modalWidth': 0,
	    'opacity': '.8',
	    'fxSpeed': 'fast'
	},

	methods = {
	    init: function (options, callback) {
	        if (options) {
	            $.extend(_settings, options);
	        }

	        _doc = $(document);
	        _win = $(window);

	        // If the plugin hasn't been initialized yet
	        markup = initMarkup(); // public element

	        //
	        markup.modal.contentInner.append(markup.modal.mediaspace);

	        var _img = new Image();
	        _img.onload = function () {

	            $img = $(_img);
	            $img.click(function () { methods.close(); });

	            markup.modal.contentInner.append($img).appendTo($('body'));
	            markup.modal.content.width(markup.modal.contentInner.outerWidth());

	            initFlash();
	            buildOverlay();

	            resizeModalContent(markup.modal.contentInner.height(), markup.modal.contentInner.width());


	            markup.modal.closerHolder.append(markup.modal.closer);
	            markup.modal.content.append(markup.modal.closerHolder, markup.modal.contentInner);
	            markup.modal.contentInner.css('display', 'block');
	            positionModalContent();

	            methods.open();
	        };
	        _img.src = '/Media/modallogo.png';
	    },

	    open: function (cb) {
	        markup.modal.overlay.fadeIn(_settings.fxSpeed, function () {
	            markup.modal.content.fadeIn(_settings.fxSpeed, function () {
	                if (cb && typeof cb === 'function') {
	                    cb();
	                }
	            });
	        });
	    },
	    close: function () {
	        markup.modal.content.fadeOut(_settings.fxSpeed, function () {
	            markup.modal.overlay.fadeOut(_settings.fxSpeed, function () {
	                removeOverlay();
	            });
	        });
	    },
	    resize: function () {
	        _doc = $(document);
	        _win = $(window);
	    }
	},

    // markup methods
	initMarkup = function () {
	    var _markup = {
	        modal: {
	            overlay: $('<div />', { 'id': 'modalOverlay' }).css({
	                'background-color': '#ffffff',
	                'display': 'none',
	                'height': '100%',
	                'left': 0,
	                'opacity': _settings.opacity,
	                'position': 'absolute',
	                'top': 0,
	                'width': '100%',
	                'z-index': 1000
	            }),
	            content: $('<div />', { 'id': 'modalHomeContent', 'class': 'modalWindow' }).css({
	                'display': 'none',
	                'position': 'absolute',
	                'background-color1': '#ffffff',
	                'z-index': 1100,
	                'opacity': 0.7
	            }),
	            contentInner: $('<div />', { 'id': 'modalContentInner' }).css({
	                'display': 'none',
	                'opacity': 0.7
	            }),
	            closerHolder: $('<div />', { 'id': 'modalCloserHolder', 'class': 'modalCloserHolder' }).css(
                {
                    'background-color': '#ffffff',
                    'opacity': 0.7
                }),
	            closer: $('<a />', { 'href': '#', 'id': 'modalCloser', 'class': 'modalCloser' }).html('X').click(function (e) {
	                e.preventDefault();
	                methods.close();
	            }),
	            image: $('<img />', { 'id': 'modalImage' }),
	            mediaspace: $('<div />', { 'id': 'mediaspace' }).css({
	                'display': 'block',
	                'width': '0px',
	                'height': '0px',
	                'position': 'absolute',
	                'top': '23000px'
	            })
	        }
	    };

	    return _markup;
	},
    initFlash = function () {
        var so = new SWFObject('/media/flash/player.swf', 'mpl', '0', '0', '9');
        so.addParam('allowfullscreen', 'true');
        so.addParam('allowscriptaccess', 'always');
        so.addParam('wmode', 'opaque');
        so.addVariable('file', '/Media/flash/dingdonobergeschoss.mp3');
        so.addVariable('frontcolor', '666666');
        so.addVariable('autostart', 'true');
        so.write('mediaspace');

    },
    buildOverlay = function () {
        //console.log('buildOverlay');
        markup.modal.overlay.css({
            'height': _doc.height(),
            'width': _doc.width()
        });
        $('body').append(markup.modal.overlay, markup.modal.content);

        // capture ESC key to close modal
        $(document.documentElement).bind('keyup', function (e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code === 27) {
                methods.close();
            }
        });
    },
	removeOverlay = function () {
	    //console.log('removeOverlay');
	    markup.modal.content.remove();
	    markup.modal.overlay.remove();
	},

    // helpers
	resizeModalContent = function (h, w) {
	    //console.log('resizeModalContent');
	    var h = parseInt(markup.modal.contentInner.css('padding-top'), 10) + parseInt(markup.modal.contentInner.css('padding-bottom'), 10) + h + markup.modal.closerHolder.height() + 10;
	    var w = parseInt(markup.modal.contentInner.css('padding-left'), 10) + parseInt(markup.modal.contentInner.css('padding-right'), 10) + w;
	    //alert('h = ' + h);
	    //alert('w = ' + w);
	    markup.modal.content.height(h);
	    markup.modal.content.width(w);
	},
	positionModalContent = function () {
	    //console.log('positionModalContent');
	    var _left = (_doc.width() - markup.modal.content.width()) / 2,
			_top = (_win.height() - markup.modal.content.height() - 90) / 2;

	    markup.modal.content.css({
	        'left': _left,
	        'top': _top
	    });
	},
	optionsFromRel = function (str) {
	    var arr = $.grep(str.split(' '), function (n, i) {
	        return (n);
	    });
	    return (arr.length > 0) ? arr : false;
	}

    return {
        init: methods.init,
        close: methods.close
    };
})();

$.fn.center = function () {
            this.css("position", "absolute");
            this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
            this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
            return this;
}

$(function () {
    $('.modal').modalWindow();
    $('form').placeholder();
});
