
if (!sunportal) {
  var sunportal = {};
}

/**
 * Returns a localized string.
 *
 * @param arguments[0] is property name in containerModel.localizedStrings
 * @param arguments[1-n] are runtime values to replace in property value before returning it
 */
sunportal.getLocalizedString = function() {
  var pname = arguments[0];
  var pvalue = containerModel.localizedStrings[pname];
  for (var i=1; i<arguments.length;i++) {
    var j = i-1;
    var re = new RegExp('\\{' + j + '\\}', 'g');
    pvalue = pvalue.replace(re, arguments[i]);
  }
  return pvalue;
}

/**
 * Extracts scripts from passed content and appends to passed node which executes them.
 *
 * @param content HTML content as String
 * @param node node containing scripts
 */
sunportal.executeScripts = function(content, node){
    var data = this.extractScriptsAndStyles(content);
    var rscripts = [];
  
    // get remoteScripts first
    var self = this;
    for(var i = 0; i < data.remoteScripts.length; i++){
        spd.io.bind({
            "url": data.remoteScripts[i],
            "useCash":	this.cacheContent,
            "load":     function(type, scriptStr){
                    spd.lang.hitch(self, rscripts.push(scriptStr));
            },
            "error":    function(type, error){
                    spd.debug("Error downloading remote script:" + data.remoteScripts[i]);
            },
            "mimetype": "text/plain",
            "sync":     true
        });
    }
    
    var scripts = "";
    
    for (var r=0; r < rscripts.length; r++) {
        scripts += rscripts[r];
    }
    for(var i = 0; i < data.scripts.length; i++){
        scripts += data.scripts[i];
    }

    //Add script to the node
    var newScript = document.createElement('script');
    newScript.text = scripts;
    node.appendChild(newScript);        
}

/**
 * Extracts all the script and style elements from passed HTML content.
 * Most of this function code has been derived from Dojo ContentPane widget
 *
 * @param s HTML content as String
 * @returns Extracted script and style elements in an object
 */
sunportal.extractScriptsAndStyles = function (s){
        // fix up paths in data
		var titles = []; var scripts = []; var linkStyles = [];
		var styles = []; var remoteScripts = []; var requires = [];
        // cut out all script tags, push them into scripts array
		match = []; var tmp = [];
		while(match){
			match = s.match(/<script([^>]*)>([\s\S]*?)<\/script>/i);
			if(!match){ break; }
			if(match[1]){
				attr = match[1].match(/src=(['"]?)([^"']*)\1/i);
				if(attr){
					// remove a spd.js or spd.js.uncompressed.js from remoteScripts
					// we declare all files with spd.js as bad, regardless of folder
					var tmp = attr[2].search(/.*(\bdojo\b(?:\.uncompressed)?\.js)$/);
					if(tmp > -1){
						spd.debug("Security note! inhibit:"+attr[2]+" from  beeing loaded again.");
					}else{
						remoteScripts.push(attr[2]);
					}
				}
			}
			if(match[2]){
				// strip out all djConfig variables from script tags nodeValue
				// this is ABSOLUTLY needed as reinitialize djConfig after dojo is initialised
				// makes a dissaster greater than Titanic, update remove writeIncludes() to
				var sc = match[2].replace(/(?:var )?\bdjConfig\b(?:[\s]*=[\s]*\{[^}]+\}|\.[\w]*[\s]*=[\s]*[^;\n]*)?;?|dojo\.hostenv\.writeIncludes\(\s*\);?/g, "");
				if(!sc){ continue; }

				// cut out all spd.require (...) calls, if we have execute 
				// scripts false widgets dont get there require calls
				// does suck out possible widgetpackage registration as well
				tmp = [];
				while(tmp && requires.length<100){
					tmp = sc.match(/dojo\.(?:(?:require(?:After)?(?:If)?)|(?:widget\.(?:manager\.)?registerWidgetPackage)|(?:(?:hostenv\.)?setModulePrefix))\((['"]).*?\1\)\s*;?/);
					if(!tmp){ break;}
					requires.push(tmp[0]);
					sc = sc.replace(tmp[0], "");
				}
				scripts.push(sc);
			}
			s = s.replace(/<script[^>]*>[\s\S]*?<\/script>/i, "");
		}

		// cut out all <link rel="stylesheet" href="..">
		match = [];
		while(match){
			match = s.match(/<link ([^>]*rel=['"]?stylesheet['"]?[^>]*)>/i);
			if(!match){ break; }
			attr = match[1].match(/href=(['"]?)([^'">]*)\1/i);
			if(attr){
				linkStyles.push(attr[2]);
			}
			s = s.replace(new RegExp(match[0]), "");
		}
        
        return {"scripts":scripts,
                "remoteScripts":remoteScripts,
                "styles":styles
        }
}

/**
 * Check for error responses (JSON) in async data response
 * Returns true when response status is FAIL, otherwise returns false
 */
sunportal.hasError = function(data) {
	// TODO: can we avoid this extra eval?
	try {
		var server = eval('(' + data + ')');
	} catch (e) {
		server = data;
	}
	if (server != null && server.response != undefined
						&& server.response.status == 'FAIL') {
		var error = 'Error\n';
		for (n in server.response.messages) {
			if (!server.response.messages.hasOwnProperty(n)) continue;
			error += server.response.messages[n] + '\n';
		}
		alert (error);
		// in case of timeout, reload page so user can re-login
		if (server.response.type == 'TIMEOUT') {
			window.location.reload();
		}
		return true;
	} else {
		return false;
	}
}

/**
 * Sets the height for the iframe element after it's content has loaded
 * Adapted from IFrame SSI script II
 * http://www.dynamicdrive.com/dynamicindex17/iframessi2.htm
 * © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
 * @param frameId is the iframe DOM element
**/
sunportal.resizePortlet = function(frameid) {
    var currentfr=document.getElementById(frameid);
    if (currentfr) {
        //ns6 syntax
        if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) {
	    spd.debug("sunportal.resizePortlet: treating as ns6...");
            //extra height in px to add to iframe in FireFox 1.0+ browsers
            var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
            var extraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0;        
            currentfr.height = currentfr.contentDocument.body.offsetHeight + extraHeight; 
        }
        //ie5+ syntax
        else if (currentfr.Document && currentfr.Document.body.scrollHeight) {
	    spd.debug("sunportal.resizePortlet: treating as ie5+...");
            currentfr.height = currentfr.Document.body.scrollHeight;
        }
        spd.debug("sunportal.resizePortlet:" +frameid + " height=" + currentfr.height);
    }
}

/**
 * create and return an iframe node for insertion
 */
sunportal.createIframe = function(iframeId, url) {   
    var iframeDiv = document.createElement("div");
    var iframe = document.createElement("iframe");
    iframe.setAttribute("src", url, 0);
    iframe.setAttribute("id", iframeId, 0);
    iframe.setAttribute("frameborder", "no", 0);
    iframe.setAttribute("width", "100%", 0)
    iframe.setAttribute("marginwidth", "0", 0);
    iframe.setAttribute("marginheight", "0", 0);
    iframe.setAttribute("vspace", "0", 0);
    iframe.setAttribute("hspace", "0", 0);
    iframe.setAttribute("scrolling", "auto", 0);
    iframe.style.overflow = "auto";
    iframeDiv.appendChild(iframe);
    
    // write a resize image
    // Note: we are writing to innerHTML here because IE seems to require it (ugh).
    var msg = sunportal.getLocalizedString("resize.portlet");
    var resize = document.createElement("div");
    resize.innerHTML = "<div id='" + iframeId + "_resize_image' class='ajaxChannelResize' title='" +
        msg + "' onclick='sunportal.resizePortlet(\"" + iframeId + "\");' />";
    iframeDiv.appendChild(resize);
    return iframeDiv;
}

/**
 * Adjust the channels iframe
 * - resize the channel/portlet
 * - add parents stylesheets to new iframe
 */
sunportal.adjustIframe = function(iframeId) {
    var iframeDoc = document.getElementById(iframeId).contentWindow.document;
    
    // Wait for iframe body to load (recursively call self)
    // confirm body exists (for IE) and innerHTML.length is > 0 (for Firefox)
    if (iframeDoc.body == null || iframeDoc.body.innerHTML.length == 0) {
        window.setTimeout("sunportal.adjustIframe(\"" + iframeId + "\");", 10);
        return;
    }

    // resize the iframe now
    sunportal.resizePortlet(iframeId);

    /* add parents stylesheets to new iframe
     *
     * Technically we shouldn't do this, but we need to propagate themes
     * to portlets using iframes.
     */

    // use cloneNode for Firefox, but create new link nodes for IE.
    if (navigator.userAgent.indexOf("Firefox") > 0) {
        var clone = true;
    } else {
        var clone = false;
    }

    var links = document.getElementsByTagName("link");
    for (i=0; i < links.length; i++){
      if (links[i].getAttribute("rel") == "stylesheet") {
          if (clone) {
              iframeDoc.getElementsByTagName('head')[0].appendChild(links[i].cloneNode(true));
          } else {
              var l = iframeDoc.createElement("link");
              l.setAttribute("rel", "stylesheet", 0);
              l.setAttribute("href", links[i].getAttribute("href"), 0);
              l.setAttribute("media", links[i].getAttribute("media"), 0);
              iframeDoc.body.appendChild(l);
          }
      }
    }
}
