/*global dojo, gadgets, document, navigator*/
var gadgets = gadgets || {};

gadgets.BartMover = function (node, e, host) {
    this.node = dojo.byId(node);
    this.marginBox = {
        l: e.pageX,
        t: e.pageY
    };
    this.mouseButton = e.button;
    var h = this.host = host, d = node.ownerDocument, _c = dojo.connect(d, "onmousemove", this, "onFirstMove");
    this.events = [dojo.connect(d, "onmousemove", this, "onMouseMove"), dojo.connect(d, "onmouseup", this, "onMouseUp"), dojo.connect(d, "ondragstart", dojo.stopEvent), dojo.connect(d.body, "onselectstart", dojo.stopEvent), _c];

	if (h && h.onMoveStart) {
        h.onMoveStart(this);
    }
};   

gadgets.BartMover.prototype.onMouseMove = function (e) {
    dojo.dnd.autoScroll(e);
    var m = this.marginBox;
    this.host.onMove(this, {
        l: m.l + e.pageX,
        t: m.t + e.pageY
    });
    dojo.stopEvent(e);
};

gadgets.BartMover.prototype.onMouseUp = function (e) {
    if (dojo.isWebKit && dojo.dnd._isMac && this.mouseButton == 2 ? e.button == 0 : this.mouseButton == e.button) {
        this.destroy();
    }
    dojo.stopEvent(e);
};

gadgets.BartMover.prototype.onFirstMove = function (e) {
	/**
	 * 
	 */
	if (dojo.isIE) {
		[].indexOf ||
		(Array.prototype.indexOf = function(v, n){
			n = (n == null) ? 0 : n;
			var m = this.length;
			for (var i = n; i < m; i++) 
				if (this[i] == v) 
					return i;
			return -1;
		});
	}
	
	var ret = false;
	var cls = ['gadgets-gadget-title-bar','gadgets-gadget-title','gadgets-gadget-title-mover'];
	
	if ((e.srcElement && cls.indexOf(e.srcElement.className) == -1) || 
			(e.originalTarget && cls.indexOf(e.originalTarget.className) == -1)) {
		ret = true;	
	}
	
	if(ret) {
		this.destroy();
		dojo.stopEvent(e);
		return;
	}
	
	var s = this.node.style,
        l, t, h = this.host;
    switch (s.position) {
    case "relative":
    case "absolute":
        l = Math.round(parseFloat(s.left));
        t = Math.round(parseFloat(s.top));
        break;
    default:
        s.position = "absolute";
        var m = dojo.marginBox(this.node);
        var b = dojo.doc.body;
        var bs = dojo.getComputedStyle(b);
        var bm = dojo._getMarginBox(b, bs);
        var bc = dojo._getContentBox(b, bs);
        l = m.l - (bc.l - bm.l);
        t = m.t - (bc.t - bm.t);
        break;
    }
    this.marginBox.l = l - this.marginBox.l;
    this.marginBox.t = t - this.marginBox.t;
    if (h && h.onFirstMove) {
        h.onFirstMove(this);
    }
    dojo.disconnect(this.events.pop());
};

gadgets.BartMover.prototype.destroy = function () {
    dojo.forEach(this.events, dojo.disconnect);
    var h = this.host;
    if (h && h.onMoveStop) {
        h.onMoveStop(this);
    }
    this.events = this.node = this.host = null;
};

gadgets.BartGadgetService = function() {
	gadgets.IfrGadgetService.call(this);
	gadgets.rpc.register('resize_iframe', this.setHeight);
	gadgets.rpc.register('set_pref', this.setUserPref);
	gadgets.rpc.register('set_title', this.setTitle);
	gadgets.rpc.register('requestNavigateTo', this.requestNavigateTo);
	gadgets.rpc.register('requestSendMessage', this.requestSendMessage);
};
gadgets.BartGadgetService.inherits(gadgets.IfrGadgetService);

gadgets.BartGadgetService.prototype.setUserPref = function(editToken, name, value) {
  var id = gadgets.container.gadgetService.getGadgetIdFromModuleId(this.f);
  var gadget = gadgets.container.getGadget(id);
  for (var i = 1, j = arguments.length; i < j; i += 2) {
		if (gadget.userPrefs[arguments[i]] == undefined) {
			gadget.userPrefs[arguments[i]] = {};
		}
	  gadget.userPrefs[arguments[i]].value = arguments[i + 1];
  }
  gadget.saveUserPrefs();
};

gadgets.BartGadget = function(opt_params) {
	gadgets.Gadget.call(this, opt_params);	
};
gadgets.BartGadget.inherits(gadgets.IfrGadget);

gadgets.BartGadget.prototype.cssClassTitleToggleButton = 'gadgets-gadget-title-toggle-button';
gadgets.BartGadget.prototype.cssClassTitleSettingsButton = 'gadgets-gadget-title-settings-button';
gadgets.BartGadget.prototype.cssClassTitleMaximizeButton = 'gadgets-gadget-title-maximize-button';
gadgets.BartGadget.prototype.cssClassTitleMinimizeButton = 'gadgets-gadget-title-minimize-button';

gadgets.BartGadget.prototype.getId = function() {
    return "gadget-chrome-"+ this.id;
};
gadgets.BartGadget.prototype.getAppId = function() {
    return this.appId;
};
gadgets.BartGadget.prototype.getToggleButtonId = function() {
    return this.getIframeId() + "_toggleButton";
};
gadgets.BartGadget.prototype.getMaximizeButtonId = function() {
    return this.getIframeId() + "_maximizeButton";
};
gadgets.BartGadget.prototype.getMinimizeButtonId = function() {
    return this.getIframeId() + "_minimizeButton";
};
gadgets.BartGadget.prototype.getOptionsMenuButtonId = function() {
    return this.getIframeId() + "_optionsMenuButton";
};

//overridden to add in elements for rounding out corners
gadgets.BartGadget.prototype.render = function(chrome) {	
	if (chrome) {
	    var gadget = this;    
	  
	  	/*
	  	 * CUSTOM BART GADGET class added
	  	 */
		if (gadget.cssClass != undefined) {
			dojo.addClass(chrome, gadget.cssClass);
		}
	        
	    this.getContent(function(content) {
	        var c = "";
	        if(navigator.userAgent.match(/Windows/)) {
	            c += " win";
	        }
	        if(navigator.userAgent.match(/Safari/)) {
	            c += " webkit";
	        }
	
	        //rounded corners...
	        var header = ''+
	            '<div class="hd'+ c +'">'+
	                '<div class="tl"></div>'+ 
	                '<div class="tlf"></div>'+ 
	                '<div class="tr"></div>'+ 
	                '<div class="trf"></div>'+ 
	            '</div>'
	            ;
	
	        var footer = ''+
	            '<div class="ft">'+
	                '<div class="bl"></div>'+ 
	                '<div class="br"></div>'+ 
	            '</div>'
	            ;
	
	        chrome.innerHTML = header + content + footer;        
		
	        if(gadget.collapsed) {
	        	gadget.setContentVisible(false);
	        }	
	        
	        var iframe = document.getElementById(gadget.getIframeId());

	        if(gadget.html != undefined && gadget.opensocialCompatible == false) {
	        	
				if (gadget.html != '') {
					dojo.html.set(iframe, gadget.html);	
					
					if (!dojo.isMozilla) {
						gadget.loadScripts(gadget.getIframeId());
					}
				} else {
					var direct_url = gadget.specUrl.substring(0, gadget.specUrl.indexOf('cmd=gadget&id='));

					gadget.ahah(direct_url+'direct_gadget='+gadget.appId+(BART.Gadgets.page_id ? '&id='+BART.Gadgets.page_id : ''), iframe.id, gadget);
				}			
	        	
	        } else {
	        	iframe.src = gadget.getIframeUrl();
	        }
			
			if(gadget.moveable) {
	    		dojo.addOnLoad(function() {
	    			gadget.makeMoveable();
	    		});	
	    	}	
	    }); 
    }
};
gadgets.BartGadget.prototype.ahah = function(url,target,gadget) {
    document.getElementById(target).innerHTML = 'Even geduld alstublieft...';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {gadget.ahahDone(target);};
        req.open("GET", url, true);
        req.send(null);
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {gadget.ahahDone(target);};
            req.open("GET", url, true);
            req.send();
        }
    }
};

gadgets.BartGadget.prototype.ahahDone = function(target) {
   if (req.readyState == 4) {
       if (req.status == 200 || req.status == 304) {
           results = req.responseText;
           document.getElementById(target).innerHTML = results;   
		   
		   this.loadScripts(this.getIframeId());
       } else {
           document.getElementById(target).innerHTML="ahah error:\n" +req.statusText;
       }
   }
};

gadgets.BartGadget.prototype.loadScripts = function(iframe_id){
	
	var iframe = document.getElementById(iframe_id);
	var codelist = [];
    var scripts = dojo.query ("script", document.getElementById(iframe_id));
    for(var i = 0; i < scripts.length; i++){
    	//iframe.appendChild(scripts[i]);
    	var src = scripts[i].getAttribute ("src");

        if(src){
        	var djd = dojo.doc;
            var sc = djd.createElement("script");
            sc.setAttribute("src", src);
            iframe.appendChild(sc);  
        }else{
        	codelist.push (scripts[i].innerHTML);
        }
    }
	
    var code = codelist.join (";");
    var djd = dojo.doc;
	
	if (code != '') {
		var sc = djd.createElement("script");
		
		sc.type = "text/javascript";
		sc.text = code;
		
    	iframe.appendChild(sc);         
	}
};

gadgets.BartGadget.prototype.getMainContent = function(continuation) {
	  var iframeId = this.getIframeId();
	  gadgets.rpc.setRelayUrl(iframeId, this.serverBase_ + this.rpcRelay);
	  gadgets.rpc.setAuthToken(iframeId, this.rpcToken);

	  if(this.html != undefined && this.opensocialCompatible == false) {
		  continuation('<div class="' + this.cssClassGadgetContent + '"><div id="' +
			      iframeId + '" name="' + iframeId + '" class="' + this.cssClassGadget +
			      '" style="' +  
			      (this.height ? 'height:' + this.height + ((this.height+'').indexOf('%') > -1 ? '' : 'px') + ';' : '') +
			      (this.width ? 'width:' + this.width + ((this.width+'').indexOf('%') > -1 ? '' : 'px') + ';' : '') +
			      'overflow:' + (this.scrolling ? 'auto' : 'hidden') + ';"></div></div>'); 
	  } else {
		  continuation('<div class="' + this.cssClassGadgetContent + '"><iframe id="' +
			      iframeId + '" name="' + iframeId + '" class="' + this.cssClassGadget +
			      '" src="about:blank' +
			      '" frameborder="no" scrolling="'+(this.scrolling ? 'yes' : 'no')+'"' +
			      (this.height ? ' height="' + this.height + '"' : '') +
			      (this.width ? ' width="' + this.width + '"' : '') +
			      '></iframe></div>'); 
	  }	  
};

gadgets.BartGadget.prototype.getIframeUrl = function() {
	return this.serverBase_ + 'ifr?' +
	      'container=' + this.CONTAINER +
	      '&mid=' +  this.id +
	      '&nocache=' + gadgets.container.nocache_ +
	      '&country=' + gadgets.container.country_ +
	      '&lang=' + gadgets.container.language_ +
	      '&view=' + gadgets.container.view_ +
	      (this.specVersion ? '&v=' + this.specVersion : '') +
	      (gadgets.container.parentUrl_ ? '&parent=' + encodeURIComponent(gadgets.container.parentUrl_) : '') +
	      (this.debug ? '&debug=1' : '') +
	      this.getAdditionalParams() +
	      this.getUserPrefsParams() +
	      (this.secureToken ? '&st=' + this.secureToken : '') +
	      '&url=' + encodeURIComponent(this.specUrl) +
	      '#rpctoken=' + this.rpcToken +
	      (this.viewParams ?
	          '&view-params=' +  encodeURIComponent(gadgets.json.stringify(this.viewParams)) : '') +
	      (this.hashData ? '&' + this.hashData : '');
	};

gadgets.BartGadget.prototype.getContentVisible = function() {
	var gadgetIframe = document.getElementById(this.getIframeId());
	if (gadgetIframe) {
		return gadgetIframe.parentNode.style.display != 'none'; 
	}
	return false;
};

gadgets.BartGadget.prototype.setContentVisible = function(visible) {
	this.collapsed = !visible;	
	var gadgetIframe = document.getElementById(this.getIframeId());
	if (gadgetIframe) {
		gadgetIframe.parentNode.style.display = visible ? '' : 'none';
		if(visible) {
			dojo.query("#gadget-chrome-"+ this.id + " .ft").removeClass("minimized");
			dojo.removeClass(this.getToggleButtonId(), "gadgets-gadget-title-toggle-button-closed");
			this.refresh();
		} else {	
			dojo.query("#gadget-chrome-"+ this.id + " .ft").addClass("minimized");
			dojo.addClass(this.getToggleButtonId(), "gadgets-gadget-title-toggle-button-closed");
		}	
	}
};

gadgets.BartGadget.prototype.handleToggle = function() {
	this.setContentVisible(!this.getContentVisible());	
	if(gadgets.container.stateStore) {
		gadgets.container.stateStore.onToggle(this);
	}
};

gadgets.BartGadget.prototype.handleMaximize = function() {

    //hide the columns and display the div that's full screen
    dojo.style("gadgets", "display", "none");
    dojo.style("maximizedGadget", "display", "block");

    //insert a placeholder before the gadget in question 
    var placeholder = dojo.doc.createElement("div");
    dojo.attr(placeholder, "id", "maximizedGadgetPlaceholder");
    dojo.place(placeholder, this.getId(), "after");

    //adjust the style on the maximized gadget so that the maximize "changes"
    //to a minimize icon
    dojo.style(this.getMaximizeButtonId(), "display", "none");
    dojo.style(this.getMinimizeButtonId(), "display", "block");

    //move the gadget into the maximizedGadget div
    dojo.place(this.getId(), "maximizedGadget", "first");

    //IE doesn't necessarily refresh, so force it
    dojo.style(this.getIframeId(), "display", "block");
};

gadgets.BartGadget.prototype.handleMinimize = function() {

    //restore the gadget to its placeholder
    dojo.place(this.getId(), "maximizedGadgetPlaceholder", "after");
    dojo.query("#maximizedGadgetPlaceholder").orphan();

    //adjust the style on the maximized gadget so that the minimize "changes"
    //to a maximize icon
    dojo.style(this.getMaximizeButtonId(), "display", "block");
    dojo.style(this.getMinimizeButtonId(), "display", "none");

    //hide the columns and display the div that's full screen
    dojo.style("gadgets", "display", "block");
    dojo.style("maximizedGadget", "display", "none");
}

//Based on www.gmodules.com/ig/gadgetsettings
gadgets.BartGadget.prototype.handleOpenUserPrefsDialog = function() {
	if (!this.userPrefsDialogContentLoaded) {
		var userPrefsDialogContent = '<script type="text/javascript">' +
		    'function addToList_'+this.id+'(fld_nr,value) {' +
		    ' 	var input 	= document.getElementById("m_'+this.id+'_" + fld_nr);' +
		    ' 	var list 	= document.getElementById("m_'+this.id+'_" + fld_nr + "_l");' +
		    '	if(input) {' +
		    '		input.value += (input.value=="" ? value : ";"+value);' +
		    '	}' +
		    '	if(list) {' +
		    '		var li = document.createElement("li");' +
		    '		li.appendChild(document.createTextNode(value));' +
		    '		list.appendChild(li)' +
		    '	}' +
		    '}' +
		    'function removeFromList_'+this.id+'(fld_nr,value) {' +
		    ' 	var input 	= document.getElementById("m_'+this.id+'_" + fld_nr);' +
		    ' 	var list 	= document.getElementById("m_'+this.id+'_" + fld_nr + "_l");' +
		    '	if(input) {' +
		    '		var values = input.value.split(";");' +
		    '		for(var i=0; i<values.length; i++) {' +
		    '			if(values[i] == value){values[i]=undefined;break;}' +
		    '		}' +
		    '		values.sort();' +
		    '	}' +
		    '	if(list) {' +
		    '		for( var x = 0; list.childNodes[x]; x++ ){' +
		    '			if(list.childNodes[x].nodeValue == value){list.removeChild(list.childNodes[x]);break;}' +
		    '		}' +
		    '	}' +
		    '}' +
		    '</script>';		
		
		if(dojo.isObject(this.userPrefsConfig)) {
			var conf = this.userPrefsConfig;
			var prefs = this.getUserPrefs();
			
			userPrefsDialogContent += '<div id="gadget_edit_div'+this.id+'"><table>';			
			
			var show_required 	= false;
			var counter 		= -1;
			for (key in conf) {
				counter++;
				
				if(conf[key].required) {
					show_required = true;
				}	
				
				var label 		= (conf[key].displayName ? conf[key].displayName : '');
				label 			= (label.length == 0 ? key : label);
				var defValue 	= (conf[key]['default'] ? conf[key]['default'] : '');
				var value 		= prefs && prefs[key] ? prefs[key] : defValue;
				
				if (!conf[key].datatype) {
					conf[key].datatype = 'STRING';
				}
				
				if(conf[key].datatype != 'HIDDEN') {
					userPrefsDialogContent += '<tr><td class="m_fieldname_'+counter+'">'+label+
						(conf[key].required ? '<span class="required">*</span>' : '')+'</td>';		            
				}
				
				switch (conf[key].datatype) {
			        case 'ENUM':
			        	userPrefsDialogContent += '<td colspan=2>&nbsp;<select id="m_'+this.id+'_'+counter+'" name="m_'+this.id+'_up_'+key+'" class="c_enum_'+this.id+'">';
			        	for (k in conf[key].enumValues) {
			        		$sel = (conf[key].enumValues[k].value == value) ? ' SELECTED' : '';
			        		userPrefsDialogContent += "<option value=\""+conf[key].enumValues[k].value+"\" "+$sel+">"+conf[key].enumValues[k].displayValue+"</option>";
			        	}
			        	userPrefsDialogContent +=  "</select></td>";			        	
			        	break;
			        case 'STRING':
			        	userPrefsDialogContent += '<td colspan=2>&nbsp;' +
    									'<input type="text" id="m_'+this.id+'_'+counter+'" name="m_'+this.id+'_up_'+key+'" class="c_text_'+this.id+'" value="'+value+'">' +
    									'</td>';    					
			        	break;
			        case 'HIDDEN':
			        	userPrefsDialogContent += '<input type="hidden" id="m_'+this.id+'_'+counter+'" name="m_'+this.id+'_up_'+key+'" value="'+value+'" />';
			          break;
			        case 'BOOL':
			        	userPrefsDialogContent += '<td colspan=2>&nbsp;' +
			        					'<input type="hidden" id="m_'+this.id+'_'+counter+'" name="m_'+this.id+'_up_'+key+'" class="c_bool_'+this.id+'" value="'+value+'">' +
			        					'<input type=checkbox onClick="document.getElementById(\'m_'+this.id+'_'+counter+'\').value = this.checked ? \'1\' : \'0\';" '+(value == '1' ? 'CHECKED' : '')+'>' +
			        					'</td>';			        	
			          break;
			        case 'LIST':
			        	userPrefsDialogContent += '<td colspan=2>&nbsp;' +
			        					'<input type="hidden" id="m_'+this.id+'_'+counter+'" name="m_'+this.id+'_up_'+key+'" class="c_list_'+this.id+'" value="">' +
			        					'<input type="text" id="m_'+this.id+'_'+counter+'_v">&nbsp;<input type="button" onClick="addToList_'+this.id+'(_get(\'m_'+this.id+'_'+counter+'\'),_get(\'m_'+this.id+'_'+counter+'_v\').value)">' +
										'<ul id="m_'+this.id+'_'+counter+'_l"></ul>' +
			        					'</td>';
			          break;
			        case 'NUMBER':
			        	userPrefsDialogContent += '<td colspan=2>&nbsp;' +
			        				'<input type="text" id="m_'+this.id+'_'+counter+'" name="m_'+this.id+'_up_'+key+'" value="'+value+'" />';
			          break;
				}
				
				if(conf[key].datatype != 'HIDDEN') {
					userPrefsDialogContent += "</tr>";
				}				
			}
			
			userPrefsDialogContent += '<tr id="required_'+this.id+'">' +
            						'<td colspan=2>' +
            							(show_required ? '<span class="required">* verplicht</span>' : '') +
            						'</td></tr>' +			
            						'</table><input id="m_'+this.id+'_numfields" type="hidden" value="'+counter+'"></div>';
		}
		this.buildUserPrefsDialog(userPrefsDialogContent);
		this.userPrefsDialogContentLoaded = true;
	}
	
	this.showUserPrefsDialog();
};

gadgets.BartGadget.prototype.handleSaveUserPrefs = function() {
	this.hideUserPrefsDialog();

	var prefs = {};
	var numFields = document.getElementById('m_' + this.id +
	      '_numfields').value;
	for (var i = 0; i < numFields; i++) {
		var input = document.getElementById('m_' + this.id + '_' + i);
	    var userPrefNamePrefix = 'm_' + this.id + '_up_';
	    var userPrefName = input.name.substring(userPrefNamePrefix.length);
	    var userPrefValue = input.value;
	    prefs[userPrefName] = userPrefValue;	    
	}
	
	this.setUserPrefs(prefs);
	this.refresh();
};

gadgets.BartGadget.prototype.handleOpenOptionsMenu = function() {
	if (dojo.hasClass(this.getOptionsMenuButtonId(), "gadgets-gadget-title-settings-button-active") ||
		!this.menuVisible) return;

    dojo.addClass(this.getOptionsMenuButtonId(), "gadgets-gadget-title-settings-button-active");
    
    var menu = dojo.doc.createElement("div");
    dojo.attr(menu, "id", this.getOptionsMenuButtonId() + "_menu");
    dojo.addClass(menu, "gadgets-gadget-title-settings-button-menu");
    menu.innerHTML =  
    	(this.userPrefsConfig && this.userPrefsConfig.length > 0 ? '<a href="#" class="menu_item menu_item_first" onclick="gadgets.container.getGadget('+ this.id +').handleOpenUserPrefsDialog();return false;">Instellingen bewerken</a>' : '') +  
    	(this.closable ? '<a href="#" class="menu_item" onclick="gadgets.container.getGadget('+ this.id +').handleClose();return false;">Deze widget verwijderen</a>' : '') + 
    	(this.menuIgoogle ? '<a href="#" class="menu_item" onclick="gadgets.container.getGadget('+ this.id +').handleAddToIGoogle();return false;" target="_blank">Deze widget op iGoogle plaatsen</a>' : '') +
    	(this.menuWebsite ? '<a href="#" class="menu_item" onclick="gadgets.container.getGadget('+ this.id +').handleAddToWebsite();return false;">Deze widget op je website plaatsen</a>' : '');

    var overlay = dojo.doc.createElement("div");
    dojo.style(overlay, {
        position: "absolute",
        height : dojo.style("gadget-chrome-"+this.id, "height") + "px",
        width : dojo.style("gadget-chrome-"+this.id, "width") + "px",
        zIndex : 1000,       
        display : "block"
    });

    dojo.addClass(overlay, "gadgetOverlay");
    dojo.place(overlay, "gadget-chrome-"+this.id, "before");
    dojo.body().appendChild(menu);

    var coords 	= dojo.coords(this.getOptionsMenuButtonId(), true);
    var box 	= dojo.coords(menu); 

    dojo.style(menu, {        
    	left : (coords.x + coords.w - box.w - 2) + "px"/*based on width of image in css class*/,
        top : (coords.y + coords.h + 2) + "px",
        display : "block",
        zIndex : 1001        
    });
    
    var self=this;
    setTimeout(function() {
        var h = dojo.connect(document, "onclick", self, function(evt) {
        	dojo.query(".gadgetOverlay").orphan();
        	if(menu.parentNode) {        		            
            	menu.parentNode.removeChild(menu);            	
            }	        	
        	var n = document.getElementById(this.getOptionsMenuButtonId());
        	if(n) {
        		dojo.removeClass(n, "gadgets-gadget-title-settings-button-active");
        	}
            dojo.disconnect(h);
        })
    }, 100); /*FIXME: cleaner way to miss the current onclick event? */
};

gadgets.BartGadget.prototype.handleClose = function() {
	if (confirm("Weet u zeker dat u " + this.title + ' wilt verwijderen?')) {
		gadgets.container.removeGadget(this);
	}		
};

gadgets.BartGadget.prototype.handleAddToIGoogle = function() {
	window.location = 'http://www.google.com/ig/adde?synd=open&source=ggyp&moduleurl=' + escape(this.specUrl);
};

gadgets.BartGadget.prototype.handleAddToWebsite = function() {
	alert('Deze functionaliteit is nog niet geimplementeerd.');
};

gadgets.BartGadget.prototype.buildUserPrefsDialog = function(content) {
	var userPrefsDialog = document.getElementById(this.getUserPrefsDialogId());
	userPrefsDialog.innerHTML = content +
    	'<div class="' + this.cssClassGadgetUserPrefsDialogActionBar +
    	'"><input type="button" value="Opslaan" onclick="gadgets.container.getGadget(' +
    	this.id +').handleSaveUserPrefs()"> <input type="button" value="Annuleren" onclick="gadgets.container.getGadget(' +
    	this.id +').handleCancelUserPrefs()"></div>';
	userPrefsDialog.childNodes[0].style.display = '';
};

gadgets.BartGadget.prototype.getTitleBarContent = function(continuation) {
    var showOptionsMenuButton = this.menuVisible && ((this.userPrefsConfig && this.userPrefsConfig.length > 0) || this.closable || this.menuIgoogle || this.menuWebsite);

	continuation(
        '<div id="' + this.cssClassTitleBar + '-' + this.id + '" class="' + this.cssClassTitleBar + '">' +
            '<span class="' + this.cssClassTitleButtonBar + '">' +
                '<a id="'+ this.getToggleButtonId() +'" href="#" onclick="gadgets.container.getGadget('+ this.id +').handleToggle();return false;" class="' + this.cssClassTitleToggleButton + '"></a>' +
                '<span id="' + this.getIframeId() + '_title" class="' + this.cssClassTitle + '">' + (this.title || '') + '</span>' +
				(showOptionsMenuButton ? '<a id="'+ this.getOptionsMenuButtonId() +'" href="#" onclick="gadgets.container.getGadget('+ this.id +').handleOpenOptionsMenu();return false;" class="' + this.cssClassTitleSettingsButton + '"></a>' : '') +
                '<a href="#" id="' + this.getIframeId() + '_mover_icon" class="gadgets-gadget-title-mover"></a>' +
                '<br>' +
            '</span>' +
            '<div style="clear:both"></div>'+
        '</div>'
    );
};

gadgets.BartGadget.prototype.makeMoveable = function() {
	var chrome = document.getElementById(this.getId());
	
	if(chrome) {	
		dojo.addClass(chrome, "gadgets-gadget-moveable");	
					
		var m = new dojo.dnd.Moveable(chrome, {mover:gadgets.BartMover, handle: this.cssClassTitleBar + '-' + this.id });
		
	    //For IE - when a node is moved from a column, the underlying iframe changes size
	    //so we need to track and it and reapply when the node becomes position:absolute
	    var widthInColumn;
	
	    //for determining if a drag actually started (vs something like a click on a button)
	    var didMove = false;
	
	    dojo.connect(m, "onMoveStart", function(mover){ 
	        dojo.style(mover.node, "zIndex", 1000);
	
	        didMove = false;
	
	        //for every drag operation, create an overlay for each iframe
	        //to prevent the iframe from intercepting mouse events
	        //which kills drag performance
	        dojo.query(".gadgets-gadget-content").forEach(function(fc) {
	            var overlay = dojo.doc.createElement("div");
	            dojo.style(overlay, {
	                position: "absolute",
	                height : dojo.style(fc, "height") + "px",
	                width : dojo.style(fc, "width") + "px"
	            });
	
	            dojo.addClass(overlay, "dndOverlay");
	            dojo.place(overlay, fc, "first");
	
	            widthInColumn = dojo.style(fc.parentNode, "width");
	        });
	
	        //console.log("onMoveStart");
	    }); 
	
	    var placeholder = dojo.doc.createElement("div");
	    dojo.addClass(placeholder, "gadgets-gadget-placeholder");
	    var isMoving = false;
	
	    //Leave a placeholder in for the element that's being drug around
	    //once it's actually on the move
	    dojo.connect(m, "onMoved", function(mover, leftTop) {
	        didMove = true;
	        if (isMoving) return;
	        isMoving = true;
	
	        dojo.style(placeholder, "height", dojo.style(mover.node, "height")- 4 + "px"/*border*/);
	        dojo.place(placeholder, m.node, "before");
	
	        //console.log("onMoved");
	    });
	
	    var lastY;
	    dojo.connect(m, "onMoving", function(mover, leftTop) {
	
	        //there's a "false start" b/c of the nature of a node
	        //transitioning to absolute positioning, so skip out the first time.
	        //and apply the widthInColumn that was tracked from onMoveStart
	        if (!isMoving) {
	            lastY = leftTop.t;
	            dojo.style(mover.node, "width", widthInColumn + "px");
	
	            //also take this opportunity to style the overlay...
	            dojo.query(".dndOverlay", mover.node).style({
	                opacity : 0.5,
	                background : "white"
	            });
	
	            return;
	        }
	
	        //maintain if nodes are moving up or down
	        var dy = lastY - leftTop.t;
	        lastY = leftTop.t;
	
	        var coords = dojo.coords(mover.node);
	
	        //calculate center of what's being moved and use it as the
	        //basis of whether or not to juggle the nodes
	        var cx = coords.l + coords.w/2;
	        var cy = coords.t + coords.h/2;
	
	        //determine if the center is overlapping with any .gadgets-gadget-chrome nodes
	        //via bounding rect intersection 
	        var targets = dojo.query(".gadgets-gadget-moveable")
	        .filter (function(x) {
	            return x != mover.node;
	        })
	        .filter(function(x) {
	            var coords = dojo.coords(x);
	
	            return (coords.x < cx && 
	                coords.x+coords.w > cx &&
	                coords.y < cy && 
	                coords.y+coords.h > cy);
	        });
	
	        //if not over any targets, then see if we're below a column
	        if (!targets.length) {
	        	var col;
	        	var colcount = dojo.query(".column").length;
	        	for(var j=0; j<colcount; j++) {
	        		var coords = dojo.coords("col"+j);
	                if (coords.l < cx && coords.l + coords.w > cx) {
	                	col = j;
	                	break;
	                }		
	                //the column may be empty
	                else if (!dojo.query(".gadgets-gadget-moveable", "col"+j).length && cx > coords.l) {
	                    col = j;
	                }
	            }
	        	
	        	if (col != undefined) {
	        		var coords = dojo.coords("col"+col); 
	        		if(cy > coords.t+coords.h) {
	        			dojo.place(placeholder, "col"+col, "last");
	        		}	
	            }	    		
	        } else {
	        	dojo.place(placeholder, targets[0], dy <= 0 ? "after" : "before");
	        }	
	    });
	
	    dojo.connect(m, "onMoveStop", function(mover){ 
	
	        dojo.style(m.node, {
	            "zIndex" :  1,
	            "width" : "auto"     
	        });
	
	        isMoving = false;
	        dojo.query(".dndOverlay").orphan();
	
	        //if no move occurred (like if someone clicked on a button, for example)
	        //then stop short.
	        if (!didMove) return; 
	
	        //insert the node back where the placeholder is at
	        //and reset style so next drag is consistent with this one
	        dojo.place(mover.node, placeholder, "after");
	        dojo.style(mover.node, {
	            position : "static",
	            top : "",
	            left : "" 
	        });
	        placeholder.parentNode.removeChild(placeholder);
	
	        //If columns were variable width, could adjust width of moved item for
	        //new column here.
	        
	        //Save position if current gadget
	        if(gadgets.container.stateStore) {
	        	gadgets.container.stateStore.onMove();
	        }	
	        
	        //console.log("onMoveStop", mover.node);
	    });
	} 
};

gadgets.BartLayoutManager = function() {
	gadgets.LayoutManager.call(this);
};
gadgets.BartLayoutManager.inherits(gadgets.LayoutManager);
gadgets.BartLayoutManager.prototype.getGadgetChrome = function(gadget) {
	var chromeId = 'gadget-chrome-' + gadget.id;
    return chromeId ? document.getElementById(chromeId) : null;
};

gadgets.BartContainer = function() {
  gadgets.IfrContainer.call(this);
};
gadgets.BartContainer.inherits(gadgets.IfrContainer);

gadgets.BartContainer.prototype.gadgetService = new gadgets.BartGadgetService();
gadgets.BartContainer.prototype.gadgetClass = gadgets.BartGadget;
gadgets.BartContainer.prototype.removeGadget = function(gadget) {
	var chrome = document.getElementById(gadget.getId());
	chrome.parentNode.removeChild(chrome);
	delete this.gadgets_[this.getGadgetKey_(gadget.id)];
	
	if(this.stateStore) {
		this.stateStore.onRemove(gadget);
	}	
};
gadgets.BartContainer._getSmallestColumn = function(limit) {
	var col = null;
	dojo.query(".column").forEach(function(c, index) {
		if(index < limit) {
			if(col == null || (dojo.query(".gadgets-gadget-chrome", c).length < dojo.query(".gadgets-gadget-chrome", col).length)) {
				col = c;
			}
		}	
	});	
	return col;
};

gadgets.BartContainer.prototype.getColumns = function() {
  return dojo.query(".column").length;
};
gadgets.BartContainer.prototype.gadgetsInColumns = function(columns) {
	for(var i=0; i<columns.length; i++) {
		var tmp = dojo.byId("col" + columns[i]);
		if(dojo.query(".gadgets-gadget-chrome", tmp).length > 0) {
			return true;
		}
	}
	
	return false;
};
gadgets.BartContainer.prototype.setColumns = function(columns) {
	if(columns > 0) {
		var colcount = dojo.query(".column").length;
		if(colcount > columns) {
			var lastcol = dojo.byId("col" + (columns-1));
			dojo.addClass(lastcol, "last");
			
			var moved = false;
  			for(var i=columns; i<colcount; i++) {
  				var tmp = dojo.byId("col" + i);
  				dojo.query(".gadgets-gadget-chrome", tmp).forEach(function(chrome) {
  					var col = gadgets.BartContainer._getSmallestColumn(columns);
  					col.appendChild(chrome);
  					moved = true;
  				});
  				
  				dojo.byId('gadgets').removeChild(tmp);
  			}
  			
  			if(moved && gadgets.container.stateStore) {
  				gadgets.container.stateStore.onMove();  		        	
  			}
		} else if(colcount < columns) {
			var lastcol = dojo.byId("col" + (colcount-1));
			dojo.removeClass(lastcol, "last");
			
			for(var i=colcount; i<columns; i++) {
				var col = dojo.doc.createElement("div");
				dojo.attr(col, "id", "col" + i);
				dojo.addClass(col, "column");
				
				if(i == columns-1) {
					dojo.addClass(col, "last");
				}
				
				var iexist = dojo.doc.createElement("div");
				dojo.addClass(iexist, "iexist");
				iexist.innerHTML = '<br/>';
				col.appendChild(iexist);
						
				dojo.byId('gadgets').appendChild(col);
			}
		}
		
		if(colcount != columns) {
			dojo.cookie('gadget_container_cols', columns, {expires: 10*365});
		}
	}
};
/**
 *
 */
gadgets.Container.prototype.getCurrentGadgetInstanceId = function() {
	return this.nextGadgetInstanceId_;
};
//override line 802 of gadgets.js
gadgets.container = new gadgets.BartContainer();
gadgets.container.layoutManager = new gadgets.BartLayoutManager();
