// define global namespace
if(!window.ch) {
    ch = {};
}
if(!ch.postfinance) {
    ch.postfinance = {};
}

// =================================================================================================

(function(){
    
	var Class = {
			
	  extend : function(parent, def) {
	  	var func, mixins = [], i, mixin;
	  	
	    if(arguments.length === 1) {
	    	def = parent;
	    	parent = null;
	    }
	    if(arguments.length === 3) {
		    func = function() {
		      if(!Class.extending) {
		      	this.init.apply(this, arguments);
		      }
		    };
		  }
		  else {
		    func = function() {
		      if(!Class.extending) {
		      	this.initialize.apply(this, arguments);
		      }
		    };
		  }
	    if(typeof(parent) === 'function') {
	      Class.extending = true;
	      if(arguments.length === 3) {
	      	func.prototype = new parent(arguments[2]);
	      }
	      else {
	      	func.prototype = new parent();
	      }
	      delete Class.extending;
	    }
	    if(def && def.include) {
	      if(def.include.reverse) {
	        // methods defined in later mixins should override prior
	        mixins = mixins.concat(def.include.reverse());
	      }
	      else {
	        mixins.push(def.include);
	      }
	      delete def.include; // clean syntax sugar
	    }	    
	    if(def) {
	    	Class.inherit(func.prototype, def);
	    }
	    for(i = 0; (mixin = mixins[i]); i++) {
	      Class.mixin(func.prototype, mixin);
	    }	    
	    return func;
	  },	  
	
	  mixin : function(dest, src, clobber) {
	  	var prop;
	  	
	    clobber = clobber || false;
	    if(typeof(src) !== 'undefined' && src !== null) {
	      for(prop in src) {      	
	        if(clobber || (!dest[prop] && typeof(src[prop]) === 'function')) {
	          dest[prop] = src[prop];
	        }
	      }
	    }
	    return dest;
	  },	  
	
	  inherit : function(dest, src, fname) {
	  	var ancestor, descendent, method, prop;
	  	
	    if(arguments.length == 3) {
	      ancestor = dest[fname];
	      descendent = src[fname];
	      method = descendent;
	      descendent = function() {
	      	var ref, result;
	      	
	        ref = this.parent;
	        this.parent = ancestor;
	        result = method.apply(this, arguments);
	        ref ? this.parent = ref : delete this.parent;
	        return result;
	      };
	      // mask the underlying method
	      descendent.valueOf = function() {
	      	return method;
	      };
	      descendent.toString = function() {
	      	return method.toString();
	      };
	      dest[fname] = descendent;
	    }
	    else {
	      for(prop in src) {
	        if(dest[prop] && typeof(src[prop]) === 'function') {
	          Class.inherit(dest, src, prop);
	        }
	        else {
	          dest[prop] = src[prop];
	        }
	      }
	    }
	    return dest;
	  }
					  
	};
	
	ch.postfinance.Class = Class;
	
})();	
       
// =================================================================================================	
	
	ch.postfinance.ContainerRegion = ch.postfinance.Class.extend({
		
		initialize : function(containerRegion, containersPerRow, containerWidth) {

			var containerRows = containerRegion.find("div.container-row");
			containerRows.each(function(i) {
				
				var nrOfContainers = $(this).find("div.container").length;
				var nrOfMissingContainers = nrOfContainers%containersPerRow;
				
				if(nrOfMissingContainers > 0) {
					var pxToMoveToLeft = (containersPerRow - nrOfMissingContainers) * containerWidth;
					
					//move line image on container-row
					$(this).css( {
						"background-position" : "-" + pxToMoveToLeft + "px bottom" }
					);
					
					//move line image on container-region, if first row
					if(i === 0) {
						containerRegion.css( {
							"background-position" : "-" + pxToMoveToLeft + "px top" }
						);
					}
				}
				
			});
		}
		
	});	

// =================================================================================================	
	
	ch.postfinance.ButtonParagraph = ch.postfinance.Class.extend({
		
		initialize : function(buttonParagraph) {
            var me = this;

            var currentMaxLineWidth = 0;
            var lineWidth = 0;
            $("input.button, a.buttonlink, a.linkbutton", buttonParagraph).each(function(){
                var button = $(this);

                if(button.hasClass("new-line")) {
                    if(lineWidth > currentMaxLineWidth) {
                        currentMaxLineWidth = lineWidth;
                    }
                    lineWidth = me.getActualWidth(button); //"reset" (no +=)
                }
                else {
                    lineWidth += me.getActualWidth(button);
                }
            });
            // don't forget the last line
            if(lineWidth > currentMaxLineWidth) {
                currentMaxLineWidth = lineWidth;
            }
            
            // prevent from applying this patch if there are any .efinance-buttons as they float left
            if($("input.efinance-button", buttonParagraph).size() === 0) {
            	buttonParagraph.css("width", currentMaxLineWidth);
            }
		},

        getActualWidth : function(node) {
            return node.width()
                + parseInt( node.css("margin-right"), 10 )
                + parseInt( node.css("margin-left"), 10 )
                + parseInt( node.css("padding-right"), 10 )
                + parseInt( node.css("padding-left"), 10 )
                + parseInt( node.css("borderLeftWidth"), 10 )
                + parseInt( node.css("borderRightWidth"), 10 );
        }
		
	});

// =================================================================================================

	ch.postfinance.FAQ = ch.postfinance.Class.extend({
		
		hideableContainers : null,

		initialize: function( rootNode ) {
			var me = this;
			
			me.hideableContainers = $("dl.faq dt", rootNode);
			me.registerEventHandlers();
			me.hideAll();
		},
		
		registerEventHandlers: function() {
			var me = this;
			
			me.hideableContainers.each( function() {
				var hideableContainer = $(this);
				me.guiInit(hideableContainer);		
				
				hideableContainer.click( function() {
					var clickedContainer = $(this);
					var clickedContainerIsOpen = clickedContainer.hasClass("open");
					me.hideAll();
					if(!clickedContainerIsOpen) {
						me.showContainer(clickedContainer);
					}
					clickedContainer.css("color", "#333333");
				});
				
				hideableContainer.mouseover( function() {
					$(this).css("color", "#333333");
				});
				
				hideableContainer.mouseout( function() {
					var clickedContainer = $(this);
					var clickedContainerIsOpen = clickedContainer.hasClass("open");
					if(!clickedContainerIsOpen) {
						clickedContainer.css("color", "#555555");
					}
				});	
						
			});	
		},
		
		// add stuff to widget that should not be there in non-js version
		guiInit: function(hideableContainer) {
			hideableContainer.css("cursor", "pointer");
		},
		
		showContainer: function(hideableContainer) {			
			var containerBody = hideableContainer.next("dd");
			
			hideableContainer.addClass("open");
			hideableContainer.css("color", "#333333");
			containerBody.show();
		},
		
		hideContainer: function(hideableContainer) {
			var containerBody = hideableContainer.next("dd");
			
			hideableContainer.removeClass("open");
			hideableContainer.css("color", "#555555");
			containerBody.hide();			
		},		
		
		hideAll: function() {
			var me = this;
			
			me.hideableContainers.each( function() {
				me.hideContainer($(this));
			});
		}
	});
	
// =================================================================================================
	
	ch.postfinance.HighlightTable = ch.postfinance.Class.extend({
		
		rootNode_ : null,
		rows_ : null,
		
		initialize : function(jRootNode) {
			var me = this;
			
			me.rootNode_ = jRootNode;
			me.rows_ = me.rootNode_.find("tbody tr").
			mouseover(function(){
				me.handleMouseOver_($(this));
			}).
			mouseout(function(){
				me.handleMouseOut_($(this));
			});
		},
		
		handleMouseOver_ : function(jRow) {
			var me = this;
			
			me.rows_.removeClass("mouseover");
			jRow.addClass("mouseover");
		},
		
		handleMouseOut_ : function(jRow) {
			var me = this;
			
			jRow.removeClass("mouseover");
		}		
	
	});
	
// =================================================================================================
	
	ch.postfinance.MessageArea = ch.postfinance.Class.extend({
		
		initialize : function(node) {		 
			 node.focus(function () {
			 if(this.value == this.defaultValue) {
				 this.value = '';
			 }
    	 });  
		}
	});
	
// =================================================================================================
	
	ch.postfinance.LabelLink = ch.postfinance.Class.extend({
		url : null,
		initialize : function(jRootNode) {
			var me = this;
			$("a",jRootNode).each(function() {
				$(this).click(function() {
					me.url = $(this).attr("href");
					me.handleClick($(this),me.url);
					return false;
				});
			});
		},
		handleClick : function(node,url) {
			var me = this;
			if (node.hasClass("helpbrowser")) {
				var fn = url.substr(url.indexOf(":")+1,url.length);
				eval(fn);
			} else {
				var target = node.attr("target");
				if(target.length > 0) {
					if (target.indexOf("_")!=-1) {
						// normale targets
						if(target==="_new" || target==="_blank") {
							window.open(url);
						} else if(target==="_top") {
							top.location.href = url;
						} else {
							window.location.href = url;
						}
					} else {
						// frameset-like target
						if(frames.length>0) {
							if(top.frames[target]) {
								top.frames[target].location.href = url;
							}
						}
					}
				} else {
					window.location.href = url;
				}
			}
		}
	});
	
// =================================================================================================

	ch.postfinance.EnableableItem = ch.postfinance.Class.extend({
		
		field_ : null,
		enableable_ : null,
		
		initialize : function(node, enableable) {
			var me = this;
			
			me.enableable_ = enableable;
			me.field_ = $("input:text, select", node).attr("disabled", "disabled").addClass("disabled");
			$("input:radio, input:checkbox", node).attr("checked", "").click(function(){
				me.enableable_.handleItemClicked(me);
				me.enable();
			});
  		
		},
		
		disable : function() {
			var me = this;
			
			me.field_.attr("disabled", "disabled").addClass("disabled");
		},
		
		enable : function() {
			var me = this;
			
			me.field_.attr("disabled", "").removeClass("disabled").focus();
		}
		
	});
  			
	ch.postfinance.Enableable = ch.postfinance.Class.extend({
		
		activeItem_ : null,
		
		initialize : function(node) {
			var me = this;
			
			$("ul.form-elements > li", node).each(function() {
				new ch.postfinance.EnableableItem($(this), me);
			});
		},
		
		handleItemClicked : function(item) {
			var me = this;
			
			if(me.activeItem_) {
				me.activeItem_.disable();
			}
			me.activeItem_ = item;
		}
		
	});
	
// =================================================================================================	