if( !window.console ) {
    window.console = function() {}
}

if (typeof Migros === 'undefined') {
    Migros = {};
}
if (typeof Migros.Steps13 === 'undefined') {
    Migros.Steps13 = {};
}


// jQuery Custom Plugins

;(function($){
	// overlay
	var
	_ns = 'modalWindow',
	_doc = null,
	_win = null,
	_content = null,
    _language = $('html').attr('lang'),

    _closeButtonText = 
    { 
        'de':'Schliessen',
        'fr':'Fermer'
    },
	
	_settings = {
		'modalHeight' : 0,
		'modalWidth' : 0,
		'opacity' : '.9',
		'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
					
                    var url = $this.attr('href');
                    if( url.toLowerCase().indexOf('.jpg') > 0 || url.toLowerCase().indexOf('.png') > 0 ) {
						var _img = new Image();
						_img.onload = function() {
							$img = $(_img);
							markup.modal.contentInner.html($img).appendTo($('body'));
							markup.modal.content.width(markup.modal.contentInner.outerWidth());
							buildOverlay();
							resizeModalContent(markup.modal.contentInner.height());
							markup.modal.content.append(markup.modal.closer, markup.modal.contentInner);
							markup.modal.contentInner.css('display','block');
							positionModalContent();
							methods.open(function() {
								resizeModalContent(markup.modal.contentInner.height());
								positionModalContent();
								markup.modal.contentInner.delegate('a', 'click', function(e) {
									e.preventDefault();
									methods.loadContent($(this).attr('href'));
								});
							});
						};
						_img.src = $this.attr('href');
                    }
                    else {
						$.ajax({
							url:$this.attr('href'),
							dataType : 'html',
							success : function(data){
								// load content and append to $(body) to get height of element
								data = $(data).find('#ajaxContent');
								markup.modal.contentInner.html(data).appendTo($('body'));
								markup.modal.content.width(markup.modal.contentInner.outerWidth());
								buildOverlay();
								resizeModalContent(markup.modal.contentInner.height());
								markup.modal.content.append(markup.modal.closer, markup.modal.contentInner);
								markup.modal.contentInner.css('display','block');
								positionModalContent();
								methods.open(function() {
									resizeModalContent(markup.modal.contentInner.height());
									positionModalContent();
									markup.modal.contentInner.delegate('a', 'click', function(e) {
										e.preventDefault();
										methods.loadContent($(this).attr('href'));
									});
								});
							}
						});
                    }
				});
			});
		},
		/*destroy : function( ) {
			return this.each(function(){
				var $this = $(this),
					data = $this.data(ns);
				$(window).unbind(ns);
				data.modalWindow.remove();
				$this.removeData(ns);
			});
		},*/
		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.height());
				    if( cb ) {
					    cb();
				    }
                }
            });
		}
	},
	
	// 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({
					'display' : 'none',
					'position' : 'fixed',
					'z-index' : 1100
				}),
				contentInner : $('<div />', { 'id' : 'modalContentInner' }).css({
					'display' : 'none'
				}),
				closer : $('<a />', { 'href' : '#', 'id' : 'modalCloser', 'class' : 'modalCloser' }).html(_closeButtonText[_language]).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) {
		//console.log('resizeModalContent');
		markup.modal.content.height(parseInt(markup.modal.contentInner.css('padding-top'),10) + parseInt(markup.modal.contentInner.css('padding-bottom'),10) + h);
	},
	positionModalContent = function() {
		//console.log('positionModalContent');
		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
		});
	},
	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.Steps13.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.Steps13.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.Steps13.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);
        }
    };
} ();

Migros.Steps13.SetTextAreasMaxLength = 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')));
        }
    });
};

$(function () {
    $('.modal').modalWindow({}, function () { console.log('callback'); });
    $('.tooltip').toolTip();
    $('form').placeholder();
    $('ul.comments-functions').toggleComments();
	$('a.showMoreToggle').expandAsset();
    Migros.Steps13.Comment.Init(); 
    Migros.Steps13.SetTextAreasMaxLength();
});
