MediaWiki:Common.js

From Aging Chart
Revision as of 21:27, 8 December 2015 by JM (Talk | contribs)

Jump to: navigation, search

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Clear the cache in Tools → Preferences
/* Any JavaScript here will be loaded for all users on every page load. */
var searchWikipedia = function(site, search, element, opts) {
  /*
    site: site host
    search: search term
    element: element to add new links
    opts: additional options
  */
  // remove   from search term
  search = search.replace(" ", "");
  //console.log ("Search term: '" + search.replace(" ", "") + "' ");

	// wikipedia url
	var wikipediaUrl = 'http://en.wikipedia.org';

	// search in wikipedia
	var queryUrlWiki = 'http://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + encodeURIComponent(search) + '&srlimit=' + (opts.maxResults || 1) + '&format=json&rawcontinue=true';
	console.log(queryUrlWiki);

	// wikipedia search
	var promise = $.ajax(queryUrlWiki + '&callback=?', {
		dataType: 'jsonp',
		cache: true,
	});
  return promise;
}

//------------------------------------------------------

var searchTitles = function(site, search, element, opts, id) {
  /*
    site: site host
    search: search term
    element: element to add new links
    opts: additional options
  */
  // remove   from search term
  search = search.replace(" ", "");
  //console.log ("Search term: '" + search.replace(" ", "") + "' ");

	// url for future links
	var linkUrl = (opts.ssl ? 'https' : 'http') + '://' + site;
	// url for API requests
	var siteUrl = (opts.ssl ? 'https' : 'http') + '://' + site + '/aging-chart';
	var apiUrl = siteUrl + (opts.apiBase || '/') + 'api.php';

	// search in titles
	var queryUrlTitle = apiUrl + '?action=query&list=search&srsearch=' + encodeURIComponent(search) + '&srlimit=' + (opts.maxResults || 1) + '&srwhat=title&format=json';
  console.log(queryUrlTitle);

	// search in titles
	var promise = $.ajax(queryUrlTitle + '&callback=?', {
		dataType: 'jsonp',
		// This prevents warnings about the unrecognized parameter "_"
		cache: true,
	});
  return promise;
}

//--------------------------------------------------------------------

var searchText = function(site, search, element, opts, id) {
  /*
    site: site host
    search: search term
    element: element to add new links
    opts: additional options
  */
  // remove   from search term
  search = search.replace(" ", "");
  //console.log ("Search term: '" + search.replace(" ", "") + "' ");

	// url for future links
	var linkUrl = (opts.ssl ? 'https' : 'http') + '://' + site;
	// url for API requests
	var siteUrl = (opts.ssl ? 'https' : 'http') + '://' + site + '/aging-chart';
	var apiUrl = siteUrl + (opts.apiBase || '/') + 'api.php';

	// search in text
	var queryUrlText = apiUrl + '?action=query&list=search&srsearch=' + encodeURIComponent(search) + '&srlimit=' + (opts.maxResults || 1) + '&srwhat=text&format=json';
  console.log(queryUrlText);

  // search in text
	var promise = $.ajax(queryUrlText + '&callback=?', {
		dataType: 'jsonp',
		// This prevents warnings about the unrecognized parameter "_"
		cache: true,
	});
  return promise;
}


//--------------------------------------------------------------------

var processLinks = function(dataWikipedia, dataTitles, dataText) {
  //console.log(dataWikipedia);
  //console.log(dataTitles);
  //console.log(dataText);
  var links = {},
      linksWikipedia = {};
  var content = "";

  // process dataTitles
  for (var i = 0; i < dataTitles[0].query.search.length; i++) {
    var title = dataTitles[0].query.search[i].title,
        link = 'http://www.agingchart.org/wiki/' + encodeURIComponent(title.replace('/', '\/'));
        links[title] = link;
  }
  // process dataText
  for (var i = 0; i < dataText[0].query.search.length; i++) {
    var title = dataText[0].query.search[i].title,
        link = 'http://www.agingchart.org/wiki/' + encodeURIComponent(title.replace('/', '\/'));
        links[title] = link;
  }

  // process dataWikipedia
  for (var i = 0; i < dataWikipedia[0].query.search.length; i++) {
    var title = dataWikipedia[0].query.search[i].title,
        link = 'http://en.wikipedia.org/wiki/' + encodeURIComponent(title.replace('/', '\/'));
    linksWikipedia[title] = link;
  }

  // form links
  content += '<h3>See also</h3>';
  console.log(links);
  // simple counter to check if we have any links to add
  var counter = 0;
  if (!$.isEmptyObject(links)) {
    //content += $('<div>').attr('class', 'popup-search-results');
    //content += '<h3>See also</h3>';
    var documentUrl = document.URL;
    for (link in links) {
      if (links[link].valueOf() != documentUrl.valueOf() &&
          links[link].valueOf() != documentUrl.valueOf().replace(/_/g, "%20") &&
          links[link].valueOf() != documentUrl.substring(0, documentUrl.indexOf('#')).valueOf()) {
        //var htmlLink = $('<a>').text(link).attr('href', links[link]);
        var htmlLink = buildHTML('a', link, {href: links[link]});
        content += htmlLink + '<br />';
        counter++;
        console.log("we increase counter");
      }
    }
  }
  if (counter === 0) {
    content += '<p>No Matches</p>';
  }
  //content += $('</div>');

  counter = 0;
  // form wikipedia links
  content += '<h4>Wikipedia:</h4>';
  if (!$.isEmptyObject(linksWikipedia)) {
    //content += $('<div>').attr('class', 'popup-search-results');
    //content += '<h4>Wikipedia:</h4>';
    var documentUrl = document.URL;
    for (link in linksWikipedia) {
      if (linksWikipedia[link].valueOf() != documentUrl.valueOf() &&
          linksWikipedia[link].valueOf() != documentUrl.valueOf().replace(/_/g, "%20") &&
          linksWikipedia[link].valueOf() != documentUrl.substring(0, documentUrl.indexOf('#')).valueOf()) {
        //var htmlLink = $('<a>').text(link).attr('href', linksWikipedia[link]);
        var htmlLink = buildHTML('a', link, {href: linksWikipedia[link]});
        content += htmlLink + '<br />';
        counter++;
      }
    }
  }
  if (counter === 0) {
    content += '<p>No Matches</p>';
  }
  console.log(content);
  return content;
}

var buildHTML = function(tag, html, attrs) {
  // you can skip html param
  if (typeof(html) != 'string') {
    attrs = html;
    html = null;
  }
  var h = '<' + tag;
  for (attr in attrs) {
    if(attrs[attr] === false) continue;
    h += ' ' + attr + '="' + attrs[attr] + '"';
  }
  return h += html ? ">" + html + "</" + tag + ">" : "/>";
}

$(document).ready(function(e) {
	// get diagram width
	var desired_width = $("img[usemap]").width();
	// get current content block width
	var current_width = $("#content").width();

	// all text should has screen width
	if (!$("body").hasClass("action-edit")) {
		$(".mw-body p").css("width", current_width);
	}

	// add custom attr for screen size
	$('#content').attr("defaultwidth", current_width);

	// fit diagram into content block
	if (desired_width > current_width)
		$('#content').css("width", desired_width + "px");


	$('area').each(function() {
		// prevent any default actions
		$(this).click(function(ev) {
			ev.preventDefault();
			ev.stopPropagation();
		});
    // get node title for search
		//var tmp2 = $('.' + $(this).attr('id') + ' h3').html();
		// get
    //var element = '.' + $(this).attr('id') + ' .links';

		$(this).qtip({
			content: {
				text: function foo(event, api) {
          var area_id = $(this).attr('id');
          var content = $('.' + area_id).html();
          content += '<div class="loader"></div>';
          console.log(content);
          var host = 'www.agingchart.org';
          var searchTerm = $('.' + $(this).attr('id') + ' h3').html();
          var links = '.' + $(this).attr('id') + ' .links';
          api.set('content.text', content);
          var one = searchWikipedia(host,
            searchTerm,
            links,
            {
              ssl: false,
              maxResults: 10
            }
          );

          var two = searchTitles(host,
            searchTerm,
            links,
            {
              ssl: false,
              maxResults: 10
            }
          );

          var three = searchText(host,
            searchTerm,
            links,
            {
              ssl: false,
              maxResults: 10
            }
          );

          $.when(one, two, three).then(function (data1, data2, data3) {
              //content = $('.' + area_id).html();
              content = processLinks(data1, data2, data3);
              $('.' + area_id + ' .links').append(content);
              content = $('.' + area_id).html();
              api.set('content.text', content);
          });
          /* promise.done(function(content) {
            var content = $('.' + area_id).html();
            // update content when links loaded
            api.set('content.text', content);
          });*/
          return content;
				},
				title: "Information",
				button: true
			},
			show: 'click',
			hide: {
				event: false
			},
			style: {
				classes: 'qtip-light qtip-shadow'
			},
      position: {
        my: "top left",
        at: "bottom right",
        adjust: {
            method: 'flipinvert'
        },
        viewport: $(window),
      }
		})
	});

});


/* TEST */

$(document).ready(function() {
	// add search form
	if ($("area").length > 0) {
		console.log("Search on page was added");
		$("#firstHeading").after('<form id="search_on_page" action=""><input type="text" style="margin-right: 10px;width:300px;" name="search" id="search_on_page_term" placeholder="Search term"><input type="submit" value="Search"></form>');

		// add submit listener
		$("#search_on_page").submit(function(e) {
			console.log("Submitted");
			e.preventDefault();
			var results = searchInAreas($("#search_on_page_term").val());
			// remove results if it exists
			if ($(".page_search_results").length)
				$(".page_search_results").remove();
			$("#search_on_page").after(results);
		});

		// add search results click listener
		$('body').on('click', 'p.page_search_results_p', function() {
			console.log("Click on <p>");
			console.log($(this).attr("area_id"));
			scr($(this).attr("area_id"));
		});

		/*$("p.page_search_results").click(function(e){
		console.log("Click on <p>");
		console.log($(this).attr("area_id"));
		scr($(this).attr("area_id"));
		});*/
	}

});

var searchInAreas = function(searchTerm) {
	var results = '<div class="page_search_results" style="font-size: 14px;">';
	var i = 1;
	$("area").each(function() {
		var title = $(this).attr("oldtitle");
		var clearTitle = replaceNewline(title);
		if (clearTitle.toLowerCase().search(searchTerm.toLowerCase()) !== -1) {
			results += '<p class="page_search_results_p" style="cursor: pointer; display: inline-block;margin-top: 10px;margin-bottom:0;" area_id="' + this.id + '">' + i + " " + clearTitle + '</p><br />';
			i++;
		}
	});
	results += '</div>';
	return results;
};

var replaceNewline = function(str) {
	return str.replace(/(\\r\\n|\\n|\\r)/g, "");
};

var scr = function(id) {
	console.log(id);
	var element = $("area#" + id);
	var type = element.attr("shape");
	var coords = element.attr("coords");

	if (type == "rect") {
		// example: (3744,3043,3926,3074)
		var x = (coord(coords, 1) + coord(coords, 3)) / 2;
		var y = (coord(coords, 2) + coord(coords, 4)) / 2;
	} else if (type == "circle") {
		var x = coord(coords, 1);
		var y = coord(coords, 2);
	} else if (type == "poly") {
		// a little math :)
		// example: (972,771,574,771,471,896,869,896)
		var coords_arr = coords.split(",");
		var sumX = 0;
		var sumY = 0;
		for (var i = 0; i < coords_arr.length; i++) {
			if (i % 2 === 0)
				sumX += Number(coords_arr[i]);
			else
				sumY += Number(coords_arr[i]);
		}
		var x = sumX / (coords_arr.length / 2);
		var y = sumY / (coords_arr.length / 2);
	} else {
		var x = coord(coords, 1);
		var y = coord(coords, 2);
	}
	console.log("Coords:" + x + ", " + y);
	var height = window.innerHeight;
	var width = window.innerWidth;
	var toScrollX = (x - window.innerWidth / 2 + $("#mw-content-text").offset().left);
	var toScrollY = y - window.innerHeight / 2 + $("#mw-content-text").offset().top;
	console.log("Coords to scroll:" + (toScrollX > 0 ? toScrollX : 0) + ", " + (toScrollY > 0 ? toScrollY : 0));
	window.scrollTo(toScrollX > 0 ? toScrollX : 0, toScrollY > 0 ? toScrollY : 0);
}

var coord = function(coords, position) {
	var arr = coords.split(",");
	//console.log("Element:" + arr[position-1]);
	return Number(arr[position - 1]);
}

/* TEST 2 */
var setRealSize = function() {
	var img = $("#mw-content-text img")[0];
	// get real size
	var theImage = new Image();
	theImage.src = $(img).attr("src");
	$(img).attr("realWidth", theImage.width);
	$(img).attr("realHeight", theImage.height);
	//console.log("Real size: " + realWidth + "    " + realHeight);

}
var resize_aging_chart = function(coef) {
	console.log("Coef: " + coef);
	var img = $("#mw-content-text img")[0];

	var cur_width = $(img).width();
	var cur_height = $(img).height();
	console.log("Current size: " + cur_width + "    " + cur_height);

	var imageWidth = $(img).attr("realWidth");
	var imageHeight = $(img).attr("realHeight");
	console.log("Image size: " + imageWidth + "    " + imageHeight);

	var wantedWidth = imageWidth * coef;
	var wantedHeight = imageHeight * coef;
	console.log("Wanted size: " + wantedWidth + "    " + wantedHeight);

	// set width of image
	//var screenWidth = window.innerWidth;
	$(img).width(wantedWidth);

	coefX = wantedWidth / cur_width;
	coefY = wantedHeight / cur_height;
	console.log("Coef:" + coefX);
	$("area").each(function() {
		// var type = $(this).attr("shape");
		var coords = $(this).attr("coords");
		var coords_str = coords.split(',');
		var coords_num = Array();
		//console.log(coords_arr);
		for (var i = 0; i < coords_str.length; i++) {
			if (i % 2) {
				coords_num[i] = Math.round(Number(coords_str[i]) * coefX);
			} else
				coords_num[i] = Math.round(Number(coords_str[i]) * coefY);
		}
		console.log("Was " + coords_str);
		console.log("Now " + coords_num.join());
		$(this).attr("coords", coords_num.join());
	});
}

$(document).ready(function() {
	if ($("area").length > 0) {
		$("#search_on_page").after('<form style="font-size: 14px; border: 1px solid #D3D3D3;display:inline-block;vertical-align:middle;padding: 5px; margin-top:5px;"><span style="display:inline-block;"> Zoom - </span><input style="display:inline-block;vertical-align:middle;" type="range" id="scale_aging_chart" value="1" step="0.05" min="0.1" max="2"><span style="display:inline-block;vertical-align:middle;"> + </span> <span id="scale_aging_chart_value" style="display:inline-block;vertical-align:middle;"></span></form>');

		setRealSize();

		$('#scale_aging_chart').change(function() {
      //$("#scale_aging_chart_value").html($(this).val());
      resize_aging_chart($(this).val());
      var desired_width = $("img[usemap]").width();
      console.log("Desired width: " + desired_width);
      var default_width = $("#content").attr("defaultwidth");
      console.log("Default width: " + default_width);
      //$(".mw-body p").css("width", current_width);
      if (desired_width > default_width )
        $('#content').css("width", desired_width + "px");
      else
        $('#content').css("width", default_width + "px");
		});
	}
});

// simple test for custom editor
$(document).ready(function() {
	if ($("textarea#Box0").length != 0) {
		var graphContent = $("textarea#Box0").val();
		//if(graphContent.indexOf("<graphviz renderer='neato'>") < 0) {
		if($("#pop-ups option").length < 1) {
			TRADITIONAL();	
		}
	}
	else {
	}
});