Commit d59468fc413d7cab3249bef4854d28fb1dda344a

  • avatar
  • arvind
  • Fri Apr 26 20:27:22 IST 2013
Making API changes
			 - /askSWeeT will ask for a SWeeT with a provided id
			 - Publish will SWeeT, no more posting to blogspot
server/alipi.py
(136 / 103)
  
1#-*-coding: utf-8 -*-
2from flask import Flask, request, render_template, g, redirect, jsonify, make_response
1from flask import Flask
2from flask import request
3from flask import render_template
4from flask import make_response
5import lxml.html
6import pymongo
37from bson import Code
4from urllib import quote_plus, unquote_plus
5from lxml.html import html5parser
6import urllib2, StringIO, lxml.html, pymongo, conf, oursql
8import urllib2
9import StringIO
10from flask import g
11from flask import redirect
12from urllib import quote_plus
13from urllib import unquote_plus
14import conf
15import oursql
16import requests
17
18from flask import jsonify
719app = Flask(__name__)
820@app.before_request
921def first():
3232 try:
3333 a = urllib2.urlopen(myhandler1)
3434 if a.geturl() != d['foruri']:
35 return "There was a server redirect, please click on the <a href='http://dev.a11y.in/web?foruri={0}'>link</a> to continue.".format(quote_plus(a.geturl()))
35 return "There was a server redirect, please click on the <a href='http://y.a11y.in/web?foruri={0}'>link</a> to continue.".format(quote_plus(a.geturl()))
3636 else:
3737 page = a.read()
3838 a.close()
3939 except ValueError:
40 return "The link is malformed, click <a href='http://dev.a11y.in/web?foruri={0}&lang={1}&interactive=1'>here</a> to be redirected.".format(quote_plus(unquote_plus(d['foruri'].encode('utf-8'))),request.args['lang'])
40 return "The link is malformed, click <a href='http://y.a11y.in/web?foruri={0}&lang={1}&interactive=1'>here</a> to be redirected.".format(quote_plus(unquote_plus(d['foruri'].encode('utf-8'))),request.args['lang'])
4141 except urllib2.URLError:
4242 return render_template('error.html')
4343 try:
4848 g.root = lxml.html.parse(StringIO.StringIO(page)).getroot()
4949 except ValueError:
5050 g.root = lxml.html.parse(d['foruri']).getroot() #Sometimes creators of the page lie about the encoding, thus leading to this execption. http://lxml.de/parsing.html#python-unicode-strings
51 if request.args.has_key('lang') == False and request.args.has_key('blog') == False and request.args.has_key('tags') == False:
51 if request.args.has_key('lang') == False and request.args.has_key('blog') == False:
5252 g.root.make_links_absolute(d['foruri'], resolve_base_href = True)
5353 for i in g.root.iterlinks():
5454 if i[1] == 'href' and i[0].tag != 'link':
5656 i[0].attrib['href'] = 'http://{0}?foruri={1}'.format(conf.DEPLOYURL[0],quote_plus(i[0].attrib['href']))
5757 except KeyError:
5858 i[0].attrib['href'] = '{0}?foruri={1}'.format(conf.DEPLOYURL[0],quote_plus(i[0].attrib['href'].encode('utf-8')))
59 setScripts()
59 setScripts()
6060 g.root.body.set("onload","a11ypi.loadOverlay();")
6161 return lxml.html.tostring(g.root)
6262
63 elif (request.args.has_key('lang') == True or request.args.has_key('tags') == True) and request.args.has_key('interactive') == True and request.args.has_key('blog') == False:
63 elif request.args.has_key('lang') == True and request.args.has_key('interactive') == True and request.args.has_key('blog') == False:
6464 setScripts()
65 if request.args['interactive'] == '1':
66 setSocialScript()
67 g.root.body.set("onload","a11ypi.ren();a11ypi.tweet(); a11ypi.facebook(); a11ypi.loadOverlay();")
68 else:
69 g.root.body.set("onload","a11ypi.ren();")
65 setSocialScript()
66 g.root.body.set("onload","a11ypi.ren();a11ypi.tweet(); a11ypi.facebook(); a11ypi.loadOverlay();")
7067 g.root.make_links_absolute(d['foruri'], resolve_base_href = True)
7168 return lxml.html.tostring(g.root)
72
69
7370 elif request.args.has_key('lang') == True and request.args.has_key('blog') == False:
7471 script_jq_mini = g.root.makeelement('script')
7572 g.root.body.append(script_jq_mini)
76 script_jq_mini.set("src", conf.JQUERYURL[0] + "/jquery-1.7.min.js")
73 script_jq_mini.set("src", conf.JQUERYURL[0] + "/jquery.min.js")
7774 script_jq_mini.set("type", "text/javascript")
7875 d['lang'] = request.args['lang']
7976 script_test = g.root.makeelement('script')
8787 g.root.make_links_absolute(d['foruri'], resolve_base_href = True)
8888 return lxml.html.tostring(g.root)
8989
90 elif request.args.has_key('interactive') == False and request.args.has_key('blog') == True:
90 elif request.args.has_key('interactive') == False and request.args.has_key('blog') == True:
9191 setScripts()
9292 g.root.make_links_absolute(d['foruri'], resolve_base_href = True)
9393 g.root.body.set('onload', 'a11ypi.loadOverlay();')
107107 script_config.set("src", conf.APPURL[0] + "/server/config.js")
108108 script_config.set("type", "text/javascript")
109109
110
110
111111 script_jq_mini = g.root.makeelement('script')
112112 g.root.body.append(script_jq_mini)
113 script_jq_mini.set("src", conf.JQUERYURL[0] + "/jquery-1.7.min.js")
113 script_jq_mini.set("src", conf.JQUERYURL[0] + "/jquery.min.js")
114114 script_jq_mini.set("type", "text/javascript")
115
115
116116 style = g.root.makeelement('link')
117117 g.root.body.append(style)
118118 style.set("rel","stylesheet")
129129 style_cust.set("type", "text/css")
130130 style_cust.set("href", conf.JQUERYCSS[0] + "/jquery-ui.css")
131131 g.root.body.append(style_cust)
132
132
133133def setSocialScript():
134134 info_button = g.root.makeelement('button')
135135 g.root.body.append(info_button)
138138 info_button.set("onClick", "a11ypi.showInfo(a11ypi.responseJSON);")
139139 info_button.text = "Info"
140140 info_button.set("title", "Have a look at the information of each renarrated element")
141
141
142142 share_button = g.root.makeelement('button')
143143 g.root.body.append(share_button)
144144 share_button.set("id", "share")
146146 share_button.set("onClick", "a11ypi.share();")
147147 share_button.text = "Share"
148148 share_button.set("title", "Share your contribution in your social network")
149
149
150150 see_orig = g.root.makeelement('button')
151151 g.root.body.append(see_orig)
152152 see_orig.set("id", "orig-button")
154154 see_orig.set("onClick", "a11ypi.showOriginal();")
155155 see_orig.text = "Original Page"
156156 see_orig.set("title", "Go to Original link, the original page of this renarrated")
157
157
158158 tweetroot = g.root.makeelement("div")
159159 tweetroot.set("id", "tweet-root")
160160 tweetroot.set("class", "alipi")
167167 tweet.set("class", "alipi twitter-share-button")
168168 tweet.set("data-via", "a11ypi")
169169 tweet.set("data-lang", "en")
170 tweet.set("data-url", "http://dev.a11y.in/web?foruri={0}&lang={1}&interactive=1".format(quote_plus(request.args['foruri']),request.args['lang']))
170 tweet.set("data-url", "http://y.a11y.in/web?foruri={0}&lang={1}&interactive=1".format(quote_plus(request.args['foruri']),(request.args['lang']).encode('unicode-escape')))
171171 tweet.textContent = "Tweet"
172172 tweetroot.append(tweet)
173173
175175 fblike.set("id", "fb-like")
176176 fblike.set("class", "alipi fb-like")
177177 fblike.set("style", "display:none;padding:10px;")
178 fblike.set("data-href", "http://dev.a11y.in/web?foruri={0}&lang={1}&interactive=1".format(quote_plus(request.args['foruri']),request.args['lang']))
178 fblike.set("data-href", "http://y.a11y.in/web?foruri={0}&lang={1}&interactive=1".format(quote_plus(request.args['foruri']),(request.args['lang']).encode('unicode-escape')))
179179 fblike.set("data-send", "true")
180180 fblike.set("data-layout", "button_count")
181181 fblike.set("data-width", "50")
182182 fblike.set("data-show-faces", "true")
183183 fblike.set("data-font", "arial")
184184 g.root.body.append(fblike)
185
185
186186 style = g.root.makeelement('link')
187187 g.root.body.append(style)
188188 style.set("rel","stylesheet")
189189 style.set("type", "text/css")
190 style.set("href", "http://dev.a11y.in/server/stylesheet.css")
190 style.set("href", "http://y.a11y.in/alipi/stylesheet.css")
191191
192
192
193193@app.route('/directory')
194194def show_directory():
195195 collection = g.db['post']
245245 response = jsonify(d)
246246 response.headers['Access-Control-Allow-Origin'] = '*'
247247 return response
248
249
248250@app.route("/replace", methods=['GET'])
249251def replace():
250252 collection = g.db['post']
251 url = request.args['url']
252253 lang = request.args['lang']
253 if request.args['type'] == 'renarration':
254 query = collection.group(
255 key = Code('function(doc){return {"xpath" : doc.xpath, "about": doc.url}}'),
256 condition={"about" : url, "lang" : lang,"elementtype":"text","type":"renarration"},
257 initial={'narration': []},
258 reduce=Code('function(doc,out){out.narration.push(doc);}')
259 )
260
261 audio_query =collection.group(
262 key = Code('function(doc){return {"xpath" : doc.xpath, "about": doc.url}}'),
263 condition={"about" : url, "lang" : lang, 'elementtype':"audio/ogg","type":"renarration"},
264 initial={'narration': []},
265 reduce=Code('function(doc,out){out.narration.push(doc);}')
266 )
254 url = request.args['url']
255 query = collection.group(
256 key = Code('function(doc){return {"xpath" : doc.xpath, "about": doc.url}}'),
257 condition={"about" : url, "lang" : lang,"elementtype":"text"},
258 initial={'narration': []},
259 reduce=Code('function(doc,out){out.narration.push(doc);}')
260 )
267261
268 image_query =collection.group(
269 key = Code('function(doc){return {"xpath" : doc.xpath, "about": doc.url}}'),
270 condition={"about" : url, "lang" : lang, 'elementtype':"image", "type":"renarration"},
271 initial={'narration': []},
272 reduce=Code('function(doc,out){out.narration.push(doc);}')
273 )
274 try:
275 for i in audio_query:
276 query.append(i)
277 except IndexError:
278 pass
279 try:
280 for i in image_query:
281 query.append(i)
282 except IndexError:
283 pass
262 print query
284263
285 elif request.args['type'] == '5el':
286 query = []
287 query = collection.group(
288 key = Code('function(doc){return {"xpath" : doc.xpath, "about": doc.url}}'),
289 condition={"about" : url, "lang" : lang,"type":"5el"},
290 initial={'narration': []},
291 reduce=Code('function(doc,out){out.narration.push(doc);}')
292 )
264 audio_query =collection.group(
265 key = Code('function(doc){return {"xpath" : doc.xpath, "about": doc.url}}'),
266 condition={"about" : url, "lang" : lang, 'elementtype':"audio/ogg"},
267 initial={'narration': []},
268 reduce=Code('function(doc,out){out.narration.push(doc);}')
269 )
270
271 image_query =collection.group(
272 key = Code('function(doc){return {"xpath" : doc.xpath, "about": doc.url}}'),
273 condition={"about" : url, "lang" : lang, 'elementtype':"image"},
274 initial={'narration': []},
275 reduce=Code('function(doc,out){out.narration.push(doc);}')
276 )
277 try:
278 for i in audio_query:
279 query.append(i)
280 except IndexError:
281 pass
282 try:
283 for i in image_query:
284 query.append(i)
285 except IndexError:
286 pass
287
293288 for i in query:
294289 for y in i['narration']:
295290 del(y['_id'])
312312 response.headers['Access-Control-Allow-Origin'] = '*'
313313 return response
314314
315@app.route('/feeds/write', methods=['POST'])
316def save_feed():
317 coll = g.db['feed']
315@app.route('/about', methods=['GET'])
316def serve_authors():
317 coll = g.db['post']
318318 d = {}
319 d['about'] = request.form['about']
320 d['blog'] = request.form['blog']
321 d['bxpath'] = request.form['bxpath']
322 d['xpath'] = request.form['xpath']
323 d['author'] = request.form['author']
324 d['type'] = request.form['type']
325 d['lang'] = request.form['lang']
326 d['location'] = request.form['location']
327 coll.insert(d)
328 if d['type'] == '5el':
329 collection = g.db['post']
330 root = html5parser.parse(d['blog']).getroot()
331 tree = root.getroottree()
332 if tree.docinfo.doctype == '':
333 lxml.html.xhtml_to_html(root)
334 d['data'] = lxml.html.tostring(root.xpath(d['bxpath'])[0]) #TODO implement a function like lxml.html.make_links_absolute
335 collection.insert(d)
336 response = make_response()
337 response.data = repr(request.form['blog'])
319 cntr = 0
320 for i in coll.find({"about":unquote_plus(request.args['about'])}):
321 i['_id'] = str(i['_id'])
322 d[cntr] = i
323 cntr+=1
324 response = jsonify(d)
338325 response.headers['Access-Control-Allow-Origin'] = '*'
339326 return response
327#Retrieve all information about a specific $about and a given $author.
328@app.route('/author', methods=['GET'])
329def serve_author():
330 coll = g.db['post']
331 d = {}
332 cntr = 0
333 for i in coll.find({"about":unquote_plus(request.args['about']),"author":unquote_plus(request.args['author'])}):
334 i['_id'] = str(i['_id'])
335 d[cntr] = i
336 cntr += 1
337 response = jsonify(d)
338 response.headers['Access-Control-Allow-Origin'] = '*'
339 return response
340340
341@app.route('/getAllLang', methods=['GET'])
342def get_lang():
343 term = request.args['term']
344 connection = oursql.Connection(conf.DBHOST[0],conf.DBUSRNAME[0],conf.DBPASSWD[0],db=conf.DBNAME[0])
345 cursor = connection.cursor(oursql.DictCursor)
346 cursor.execute('select * from `languages` as l where l.name like ?', (term+'%',))
347 r = cursor.fetchall()
348 connection.close()
349 d = {}
350 d['return'] = r
351 response = jsonify(d)
352 response.headers['Access-Control-Allow-Origin'] = '*'
353 return response
354
355
356@app.route("/askSWeeT",methods=['POST'])
357def askSweet():
358 id = request.form['id']
359 response = requests.api.get(conf.SWEETURL[0]"/query/"+id)
360 collection = g.db['post']
361 if response.status_code == 200:
362 collection.insert(response.json)
363 reply = make_response()
364 return reply
365
341366@app.route("/menu",methods=['GET'])
342367def menuForDialog():
343368 if request.args.has_key('option') == False:
386386 initial={'lang': []},
387387 reduce=Code('function(doc, out){if (out.lang.indexOf(doc.lang) == -1) out.lang.push(doc.lang)}') #here xpath for test
388388 )
389
389
390390 #send the response
391391 if (langForUrl):
392392 connection.disconnect()
393393 return json.dumps(langForUrl[0]['lang'])
394
395394 else:
396395 connection.disconnect()
397396 return "empty"
398397
399@app.route("/demo",methods=['GET'])
400def doDemo():
401 root = lxml.html.parse(request.args['foruri']).getroot()
402 root2 = html5parser.parse(request.args['blog']).getroot()
403 tree2 = root2.getroottree()
404 if tree2.docinfo.doctype == '':
405 lxml.html.xhtml_to_html(root2)
406 root.make_links_absolute(request.args['foruri'], resolve_base_href = True)
407 root.xpath(request.args['xpath'])[0].addnext(root2.xpath(request.args['bxpath'])[0])
408 return lxml.html.tostring(root)
398
399@app.route('/info', methods=['GET'])
400def serve_info():
401 coll = g.db['post']
402 d = {}
403 cntr = 0
404 for i in coll.find({"about":unquote_plus(request.args['about']),"lang":request.args['lang']}):
405 i['_id'] = str(i['_id'])
406 d[cntr] = i
407 cntr+=1
408 response = jsonify(d)
409 response.headers['Access-Control-Allow-Origin'] = '*'
410 return response
411
412
409413import logging,os
410414from logging import FileHandler
411415
server/ui.js
(789 / 782)
  
11//-*-coding: utf-8 -*-
22var a11ypi = {
3 auth : " ",
4 loc:" ",
5 elementTagName: " ",
6 elementId: " ",
7 flag : 0,
8 fflag : 0,
9 showbox : 0,
10 showlinks : 0,
11 blog_flag: false,
12 target : false,
13 pageHtml:'',
14 d: {},
15 responseJSON:'',
16 testContext : function()
17 {
18 if(document.getElementById('social_overlay') != null)
3 auth : " ",
4 loc:" ",
5 elementTagName: " ",
6 elementId: " ",
7 flag : 0,
8 fflag : 0,
9 showbox : 0,
10 showlinks : 0,
11 blog_flag: false,
12 target : false,
13 pageHtml:'',
14 d: {},
15 responseJSON:'',
16 testContext : function()
17 {
18 if(document.getElementById('social_overlay') != null)
1919 document.body.removeChild(document.getElementById('social_overlay'));
20 $(document).ready(function(){$('body *').contents().filter(function()
21 {
22 try{
23 if(this.nodeType == 3 && !($(this).hasClass('alipi')))
24 {
25 return (this.nodeType == 3) && this.nodeValue.match(/\S/);}}
26 catch(err)
27 {
28 }}).parent().attr('m4pageedittype','text')});
29
30 vimg = document.getElementsByTagName('img');
31 for(i=0; i<vimg.length; i++)
32 {
20 $(document).ready(function(){$('body *').contents().filter(function()
21 {
22 try{
23 if(this.nodeType == 3 && !($(this).hasClass('alipi')))
24 {
25 return (this.nodeType == 3) && this.nodeValue.match(/\S/);}}
26 catch(err)
27 {
28 }}).parent().attr('m4pageedittype','text')});
29
30 vimg = document.getElementsByTagName('img');
31 for(i=0; i<vimg.length; i++)
32 {
3333 vimg[i].setAttribute('m4pageedittype','image');
34 }
35 },
34 }
35 },
3636
37 createMenu: function(type) {
38 var xyz = '';
39 if(type == 'renarration')
37 createMenu: function(type) {
38 var xyz = '';
39 if(type === '1.0')
4040 xyz = document.getElementById("show-box");
41 else
41 else
4242 xyz = document.getElementById("show-comment");
43 xyz.innerHTML = '';
44 a = a11ypi.getParams();
45 for(var i in a11ypi.showbox)
46 {
43 xyz.innerHTML = '';
44 a = a11ypi.getParams();
45 for(var i in a11ypi.showbox)
46 {
4747 if(a11ypi.showbox[i]['type'] == type)
4848 {
49 var para = document.createElement("p");
50 var newel = document.createElement("a");
51 newel.textContent = a11ypi.showbox[i]['lang'];
52 if(type == 'renarration')
53 $(newel).attr("href",config.deploy+"/?foruri="+a['foruri']+"&lang="+a11ypi.showbox[i]['lang']+"&interactive=1"+"&type="+type);
54 else
55 $(newel).attr("href",config.deploy+"/?foruri="+a['foruri']+"&tags="+a11ypi.showbox[i]['lang']+"&interactive=0"+"&type="+type);
56 para.appendChild(newel);
57 xyz.appendChild(para);
49 var para = document.createElement("p");
50 var newel = document.createElement("a");
51 newel.textContent = a11ypi.showbox[i]['lang'];
52 if(type === '1.0')
53 $(newel).attr("href",config.deploy+"/?foruri="+a['foruri']+"&lang="+a11ypi.showbox[i]['lang']+"&interactive=1"+"&type="+type);
54 else
55 $(newel).attr("href",config.deploy+"/?foruri="+a['foruri']+"&tags="+a11ypi.showbox[i]['lang']+"&interactive=0"+"&type="+type);
56 para.appendChild(newel);
57 xyz.appendChild(para);
5858 }
59 }
60 },
61
62 ajax: function() {
63 if(a11ypi.flag == '0')
64 {
59 }
60 },
61
62 ajax: function() {
63 if(a11ypi.flag == '0')
64 {
6565 a11ypi.flag = 1;
6666 a = a11ypi.getParams();
6767 $.getJSON(config.deploy+'/menu?', {"url":decodeURIComponent(a['foruri'])}, function(data)
68 {
69 a11ypi.showbox = data;
70 $('#see-narration').show();
71 $("#blog-filter").show(); a11ypi.blogFilter();
72 $("#go").show();
73 });
68 {
69 a11ypi.showbox = data;
70 $('#see-narration').show();
71 $("#blog-filter").show(); a11ypi.blogFilter();
72 $("#go").show();
73 });
7474
7575 req = {"about":decodeURIComponent(a['foruri']), "lang":a['lang']};
7676 $.getJSON(config.deploy+'/info?', req, function(data)
77 {
78 a11ypi.responseJSON = data;
79 });
80 }
81 },
82 ajax1: function() {
83 if(a11ypi.fflag == '0')
84 {
85 a11ypi.fflag = 1;
86 var xhr = new XMLHttpRequest();
87 xhr.onreadystatechange = function()
88 {
89 if(xhr.readyState == 4)
77 {
78 a11ypi.responseJSON = data;
79 });
80 }
81 },
82 ajax1: function() {
83 if(a11ypi.fflag == '0')
9084 {
91 if(xhr.responseText == "empty")
92 {
93// a11ypi.clearMenu();
94 }
95 else
96 {
97 a11ypi.createMenuFilter(JSON.parse(xhr.responseText));
98 }
85 a11ypi.fflag = 1;
86 var xhr = new XMLHttpRequest();
87 xhr.onreadystatechange = function()
88 {
89 if(xhr.readyState == 4)
90 {
91 if(xhr.responseText == "empty")
92 {
93 // a11ypi.clearMenu();
94 }
95 else
96 {
97 a11ypi.createMenuFilter(JSON.parse(xhr.responseText));
98 }
99 }
100 }
101 xhr.open("POST",config.root+"/menu",true);
102 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
103 a = a11ypi.getParams();
104 data = 'url='+a['foruri']+'&option='+a['blog'];
105 xhr.send(data) ;
99106 }
100 }
101 xhr.open("POST",config.root+"/menu",true);
102 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
103 a = a11ypi.getParams();
104 data = 'url='+a['foruri']+'&option='+a['blog'];
105 xhr.send(data) ;
106 }
107 },
108107
109 getURL: function(e) {
110 window.location = window.location.href + "&lang=" + e.value;
111 window.reload();
112 },
113 ren: function()
114 {
115 a = a11ypi.getParams();
116 var url = decodeURIComponent(a['foruri']);
117 var type = a['type'];
118 var lang = '';
119 if( type != 'renarration')
108 },
109
110 getURL: function(e) {
111 window.location = window.location.href + "&lang=" + e.value;
112 window.reload();
113 },
114 ren: function()
115 {
116 a = a11ypi.getParams();
117 var url = decodeURIComponent(a['foruri']);
118 var type;
119 if(a['type'])
120 type = a['type'];
121 else
122 type = '1.0'
123 var lang = '';
124
125 if( type != '1.0')
120126 lang = a['tags'];
121 else
127 else
122128 lang = a['lang'];
123129
124 $.getJSON(config.deploy+"/replace?",{"url":url,"lang":lang,"type":type},function(data)
125 {
126 for(var i=0;i<data['r'].length;i++)
127 {
128 for(var x in data['r'][i]['narration'])
129 {
130 // path = data['r'][i]['narration'][x]['xpath'];
131 // newContent = data['r'][i]['narration'][x]['data'];
132 // elementType = data['r'][i]['narration'][x]['elementtype'];
133 a11ypi.evaluate(data['r'][i]['narration'][x]);
134 }
135 }
136 });
137 },
138 evaluate: function(a)
139 {
140 try{
130 $.getJSON(config.deploy+"/replace?",{"url":url,"lang":lang,"type":type},function(data)
131 {
132 for(var i=0;i<data['r'].length;i++)
133 {
134 for(var x in data['r'][i]['narration'])
135 {
136 // path = data['r'][i]['narration'][x]['xpath'];
137 // newContent = data['r'][i]['narration'][x]['data'];
138 // elementType = data['r'][i]['narration'][x]['elementtype'];
139
140 a11ypi.evaluate(data['r'][i]['narration'][x]);
141 }
142 }
143 });
144 },
145 evaluate: function(a)
146 {
147 try{
141148 var nodes = document.evaluate(a['xpath'], document, null, XPathResult.ANY_TYPE,null);
142149
143 }
144 catch(e)
145 {
146 console.log(e);
147 }
148 if(a['type'] == 'renarrration')
149 {
150 try{
151 var result = nodes.iterateNext();
152 while (result)
150 }
151 catch(e)
153152 {
154 if (a['elementtype'] == 'image')
155 {
156 if(a['data'] != '')
157 {
158 result.setAttribute('src',a['data'].split(',')[1]); //A hack to display images properly, the size has been saved in the database.
159 width = a['data'].split(',')[0].split('x')[0];
160 height = a['data'].split(',')[0].split('x')[1];
161 result.setAttribute('width',width);
162 result.setAttribute('height', height);
163 result.setAttribute('class','blink');
164 }
165 else
166 $(result).hide();
167 }
168 else if(a['elementtype'] == 'audio/ogg')
169 {
170 a['data'] = decodeURIComponent(a['data']);
171 audio = '<audio controls="controls" src="'+a['data']+'" style="display:table;"></audio>';
172 $(result).before(audio);
173 result.setAttribute('class','blink');
174 }
175 else{
176 result.innerHTML = a['data'];
177 result.setAttribute('class','blink');
178 }
179 result=nodes.iterateNext();
153 console.log(e);
180154 }
181 }
182 catch (e)
183 {
184 // dump( 'error: Document tree modified during iteration ' + e );
185 }
186 }
187 else if(a['type']=='5el')
188 {
189
190 try{
191 var result = nodes.iterateNext();
192 while (result)
155 if(a['type'] == '1.0')
193156 {
194 $(result).html($(result).html()+a['data']);
195 $(result).get(0).scrollIntoView();
196 result=nodes.iterateNext();
157 try{
158 var result = nodes.iterateNext();
159 while (result)
160 {
161 if (a['elementtype'] == 'image')
162 {
163 if(a['data'] != '')
164 {
165 result.setAttribute('src',a['data'].split(',')[1]); //A hack to display images properly, the size has been saved in the database.
166 width = a['data'].split(',')[0].split('x')[0];
167 height = a['data'].split(',')[0].split('x')[1];
168 result.setAttribute('width',width);
169 result.setAttribute('height', height);
170 result.setAttribute('class','blink');
171 }
172 else
173 $(result).hide();
174 }
175 else if(a['elementtype'] == 'audio/ogg')
176 {
177 a['data'] = decodeURIComponent(a['data']);
178 audio = '<audio controls="controls" src="'+a['data']+'" style="display:table;"></audio>';
179 $(result).before(audio);
180 result.setAttribute('class','blink');
181 }
182 else{
183 result.innerHTML = a['data'];
184 result.setAttribute('class','blink');
185 }
186 result=nodes.iterateNext();
187 }
188 }
189 catch (e)
190 {
191 // dump( 'error: Document tree modified during iteration ' + e );
192 }
197193 }
194 else if(a['type']=='5el')
195 {
196
197 try{
198 var result = nodes.iterateNext();
199 while (result)
200 {
201 $(result).html($(result).html()+a['data']);
202 $(result).get(0).scrollIntoView();
203 result=nodes.iterateNext();
204 }
198205 }
199206 catch (e)
200 {
201 //dump( 'error: Document tree modified during iteration ' + e );
202 }
203 }
204 },
205 filter: function()
206 {
207 var xhr = new XMLHttpRequest();
208 xhr.onreadystatechange = function()
209 {
207 {
208 //dump( 'error: Document tree modified during iteration ' + e );
209 }
210 }
211 },
212 filter: function()
213 {
214 var xhr = new XMLHttpRequest();
215 xhr.onreadystatechange = function()
216 {
210217 if(xhr.readyState == 4)
211218 {
212 if(xhr.responseText =='empty')
213 {
214// a11ypi.clearMenu();
215// alert("An internal server error occured, please try later.");
219 if(xhr.responseText =='empty')
220 {
221 // a11ypi.clearMenu();
222 // alert("An internal server error occured, please try later.");
223 }
224 else
225 {
226
227 d ={};
228 var response=xhr.responseText.substring(3).split('###');
229 for (var j= 0; j< response.length ; j++){
230 chunk = response[j].substring(1).split('&');
231
232 for (var i= 0; i< chunk.length ; i++){
233 pair =chunk[i].split("::");
234 key = pair[0];
235 value = pair[1];
236 d[key] = value;
237 }
238 path = d['xpath'];
239 newContent = d['data'];
240 elementType = d['elementtype'];
241 a11ypi.evaluate(path,newContent,elementType);
242 }
243 }
244 }
216245 }
217 else
246 a = a11ypi.getParams();
247 var url = a['foruri'];
248 var lang= a['lang'];
249 var blog= a['blog'];
250 var data="url="+url+"&lang="+encodeURIComponent(lang)+"&blog="+encodeURIComponent(blog);
251
252 xhr.open("POST",config.root+"/filter",true);
253 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
254 xhr.send(data);//
255 },
256 createMenuFilter: function(menu_list) {
257 var xyz = document.getElementById("show-box");
258 xyz.innerHTML = '';
259 d = window.location.search.split('?')[1];
260 a = a11ypi.getParams();
261 var page = a['foruri'];
262 var blog = a['blog'];
263 for(var i=0;i<menu_list.length;i++)
218264 {
219
220 d ={};
221 var response=xhr.responseText.substring(3).split('###');
222 for (var j= 0; j< response.length ; j++){
223 chunk = response[j].substring(1).split('&');
224
225 for (var i= 0; i< chunk.length ; i++){
226 pair =chunk[i].split("::");
227 key = pair[0];
228 value = pair[1];
229 d[key] = value;
230 }
231 path = d['xpath'];
232 newContent = d['data'];
233 elementType = d['elementtype'];
234 a11ypi.evaluate(path,newContent,elementType);
235 }
236 }
237 }
238 }
239 a = a11ypi.getParams();
240 var url = a['foruri'];
241 var lang= a['lang'];
242 var blog= a['blog'];
243 var data="url="+url+"&lang="+encodeURIComponent(lang)+"&blog="+encodeURIComponent(blog);
244
245 xhr.open("POST",config.root+"/filter",true);
246 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
247 xhr.send(data);//
248 },
249 createMenuFilter: function(menu_list) {
250 var xyz = document.getElementById("show-box");
251 xyz.innerHTML = '';
252 d = window.location.search.split('?')[1];
253 a = a11ypi.getParams();
254 var page = a['foruri'];
255 var blog = a['blog'];
256 for(var i=0;i<menu_list.length;i++)
257 {
258265 var para = document.createElement("p");
259266 var newel = document.createElement("a");
260267 newel.textContent = menu_list[i];
261268 $(newel).attr("href",config.deploy+"/?foruri="+page+"&blog="+blog+"&lang="+menu_list[i]+"&interactive=1");
262269 para.appendChild(newel);
263270 xyz.appendChild(para);
264 }
265 },
266 clearMenuFilter: function() {
267 var xyz = document.getElementById("menu-button");
268 while(null!= xyz.firstChild)
269 {
271 }
272 },
273 clearMenuFilter: function() {
274 var xyz = document.getElementById("menu-button");
275 while(null!= xyz.firstChild)
276 {
270277 xyz.removeChild(xyz.firstChild);
271 }
272 },
273 getURLFilter: function(e) {
274 a= a11ypi.getParams();
275 window.location = config.deploy+"/?foruri="+a['foruri']+"&blog="+a['blog'] + "&lang=" + e.value+"&interactive=1";
276 window.reload();
277 },
278 showOriginal: function(){
279 var url=decodeURIComponent(window.location.search.split("=")[1].split("&")[0]);
280 window.open(url);
281 },
282 tweet:function(){
283 !function(d,s,id){
278 }
279 },
280 getURLFilter: function(e) {
281 a= a11ypi.getParams();
282 window.location = config.deploy+"/?foruri="+a['foruri']+"&blog="+a['blog'] + "&lang=" + e.value+"&interactive=1";
283 window.reload();
284 },
285 showOriginal: function(){
286 var url=decodeURIComponent(window.location.search.split("=")[1].split("&")[0]);
287 window.open(url);
288 },
289 tweet:function(){
290 !function(d,s,id){
284291 var js,fjs=d.getElementsByTagName(s)[0];
285292 if(!d.getElementById(id)){
286 js=d.createElement(s);
287 js.id=id;js.src="//platform.twitter.com/widgets.js";
288 fjs.parentNode.insertBefore(js,fjs);
293 js=d.createElement(s);
294 js.id=id;js.src="//platform.twitter.com/widgets.js";
295 fjs.parentNode.insertBefore(js,fjs);
289296 }
290 }
291 (document,"script","twitter-wjs");
292 },
293 facebook: function() {
294 (function(d, s, id) {
297 }
298 (document,"script","twitter-wjs");
299 },
300 facebook: function() {
301 (function(d, s, id) {
295302 var js, fjs = d.getElementsByTagName(s)[0];
296303 if (d.getElementById(id)) return;
297304 js = d.createElement(s); js.id = id;
298305 js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
299306 fjs.parentNode.insertBefore(js, fjs);
300 }
301 (document, 'script', 'facebook-jssdk'));
302 },
303 loadOverlay: function()
304 {
305 var overlay_template = '<div id="renarrated_overlay" class="alipi ui-widget-header ui-corner-all">'+
306 '<button id="outter-down-button" class="alipi" onclick="a11ypi.outterToggle();" up="true" title="Move this bar to top">Move</button> '+
307 }
308 (document, 'script', 'facebook-jssdk'));
309 },
310 loadOverlay: function()
311 {
312 var overlay_template = '<div id="renarrated_overlay" class="alipi ui-widget-header ui-corner-all">'+
313 '<button id="outter-down-button" class="alipi" onclick="a11ypi.outterToggle();" up="true" title="Move this bar to top">Move</button> '+
307314 '<button id="outter-up-button" class="alipi" onclick="a11ypi.outterToggle();" title="Move this bar to bottom">Move</button> '+
308315 '<button id="edit-current" class="alipi" onclick="a11ypi.editPage();" title="Allow to edit this page">Re-narrate</button> '+
309316 '<button id="see-narration" class="alipi" onclick="a11ypi.showBox();" title="See other renarrations, which are in same or other languages"> '+
310317 'Re-narrations</button>'+
311 '<button id="see-comment" class="alipi" onclick="a11ypi.showComment();" title="5el"> '+
312 '5el</button>'+
313 '<button id="see-links" class="alipi" onclick="a11ypi.showBox1();" title="See other re-narrated pages of this domain">Re-narrated Pages '+
318 // '<button id="see-comment" class="alipi" onclick="a11ypi.showComment();" title="5el"> '+
319 // '5el</button>'+
320 '<button id="see-links" class="alipi" onclick="a11ypi.showBox1();" title="See other re-narrated pages of this domain">Re-narrated Pages '+
314321 '</button>'+
315 '<select id="blog-filter" class="alipi" onChange="a11ypi.checkSelect();" title="Select one of the blog name"></select>'+
316 '<button id="go" class="alipi ui-icon-circle-arrow-e" onclick="a11ypi.go();" title="Filter by blog" >|Y|</button>'+
317 '<div id="show-box" title="Choose a narration"></div> '+
322 '<select id="blog-filter" class="alipi" onChange="a11ypi.checkSelect();" title="Select one of the blog name"></select>'+
323 '<button id="go" class="alipi ui-icon-circle-arrow-e" onclick="a11ypi.go();" title="Filter by blog" >|Y|</button>'+
324 '<div id="show-box" title="Choose a narration"></div> '+
318325 '<div id="show-comment" title="Comments for"></div> '+
319326 '<div id="show-links" title="List of pages narrated in this domain" class="alipi"></div> '+
320327 '<div id="share-box" class="alipi" title="Share this page in any following social network"></div>';
321
322 var pub_overlay_template = '<div id="pub_overlay" class="alipi ui-widget-header ui-corner-all">'+
328
329 var pub_overlay_template = '<div id="pub_overlay" class="alipi ui-widget-header ui-corner-all">'+
323330 '<button id="icon-up" class="alipi" down="true" onClick="a11ypi.hide_overlays();" title="Move this bar to top">Move</button>'+ //&#x25B2
324331 '<button id="icon-down" class="alipi" onClick="a11ypi.hide_overlays();" title="Move this bar to bottom">Move</button>'+ //&#x25BC
325332 '<button id="exit-mode" class="alipi" onclick="a11ypi.exitMode();" title="Do not want to save any changes, just take me out of this editing"> '+
326333 'Exit</button>'+
327 '<button id="help-window" class="alipi" onclick="a11ypi.help_window();" title="How may I help you in editing this page?">Help</button>'+
328 '<button id="undo-button" class="alipi" onclick="util.undoChanges();"title="Undo previous change, one by one">Undo changes</button>'+
329 '<button id="publish-button" class="alipi" onclick="a11ypi.publish();"title="Publish your changes to blog">Publish</button></div>';
334 '<button id="help-window" class="alipi" onclick="a11ypi.help_window();" title="How may I help you in editing this page?">Help</button>'+
335 '<button id="undo-button" class="alipi" onclick="util.undoChanges();"title="Undo previous change, one by one">Undo changes</button>'+
336 '<button id="publish-button" class="alipi" onclick="a11ypi.publish();"title="Publish your changes to blog">Publish</button></div>';
330337
331 var element_edit_overlay_template = '<div id="element_edit_overlay" class="alipi ui-widget-header ui-corner-all" >'+
332 '<button id="edit-text" class="alipi" onclick="a11ypi.displayEditor();" title="Help you to edit this element by providing an editor on right'+
338 var element_edit_overlay_template = '<div id="element_edit_overlay" class="alipi ui-widget-header ui-corner-all" >'+
339 '<button id="edit-text" class="alipi" onclick="a11ypi.displayEditor();" title="Help you to edit this element by providing an editor on right'+
333340 ' & reference on left.">Edit Text</button>'+
334 '<button id="add-audio" class="alipi" onclick="a11ypi.addAudio();" title="Allow you to give an audio file(.ogg) link to add your audio '+
341 '<button id="add-audio" class="alipi" onclick="a11ypi.addAudio();" title="Allow you to give an audio file(.ogg) link to add your audio '+
335342 'to this element ">Add Audio</button>'+
336 '<button id="replace-image" class="alipi" onclick="a11ypi.imageReplacer();" title="Allow you to give an image file(jpeg/jpg/gif/png) '+
343 '<button id="replace-image" class="alipi" onclick="a11ypi.imageReplacer();" title="Allow you to give an image file(jpeg/jpg/gif/png) '+
337344 'link to replace with this image">Replace Image</button>'+
338345 '<button id="delete-image" class="alipi" onclick="pageEditor.deleteImage();" title="Remove this image from page">Delete Image</button>'+
339346 '<button id="close-element" class="alipi" onclick="pageEditor.cleanUp();" title="Close" ></button>'+
340347 '<label id="cant-edit" class="alipi">No selection / Too large selection </label> '+
341348 '</div>';
342349
343 $('body').append(overlay_template);
344 $('body').append(pub_overlay_template);
345 $('body').append(element_edit_overlay_template);
346
347 $('#outter-up-button').show();
348 $('#go').button({disabled : true});
349 $('#undo-button').button({ disabled: true});
350 $('#publish-button').button({ disabled: true});
351 $('input:.alipi, select:.alipi').button();
350 $('body').append(overlay_template);
351 $('body').append(pub_overlay_template);
352 $('body').append(element_edit_overlay_template);
352353
353 $("#outter-down-button").button({icons:{primary:"ui-icon-circle-arrow-n"},text:false}); $('#outter-down-button').children().addClass('alipi');
354 $("#outter-up-button").button({icons:{primary:"ui-icon-circle-arrow-s"},text:false}); $('#outter-up-button').children().addClass('alipi');
355 $("#edit-current").button({icons:{primary:"ui-icon-pencil"}}); $('#edit-current').children().addClass('alipi');
356 $("#see-narration").button({icons:{primary:"ui-icon-document-b"}}); $('#see-narration').children().addClass('alipi');
357 $("#see-comment").button({icons:{primary:"ui-icon-document-b"}}); $('#see-comment').children().addClass('alipi');
358 $("#see-links").button({icons:{primary:"ui-icon-link"}}); $('#see-links').children().addClass('alipi');
359 /*$("#blog-filter").button({icons:{secondary:"ui-icon-triangle-1-s"}}); */ $('#blog-filter').children().addClass('alipi');
360 $("#go").button({icons:{primary:"ui-icon-arrowthick-1-e"},text:false}); $('#go').children().addClass('alipi');
361 $("#share").button({icons:{primary:"ui-icon-signal-diag"}}); $('#share').children().addClass('alipi');
362 $("#orig-button").button({icons:{primary:"ui-icon-extlink"}}); $('#orig-button').children().addClass('alipi');
363 $("#info").button({icons:{primary:"ui-icon-info"}}); $('#info').children().addClass('alipi');
354 $('#outter-up-button').show();
355 $('#go').button({disabled : true});
356 $('#undo-button').button({ disabled: true});
357 $('#publish-button').button({ disabled: true});
358 $('input:.alipi, select:.alipi').button();
364359
365 $("#icon-up").button({icons:{primary:"ui-icon-circle-arrow-n"},text:false}); $('#icon-up').children().addClass('alipi');
366 $("#icon-down").button({icons:{primary:"ui-icon-circle-arrow-s"},text:false}); $('#icon-down').children().addClass('alipi');
367 $("#exit-mode").button({icons:{primary:"ui-icon-power"}}); $('#exit-mode').children().addClass('alipi');
368 $("#help-window").button({icons:{primary:"ui-icon-help"}}); $('#help-window').children().addClass('alipi');
369 $("#undo-button").button({icons:{primary:"ui-icon-arrowreturnthick-1-w"}}); $('#undo-button').children().addClass('alipi');
370 $("#publish-button").button({icons:{primary:"ui-icon-circle-check"}}); $('#publish-button').children().addClass('alipi');
360 $("#outter-down-button").button({icons:{primary:"ui-icon-circle-arrow-n"},text:false}); $('#outter-down-button').children().addClass('alipi');
361 $("#outter-up-button").button({icons:{primary:"ui-icon-circle-arrow-s"},text:false}); $('#outter-up-button').children().addClass('alipi');
362 $("#edit-current").button({icons:{primary:"ui-icon-pencil"}}); $('#edit-current').children().addClass('alipi');
363 $("#see-narration").button({icons:{primary:"ui-icon-document-b"}}); $('#see-narration').children().addClass('alipi');
364 $("#see-comment").button({icons:{primary:"ui-icon-document-b"}}); $('#see-comment').children().addClass('alipi');
365 $("#see-links").button({icons:{primary:"ui-icon-link"}}); $('#see-links').children().addClass('alipi');
366 /*$("#blog-filter").button({icons:{secondary:"ui-icon-triangle-1-s"}}); */ $('#blog-filter').children().addClass('alipi');
367 $("#go").button({icons:{primary:"ui-icon-arrowthick-1-e"},text:false}); $('#go').children().addClass('alipi');
368 $("#share").button({icons:{primary:"ui-icon-signal-diag"}}); $('#share').children().addClass('alipi');
369 $("#orig-button").button({icons:{primary:"ui-icon-extlink"}}); $('#orig-button').children().addClass('alipi');
370 $("#info").button({icons:{primary:"ui-icon-info"}}); $('#info').children().addClass('alipi');
371371
372 $("#edit-text").button({icons:{primary:"ui-icon-pencil"}}); $('#edit-text').children().addClass('alipi');
373 $("#add-audio").button({icons:{primary:"ui-icon-circle-plus"}}); $('#add-audio').children().addClass('alipi');
374 $("#replace-image").button({icons:{primary:"ui-icon-transferthick-e-w"}}); $('#replace-image').children().addClass('alipi');
375 $("#delete-image").button({icons:{primary:"ui-icon-trash"}}); $('#delete-image').children().addClass('alipi');
376 $("#close-element").button({icons:{primary:"ui-icon-circle-close"},text:false}); $("#close-element").children().addClass('alipi');
372 $("#icon-up").button({icons:{primary:"ui-icon-circle-arrow-n"},text:false}); $('#icon-up').children().addClass('alipi');
373 $("#icon-down").button({icons:{primary:"ui-icon-circle-arrow-s"},text:false}); $('#icon-down').children().addClass('alipi');
374 $("#exit-mode").button({icons:{primary:"ui-icon-power"}}); $('#exit-mode').children().addClass('alipi');
375 $("#help-window").button({icons:{primary:"ui-icon-help"}}); $('#help-window').children().addClass('alipi');
376 $("#undo-button").button({icons:{primary:"ui-icon-arrowreturnthick-1-w"}}); $('#undo-button').children().addClass('alipi');
377 $("#publish-button").button({icons:{primary:"ui-icon-circle-check"}}); $('#publish-button').children().addClass('alipi');
377378
378 $('#renarrated_overlay').addClass('barOnTop');
379 a11ypi.ajax();
380 a11ypi.ajaxLinks1();
381 $('#edit-current').show();
379 $("#edit-text").button({icons:{primary:"ui-icon-pencil"}}); $('#edit-text').children().addClass('alipi');
380 $("#add-audio").button({icons:{primary:"ui-icon-circle-plus"}}); $('#add-audio').children().addClass('alipi');
381 $("#replace-image").button({icons:{primary:"ui-icon-transferthick-e-w"}}); $('#replace-image').children().addClass('alipi');
382 $("#delete-image").button({icons:{primary:"ui-icon-trash"}}); $('#delete-image').children().addClass('alipi');
383 $("#close-element").button({icons:{primary:"ui-icon-circle-close"},text:false}); $("#close-element").children().addClass('alipi');
382384
383 d = window.location.search.split('?')[1];
384 var a =[];
385 for (var i = 0;i<d.split('&').length;i++){
385 $('#renarrated_overlay').addClass('barOnTop');
386 a11ypi.ajax();
387 a11ypi.ajaxLinks1();
388 $('#edit-current').show();
389
390 d = window.location.search.split('?')[1];
391 var a =[];
392 for (var i = 0;i<d.split('&').length;i++){
386393 a[d.split('&')[i].split('=')[0]] = d.split('&')[i].split('=')[1];
387 }
388 if(a['blog'] != undefined ) {
394 }
395 if(a['blog'] != undefined ) {
389396 $('#go').hide();
390397 $('#blog-filter').hide();
391 } else {
392 }
398 } else {
399 }
393400
394 if($('#orig-button').text() == 'Original Page') {
401 if($('#orig-button').text() == 'Original Page') {
395402 $('#share').insertAfter($('#go')); $('#share').show();
396403 $('#info').insertAfter($('#go')); $('#info').show();
397404 $('#orig-button').insertAfter($('#go')); $('#orig-button').show();
398405 $('#share-box').append($('#fb-like')); $('#share-box').append($('#tweet-root'));
399 }
400 },
401 checkSelect: function()
402 {
403 if($('#blog-filter').val() != "Choose a blog") {
406 }
407 },
408 checkSelect: function()
409 {
410 if($('#blog-filter').val() != "Choose a blog") {
404411 $('#go').button({disabled : false});
405 } else {
412 } else {
406413 $('#go').button({disabled : true});
407 }
408 },
414 }
415 },
409416
410 help_window: function() {
411 var help_template = '<div id="helpwindow" class="alipi ui-widget-header ui-corner-all">'+
412 '<label id="txtlab" class="alipi" style="color:#aaa;font-size:100%;">TEXT :- It will popup a '+
417 help_window: function() {
418 var help_template = '<div id="helpwindow" class="alipi ui-widget-header ui-corner-all">'+
419 '<label id="txtlab" class="alipi" style="color:#aaa;font-size:100%;">TEXT :- It will popup a '+
413420 'window and allow you to modify/replace text of select element on editor(right) box.'+
414421 '<p class="alipi">To delete - Empty the editor(right) box and press "Save changes".'+
415422 '</p><p class="alipi" style="margin-left:50px";>Add Audio - It allows you to '+
430430 'Author - Who is a crafter?</p><p class="alipi" style="margin-left:50px";>'+
431431 'Alipi blog - If you don\'t have blogspot ID then check this to post it to our blog.</p></div>';
432432
433 $('body').append(help_template);
434 $(document).unbind('mouseover'); // Unbind the css on mouseover
435 $(document).unbind('mouseout'); // Unbind the css on mouseout
433 $('body').append(help_template);
434 $(document).unbind('mouseover'); // Unbind the css on mouseover
435 $(document).unbind('mouseout'); // Unbind the css on mouseout
436436
437 $(function() {
437 $(function() {
438438 $( "#helpwindow" ).dialog({
439 width:800,
440 height:550,
441 modal: true,
442 close: function() {
443 $("#helpwindow").remove();
444 }
439 width:800,
440 height:550,
441 modal: true,
442 close: function() {
443 $("#helpwindow").remove();
444 }
445445 });
446 });
447 },
448
449 exitMode: function() {
450 var exit = window.confirm("Do you really want to exit from edit mode?");
451 if (exit == true) {
446 });
447 },
448
449 exitMode: function() {
450 var exit = window.confirm("Do you really want to exit from edit mode?");
451 if (exit == true) {
452452 window.location.reload();
453 }
454 },
453 }
454 },
455455
456 hide_overlays: function() {
457 if($('#icon-up').attr('down') == 'true') {
456 hide_overlays: function() {
457 if($('#icon-up').attr('down') == 'true') {
458458 $('#icon-up').attr('down', 'false');
459459 $('#icon-up').show(); $('#icon-down').hide();
460460 $('#pub_overlay').addClass('barOnBottom'); $('#pub_overlay').removeClass('barOnTop');
461 } else {
461 } else {
462462 $('#icon-up').attr('down', 'true');
463463 $('#icon-down').show(); $('#icon-up').hide();
464464 $('#pub_overlay').addClass('barOnTop'); $('#pub_overlay').removeClass('barOnBottom');
465465
466 }
467 },
468
469 outterToggle: function() {
470 if($('#outter-down-button').attr('up') == 'true' ) {
471 $('#outter-down-button').attr('up', 'false');
466 }
467 },
468
469 outterToggle: function() {
470 if($('#outter-down-button').attr('up') == 'true' ) {
471 $('#outter-down-button').attr('up', 'false');
472472 $('#outter-up-button').hide(); $('#outter-down-button').show();
473473 $('#renarrated_overlay').addClass('barOnBottom'); $('#renarrated_overlay').removeClass('barOnTop');
474 } else {
474 } else {
475475 $('#outter-down-button').attr('up', 'true');
476476 $('#outter-up-button').show(); $('#outter-down-button').hide();
477477 $('#renarrated_overlay').addClass('barOnTop'); $('#renarrated_overlay').removeClass('barOnBottom');
478 }
479 },
480
481
482 getLoc: function() {
478 }
479 },
483480
484 $( "#loc-select" ).autocomplete({
485 source: function(req, add){
486481
487 //pass request to server
488 $.getJSON(config.deploy+"/getLoc?", req, function(data) {
489 $('#loc-img').hide();
482 getLoc: function() {
490483
491 //create array for response objects
492 var suggestions = [];
484 $( "#loc-select" ).autocomplete({
485 source: function(req, add){
493486
494 //process response
495 $.each(data['return'], function(i,val){
496 suggestions.push(val['name']+', '+val['country_name']);
497 });
498 //pass array to callback
499 add(suggestions);
500 });
501 $('#loc-img').show();
502 },
503 });
504 },
487 //pass request to server
488 $.getJSON(config.deploy+"/getLoc?", req, function(data) {
489 $('#loc-img').hide();
505490
506 getLang: function() {
507 $( "#lang-select" ).autocomplete({
508 source: function(req, add){
491 //create array for response objects
492 var suggestions = [];
509493
510 //pass request to server
511 $.getJSON(config.deploy+"/getLang?", req, function(data) {
512 $('#lang-img').hide();
494 //process response
495 $.each(data['return'], function(i,val){
496 suggestions.push(val['name']+', '+val['country_name']);
497 });
498 //pass array to callback
499 add(suggestions);
500 });
501 $('#loc-img').show();
502 },
503 });
504 },
513505
514 //create array for response objects
515 var suggestions = [];
506 getLang: function() {
507 $( "#lang-select" ).autocomplete({
508 source: function(req, add){
516509
517 //process response
518 $.each(data['return'], function(i, val){
519 //suggestions.push(val.country);
520 suggestions.push(val['name']);
521 });
522 //pass array to callback
523 add(suggestions);
524 });
525 $('#lang-img').show();
526 },
527 });
510 //pass request to server
511 $.getJSON(config.deploy+"/getLang?", req, function(data) {
512 $('#lang-img').hide();
528513
514 //create array for response objects
515 var suggestions = [];
529516
530 },
517 //process response
518 $.each(data['return'], function(i, val){
519 //suggestions.push(val.country);
520 suggestions.push(val['name']);
521 });
522 //pass array to callback
523 add(suggestions);
524 });
525 $('#lang-img').show();
526 },
527 });
531528
532 publish: function() {
533 if(util.hasChangesPending())
534 {
529
530 },
531
532 publish: function() {
533 if(util.hasChangesPending())
534 {
535535 $('#pub_overlay').slideUp();
536 $('#element_edit_overlay').slideUp();
536 $('#element_edit_overlay').slideUp();
537537 $('#icon_on_overlay').slideUp();
538538 if (a11ypi.target == false ) {
539 var publish_template = '<div id="targetoverlay" title="Who are you narrating to?" class="alipi ui-widget-header ui-corner-all"> '+
540 // '<div id="infovis" class="alipi"> </div>'+
541 '<label id="tar-lab1" class="alipi" >Enter few attributes of the target community </label>'+
542 '<label id="tar-lab2" class="alipi" >Location of the target community: </label> '+
543 '<input id="loc-select" class="alipi" placeholder="Type city/town name"/> '+
544 '<img id="loc-img" src="http://dev.a11y.in/wsgi/images/db_loading.gif" /> '+
545 '<label id="tar-lab3" class="alipi" >Language of re-narration: </label> '+
546 '<input id="lang-select" class="alipi" placeholder="Type language name"/>'+
539 var publish_template = '<div id="targetoverlay" title="Who are you narrating to?" class="alipi ui-widget-header ui-corner-all"> '+
540 // '<div id="infovis" class="alipi"> </div>'+
541 '<label id="tar-lab1" class="alipi" >Enter few attributes of the target community </label>'+
542 '<label id="tar-lab2" class="alipi" >Location of the target community: </label> '+
543 '<input id="loc-select" class="alipi" placeholder="Type city/town name"/> '+
544 '<img id="loc-img" src="http://dev.a11y.in/wsgi/images/db_loading.gif" /> '+
545 '<label id="tar-lab3" class="alipi" >Language of re-narration: </label> '+
546 '<input id="lang-select" class="alipi" placeholder="Type language name"/>'+
547547 '<img id="lang-img" src="http://dev.a11y.in/wsgi/images/db_loading.gif"/> '+
548 '<label id="tar-lab4" class="alipi" >Select a style of re-narration: </label> '+
549 '<select id="style-select" class="alipi" > '+
550 '<option>Translation</option><option>Technical</option><option>Fun</option><option>Simplification</option> '+
551 '<option>Correction</option><option>Evolution</option><option>Other</option></select>'+
552 '<label id="tar-lab5" class="alipi" >Enter an author name for your contribution: </label> '+
553 '<input id="auth-select" class="alipi" type="text" placeholder="John" /> '+
554 '<div id="blogset" > You can choose to post this in your own blog or in the default Alipi blog</div> '+
555 '<p id="tar-p" ><input id="our-check" class="alipi" type="radio"name="blog" /> '+
556 '<label id="tar-lab6" class="alipi" > Alipi Blog</label><input id="your-check" class="alipi" type="radio" name="blog" /> '+
557 '<label id="tar-lab7" class="alipi">Personal Blog</label></p></div>';
558
559 $('body').append(publish_template);
560 a11ypi.getLoc();
561 a11ypi.getLang();
562 a11ypi.target = true;
548 '<label id="tar-lab4" class="alipi" >Select a style of re-narration: </label> '+
549 '<select id="style-select" class="alipi" > '+
550 '<option>Translation</option><option>Technical</option><option>Fun</option><option>Simplification</option> '+
551 '<option>Correction</option><option>Evolution</option><option>Other</option></select>'+
552 '<label id="tar-lab5" class="alipi" >Enter an author name for your contribution: </label> '+
553 '<input id="auth-select" class="alipi" type="text" placeholder="John" /> '+
554 '<div id="blogset" > You can choose to post this in your own blog or in the default Alipi blog</div> '+
555 '<p id="tar-p" ><input id="our-check" class="alipi" type="radio"name="blog" /> '+
556 '<label id="tar-lab6" class="alipi" > Alipi Blog</label><input id="your-check" class="alipi" type="radio" name="blog" /> '+
557 '<label id="tar-lab7" class="alipi">Personal Blog</label></p></div>';
558
559 $('body').append(publish_template);
560 a11ypi.getLoc();
561 a11ypi.getLang();
562 a11ypi.target = true;
563563 }
564564
565565 $(document).unbind('mouseover'); // Unbind the css on mouseover
566566 $(document).unbind('mouseout'); // Unbind the css on mouseout
567567
568568 $('#pub_overlay').slideUp();
569 $('#element_edit_overlay').slideUp();
570// $('#icon_on_overlay').slideUp();
569 $('#element_edit_overlay').slideUp();
570 // $('#icon_on_overlay').slideUp();
571571
572572 $(function() {
573 $( "#targetoverlay" ).dialog({
574 height:550,
575 width:600,
576 modal: true,
577 buttons: {
578 Publish: function() {
579 util.publish();
580 }
581 },
582 close: function() {
583 $('#pub_overlay').slideDown();
584// $('#element_edit_overlay').slideDown();
585// $('#icon_on_overlay').slideDown();
586 $( "#targetoverlay" ).hide();
587 }
588 });
573 $( "#targetoverlay" ).dialog({
574 height:550,
575 width:600,
576 modal: true,
577 buttons: {
578 Publish: function() {
579 util.publish();
580 }
581 },
582 close: function() {
583 $('#pub_overlay').slideDown();
584 // $('#element_edit_overlay').slideDown();
585 // $('#icon_on_overlay').slideDown();
586 $( "#targetoverlay" ).hide();
587 }
588 });
589589 });
590 }
591 },
590 }
591 },
592592
593 hideAll: function() {
594 var boxes = '#show-links, #show-box, #show-comment';
595 $(boxes).dialog('close');
596 },
597
598 showBox: function() {
599 this.hideAll();
600 $(document).unbind('mouseover'); // Unbind the css on mouseover
601 $(document).unbind('mouseout'); // Unbind the css on mouseout
593 hideAll: function() {
594 var boxes = '#show-links, #show-box, #show-comment';
595 $(boxes).dialog('close');
596 },
602597
603 $(function() {
598 showBox: function() {
599 this.hideAll();
600 $(document).unbind('mouseover'); // Unbind the css on mouseover
601 $(document).unbind('mouseout'); // Unbind the css on mouseout
602
603 $(function() {
604604 $( "#show-box" ).dialog( "destroy" );
605
605
606606 $( "#show-box" ).dialog({
607 width: 300,
608 height: 300,
609 modal: true
607 width: 300,
608 height: 300,
609 modal: true
610610 });
611 });
612 d = window.location.search.split('?')[1];
613 var a = a11ypi.getParams();
614 if (a['blog'] === undefined ) {
615 a11ypi.createMenu('renarration');
616 }
617 else {
611 });
612 d = window.location.search.split('?')[1];
613 var a = a11ypi.getParams();
614 if (a['blog'] === undefined ) {
615 a11ypi.createMenu('1.0');
616 }
617 else {
618618 $('#show-box').attr('title', 'Choose a re-narration from the blog you specified.');
619619 a11ypi.ajax1();
620 }
621 },
622 showComment: function() {
623 this.hideAll();
624 $(document).unbind('mouseover'); // Unbind the css on mouseover
625 $(document).unbind('mouseout'); // Unbind the css on mouseout
626
627 $(function() {
620 }
621 },
622 showComment: function() {
623 this.hideAll();
624 $(document).unbind('mouseover'); // Unbind the css on mouseover
625 $(document).unbind('mouseout'); // Unbind the css on mouseout
626
627 $(function() {
628628 $( "#show-comment" ).dialog( "destroy" );
629
629
630630 $( "#show-comment" ).dialog({
631 width: 300,
632 height: 300,
633 modal: true
631 width: 300,
632 height: 300,
633 modal: true
634634 });
635 });
636 a11ypi.createMenu('5el');
637 },
635 });
636 a11ypi.createMenu('5el');
637 },
638638
639 ajaxLinks1: function() {
640 var xhr = new XMLHttpRequest();
641 xhr.onreadystatechange = function()
642 {
639 ajaxLinks1: function() {
640 var xhr = new XMLHttpRequest();
641 xhr.onreadystatechange = function()
642 {
643643 if(xhr.readyState == 4)
644644 {
645 if(xhr.responseText == "empty")
646 { }
647 else
648 {
649 $('#see-links').show();
650 a11ypi.showlinks = JSON.parse(xhr.responseText);
651 }
645 if(xhr.responseText == "empty")
646 { }
647 else
648 {
649 $('#see-links').show();
650 a11ypi.showlinks = JSON.parse(xhr.responseText);
651 }
652652 }
653 }
654 xhr.open("POST",config.root+"/domain",true);
655 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
656 d = window.location.search.split('?')[1];
657 a = a11ypi.getParams();
658 xhr.send('url='+a['foruri'])
659 },
660 showBox1: function() {
661 this.hideAll();
662 $(document).unbind('mouseover'); // Unbind the css on mouseover
663 $(document).unbind('mouseout'); // Unbind the css on mouseout
653 }
654 xhr.open("POST",config.root+"/domain",true);
655 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
656 d = window.location.search.split('?')[1];
657 a = a11ypi.getParams();
658 xhr.send('url='+a['foruri'])
659 },
660 showBox1: function() {
661 this.hideAll();
662 $(document).unbind('mouseover'); // Unbind the css on mouseover
663 $(document).unbind('mouseout'); // Unbind the css on mouseout
664664
665 $(function() {
665 $(function() {
666666 $( "#show-links" ).dialog( "destroy" );
667
667
668668 $( "#show-links" ).dialog({
669 width: 500,
670 height: 300,
671 modal: true
669 width: 500,
670 height: 300,
671 modal: true
672672 });
673 });
674 a11ypi.createDomainMenu();
675 },
676 createDomainMenu: function() {
677 var xyz = $("#show-links");
678 xyz.html('');
679 menu_list = a11ypi.showlinks;
680 for(var i=0; i<menu_list.length;i++)
681 {
673 });
674 a11ypi.createDomainMenu();
675 },
676 createDomainMenu: function() {
677 var xyz = $("#show-links");
678 xyz.html('');
679 menu_list = a11ypi.showlinks;
680 for(var i=0; i<menu_list.length;i++)
681 {
682682 var para = document.createElement("p");
683683 var newel = document.createElement("a");
684684 newel.textContent = menu_list[i];
686686 newel.setAttribute("class","alipiShowLink");
687687 para.appendChild(newel);
688688 xyz.append(para);
689 }
690 $('.alipiShowLink').hover(
689 }
690 $('.alipiShowLink').hover(
691691 function() {
692 var xhr = new XMLHttpRequest();
693 xhr.onreadystatechange = function()
694 {
695 if(xhr.readyState == 4)
696 {
697 if(xhr.responseText == "empty")
698 { }
699 else
700 {
701 menu_list = JSON.parse(xhr.responseText);
702 x = '';
703 for(i=0; i<menu_list.length; i++) {
704 if (i == menu_list.length-1) {
705 x += menu_list[i];
706 } else {
707 x += menu_list[i] + ", ";
692 var xhr = new XMLHttpRequest();
693 xhr.onreadystatechange = function()
694 {
695 if(xhr.readyState == 4)
696 {
697 if(xhr.responseText == "empty")
698 { }
699 else
700 {
701 menu_list = JSON.parse(xhr.responseText);
702 x = '';
703 for(i=0; i<menu_list.length; i++) {
704 if (i == menu_list.length-1) {
705 x += menu_list[i];
706 } else {
707 x += menu_list[i] + ", ";
708 }
709 }
710 $('#show-links').title = x;
711 }
712 }
708713 }
709 }
710 $('#show-links').title = x;
711 }
712 }
713 }
714 xhr.open("POST",config.root+"/menu",true);
715 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
716 xhr.send('url='+encodeURIComponent($(this).attr('href'))) ;
714 xhr.open("POST",config.root+"/menu",true);
715 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
716 xhr.send('url='+encodeURIComponent($(this).attr('href'))) ;
717717 },
718718 function () {$('#show-links').title= '';}
719 );
720 },
721 blogFilter: function() {
722 if (a11ypi.blog_flag == false) {
723 a11ypi.blog_flag = true;
724 var xhr = new XMLHttpRequest();
725 xhr.onreadystatechange = function()
726 {
727 if(xhr.readyState == 4)
728 {
729 if(xhr.responseText == "empty")
730 { }
731 else
719 );
720 },
721 blogFilter: function() {
722 if (a11ypi.blog_flag == false) {
723 a11ypi.blog_flag = true;
724 var xhr = new XMLHttpRequest();
725 xhr.onreadystatechange = function()
732726 {
733 var sel = $("#blog-filter");
734 var menu_list = JSON.parse(xhr.responseText);
735 opt = document.createElement("option");
736 opt.textContent = "Choose a blog";
737 sel.append(opt);
738 for (var i=0; i < menu_list.length; i++)
727 if(xhr.readyState == 4)
739728 {
740 opt = document.createElement("option");
741 opt.textContent = menu_list[i];
742 sel.append(opt);
729 if(xhr.responseText == "empty")
730 { }
731 else
732 {
733 var sel = $("#blog-filter");
734 var menu_list = JSON.parse(xhr.responseText);
735 opt = document.createElement("option");
736 opt.textContent = "Choose a blog";
737 sel.append(opt);
738 for (var i=0; i < menu_list.length; i++)
739 {
740 opt = document.createElement("option");
741 opt.textContent = menu_list[i];
742 sel.append(opt);
743 }
744 }
743745 }
744746 }
747 xhr.open("POST",config.root+"/blog",true);
748 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
749 a = a11ypi.getParams();
750 xhr.send('url='+a['foruri']);
745751 }
746 }
747 xhr.open("POST",config.root+"/blog",true);
748 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
749 a = a11ypi.getParams();
750 xhr.send('url='+a['foruri']);
751 }
752 },
753 go: function() {
754 var a =[];
755 for (var i = 0;i<d.split('&').length;i++){
752 },
753 go: function() {
754 var a =[];
755 for (var i = 0;i<d.split('&').length;i++){
756756 a[d.split('&')[i].split('=')[0]] = d.split('&')[i].split('=')[1];
757 }
758 if ($("#blog-filter").val() == null)
759 { }
760 else {
757 }
758 if ($("#blog-filter").val() == null)
759 { }
760 else {
761761 window.open(config.deploy+"/?foruri=" + a['foruri'] + "&blog=" + $("#blog-filter").val());
762 }
763 },
764 share: function() {
765 $('#fb-like').css('display', 'block');
766 $('#tweet-root').css('display', 'block');
767 $( "#share-box" ).dialog({
762 }
763 },
764 share: function() {
765 $('#fb-like').css('display', 'block');
766 $('#tweet-root').css('display', 'block');
767 $( "#share-box" ).dialog({
768768 position: 'center',
769769 width:450,
770770 height:180,
771771 modal: true,
772 });
773 },
774 editPage: function() {
775 this.hideAll();
776 a11ypi.testContext();
777 $('#pub_overlay').show(); $('#pub_overlay').addClass('barOnTop');
778 $('#icon-down').show();
779 $('#renarrated_overlay').hide();
780 $('body *').contents().filter(function(){
772 });
773 },
774 editPage: function() {
775 this.hideAll();
776 a11ypi.testContext();
777 $('#pub_overlay').show(); $('#pub_overlay').addClass('barOnTop');
778 $('#icon-down').show();
779 $('#renarrated_overlay').hide();
780 $('body *').contents().filter(function(){
781781 {
782 try{
783 if(!($(this).hasClass('alipi')) && $(this).attr('m4pageedittype') )
784 return this;
785 }
786 catch(err)
787 {
788 //pass
789 }
782 try{
783 if(!($(this).hasClass('alipi')) && $(this).attr('m4pageedittype') )
784 return this;
785 }
786 catch(err)
787 {
788 //pass
789 }
790790 }
791 }).click(pageEditor.startEdit);
791 }).click(pageEditor.startEdit);
792792
793 $('body *').contents().filter(function(){
793 $('body *').contents().filter(function(){
794794 {
795 try{
796 if(!($(this).hasClass('alipi')) || $(this).attr('m4pageedittype'))
797 return this;
798 }
799 catch(err)
800 {
801 //pass
802 }
795 try{
796 if(!($(this).hasClass('alipi')) || $(this).attr('m4pageedittype'))
797 return this;
798 }
799 catch(err)
800 {
801 //pass
802 }
803803 }
804 }).click(pageEditor.noEdit);
805
806 $(document).mouseover(a11ypi.highlightOnHover);
807 $(document).mouseout(a11ypi.unhighlightOnMouseOut);
808 },
804 }).click(pageEditor.noEdit);
809805
810 displayEditor: function() {
811 var template = '<div id="editoroverlay" title="Editor" class="alipi ui-widget-header ui-corner-all">'+
806 $(document).mouseover(a11ypi.highlightOnHover);
807 $(document).mouseout(a11ypi.unhighlightOnMouseOut);
808 },
809
810 displayEditor: function() {
811 var template = '<div id="editoroverlay" title="Editor" class="alipi ui-widget-header ui-corner-all">'+
812812 '<button id="close-adv" class="alipi" onclick="a11ypi.closeAdv();" title="Want to close View Source & display without HTML code?"> '+
813813 'Render source</button> '+
814814 '<button id="adv-ref" class="alipi" onclick="a11ypi.showAdv();" title="Want to see HTML code? Then click me !!">View Source</button> '+
815 '<label id="ref-lab" class="alipi" style="left:3%;">Here is original piece (Reference)</label>'+
816 '<div id="reference" class="alipi" readonly="yes"></div>'+
815 '<label id="ref-lab" class="alipi" style="left:3%;">Here is original piece (Reference)</label>'+
816 '<div id="reference" class="alipi" readonly="yes"></div>'+
817817 '<textarea id="adv-reference" class="alipi" readonly="yes"></textarea> '+
818 '<label id="edit-lab" class="alipi" style="left:53%;">Where you should edit (Editor)</label>'+
819 '<div id="editor" class="alipi" contenteditable="true" '+
820 '</div>';
821 $('body').append(template);
822 $('#pub_overlay').slideUp();
823 $('#element_edit_overlay').hide();
818 '<label id="edit-lab" class="alipi" style="left:53%;">Where you should edit (Editor)</label>'+
819 '<div id="editor" class="alipi" contenteditable="true" '+
820 '</div>';
821 $('body').append(template);
822 $('#pub_overlay').slideUp();
823 $('#element_edit_overlay').hide();
824824
825 var tag = pageEditor.event.target.nodeName;
826 $(pageEditor.event.target).removeAttr('m4pageedittype');
827 $(pageEditor.event.target).children().removeAttr('m4pageedittype');
828
829 $('#adv-reference').text('<'+tag+'>'+$(pageEditor.event.target).html()+'</'+tag+'>');
830 $('#reference').html($(pageEditor.event.target).html());
831 $('#editor').html($(pageEditor.event.target).html());
832 $("#adv-ref").button({icons:{primary:"ui-icon-script"},text:true}); $('#adv-ref').children().addClass('alipi');
833 $("#close-adv").button({icons:{primary:"ui-icon-bookmark"},text:true}); $('#close-adv').children().addClass('alipi');
834 $('#close-adv').hide();
835 $('#adv-ref').button();
825 var tag = pageEditor.event.target.nodeName;
826 $(pageEditor.event.target).removeAttr('m4pageedittype');
827 $(pageEditor.event.target).children().removeAttr('m4pageedittype');
836828
837 $(document).unbind('mouseover'); // Unbind the css on mouseover
838 $(document).unbind('mouseout'); // Unbind the css on mouseout
829 $('#adv-reference').text('<'+tag+'>'+$(pageEditor.event.target).html()+'</'+tag+'>');
830 $('#reference').html($(pageEditor.event.target).html());
831 $('#editor').html($(pageEditor.event.target).html());
832 $("#adv-ref").button({icons:{primary:"ui-icon-script"},text:true}); $('#adv-ref').children().addClass('alipi');
833 $("#close-adv").button({icons:{primary:"ui-icon-bookmark"},text:true}); $('#close-adv').children().addClass('alipi');
834 $('#close-adv').hide();
835 $('#adv-ref').button();
839836
840 $( "#editoroverlay" ).dialog({
837 $(document).unbind('mouseover'); // Unbind the css on mouseover
838 $(document).unbind('mouseout'); // Unbind the css on mouseout
839
840 $( "#editoroverlay" ).dialog({
841841 position: 'center',
842842 width:$(window).width()-10,
843843 height:$(window).height()-50,
844844 modal: true,
845845 buttons: {
846 "+": function() {
847 if($('#editor').css('font-size') >= '30px') {
848 // passthrough
849 }
850 else {
851 var font = parseFloat($('#editor').css('font-size')) + 1;
852 $('#editor').css('font-size', font+'px');
853 font = parseFloat($('#reference').css('font-size')) + 1;
854 $('#reference').css('font-size', font+'px');
855 font = parseFloat($('#adv-reference').css('font-size')) + 1;
856 $('#adv-reference').css('font-size', font+'px');
857 }
858 },
859 "-": function() {
860 if($('#editor').css('font-size') <= '10px') {
861 //passthrough
862 }
863 else {
864 var font = parseFloat($('#editor').css('font-size')) - 1;
865 $('#editor').css('font-size', font+'px');
866 font = parseFloat($('#reference').css('font-size')) - 1;
867 $('#reference').css('font-size', font+'px');
868 font = parseFloat($('#adv-reference').css('font-size')) - 1;
869 $('#adv-reference').css('font-size', font+'px');
870 }
871 },
872 "Add Link": function() {
873 pageEditor.handler();
874 },
875 "Save changes": function() {
876 $('#pub_overlay').slideDown();
877 $('#element_edit_overlay').slideDown();
878 $('#icon_on_overlay').slideDown();
879 manager.recordText(pageEditor.event.target);
880 pageEditor.cleanUp(pageEditor.event.target);
881 $( "#editoroverlay" ).remove();
882 }
846 "+": function() {
847 if($('#editor').css('font-size') >= '30px') {
848 // passthrough
849 }
850 else {
851 var font = parseFloat($('#editor').css('font-size')) + 1;
852 $('#editor').css('font-size', font+'px');
853 font = parseFloat($('#reference').css('font-size')) + 1;
854 $('#reference').css('font-size', font+'px');
855 font = parseFloat($('#adv-reference').css('font-size')) + 1;
856 $('#adv-reference').css('font-size', font+'px');
857 }
858 },
859 "-": function() {
860 if($('#editor').css('font-size') <= '10px') {
861 //passthrough
862 }
863 else {
864 var font = parseFloat($('#editor').css('font-size')) - 1;
865 $('#editor').css('font-size', font+'px');
866 font = parseFloat($('#reference').css('font-size')) - 1;
867 $('#reference').css('font-size', font+'px');
868 font = parseFloat($('#adv-reference').css('font-size')) - 1;
869 $('#adv-reference').css('font-size', font+'px');
870 }
871 },
872 "Add Link": function() {
873 pageEditor.handler();
874 },
875 "Save changes": function() {
876 $('#pub_overlay').slideDown();
877 $('#element_edit_overlay').slideDown();
878 $('#icon_on_overlay').slideDown();
879 manager.recordText(pageEditor.event.target);
880 pageEditor.cleanUp(pageEditor.event.target);
881 $( "#editoroverlay" ).remove();
882 }
883883 },
884884 close: function() {
885 pageEditor.cleanUp(pageEditor.event.target);
886 $("#editoroverlay" ).remove();
885 pageEditor.cleanUp(pageEditor.event.target);
886 $("#editoroverlay" ).remove();
887887 }
888 });
888 });
889889
890 $($($('<label>').insertAfter($('.ui-dialog-buttonset').children()[0])).html('Magnify or Demagnify')); // Element added externally with css
891 $($('.ui-dialog-buttonset').children()[1]).attr('id','mag-demag');
892 $($('.ui-dialog-buttonset').children()[0]).attr('id','mag'); // '+'
893 $($('.ui-dialog-buttonset').children()[2]).attr('id','demag'); // '-'
894 $($('.ui-dialog-buttonset').children()[3]).attr('id','add-link'); // 'Link'
895 $($('.ui-dialog-buttonset').children()[4]).attr('id','save-changes'); // 'Save Changes'
890 $($($('<label>').insertAfter($('.ui-dialog-buttonset').children()[0])).html('Magnify or Demagnify')); // Element added externally with css
891 $($('.ui-dialog-buttonset').children()[1]).attr('id','mag-demag');
892 $($('.ui-dialog-buttonset').children()[0]).attr('id','mag'); // '+'
893 $($('.ui-dialog-buttonset').children()[2]).attr('id','demag'); // '-'
894 $($('.ui-dialog-buttonset').children()[3]).attr('id','add-link'); // 'Link'
895 $($('.ui-dialog-buttonset').children()[4]).attr('id','save-changes'); // 'Save Changes'
896896
897 $('#adv-reference').height($('#editor').height() + 40);
898 $('#reference').height($('#editor').height());
899 $('#mag').attr('title', 'To magnify letters/Increase font size');
900 $('#demag').attr('title', 'To demagnify letters/Decrease font size');
901 $('#add-link').attr('title', 'Add link(href) to the selected text portion (Before clicking this button, select some portion of text in "Editor")');
902 $('#save-changes').attr('title', 'Save edited text onto the page')
903 },
897 $('#adv-reference').height($('#editor').height() + 40);
898 $('#reference').height($('#editor').height());
899 $('#mag').attr('title', 'To magnify letters/Increase font size');
900 $('#demag').attr('title', 'To demagnify letters/Decrease font size');
901 $('#add-link').attr('title', 'Add link(href) to the selected text portion (Before clicking this button, select some portion of text in "Editor")');
902 $('#save-changes').attr('title', 'Save edited text onto the page')
903 },
904904
905 showAdv: function() {
906 $('#reference').hide();
907 $('#adv-reference').show();
908 $('#adv-ref').hide();
909 $('#close-adv').show();
910 },
911 closeAdv: function() {
912 $('#reference').show();
913 $('#adv-reference').hide();
914 $('#close-adv').hide();
915 $('#adv-ref').show();
916 },
917
918 reflectInReference: function() {
919 var tag = pageEditor.event.target.nodeName;
920 $("#reference").html() = $("#editor").html();
921 },
905 showAdv: function() {
906 $('#reference').hide();
907 $('#adv-reference').show();
908 $('#adv-ref').hide();
909 $('#close-adv').show();
910 },
911 closeAdv: function() {
912 $('#reference').show();
913 $('#adv-reference').hide();
914 $('#close-adv').hide();
915 $('#adv-ref').show();
916 },
922917
923 imageReplacer: function() {
924 var imageInputTemplate = '<div id="imageInputElement" title="Enter url" class="alipi ui-widget-header ui-corner-all">'+
925 '<input type="text" id="imageInput" placeholder="http://foo.com/baz.jpg" class="alipi" value=""/></div>';
918 reflectInReference: function() {
919 var tag = pageEditor.event.target.nodeName;
920 $("#reference").html() = $("#editor").html();
921 },
926922
927 $('body').append(imageInputTemplate);
928 $(document).unbind('mouseover'); // Unbind the css on mouseover
929 $(document).unbind('mouseout'); // Unbind the css on mouseout
923 imageReplacer: function() {
924 var imageInputTemplate = '<div id="imageInputElement" title="Enter url" class="alipi ui-widget-header ui-corner-all">'+
925 '<input type="text" id="imageInput" placeholder="http://foo.com/baz.jpg" class="alipi" value=""/></div>';
930926
931 $('#pub_overlay').slideUp();
932 $('#element_edit_overlay').slideUp();
933 $('#icon_on_overlay').slideUp();
927 $('body').append(imageInputTemplate);
928 $(document).unbind('mouseover'); // Unbind the css on mouseover
929 $(document).unbind('mouseout'); // Unbind the css on mouseout
934930
935 $( "#imageInputElement" ).dialog({
931 $('#pub_overlay').slideUp();
932 $('#element_edit_overlay').slideUp();
933 $('#icon_on_overlay').slideUp();
934
935 $( "#imageInputElement" ).dialog({
936936 width:300,
937937 height:200,
938938 modal: true,
939939 buttons: {
940 OK: function() {
941 var formValue = $('#imageInput').val();
942 if(formValue != '\/S/')
943 {
944 manager.recordImage(pageEditor.event.target, formValue);
945 pageEditor.cleanUp(pageEditor.event.target);
946 $( "#imageInputElement" ).remove();
947 }
948 }
940 OK: function() {
941 var formValue = $('#imageInput').val();
942 if(formValue != '\/S/')
943 {
944 manager.recordImage(pageEditor.event.target, formValue);
945 pageEditor.cleanUp(pageEditor.event.target);
946 $( "#imageInputElement" ).remove();
947 }
948 }
949949 },
950950 close: function() {
951 pageEditor.cleanUp(pageEditor.event.target);
952 $("#imageInputElement" ).remove();
951 pageEditor.cleanUp(pageEditor.event.target);
952 $("#imageInputElement" ).remove();
953953 }
954 });
955
956 },
954 });
957955
958 addAudio: function() {
959 var audioInputTemplate = '<div id="audioInputElement" title="Enter url" class="alipi ui-widget-header ui-corner-all">'+
960 '<input type="text" id="audioInput" placeholder="http://foo.com/baz.ogg" class="alipi" value=""/></div>';
956 },
961957
962 $('body').append(audioInputTemplate);
963 $(document).unbind('mouseover'); // Unbind the css on mouseover
964 $(document).unbind('mouseout'); // Unbind the css on mouseout
958 addAudio: function() {
959 var audioInputTemplate = '<div id="audioInputElement" title="Enter url" class="alipi ui-widget-header ui-corner-all">'+
960 '<input type="text" id="audioInput" placeholder="http://foo.com/baz.ogg" class="alipi" value=""/></div>';
965961
966 $('#pub_overlay').slideUp();
967 $('#element_edit_overlay').slideUp();
968 $('#icon_on_overlay').slideUp();
962 $('body').append(audioInputTemplate);
963 $(document).unbind('mouseover'); // Unbind the css on mouseover
964 $(document).unbind('mouseout'); // Unbind the css on mouseout
969965
970 $( "#audioInputElement" ).dialog({
966 $('#pub_overlay').slideUp();
967 $('#element_edit_overlay').slideUp();
968 $('#icon_on_overlay').slideUp();
969
970 $( "#audioInputElement" ).dialog({
971971 width:300,
972972 height:200,
973973 modal: true,
974974 buttons: {
975 OK: function() {
976 pageEditor.addAudio();
977 pageEditor.cleanUp(pageEditor.event.target);
978 $( "#audioInputElement" ).remove();
979 }
975 OK: function() {
976 pageEditor.addAudio();
977 pageEditor.cleanUp(pageEditor.event.target);
978 $( "#audioInputElement" ).remove();
979 }
980980 },
981981 close: function() {
982 pageEditor.cleanUp(pageEditor.event.target);
983 $("#audioInputElement" ).remove();
982 pageEditor.cleanUp(pageEditor.event.target);
983 $("#audioInputElement" ).remove();
984984 }
985 });
986 },
987
988 highlightOnHover: function(event) {
989 if( !($(event.target).hasClass('alipi')) ) {
985 });
986 },
987
988 highlightOnHover: function(event) {
989 if( !($(event.target).hasClass('alipi')) ) {
990990 $(event.target).addClass('highlightElement');
991 }
992 },
991 }
992 },
993993
994 unhighlightOnMouseOut: function(event) {
995 $(event.target).removeClass('highlightElement');
996 },
997 showInfo: function(data) {
998 infoWindow = window.open(config.deploy+'/blank','Info page');
999 window.setTimeout(function(){a11ypi.pushInfo(infoWindow.document.getElementById('info_content'),infoWindow,data);},2500);
1000 },
1001 pushInfo: function(ele, win, data) //ele contains the info_content element from blank.html
1002 {
1003 win.infoFullJSON = a11ypi.responseJSON;
1004 win.onLoad();
1005 },
1006 getParams: function()
1007 {
1008 var a = [];
1009 if(window.location.hostname == config.hostname)
1010 {
994 unhighlightOnMouseOut: function(event) {
995 $(event.target).removeClass('highlightElement');
996 },
997 showInfo: function(data) {
998 infoWindow = window.open(config.deploy+'/blank','Info page');
999 window.setTimeout(function(){a11ypi.pushInfo(infoWindow.document.getElementById('info_content'),infoWindow,data);},2500);
1000 },
1001 pushInfo: function(ele, win, data) //ele contains the info_content element from blank.html
1002 {
1003 win.infoFullJSON = a11ypi.responseJSON;
1004 win.onLoad();
1005 },
1006 getParams: function()
1007 {
1008 var a = [];
1009 if(window.location.hostname == config.hostname)
1010 {
10111011 d = window.location.search.split('?')[1];
1012 for (var i = 0;i<d.split('&').length;i++){
1013 a[d.split('&')[i].split('=')[0]] = decodeURIComponent(d.split('&')[i].split('=')[1]);
1012 for (var i = 0;i<d.split('&').length;i++){
1013 a[d.split('&')[i].split('=')[0]] = decodeURIComponent(d.split('&')[i].split('=')[1]);
10141014 }
10151015 return a;
1016 }
1017 else
1018 {
1016 }
1017 else
1018 {
10191019 a['foruri'] = window.location.href;
10201020 return a;
1021 }
1022 }
1021 }
1022 }
10231023};
  
11var pageEditor = {
2 event: 0 , //Use this var to store the event object, which will be passed for editor.
3 m4pageedittype: '',
4 savedHtml: '',
5 url:'',
6 selection:'',
7 startEdit: function(event)
8 {
9 if(event.target.nodeName != 'AUDIO'){
2 event: 0 , //Use this var to store the event object, which will be passed for editor.
3 m4pageedittype: '',
4 savedHtml: '',
5 url:'',
6 selection:'',
7 startEdit: function(event)
8 {
9 if(event.target.nodeName != 'AUDIO'){
1010 event.stopPropagation();
1111 event.preventDefault();
12 }
13 pageEditor.event = event;
14 pageEditor.m4pageedittype = $(event.target).attr('m4pageedittype');
15 $('*').removeClass('highlightOnSelect');
12 }
13 pageEditor.event = event;
14 pageEditor.m4pageedittype = $(event.target).attr('m4pageedittype');
15 $('*').removeClass('highlightOnSelect');
1616
17 if (pageEditor.event) {
17 if (pageEditor.event) {
1818 xAxis = pageEditor.event.clientX;
1919 yAxis = pageEditor.event.clientY;
2020 $("#element_edit_overlay").css("top", yAxis);
2121 $("#element_edit_overlay").css("left", xAxis);
22 }
22 }
2323
24 if($(event.target).attr('m4pageedittype') == 'text') {
24 if($(event.target).attr('m4pageedittype') == 'text') {
2525 $(event.target).addClass('highlightOnSelect'); // To show selected element
2626
27 $('#edit-text').show();
27 $('#edit-text').show();
2828 $('#add-audio').show();
2929 $('#close-element').show();
3030 $('#replace-image').hide();
3535 $('#element_edit_overlay').slideDown();
3636 // At this point 'displayEditor' function will be performed on click of 'Edit Text' button
3737 // displayEditor function is in ui.js file
38 }
39 else if($(event.target).attr('m4pageedittype') == 'image') {
38 }
39 else if($(event.target).attr('m4pageedittype') == 'image') {
4040 $(event.target).addClass('highlightOnSelect'); // To show selected element
4141
4242 $('#replace-image').show();
5050 $('#pub_overlay').slideDown();
5151 // At this point 'imageReplacer' function will be performed on click of 'Replace Image' button
5252 // imageReplacer function is in ui.js
53 }
54 },
53 }
54 },
5555
56 noEdit: function(event)
57 {
58 if (event) {
56 noEdit: function(event)
57 {
58 if (event) {
5959 xAxis = event.clientX;
6060 yAxis = event.clientY;
6161 $("#element_edit_overlay").css("top", yAxis);
6262 $("#element_edit_overlay").css("left", xAxis);
63 }
64 $('*').removeClass('highlightOnSelect');
65 if(!($(event.target).attr('m4pageedittype'))) {
63 }
64 $('*').removeClass('highlightOnSelect');
65 if(!($(event.target).attr('m4pageedittype'))) {
6666 $('#edit-text').hide();
6767 $('#add-audio').hide();
6868 $('#replace-image').hide();
7373 $("body").css("overflow", "auto");
7474 $('#pub_overlay').slideDown();
7575 $('#element_edit_overlay').slideDown();
76 }
77 },
78
79 handler: function()
80 {
81 var sel = window.getSelection();
82 y = sel.anchorOffset;
83 z = sel.focusOffset;
84 if(y != z)
85 {
76 }
77 },
78
79 handler: function()
80 {
81 var sel = window.getSelection();
82 y = sel.anchorOffset;
83 z = sel.focusOffset;
84 if(y != z)
85 {
8686 pageEditor.savedHtml = $('#editor').html();
8787 var url = prompt("Enter url");
8888 if(url)
8989 {
90 sel.anchorNode.textContent = sel.anchorNode.textContent.substr(0,y)+'<a href="'+url+'">'+sel.anchorNode.textContent.substr(y,z-y)+"</a>"+sel.anchorNode.textContent.substr(z);
91 abc = $('#editor').html();
92 abc = abc.replace(/(&lt;)/g,'<');
93 abc = abc.replace(/(&gt;)/g,'>');
94 $('#editor').html(abc);
90 sel.anchorNode.textContent = sel.anchorNode.textContent.substr(0,y)+'<a href="'+url+'">'+sel.anchorNode.textContent.substr(y,z-y)+"</a>"+sel.anchorNode.textContent.substr(z);
91 abc = $('#editor').html();
92 abc = abc.replace(/(&lt;)/g,'<');
93 abc = abc.replace(/(&gt;)/g,'>');
94 $('#editor').html(abc);
9595 }
9696 else
9797 {
98 $('#dialog-message').html('<p>Please enter a valid url</p>');
99 $('#dialog-message').dialog({
100 modal: true,
101 buttons:{
102 OK:function(){
103 $(this).dialog("close");
104 $(this).html('');
105 }
106 }});
98 $('#dialog-message').html('<p>Please enter a valid url</p>');
99 $('#dialog-message').dialog({
100 modal: true,
101 buttons:{
102 OK:function(){
103 $(this).dialog("close");
104 $(this).html('');
105 }
106 }});
107107 }
108 }
109 else{
108 }
109 else{
110110 $('#dialog-message').html('<p>Please choose a portion of text and then click <b>Add link</b>.</p>');
111111 $('#dialog-message').dialog({
112 modal: true,
113 buttons:{
114 OK:function(){
115 $(this).dialog("close");
116 $(this).html('');
117 }
118 }});
119 }
120 },
121
122 addAudio: function(){
123 url = $('#audioInput').val();
124 console.log(url);
125 if(url.substr(-4) =='.ogg'){
112 modal: true,
113 buttons:{
114 OK:function(){
115 $(this).dialog("close");
116 $(this).html('');
117 }
118 }});
119 }
120 },
121
122 addAudio: function(){
123 url = $('#audioInput').val();
124 if(url.substr(-4) =='.ogg'){
126125 manager.recordAudio(pageEditor.event.target);
127 }
128 // else{
129 // $('#dialog-message').html('<p>Please enter a valid url</p>');
130 // $('#dialog-message').dialog({
131 // modal: true,
132 // buttons:{
133 // OK:function(){
134 // $(this).dialog("close");
135 // $(this).html('');
136 // }
137 // }});
138 // }
139 },
126 }
127 // else{
128 // $('#dialog-message').html('<p>Please enter a valid url</p>');
129 // $('#dialog-message').dialog({
130 // modal: true,
131 // buttons:{
132 // OK:function(){
133 // $(this).dialog("close");
134 // $(this).html('');
135 // }
136 // }});
137 // }
138 },
140139
141 deleteImage: function(){
142 manager.deleteImage(pageEditor.event.target);
143 pageEditor.cleanUp(pageEditor.event.target);
144 },
145
146 cleanUp: function(element)
147 {
148 if(util.hasChangesPending()) {
140 deleteImage: function(){
141 manager.deleteImage(pageEditor.event.target);
142 pageEditor.cleanUp(pageEditor.event.target);
143 },
144
145 cleanUp: function(element)
146 {
147 if(util.hasChangesPending()) {
149148 $('#undo-button').button('option', 'disabled', false); // Another way of enabling UI-JQUERY button
150149 $('#publish-button').button({ disabled: false}); // Enabling UI-JQUERY button
151 } else {
150 } else {
152151 $('#undo-button').button({ disabled: true}); // Disabling button
153152 $('#publish-button').button({ disabled: true}); // Disabling button
154 }
153 }
155154
156 $(element).attr('m4pageedittype', pageEditor.m4pageedittype);
157 $(element).children().attr('m4pageedittype', pageEditor.m4pageedittype);
158// $('#icon_on_overlay').slideDown();
159 $('#pub_overlay').slideDown();
160 $('#element_edit_overlay').hide();
161 $("body").css("overflow", "auto");
162 $('*').removeClass('highlightOnSelect');
163// $('#element_edit_overlay').slideDown();
164 $(document).mouseover(a11ypi.highlightOnHover);
165 $(document).mouseout(a11ypi.unhighlightOnMouseOut);
166// $(pageEditor.event.target).removeClass('highlightOnSelect'); // Remove hightlight of selected element
167 },
155 $(element).attr('m4pageedittype', pageEditor.m4pageedittype);
156 $(element).children().attr('m4pageedittype', pageEditor.m4pageedittype);
157 // $('#icon_on_overlay').slideDown();
158 $('#pub_overlay').slideDown();
159 $('#element_edit_overlay').hide();
160 $("body").css("overflow", "auto");
161 $('*').removeClass('highlightOnSelect');
162 // $('#element_edit_overlay').slideDown();
163 $(document).mouseover(a11ypi.highlightOnHover);
164 $(document).mouseout(a11ypi.unhighlightOnMouseOut);
165 // $(pageEditor.event.target).removeClass('highlightOnSelect'); // Remove hightlight of selected element
166 },
168167};
169168
170169var DOM = {
171 getXpath : function (element)
172 {
173 var str = '';
174 var currentNode = element;
175 var path = '';
176 var index = -1;
170 getXpath : function (element)
171 {
172 var str = '';
173 var currentNode = element;
174 var path = '';
175 var index = -1;
177176
178 if (currentNode.nodeName != "#text")
179 {
177 if (currentNode.nodeName != "#text")
178 {
180179 path = DOM.makePath(currentNode);
181 }
182 else
183 {
180 }
181 else
182 {
184183 path = DOM.makePath(currentNode.parentNode);
185 }
184 }
186185
187
188 return path;
189 },
190 getElementIdx : function getElementIdx(elt)
191 {
192 var count = 1;
193 for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling)
194 {
186
187 return path;
188 },
189 getElementIdx : function getElementIdx(elt)
190 {
191 var count = 1;
192 for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling)
193 {
195194 if(sib.nodeType == 1 && sib.tagName == elt.tagName)count++
196 }
197
198 return count;
199 },
200
201 makePath : function makePath(elt){
202 var path = '';
203 for (; elt && elt.nodeType == 1; elt = elt.parentNode)
204 {
195 }
196
197 return count;
198 },
199
200 makePath : function makePath(elt){
201 var path = '';
202 for (; elt && elt.nodeType == 1; elt = elt.parentNode)
203 {
205204 if(elt.id == "")
206205 {
207 idx = DOM.getElementIdx(elt);
208 xname = elt.tagName;
209 if (idx > 1)
210 xname += "[" + idx + "]";
211 path = "/" + xname + path;
206 idx = DOM.getElementIdx(elt);
207 xname = elt.tagName;
208 if (idx > 1)
209 xname += "[" + idx + "]";
210 path = "/" + xname + path;
212211 }
213212 else
214213 {
215 path = "//*[@id='"+elt.id+"']"+path;
216 break;
214 path = "//*[@id='"+elt.id+"']"+path;
215 break;
217216 }
218 }
219 return path;
220 },
221 settextContent : function(element, content){
222 $(element).html(content);
223 },
224 gettextContent:function(element)
225 {
226 return $(element).html();
227 },
217 }
218 return path;
219 },
220 settextContent : function(element, content){
221 $(element).html(content);
222 },
223 gettextContent:function(element)
224 {
225 return $(element).html();
226 },
228227};
229228
230229var util = {
231 history: [],
232 command: [],
230 history: [],
231 command: [],
233232
234 forEach : function(array, callback) {
235 var i = 0, length = array.length, value;
233 forEach : function(array, callback) {
234 var i = 0, length = array.length, value;
236235
237 if (length) {
236 if (length) {
238237 for (value = array[0]; i < length && callback.call(value, i, value) !== false; value = array[++i]) {
239238 }
240 }
241 },
242 hasChangesPending : function(){
243 return util.history.length > 0;
244 },
245 formUncomplete : function formUnomplete(){
246 return (locName == '' && langName=='' && styleName == '' );
247 },
248
249 makeChanges: function (command, selectedElement) {
250 var poofPosition, poofDiv;
251 util.command = command;
252 switch (util.command.command) {
253 case 'TEXT_UPDATE':
239 }
240 },
241 hasChangesPending : function(){
242 return util.history.length > 0;
243 },
244 formUncomplete : function formUnomplete(){
245 return (locName == '' && langName=='' && styleName == '' );
246 },
247
248 makeChanges: function (command, selectedElement) {
249 var poofPosition, poofDiv;
250 util.command = command;
251 switch (util.command.command) {
252 case 'TEXT_UPDATE':
254253 DOM.settextContent(util.command.element, util.command.data);
255254 break;
256 case 'IMAGE_DELETE':
255 case 'IMAGE_DELETE':
257256 $(selectedElement).hide();
258257 break;
259 case 'IMAGE_SRC_UPDATE':
258 case 'IMAGE_SRC_UPDATE':
260259 imageMatcher = new RegExp("(\\d+)x(\\d+),(.+)").exec(util.command.data);
261260 imageWidth = imageMatcher[1];
262261 imageHeight = imageMatcher[2];
263262 imageSrc = imageMatcher[3];
264263
265264 if (imageSrc && util.command.element.src != imageSrc) {
266 util.command.element.src = imageSrc;
265 util.command.element.src = imageSrc;
267266 }
268267 if (imageWidth == 0) {
269 util.command.element.removeAttribute('width');
268 util.command.element.removeAttribute('width');
270269 } else {
271 util.command.element.width = imageWidth;
270 util.command.element.width = imageWidth;
272271 }
273272
274273 if (imageHeight == 0) {
275 util.command.element.removeAttribute('height');
274 util.command.element.removeAttribute('height');
276275 } else {
277 util.command.element.height = imageHeight;
276 util.command.element.height = imageHeight;
278277 }
279278 break;
280279
281 case 'ANCHOR_UPDATE':
280 case 'ANCHOR_UPDATE':
282281 $(util.command.element).attr('href', util.command.data);
283282 break;
284283
285 case 'ANCHOR_CREATE':
284 case 'ANCHOR_CREATE':
286285 anchorElement = DOM.BUILDER.A({ 'href' : util.command.data });
287 console.log(util.command.element);
288286 util.command.element.parentNode.replaceChild(anchorElement, util.command.element);
289287 anchorElement.appendChild(util.command.element);
290288 util.command.previousData = anchorElement;
291289 break;
292290
293 case 'AUDIO_UPDATE':
291 case 'AUDIO_UPDATE':
294292 util.command.element.setAttribute('src', util.command.data);
295293 //pageEditor.showMessage('Audio changed');
296294 break;
297
298 case 'AUDIO_CREATE':
295
296 case 'AUDIO_CREATE':
299297 audioElement = document.createElement('audio');
300298 audioElement.setAttribute("class", "alipi");
301299 audioElement.setAttribute('src',util.command.data);
302300 audioElement.setAttribute('controls','controls');
303301 audioElement.setAttribute('mime-type','audio/ogg');
304 $(audioElement).insertBefore($(selectedElement));
302 $(audioElement).insertBefore($(selectedElement));
305303 util.command.element = audioElement;
306304 break;
307305
308 default:
306 default:
309307 console.error('Unknown util.command:', util.command);
310 }
308 }
311309
312 util.history.push(util.command);
313 },
310 util.history.push(util.command);
311 },
314312
315 undoChanges:function () {
316 var imageElement, command=util.command;
313 undoChanges:function () {
314 var imageElement, command=util.command;
317315
318 if (util.hasChangesPending()) {
316 if (util.hasChangesPending()) {
319317 command = util.history.pop();
320318 switch (command.command) {
321319 case 'TEXT_UPDATE':
322 command.element.innerHTML = command.previousData;
323 break;
320 command.element.innerHTML = command.previousData;
321 break;
324322
325323 case 'DELETE':
326 DOM.restoreStyleProperty(command.element, 'display', '');
327 break;
324 DOM.restoreStyleProperty(command.element, 'display', '');
325 break;
328326
329327 case 'IMAGE_SRC_UPDATE':
330 command.element.src = command.previousData.src;
331 if (command.previousData.size.width) {
332 command.element.width = command.previousData.size.width;
333 } else {
334 command.element.removeAttribute('width');
335 }
336 if (command.previousData.size.height) {
337 command.element.height = command.previousData.size.height;
338 } else {
339 command.element.removeAttribute('height');
340 }
341 break;
342
328 command.element.src = command.previousData.src;
329 if (command.previousData.size.width) {
330 command.element.width = command.previousData.size.width;
331 } else {
332 command.element.removeAttribute('width');
333 }
334 if (command.previousData.size.height) {
335 command.element.height = command.previousData.size.height;
336 } else {
337 command.element.removeAttribute('height');
338 }
339 break;
340
343341 case 'AUDIO_CREATE':
344 $(command.element).remove();
345 break;
342 $(command.element).remove();
343 break;
346344 case 'ANCHOR_UPDATE':
347 command.element.setAttribute('href', command.previousData);
348 break;
345 command.element.setAttribute('href', command.previousData);
346 break;
349347
350348 case 'ANCHOR_CREATE':
351 command.previousData.parentNode.replaceChild(command.element, command.previousData);
352 break;
349 command.previousData.parentNode.replaceChild(command.element, command.previousData);
350 break;
353351 case 'IMAGE_DELETE':
354 $(command.element).show();
355 break;
352 $(command.element).show();
353 break;
356354 default:
357 console.error('Unknown command:', command);
355 console.error('Unknown command:', command);
358356 }
359357 pageEditor.cleanUp(pageEditor.event.target);
360 } else {
361 }
362 },
363 checkHistoryChanges: function()
364 {
365 if(util.hasChangesPending())
366 {
358 } else {
359 }
360 },
361 checkHistoryChanges: function()
362 {
363 if(util.hasChangesPending())
364 {
367365 $('#undo-button').attr('disabled',false);
368366 $('#publish-button').attr('disabled',false);
369 }
370 else{
367 }
368 else{
371369 $('#undo-button').attr('disabled',true);
372370 $('#publish-button').attr('disabled',true);
373 }
374 },
371 }
372 },
375373
376 publish:function (){
377 var result;
378 if ($('#loc-select').val() == '' || $('#lang-select').val() == '' || $('#auth-select').val() == '' || ($('#your-check').attr('checked') == undefined && $('#our-check').attr('checked') == undefined )) {
374 publish:function (){
375 var result;
376 if ($('#loc-select').val() == '' || $('#lang-select').val() == '' || $('#auth-select').val() == '' || ($('#your-check').attr('checked') == undefined && $('#our-check').attr('checked') == undefined )) {
379377 alert("please furnish all the details");
380 } else {
378 } else {
381379 if($('#your-check').attr('checked') != undefined)
382380 {
383 localStorage.myContent = util.buildDataString();
384 window.location.href = "http://dev.a11y.in/test.html";
381 localStorage.myContent = util.buildDataString();
382 window.location.href = "http://dev.a11y.in/test.html";
385383 }
386384 else{
387 $(function(){
388 $( "#targetoverlay" ).dialog('close');
389 $('#pub_overlay').slideUp();
390 $('#element_edit_overlay').hide();
391// $('#icon_on_overlay').slideUp();
392 // $( "#success-dialog" ).dialog({
393 // modal: true,
394 // });
395 var success_template = '<div id="success-dialog" title="Posting your changes" class="alipi ui-widget-header ui-corner-all" '+
396 '<p style="color:#aaa"><b>Please wait !!!</b></p><p style="color:#aaa">Your contribution is being posted</p></div>';
397 $('body').append(success_template);
398 $(function() {
399 $( "#success-dialog" ).dialog({
400 modal: true,
385 $(function(){
386 $( "#targetoverlay" ).dialog('close');
387 $('#pub_overlay').slideUp();
388 $('#element_edit_overlay').hide();
389 // $('#icon_on_overlay').slideUp();
390 // $( "#success-dialog" ).dialog({
391 // modal: true,
392 // });
393 var success_template = '<div id="success-dialog" title="Posting your changes" class="alipi ui-widget-header ui-corner-all" '+
394 '<p style="color:#aaa"><b>Please wait !!!</b></p><p style="color:#aaa">Your contribution is being posted</p></div>';
395 $('body').append(success_template);
396 $(function() {
397 $( "#success-dialog" ).dialog({
398 modal: true,
399 });
400 });
401401 });
402 });
403 });
404 $.ajax({
405 url: 'http://dev.a11y.in/test',
406 type: "POST",
407 data : util.buildDataString()+'&title='+encodeURIComponent(document.title)
408 }).done(function(){
409 window.location.reload();
410 });
402 $.post(config.sweet+'/add', {data : JSON.stringify(util.buildDataString())},
403 function(data){
404 data = JSON.parse(data);
405 for(var i in data){
406 $.post(config.deploy+'/askSWeeT',{'id':data[i]['id']},function(){
407 console.log("success!!");});
408 }
409 }); //+'&title='+encodeURIComponent(document.title)
410// }).done(function(){
411 // console.log("test");
412 //window.location.reload();
413// });
411414 }
412 }
413 },
414
415 buildDataString : function (){
416 var check_xpath = [], temp_history = [], index = [];
417 for(x=0; x<util.history.length; x++) {
415 }
416 },
417
418 buildDataString : function (){
419 var check_xpath = [], temp_history = [], index = [];
420 for(x=0; x<util.history.length; x++) {
418421 check_xpath.push(util.history[x].xpath);
419 }
420 for(i=0; i<check_xpath.length-1; i++) {
422 }
423 for(i=0; i<check_xpath.length-1; i++) {
421424 for(j=i+1; j<check_xpath.length; j++) {
422 if ((check_xpath[i] == check_xpath[j]) && (util.history[i].elementType == util.history[j].elementType)) {
423 index.push(i);
424 }
425 if ((check_xpath[i] == check_xpath[j]) && (util.history[i].elementType == util.history[j].elementType)) {
426 index.push(i);
427 }
425428 }
426 }
427 if (index.length > 0) {
429 }
430 if (index.length > 0) {
428431 for (var z=0; z<index.length; z++) {
429 delete util.history[index[z]];
432 delete util.history[index[z]];
430433 }
431 }
432
433 for (var x=0; x<util.history.length; x++) {
434 }
435
436 for (var x=0; x<util.history.length; x++) {
434437 if (util.history[x] != undefined) {
435 temp_history.push(util.history[x]);
438 temp_history.push(util.history[x]);
436439 }
437 }
440 }
438441
439 util.history = temp_history;
440 var command = util.command, buffer;
441 buffer = new StringUtil.StringBuffer();
442 util.forEach(util.history, function(index, command) {
443 buffer.append('###'); //separates the commands
444 buffer.append('about='); //url=about //removed '&' on purpose
445 buffer.append(window.location.search.split('=')[1]);
446 buffer.append('&lang=');//lang
447 buffer.append(encodeURIComponent($('#lang-select').val()));
448 buffer.append('&location=');//location
449 buffer.append(encodeURIComponent($('#loc-select').val()));
450 buffer.append('&style=');//style
451 buffer.append(encodeURIComponent($('#style-select').val()));
452 buffer.append('&blog='); //blog where to post
453 buffer.append(encodeURIComponent("blog"));
454 buffer.append('&elementtype='); // text, audio, img
455 buffer.append(encodeURIComponent(command.elementType));
456 buffer.append('&xpath=');//xpath
457 buffer.append(encodeURIComponent(command.xpath));
458 buffer.append('&data='); //data
459 buffer.append(encodeURIComponent(command.data));
460 buffer.append('&author='); //author
461 if ($('#auth-select').val() == '' || $('#auth-select').val() == /\S/) {
462 buffer.append(encodeURIComponent('Anonymous'));
463 } else {
464 buffer.append(encodeURIComponent($('#auth-select').val()));
465 }
466 });
467 return buffer.toString().substring(3);
468 },
442 util.history = temp_history;
443 var command = util.command, buffer;
444 // buffer = new StringUtil.StringBuffer();
445
446 var buff = [];
447 util.forEach(util.history, function(index, command) {
448 var dict = {};
449 dict['type'] = 1; //TYPE refers to the sweet type. The application says the type, 1 is re-narration.
450 dict['about'] = window.location.search.split('=')[1];
451 dict['lang'] = $('#lang-select').val();
452 dict["location"] = $('#loc-select').val();
453 dict["style"] = $('#style-select').val();
454 dict["blog"] = "blog";
455 dict["elementtype"] = command.elementType;
456 dict["xpath"] = command.xpath;
457 dict["data"] = command.data;
458 if ($('#auth-select').val() == '' || $('#auth-select').val() == /\S/) {
459 dict["author"] = "Anonymous";
460 } else {
461 dict["author"] = $('#auth-select').val();
462 }
463 buff.push(dict);
464
465 // buffer.append('###'); //separates the commands
466 // buffer.append('about='); //url=about //removed '&' on purpose
467 // buffer.append(window.location.search.split('=')[1]);
468 // buffer.append('&lang=');//lang
469 // buffer.append(encodeURIComponent($('#lang-select').val()));
470 // buffer.append('&location=');//location
471 // buffer.append(encodeURIComponent($('#loc-select').val()));
472 // buffer.append('&style=');//style
473 // buffer.append(encodeURIComponent($('#style-select').val()));
474 // buffer.append('&blog='); //blog where to post
475 // buffer.append(encodeURIComponent("blog"));
476 // buffer.append('&elementtype='); // text, audio, img
477 // buffer.append(encodeURIComponent(command.elementType));
478 // buffer.append('&xpath=');//xpath
479 // buffer.append(encodeURIComponent(command.xpath));
480 // buffer.append('&data='); //data
481 // buffer.append(encodeURIComponent(command.data));
482 // buffer.append('&author='); //author
483 // if ($('#auth-select').val() == '' || $('#auth-select').val() == /\S/) {
484 // buffer.append(encodeURIComponent('Anonymous'));
485 // } else {
486 // buffer.append(encodeURIComponent($('#auth-select').val()));
487 // }
488 });
489 // return buffer.toString().substring(3);
490
491 return buff;
492 },
469493};
470494
471495var manager = {
472 recordText:function (selectedElement) {
473 var prevData = $(selectedElement).html();
474 var command = {
496 recordText:function (selectedElement) {
497 var prevData = $(selectedElement).html();
498 var command = {
475499 command : 'TEXT_UPDATE',
476500 element : selectedElement,
477501 url : window.location.href,
503503 elementType : 'text',
504504 data : DOM.gettextContent($('#editor')),
505505 previousData : prevData
506 };
507 util.makeChanges(command, selectedElement);
508 },
509 recordAudio:function(selectedElement){
510 var command = {
511 command : 'AUDIO_CREATE',
512 element : selectedElement,
513 url : window.location.href,
514 xpath : DOM.getXpath(selectedElement),
515 elementType: 'audio/ogg',
516 data : url,
517 previousData : ''
518
519 };
520 util.makeChanges(command,selectedElement);
521 },
522 deleteElement : function(selectedElement) {
523 var command = {
506 };
507 util.makeChanges(command, selectedElement);
508 },
509 recordAudio:function(selectedElement){
510 var command = {
511 command : 'AUDIO_CREATE',
512 element : selectedElement,
513 url : window.location.href,
514 xpath : DOM.getXpath(selectedElement),
515 elementType: 'audio/ogg',
516 data : url,
517 previousData : ''
518
519 };
520 util.makeChanges(command,selectedElement);
521 },
522 deleteElement : function(selectedElement) {
523 var command = {
524524 command : 'DELETE',
525525 element : selectedElement,
526526 url : '',
529529 xpath : '',
530530 data : '',
531531 previousData : ''
532 };
533 util.makeChanges(command, selectedElement);
534 },
535 recordImage: function(selectedElement, url)
536 {
537 var command = {
532 };
533 util.makeChanges(command, selectedElement);
534 },
535 recordImage: function(selectedElement, url)
536 {
537 var command = {
538538 command : 'IMAGE_SRC_UPDATE',
539539 element : selectedElement,
540540 elementType : 'image',
542542 url : window.location.href,
543543 data : new StringUtil.StringBuffer().append(selectedElement.width).append('x').append(selectedElement.height).append(',').append(url).toString(),
544544 previousData : {
545 'src' : selectedElement.src,
546 'size' : { width: selectedElement.width, height: selectedElement.height }
545 'src' : selectedElement.src,
546 'size' : { width: selectedElement.width, height: selectedElement.height }
547547 }
548 };
549 util.makeChanges(command, selectedElement);
550 },
551 deleteImage : function(selectedElement) {
552 var command = {
548 };
549 util.makeChanges(command, selectedElement);
550 },
551 deleteImage : function(selectedElement) {
552 var command = {
553553 command : 'IMAGE_DELETE',
554554 element : selectedElement,
555555 url : window.location.href,
558558 xpath : '',
559559 data : '',
560560 previousData : {
561 'src' : selectedElement.src,
562 'size' : { width: selectedElement.width, height: selectedElement.height }
561 'src' : selectedElement.src,
562 'size' : { width: selectedElement.width, height: selectedElement.height }
563563 }
564 };
565 util.makeChanges(command, selectedElement);
566 },
564 };
565 util.makeChanges(command, selectedElement);
566 },
567567
568568};
569569//Implementing the class for doing StringBuffer.
570570var StringUtil = StringUtil || {};
571571(function(StringUtil){
572 StringUtil.StringBuffer = function StringBuffer() {
573 var buffer = [];
574 this.append = function append(string) {
572 StringUtil.StringBuffer = function StringBuffer() {
573 var buffer = [];
574 this.append = function append(string) {
575575 buffer.push(string);
576576 return this;
577 };
577 };
578578
579 this.toString = function toString() {
579 this.toString = function toString() {
580580 return buffer.join('');
581 };
582 };
581 };
582 };
583583})(StringUtil);