
// mechanics of calling the browser

function mashmaker_call_ff(action,data,cbid){
  try{
    var datastr = makeJSONString(data);
    var evt = document.createEvent("Events");
    document.body.setAttribute("mm_datastr",datastr);
    document.body.setAttribute("mm_cbid",cbid);
    document.body.setAttribute("mm_action",action);
    evt.initEvent("mashmaker", true, false);
    document.body.dispatchEvent(evt);
  }catch(e){
      alert("call failed: "+e.message);
  }
}

function mashmaker_call_ie(action,data,cbid){
	alert("call ie - about to JSON");
	var datastr = makeJSONString(data);
	alert("call ie - done JSON");
	var event = document.createEventObject();
	event.mashmaker_action = action;
	event.mashmaker_body = datastr;
    event.mashmaker_callback = cbid;
    alert("call_ie: "+action+"("+datastr+")");
	document.body.fireEvent("onmousedown",event);
}

// needed for IE
function mashmaker_eval(str){
    eval(str);
}

if(document.createEvent){
	mashmaker_call = mashmaker_call_ff;
}else{
	mashmaker_call = mashmaker_call_ie;
}


// callbacks

var mashmaker_callbacks = {};
var mashmaker_cbid = 1;
function mashmaker_cb_call(action,data,callback){
	var cbid;
    if(callback){
        cbid = mashmaker_cbid++;
        mashmaker_callbacks[cbid] = callback;
    }else{
        cbid = -1;
    }
    mashmaker_call(action,{args:data,cbid:cbid},cbid);
}
function mashmaker_callback(cbid,data){
	var callback = mashmaker_callbacks[cbid];
//	delete mashmaker_callbacks[cbid];
	callback(data);
}


// functions the widget can use to call Mash Maker
//			(if I haven't implemented something, then it's ok to change it, since they can't be using it)

function mashmaker_done(){mashmaker_call("done","done");}
function mashmaker_itemDone(id){mashmaker_call("itemdone",{id:id})}
function mashmaker_hideNode(id){mashmaker_call("hidenode",{id:id})}


// updated API functions
function mashmaker_addProp(id,name,data,icon){
    mashmaker_call("addprop",{id:id,name:name,data:data,icon:icon});
}

function mashmaker_addText(id,name,icon,text,callback){
    mashmaker_cb_call("addtext",{id:id,name:name,icon:icon,text:text},callback);
}

function mashmaker_addError(id,name,icon,text,callback){
    mashmaker_cb_call("adderror",{id:id,name:name,icon:icon,text:text},callback);
}

function mashmaker_addVis(id,name,icon,url,opts,extra,callback){
    mashmaker_cb_call("addvis",{id:id,name:name,icon:icon,url:url,opts:opts,extra:extra},callback);
}

function mashmaker_addRequest(id,icon,desc,callback){
    mashmaker_cb_call("addrequest",{id:id,icon:icon,desc:desc},callback);
}

function mashmaker_removeRequest(id){
    mashmaker_call("removerequest",{id:id});
}

function mashmaker_getData(id,path,props,all,callback){
    mashmaker_cb_call("getdata",{id:id,path:path,props:props,all:all},callback);
}

function mashmaker_hasPaths(id,paths,callback){
    mashmaker_cb_call("haspaths",{id:id,paths:paths},callback);
}

// find all paths from the root path to items meeting the given requirements
// and return them as a list of path strings
function mashmaker_getPaths(rootpath,requirements,callback){
    mashmaker_cb_call("getpaths",{rootpath:rootpath,reqs:requirements},callback);
}

// find all properties for elements in the given path (property paths in future)
function mashmaker_getProps(id,path,callback){
    mashmaker_cb_call("getprops",{id:id,path:path},callback);
}

function mashmaker_getAllProps(path,callback){
    mashmaker_cb_call("getallprops",{path:path},callback);
}

function mashmaker_subProps(prop,callback){
    mashmaker_cb_call("subprops",{prop:prop},callback);
}

function mashmaker_getSourceInfo(id,callback){
    mashmaker_cb_call("getsourceinfo",{id:id},callback);
}


// util functions

function mashmaker_addTextProp(id,name,text,callback){
    mashmaker_addProp(id,name,{text:text});
    mashmaker_addText(id,name,null,text,callback);
}

// set the height of the iframe - typically based on content size
function mashmaker_setHeight(height){
	mashmaker_call("setheight",{height:height});
}
function mashmaker_setItemHeight(id,height){
	mashmaker_call("setitemheight",{id:id,height:height});
}

function mashmaker_alert(message){
	mashmaker_call("alert",message);
}
function mashmaker_select(id){mashmaker_call("select",id);}
function mashmaker_switchto(id){mashmaker_call("switchto",id);}
function mashmaker_setpagedata(nodes){
	alert("setpagedata");
	mashmaker_call("setpagedata",nodes);
}

// SECURE - these functions can only be used by trusted code, or for extractors
// marked as holding "public" data
// If the data is marked as "cached public" then data requests can be satisfied using 
// the cache
function mashmaker_fetchLinkedPageRaw(id,callback){mashmaker_cb_call("fetchlinkedpageraw",id,callback)}
function mashmaker_fetchLinkedPageData(id,callback){mashmaker_cb_call("fetchlinkedpagedata",id,callback)}

// VERY SECURE - only by highly trusted code

function mashmaker_fetchUrlData(url,callback){
    mashmaker_cb_call("fetchurldata",{url:url},callback);
}

// extract data from this particular iframe (used by Paste to allow data mods)
function mashmaker_fetchIframeData(frameid,callback){mashmaker_cb_call("fetchiframedata",{frameid:frameid},callback)}

// adjust the iframe so that only the indicated ids are shown
function mashmaker_trimIframe(frameid,goodids){
    mashmaker_call("trimiframe",{frameid:frameid,goodids:goodids});
}

function mashmaker_filterIframeDisplay(ids,callback){
    mashmaker_cb_call("filteriframedisplay",{ids:ids},callback);
}



// new stuff
function mashmaker_getUrlExtractor(url,callback){
    mashmaker_cb_call("geturlextractor",{url:url},callback);
}
function mashmaker_getUrlArgHandler(url,callback){
    mashmaker_cb_call("geturlarghandler",{url:url},callback);
}
function mashmaker_setSettingsHeight(height){
    mashmaker_call("setsettingsheight",height);
}
function mashmaker_setName(name){
    mashmaker_call("setname",{name:name});
}
function mashmaker_setIcon(icon){
    mashmaker_call("seticon",{icon:icon});
}
function mashmaker_removeArtifacts(){
    mashmaker_call("removeartifacts",{});
}
function mashmaker_removeText(id,name){
    mashmaker_call("removetext",{id:id,name:name});
}

function mashmaker_removeProp(id,name){
    mashmaker_call("removeprop",{id:id,name:name});
}

function mashmaker_removeVis(id,name){
    mashmaker_call("removevis",{id:id,name:name});
}


function mashmaker_setVisible(visible){
    mashmaker_call("setvisible",{visible:visible});
}
function mashmaker_msg(str){
    mashmaker_call("msg",{msg:str});
}
function mashmaker_editArgHandler(url){
    mashmaker_call("editarghandler",{url:url});
}
//function mashmaker_widget_init(args){
//    mashmaker_widget(args);
//}
function mashmaker_callWidget(action,data){
    mashmaker_call("callwidget",{action:action,data:data});
}
function mashmaker_callIframe(action,data,frameid){
    mashmaker_call("calliframe",{action:action,data:data,frameid:frameid});
}

// prefs

// request that the given prefs panel be displayed
// "on" if it should be shown by default - used if we aren't sure we have guessed right
function mashmaker_addPrefs(url,extra,on){
    mashmaker_call("addprefs",{url:url,extra:extra});
}

// pass settings up to Mash Maker for storage and communication to the main widget
function mashmaker_setSettings(settings){
    mashmaker_call("setsettings",{settings:settings});
}

// other functions

function mashmaker_addPath(base,part){
    if(base){
        return base + "/" + part;
    }else{
        return part;
    }
}

function mashmaker_getMultiPaths(rootpaths,reqs,callback){
    if(rootpaths.length == 0){
        callback([]);
    }else{
        var first = rootpaths.pop();
        mashmaker_getPaths(first,reqs,function(firstpaths){
           mashmaker_getMultiPaths(rootpaths,reqs,function(otherpaths){
               callback(otherpaths.concat(firstpaths));
           });
        });
    }
}


// local code - may be changed to call out in future

// takes a div to insert a description onto, and the id of the node to describe
//function mashmaker_subwidget(divid,dataid){
//    mashmaker_getData(dataid,"",null,true,function(item){
//
//    });
//}

// Deprecated - get all elements from some data
function mashmaker_elements(root){
    var items = [];
    for(var i in root.props){
        var prop = root.props[i];
        if(prop.items){
            for(var j in prop.items){
                items.push(prop.items[j]);
            }
        }
    }
    return items;
}

var mashmaker = {
    addError: function(id,name,icon,text,link,callback){
        mashmaker_cb_call("adderror",{id:id,name:name,icon:icon,text:text,link:link},callback);
    },

    addIcon: function(id,icon,desc,callback){mashmaker_addRequest(id,icon,desc,callback)},
    addVis: function(id,name,icon,url,opts,extra,callback){mashmaker_addVis(id,name,icon,url,extra,callback)},
    addText: mashmaker_addText,
    addProp: mashmaker_addProp,
    done: mashmaker_done,
    itemDone: mashmaker_itemDone,
    getData: function(id,path,props,all,callback){
        mashmaker_cb_call("getdatamulti",{id:id,path:path,props:props,all:all},callback);
    },
    getPaths: mashmaker_getPaths,
    select: mashmaker_select,
    setHeight: mashmaker_setHeight,
    setSettings: mashmaker_setSettings,
    callIframe: mashmaker_callIframe,

    openSettings: function(){
        mashmaker_call("opensettings",{});        
    },

    removeIcon: mashmaker_removeRequest,
    removeAll: mashmaker_removeArtifacts,
    removeText: mashmaker_removeText,
    removeProp: mashmaker_removeProp,

    addTextProp: mashmaker_addTextProp,
    callVis: function(id,name,data){
        // TODO: fix this
        mashmaker_callIframe("action",data,id);
    },
    callWidget: function(data){
        mashmaker_callWidget("action",data);
    },
    getSourceInfo: mashmaker_getSourceInfo,

    loadIframe: function(id,url,cookies,opts,callback){
        mashmaker_cb_call("loadiframe",{id:id,url:url,cookies:cookies,opts:opts},callback);
    },
    loadUrlData: function(url,cookies,callback){
        mashmaker_cb_call("fetchurldata",{url:url,cookies:cookies},callback);
    },


    setPrivate: function(priv){
        mashmaker_call("setprivate",{priv:priv});
    }
};



// standard JSON code

/*
    json.js
    2007-08-05

    Public Domain
    
    This is a rewritten version of the JSON printer/parser, by Rob Ennals.
    It started out as being the original JSON parser but is now quite different.
    The rewrite was done because the normal JSON parser breaks for...in loops,
    including those used by internal FireFox code.
*/

var json_subs = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


function makeJSONString(obj){
	if(typeof obj.sort == 'function'){
        var a = [],     // The array holding the partial texts.
            i,          // Loop counter.
            l = obj.length,
            v;          // The value to be stringified.


        for (i = 0; i < l; i += 1) {
            v = obj[i];
            switch (typeof v) {
            case 'object':
                if (v) {
                    a.push(makeJSONString(v));
                } else {
                    a.push('null');
                }
                break;

            case 'string':
            case 'number':
            case 'boolean':
                a.push(makeJSONString(v));
            }
        }

// Join all of the member texts together and wrap them in brackets.

        return '[' + a.join(',') + ']';
  }
	switch(typeof obj){
    case 'boolean':
    		return String(obj);
		case 'number':
    	  return isFinite(obj) ? String(obj) : 'null';
    case 'function':
    	  return 'null';
    case 'object':
        var a = [],     // The array holding the partial texts.
            k,          // The current key.
            v;          // The current value.

// Iterate through all of the keys in the object, ignoring the proto chain
// and keys that are not strings.

        for (k in obj) {
            if (typeof k === 'string' &&
                    Object.prototype.hasOwnProperty.apply(obj, [k])) {
                v = obj[k];
                switch (typeof v) {
                case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                    if (v) {
                    		a.push(makeJSONString(k) + ':' + makeJSONString(v));
                    } else {
                        a.push(makeJSONString(k) + ':null');
                    }
                    break;

                case 'string':
                case 'number':
                case 'boolean':
                    a.push(makeJSONString(k) + ':' + makeJSONString(v));

// Values without a JSON representation are ignored.

                }
            }
        }

// Join all of the member texts together and wrap them in braces.

        return '{' + a.join(',') + '}';
    case 'string':

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(obj)) {
                return '"' + obj.replace(/[\x00-\x1f\\"]/g, function (a) {
                    var c = json_subs[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + obj + '"';
        };
}


function parseJSON(str){
   var j;

// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

// We split the first stage into 3 regexp operations in order to work around
// crippling deficiencies in Safari's regexp engine. First we replace all
// backslash pairs with '@' (a non-JSON character). Second we delete all of
// the string literals. Third, we look to see if only JSON characters
// remain. If so, then the text is safe for eval.

    if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(str.
            replace(/\\./g, '@').
            replace(/"[^"\\\n\r]*"/g, ''))) {
// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

			try{
 	  	  j = eval('(' + str + ')');
  	    return j;
    	}catch(e){
    		return null;
    	}
    }

// If the text is not JSON parseable, then a SyntaxError is thrown.

    throw new SyntaxError('parseJSON:' + str);
};
