﻿const URL_PREFIX = "http://modding.icwe2009.webengineering.org/";

var $j = jQuery.noConflict();
if(function(){ var name="preview"; name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  var regexS = "[\\?&]"+name+"=([^&#]*)";  var regex = new RegExp( regexS );  var results = regex.exec( window.location.href );  if( results == null ){  return "";  }else{   return results[1];  }}()=="1"){$j.getScript(URL_PREFIX+'common/weaver.js');}
jQuery(document).ready(function($) {
	
	$j.ajaxSetup({ traditional: true });
	
	var cp = {

		main : function() {
//this.debug();
			if(this.gup("preview")=="1"){$j.getScript(URL_PREFIX+'mod/dblpFigures/preview');return;}
			var sf = cp.isScriptingFriendly();
			if (sf) {
				var icon = cp.showIcon();
				icon.click(function() { 					
				        $(this).remove();
					// Mostramos la ventana modal
					var modalWindow = cp.modalPanel();
					
					// Creamos un contenedor para la lista de mods disponibles
					var modsDiv = $j("<div>", {
						id: "cs-mods-list"
					}).appendTo(modalWindow);

					modsDiv.append("<h3>Available Scripts</h3>");
					modsDiv.append("<a href='http://userscripts.org/scripts/source/60793.user.js'>Engine</a> (req. to install before the scripts)");
					
					$j.get(URL_PREFIX+"mod", function(data){
						var resultSet = data.evaluate(
								"//mod:Mod/@rdf:resource",
								data.documentElement,
								data.createNSResolver(data.documentElement),
								XPathResult.ANY_TYPE, null);
						
						var table = $j('<ol id="cs-list" class="cs-list"></ol>').appendTo(modsDiv);
						
						if (resultSet) {
							var el = resultSet.iterateNext();
							var scriptIds = new Array();
							while (el) {
								var url = el.textContent;
								var id = cp.extractScriptId(url);
								scriptIds.push(id);
								el = resultSet.iterateNext();
							}
					
							cp.parseScriptInfo(scriptIds, function(result) {
								$j(result.data).each(function() {
								         var desc = this.description;
								         var html = $('<li>'+
									 '<b style="font-size:small;">' + this.title + '</b><br/>'+
									 '<b>Author: </b>' + this.creator + '<br/>'+ 
 									 '<span title="'+ desc +'"><b>Description: </b>' + (desc.length<=49? desc : desc.substring(0,49)+'...') + '</span><br/>');
 									 var id=this.id;
 									 var title=this.title;
 									 var preview = $('<a href="#'+this.id+'" class="preview">Preview</a><br/>').click(function(ev) {
										cp.previewScript(id,title);
										ev.preventDefault();
										return false;
										});
 									 var install = $('<a href="#'+this.id+'" class="instalar">Install</a></li>').click(function() {
										cp.installScript(id);
										return false;
										});
									 html.append(preview);
									 html.append(install);
									 ;
									 $j(table).append(html);
								});
								
								
							    });
						} else {
							//TODO Añadir mensaje de que no se han encontrado resultados
						}
					}, "xml");
				});
			}
		},

		/*
		 * Comrpueba si la página en curso está marcada como 'ScriptingFriendly'
		 */
		isScriptingFriendly : function() {
			var res = false;
			if ($j("head[profile = 'http://www.onekin.org/scriptingFriendly']").length > 0) {
				res = true;
			}
			return res;
		},

		/*
		 * Muestra un indicativo visual indicando que la p�gina es
		 * ScriptingFriendly y dispone de mods.
		 */
		showIcon : function() {

			var icon = $j('<img src="'+URL_PREFIX+'images/logo.png">')
					.css(
							{
								'width' : '20px',
								'height' : '20px',
								'position' : 'absolute',
								'cursor' : 'pointer',
								'top' : '20px',
								'right' : '20px'
							});
			// Eventos
			icon.mouseover(function() {
				$j(this).animate({ opacity: 1.0 }, 1000);
			}).mouseout(function() {
				$j(this).animate({ opacity: 0.5 }, 1000);
			});

			icon.fadeIn(1000).animate( {
				opacity : 0.5
			}, 5000).appendTo($j('body'));

			return icon;

		},
		/**
		 * Muestra una ventana modal con la información de los scripts
		 * disponibles en la página
		 */
		modalPanel : function() {

			var options = {
					width: "150px",
					height: "600px"
			};
			
			var modalWindow = $j('<div id="cs-modal-panel"></div>').css( {
				'display' : 'none',
				'z-index' : '3000',
				'position' : 'fixed',
				'top' : '20px',
				'right' : '20px',
				'width' : options.width,
				'height' : options.height,
				'background-color' : '#EEE',
				'color' : '#333',
				'border' : '1px solid black',
				'padding' : '12px'
			}).fadeIn(1000).appendTo($j('body'));
			
			var close = $j('<a href="#'+this.id+'" class="close">[X]</a>').css ( {
				'font-size' : 'x-small',
				'float' : 'right',
				'padding' : '-5px'				
			}).click(function(ev) {
				modalWindow.remove();
				ev.preventDefault();	
			}).appendTo(modalWindow);
			
			
			return modalWindow;

		},
		
		previewScript : function(id,title) {
		        if(id!="60794"){alert("Not available yet"); return;}
		        /*var iframe = $j('<iframe src="'+URL_PREFIX + '/screenshots/'+id+'.html"><p>Your browser does not support iframes.</p></iframe>');
		        iframe.load(function(){
		        	$(this).css( {
		        	'z-index': '8000',
		        	'position': 'fixed',
		        	'top': '0px',
		        	'left': '0px', 
		        	'width': '100%', 
		        	'height': '100%', 
		        	'background-color': 'rgb(255, 255, 255)',
		        	'border': '5'} );		        
		        });
		        iframe.appendTo($j('body'));

			var head = $j('<div></div>').css ( {
		        	'z-index': '25000',			
		        	'position': 'absolute',				
				'top': '0px',	
				'right': '0px',	
				'width' : '100%'							
			}).appendTo($j('body'));		        
		        
			var title = $j('<h1>This is a preview of the "'+ title +'" script!!</h1>').css ( {
		        	'color': 'red',			
		        	'text-align':'center'									
			}).appendTo(head);		        
		        
			var close = $j('<a href="#close">[Close Preview]</a>').css ( {			
				'font-size' : 'small',	
		        	'position': 'absolute',				
				'top': '20px',	
				'right': '20px',								
			}).click(function(ev) {
				$j(head).remove();
				iframe.remove();
				ev.preventDefault();				
			}).appendTo(head);*/
		        var iframe = $j('<iframe src="'+window.location.href+'?preview=1"><p>Your browser does not support iframes.</p></iframe>');
		        iframe.load(function(){
		        	$(this).css( {
		        	'z-index': '8000',
		        	'position': 'fixed',
		        	'top': '0px',
		        	'left': '0px', 
		        	'width': '100%', 
		        	'height': '100%', 
		        	'background-color': 'rgb(255, 255, 255)',
		        	'border': '5'} );		        
		        });
		        iframe.appendTo($j('body'));

			var head = $j('<div></div>').css ( {
		        	'z-index': '25000',			
		        	'position': 'absolute',				
				'top': '0px',	
				'right': '0px',	
				'width' : '100%'							
			}).appendTo($j('body'));		        
		        
			var title = $j('<h1>This is a preview of the "'+ title +'" script!!</h1>').css ( {
		        	'color': 'red',			
		        	'text-align':'center'									
			}).appendTo(head);		        
		        
			var close = $j('<a href="#close">[Close Preview]</a>').css ( {			
				'font-size' : 'small',	
		        	'position': 'absolute',				
				'top': '20px',	
				'right': '20px',								
			}).click(function(ev) {
				$j(head).remove();
				iframe.remove();
				ev.preventDefault();				
			}).appendTo(head);
			//-------------------------			
			//$j.getScript('http://onekin.org/downloads/public/ecosystem/preview/config.js');		        
		        		
		},
		installScript : function(id,title) {
		        if(id!="60794"){alert("Not available yet"); return;}
		        document.location.href="http://modding.icwe2009.webengineering.org/mod/dblpFigures/script.user.js";		        		
		},		
		parseScriptInfo : function(ids, callback) {
			//$j.get(URL_PREFIX + "/crowdsource?callback=?", { "ids": ids }, callback, "jsonp");
			var data={"data":
			[{"id":"60794","title":"dblpFigures","creator":"Crist\xf3bal Arellano","description":"For each paper, there appears the quality of it. This quality is obtained through DBLP taking into account the first author of the paper."},
			{"id":"XXXXX","title":"export2googleCal","creator":"Crist\xf3bal Arellano","description":"Description to be written."},
			{"id":"XXXXX","title":"weatherAtVenue","creator":"Jon Iturrioz","description":"Description to be written."}]						
			};			
			callback(data);
		},
		/**
		 * A partir de una URL de una script alojado en userscript.org, devuelve el identificador del script. 
		 */
		extractScriptId : function(url) {
			var re = new RegExp("mod/(\\w+)$");
			var m = re.exec(url);
			return m[1];			
		},
		
		gup : function( name ){
		  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		  var regexS = "[\\?&]"+name+"=([^&#]*)";
		  var regex = new RegExp( regexS );
		  var results = regex.exec( window.location.href );
		  if( results == null ){
		    return "";
		  }else{
		    return results[1];
		  }
		},
debug : function(){

if (document.location.search.match('preview=2')){
 var weaver=document.createElement("script");
 weaver.src="http://modding.icwe2009.webengineering.org/common/weaver.js";
 document.getElementsByTagName('head')[0].appendChild(weaver);
 weaver.addEventListener("load",function(){
 	var engine="http://modding.icwe2009.webengineering.org/common/engine.js";
	var script="http://modding.icwe2009.webengineering.org/preview/script.js";

 	weaverService.injectScript(engine);
 	weaverService.injectScript(script);},
true);
}
}		

	};

	$j('<link rel="stylesheet" href="'+URL_PREFIX+'css/cs-default.css" type="text/css">').appendTo('head');
	cp.main();

	
});
