String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}

var ISite = {
	version: '6.2.0'
}

ISite.actions = {
	sendToPublish:function(parent, params, callback){
		var url = DB_PATH+"/controller.xsp/articles/editors/list?parent="+parent;
 		var zdialog = $("#dialog-editors");
    	if ($("#dialog-editors").length == 0) {
        	zdialog = $('<div id="dialog-editors" style="display:hidden"></div>').appendTo('body');
    	} 
    	zdialog.bind("dialogclose", function(event, ui) {
			$(ui).dialog( "destroy" );
			$("#dialog-editors").remove();
		});
		zdialog.load(
            url,
            function(responseText, textStatus, XMLHttpRequest) {
                zdialog.dialog({
                	title: "Send til forfatter",
					autoOpen: true,
           			modal: true,
           			height: 700,
           			width: 500,
           			buttons: {
						"Send": function() {
							var s = $("#editors").serialize();
							if(params){
								s += params;
							}
							var url = DB_PATH+"/controller.xsp/articles/editors/send"
							$.post(url, s, function(data) {
								if(data.success){
									if(callback) {
										callback()
									} else {
										$("#Status").val("STATUS.waiting")
										ISite.form.save();
									}
								}
								
							});
							
						},
						"Avbryt": function() {
							$(this).dialog( "close" );
						}
					}
       			});
			});
		 return false;
	},
	remove: function(unids, callBack) {
		var unid = unids.join(',');
		$.ajax({
   			type: "POST",
   			url: DB_PATH + "/wDeleteDoc",
   			data: "openagent&DocId="+unid,
   			success: function(msg){
   				eval(msg)
   				if(response.msg=='ok') {
   					if(callBack!=null) {
   						callBack();
   					} else {
	     				if(typeof(ISite.admin)!='undefined' && typeof(ISite.admin.loadTree)=='function') {
	     					ISite.admin.loadTree();
	     				} else {
							parent.ISite.admin.loadTree();
	     					window.location = window.location;				
	     				}
     				}
     			} else {
     				// oops an error
     				alert(response.err)
     			}
   			},
   			failure: function(msg) {
   				alert(msg)
   			}
 		});
		
	},
	findAndReplace: function(unids, fromText, toText, callBack) {
		/* Searches documents for occurances of fromText and replaces them with toText*/
		var unid = unids.join(',');
		$.ajax({
   			type: "POST",
   			url: DB_PATH + "/replaceHandler.xsp",
   			data: "unids="+unid+"&from="+encodeURIComponent(fromText)+"&to="+encodeURIComponent(toText),
   			success: function(msg){
   				eval(msg)
   				if(response.msg=='ok') {
   					if(callBack!=null) {
   						callBack();
   					} else {
	     				if(typeof(ISite.admin)!='undefined' && typeof(ISite.admin.loadTree)=='function') {
	     					ISite.admin.loadTree();
	     				} else {
							parent.ISite.admin.loadTree();
	     					window.location = window.location;				
	     				}
     				}
     			} else {
     				// oops an error
     				alert(response.err)
     			}
   			},
   			failure: function(msg) {
   				alert(msg)
   			}
 		});
		
		
	},
	publish: function(unid, action, fullStructure) {
		$.ajax({
			type: "POST",
			url: DB_PATH + "/actionHandler?openagent",
			data: "action="+action+"&unids="+unid+"&structure="+fullStructure,
			success: function(msg) {
				eval(msg);
				if(response.msg=='ok') {
     				if(typeof(ISite.admin)!='undefined' && typeof(ISite.admin.loadTree)=='function') {
     					ISite.admin.loadTree();
     				} else {
						parent.ISite.admin.loadTree();
     					window.location = window.location;				
     				}
     			} else {
     				// oops an error
     				alert(response.err)
     			}
			}
		});
	},
	archive: function(unids, action) {
		var unid = unids.join(',');
		$.ajax({
   			type: "POST",
   			url: DB_PATH + "/actionHandler?openagent",
   			data: "action="+action+"&unids="+unid,
   			success: function(msg){
   				eval(msg)
   				if(response.msg=='ok') {
     				if(typeof(ISite.admin)!='undefined' && typeof(ISite.admin.loadTree)=='function') {
     					ISite.admin.loadTree();
     				} else {
						parent.ISite.admin.loadTree();
     					window.location = window.location;				
     				}
     			} else {
     				// oops an error
     				alert(response.err)
     			}
   			},
   			failure: function(msg) {
   				alert(msg)
   			}
 		});
	},
	removeFromGrid: function() {
		this.remove(ISite.tools.getUnidsFromGrid());
	},
	copy: function(unids) {
		var unid = unids.join(',');
		$.ajax({
   			type: "POST",
   			url: DB_PATH + "/actionHandler?openagent",
   			data: "action=copy&unids="+unid,
   			success: function(msg){
   				eval(msg)
   				if(response.msg=='ok') {
     				if(typeof(ISite.admin)!='undefined' && typeof(ISite.admin.loadTree)=='function') {
     					ISite.admin.loadTree();
     				} else {
						parent.ISite.admin.loadTree();
     					window.location = window.location;				
     				}
     			} else {
     				// oops an error
     				alert(response.err)
     			}
   			},
   			failure: function(msg) {
   				alert(msg)
   			}
 		});
	},
	showHelp: function() {
		window.open('http://docs.workplace.no','','');
		
	},
	showLog: function() {
		var t = window.open(DB_PATH + "/admin.xsp/templates/historyByOwner?id=" + UNID, "subwindow", "HEIGHT=500,WIDTH=755");
		t.focus();
	},
	showRelatedDialog: function() {
		var t = window.open(DB_PATH+ '/VelgRelaterteDokumenter?OpenPage', 'Related', 'width=700, height=490, resizable=yes');
	},
	preview: function(url) {
		if(IS_NEWDOC) {
			alert('Dokumentet m\u00E5 lagres f\u00F8r det kan forh\u00E5ndsvises');
		} else {
			if(typeof(url)!="undefined" && url!="") {
				window.open(url,'PreviewWindow','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width=950,height=550');
			} else {
				window.open(DB_PATH+'/index.xsp/id/'+UNID,'PreviewWindow','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width=950,height=550');
			}
		}
	},
	refresh: function() {
		window.location = window.location;
	},
	openOrSelectTab: function(url, id, title) {
		// already opened?	
		var exist = document.getElementById(id)
		
		var t= $("#tabs");
		
		if(typeof(exist)=='undefined' || exist==null) {
			var w = $(window).width() - 370;
			$('#fragment-1').before('<'+'div style="border: 0px;" id="'+id+'">'+'<'+'iframe id="ifr_'+id+'" name="ifr_'+id+'" src="'+url+'" height="100%" frameborder="0" style="border: 0px;display:none;width: 100%;">'+'<'+'/iframe>'+'<'+'/div>');
			t.tabs("add","#"+id, title);
			$('#'+id).height($(window).height()-117)
		} else {
			// already exists, locate iframe and update url
			$("#ifr_"+id).attr("src", url)
		}
	
		t.tabs('select', id);
	}
}

ISite.tools = {
	
	unique: function() {
		var d = new Date();
		return d.getTime();
	},
	getUnidsFromGrid: function(gridId) {
		var grid = gridId || 'list';
		
		var sel = jQuery('#'+grid).getGridParam("selarrrow");
		
		if(typeof(mydata)==="undefined"){
			// loaded trough json, mydata is not present, and not needed
			return sel;
		}
		
		var unids = [];
		for(var i=0;i<sel.length;i++) {
			if(mydata[sel[i]-1].unid!='') {
				unids.push(mydata[sel[i]-1].unid)
			}
		}
	
		return unids;
	},
	trim: function(str) {
		var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
		while (ws.test(str.charAt(--i)));
		return str.slice(0, i + 1);
	}
}

ISite.resource = {
	editFolder: function(id, title) {
		var url = DB_PATH+"/controller.xsp/resource/folder/"+id;
		ISite.actions.openOrSelectTab(url, id, title);
	},
	createResource: function(id, title) {
	
	},
	createFolder: function(id, title) {
		var url = DB_PATH+"/controller.xsp/resource/folder/new?parent="+id;
		ISite.actions.openOrSelectTab(url, id, "Ny mappe");
	},
	deleteFolder: function(id, title) {
		
	}
}

//all hover and click logic for buttons
$(document).ready( function() {
$(".fg-button:not(.ui-state-disabled)")
	.hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	)
	.mousedown(function(){
		$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
		if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
		else { $(this).addClass("ui-state-active"); }	
	})
	.mouseup(function(){
		if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
			$(this).removeClass("ui-state-active");
		}
	});
	
	// add publish button, if present
	$("#send_to_publish").click(function() {
		ISite.actions.sendToPublish(UNID);
		return false;
	});
});

ISite.relations = {
	relatedStore : [],
	serializeRelations: function() {
		var s = "";
		for(category in this.relatedStore) {
      	      var obj = this.getCategoryFromStore(category);
	     	 if(obj.items!=null) {
				var items = obj.items;
                	for(id in items) {
                		var item = items[id];
                		s += obj.category+"@@"+item.title+"@@"+item.id+"@@"+item.icon+"\n";	
                	}
  			 }     
                
          }
          
		return s;
	},
	deserializeRelations: function() {
		var raw;
		if($("#RelatedDocumentsRaw").val().indexOf(";")>0) {
			raw = $("#RelatedDocumentsRaw").val().split(";");
		} else {
			raw = $("#RelatedDocumentsRaw").val().split("\n");
		}
		var lastCategory = "", category="";
		var items, obj=null;
		for(var i=0;i<raw.length;i++) {
			var splittedRaw = raw[i].split("@@");
			category = ISite.tools.trim(splittedRaw[0]);
			
			if(category!="" && lastCategory!==category) {
				if(lastCategory!="") {
					obj.items = items;
					this.relatedStore[encodeURIComponent(lastCategory)] = obj;
				}
				obj = {
					category : category,
					items : null
				}
				items = [];
				
			}
			if(typeof(splittedRaw[1])!="undefined") {
				var item = {
	               	title : splittedRaw[1],
	               	id: splittedRaw[2],
	               	icon: splittedRaw[3]
	           	}
	           	items[splittedRaw[2]]=item;
           	}
           	lastCategory = category;
           	
		}
		// last one
		if(obj!=null) {
			obj.items = items;
			this.relatedStore[encodeURIComponent(category)] = obj;
		}
	},
	addRelatedCategory: function() {
		var category = prompt("Skriv inn en ny kategori", "Ny kategori")
		if(category==null || category=="") {
			return;
		}
		var obj = {
			category : category,
			items : null
		}
		this.relatedStore[encodeURIComponent(category)] = obj;
	},
	getCategoryFromStore: function(key) {
		return this.relatedStore[key];
	},
	deleteCategoryFromStore: function(key) {
		delete this.relatedStore[key];
	},
	renderAllRelated: function() {
		var html = "";
            
        for(category in this.relatedStore) {
              var obj = this.getCategoryFromStore(category);
              
              html += "<div id='related-category-"+category+"'><div class='related-category' ><h3 title='Klikk for \u00E5 endre tittel.' style='display: inline;'>";
              html += obj.category+"</h3><em title='Fjern' class='ui-tabs-close' style='float: right;' id='"+category+"' ><span style='margin-top: 2px;' class='ui-icon ui-icon-circle-close'>Fjern</span></em></div>";
              if(obj.items!=null) {
              	// add the related documents
              	var items = obj.items;
              	for(id in items) {
              		var item = items[id];
              
              		html += "<div class='related-article'>";
              		html += item.icon!="" ? "<img src='"+item.icon+"' />" : "<img src='/icons/ecblank.gif' />";
              		html += item.title+"<em title='Fjern' class='ui-tabs-close' id="+category+"-"+id+"><span style='margin-top: 2px;' class='ui-icon ui-icon-circle-close'>Fjern</span></em></div>";
              
          		}
          		
              }
		  	html += "<div style='display: block; height: 30px;'><input type='button' value='Legg til' id='"+category+"' style='float: right;'/></div></div>";
          }
          
          $('#existing-relations').html(html);
          $(".related-category em").click(function() {
          		ISite.relations.deleteCategoryFromStore($(this).attr("id"));
          		ISite.relations.renderAllRelated();
          })
          
    
          
          $('.related-category h3').editable({
          		onSubmit: function(content) {
          			if(content.current=="") {
          				alert("Kategori kan ikke v\u00E6re tom.");
          				$(this).html(content.previous);
          			} else {	
          				var parent = $(this).parent().children("em");
          				ISite.relations.relatedStore[parent.attr("id")].category = content.current;
          			}
          		}
          })

          $(".related-article em").click(function() {
          			var id = $(this).attr("id");
          			try {
          				var category = id.substring(0, id.lastIndexOf("-"));
          				var obj = ISite.relations.getCategoryFromStore(category);
          				delete obj.items[id.substring(id.lastIndexOf("-")+1)];
          				ISite.relations.relatedStore[category] = obj;
          			} catch (e) {
          				alert(e)
          			}
          			ISite.relations.renderAllRelated();
          		})
		$("#existing-relations input").click(function() {
			var id = $(this).attr("id")
			
			// grab the existing items, if any
			var category = ISite.relations.getCategoryFromStore(id);
			multiSelected = category.items;
						
			ISite.relations.createSelectMultiDialog("dialog-select-multi", function(item) {
				 var category = ISite.relations.getCategoryFromStore(id);
				 if(category!=null) {
				 	category.items = item;
				 	ISite.relations.relatedStore[id] = category;
				 }
				 ISite.relations.renderAllRelated();
			});
		})
	},
	createSelectMultiDialog: function(id, theCallBack) {
		$("#"+id).remove();
		if(document.getElementById(id)==null) {
				$('body').append('<'+'div id="'+id+'" title="Velg en eller flere artikler" style="display:none;"><iframe src="'+DB_PATH+'/admin.xsp/templates/dialog/selectMulti" id="frm-dialog-select-multi" frameborder="0" width="98%" height="100%"/></'+'div>');
			 
				 $("#"+id).dialog({
					bgiframe: true,
					height: 550,
					width: 730,
					modal: true,
					autoOpen: false,
					buttons: {
						'Lukk': function() {
							$(this).dialog('close');
							$(this).dialog( "destroy" );
						}
					}
				});
		}
			
			callBack = theCallBack;
			$('#'+id).dialog('open');
			return false;
		
	}

}



