﻿var _xmlHeader = "<?xml version='1.0' encoding='utf-8'?><?xml-stylesheet type='text/xsl' href='CruiseSample.xsl'?>";

var _ua = navigator.userAgent.toLowerCase();
var _isFirefox = null != _ua.match(/firefox/i);
var _isSafari = null != _ua.match(/safari/i);
var _isInternetExplorer = null != _ua.match(/msie/i);

function SupportsCopy() {
	return _isFirefox || _isInternetExplorer;
}

function xLoadXMLData(xmlData) {
    var xmlDoc;

    if (window.ActiveXObject) {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(xmlData);
        return xmlDoc;
    }
    else if (document.implementation && document.implementation.createDocument) {
        xmlDoc = document.implementation.createDocument("", "", null);

        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xmlData, "text/xml");

        return xmlDoc;
    }
    else {
        return null;
    }
}

function xLoadXMLDocument(xmlFile) {
    var xmlDoc;

    if (window.ActiveXObject) {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.load(xmlFile);
        return xmlDoc;
    }
    else if (document.implementation && document.implementation.createDocument) {
        xmlDoc = document.implementation.createDocument("", "", null);
        xmlDoc.async = false;
        xmlDoc.load(xmlFile);
        return xmlDoc;
    }
    else {
        return null;
    }
}

function xApplyXSLT(xmlDoc, xslDoc) {
    if (window.ActiveXObject) {
        return xmlDoc.transformNode(xslDoc);
    }
    else if (window.XSLTProcessor) {
        var xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xslDoc);
        var outputXHTML = xsltProcessor.transformToDocument(xmlDoc);
        return xXMLDocumentToString(outputXHTML);
    }
}

function xXMLDocumentToString(xmlDoc) {
    if (window.ActiveXObject) {
        return xmlDoc.xml
    }
    else if (XMLSerializer) {
        var serializer = new XMLSerializer();
        return serializer.serializeToString(xmlDoc);
    }
}

function showContent(contentType, text) {
	var popupWindow = window.open(contentType, contentType, "width=768,height=800");
	var output = "<textarea style='width:100%; height:100%;'>" + text + "</textarea>";
	popupWindow.document.write(output);
}

function xCopy(htmlData, textData) {
    try {
        var copyDiv = document.getElementById('copyDiv');
        copyDiv.innerHTML = htmlData;

        if (document.selection) {
            var range = document.selection.createRange();
            range.moveToElementText(copyDiv);
            range.select();
            range.execCommand("Copy");
            return true
        }
        else {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

            var htmlstring = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            if (!htmlstring) return false;
            htmlstring.data = htmlData;

            var asText = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            if (!asText) return false;
            asText.data = textData;

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return false;

            trans.addDataFlavor("text/html");
            trans.setTransferData("text/html", htmlstring, htmlData.length * 2);

            trans.addDataFlavor("text/unicode");
            trans.setTransferData("text/unicode", asText, textData.length * 2);

            var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
            if (!clipboard) return false;

            clipboard.setData(trans, null, Components.interfaces.nsIClipboard.kGlobalClipboard);

            return true;
        }
    }
    catch (err) {
    }
}

function GetViewport() {
    var viewportwidth;
    var viewportheight;
    var scrolltop;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof window.innerWidth != 'undefined') 
    {   
        viewportwidth = window.innerWidth;
        viewportheight = window.innerHeight;
        scrolltop = window.pageYOffset;
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) 
     {
         viewportwidth = document.documentElement.clientWidth;
         viewportheight = document.documentElement.clientHeight;
         scrolltop = document.documentElement.scrollTop;
    }

    // older versions of IE

    else 
    {
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
        viewportheight = document.getElementsByTagName('body')[0].clientHeight;
        scrolltop = document.getElementsByTagName('body')[0].scrollTo;
    }
    
    var viewport = new Object();
    viewport.Height = viewportheight;
    viewport.Width = viewportwidth;
    viewport.ScrollTop = scrolltop;
    //alert("Height: " + viewportheight);
    //alert("Width: " + viewportwidth);
    //alert("ScrollTop: " + scrolltop);    
    return viewport;

}

function MapContentSourceToHTMLXSLFile(contentSource) {
    return "CopyXSL/" + contentSource + ".xsl";
}

function MapContentSourceToTextXSLFile(contentSource) {
    return "CopyXSL/" + contentSource + "Text.xsl";
}

function ReplaceAll(textData, toReplace, replacement) {
    while (textData.indexOf(toReplace) > -1) {
        textData = textData.replace(toReplace, replacement);
    }

    return textData;
}

function CleanUpTextData(rawTextData) {
    // The output of an XSL needs to be a XML doc
    // Now remove the minimal markup that we used to make the raw text an XML
    var textData = rawTextData.replace('<?xml version="1.0" encoding="UTF-16"?>', '');
    textData = textData.replace('<?xml version="1.0" encoding="UTF-8"?>', '');
    textData = textData.replace("<root>", "");
    textData = textData.replace("</root>", "");

    // Remove extra blanks
    var textDataBuffer = "";

    var previousChar = '\0';

    for (var i = 0; i < textData.length; i++) {
        var nextChar = textData.charAt(i);

        // Convert tabs to spaces as we go
        if (nextChar == '\x09') {
            nextChar = '\x20';
        }

        if ((nextChar != '\x20') || (previousChar > '\x20')) {
            textDataBuffer += nextChar;
        }

        previousChar = nextChar;
    }

    textData = textDataBuffer;

    // Replace identities we have encountered      
    textData = ReplaceAll(textData, "&amp;", "&");
    textData = ReplaceAll(textData, "&gt;", ">");
    textData = ReplaceAll(textData, "&lt;", "<");
    textData = ReplaceAll(textData, "&copy;", "\xA9");

    // Replace runaway linefeeds
    textData = ReplaceAll(textData, "\r\n\r\n\r\n", "\r\n\r\n");

    // Do not start with a double linefeed
    // startsWith not recognized as built-in on Firefox
    if (textData.indexOf("\r\n\r\n") == 0) {
        textData = textData.replace("\r\n\r\n", "");
    }


    // In fact to don't start with a linefeed.
    // startsWith not recognized as built-in on Firefox
    if (textData.indexOf("\r\n") == 0) {
        textData = textData.replace("\r\n\r\n", "");
    }


    // Get ride of dumb linefeeds between a ':' and the item that follows
    textData = ReplaceAll(textData, ": \r\n", ": ");
    textData = ReplaceAll(textData, ":\r\n", ":");

    return textData;
}

function BuildRows(rawTextData) {
    // Remove extra blanks
    var rowStart = rawTextData.indexOf("<row>");
    var rowEnd = rawTextData.indexOf("</row>");

    var beforeRow = "";
    var rowContents = "";
    var afterRow = "";

    if (rowStart > -1) {
        beforeRow = rawTextData.substring(0, rowStart - 1);

        if (rowEnd > -1) {
            rowContents = rawTextData.substring(rowStart + 5, rowEnd - 1);
            rowContents = ReplaceAll(rowContents, "\r\n", " ");
        }
        else {
            rowContents = rawTextData.substring(rowStart + 5);
        }
    }
    else {
        return rawTextData;
    }

    if ((rowEnd > -1) && (rawTextData.length > (rowEnd + 7))) {
        afterRow = rawTextData.substring(rowEnd + 6);
        afterRow = "\r\n" + BuildRows(afterRow);
    }

    return beforeRow + rowContents + afterRow;
}

function CopyContent(text, contentSource) {
    // Uncomment the line below to see the XML
    // showContent("XML", text);	
    var xmlDoc = xLoadXMLData(text);

    var xslHTMLDoc = xLoadXMLDocument(MapContentSourceToHTMLXSLFile(contentSource));
    var xslTextDoc = xLoadXMLDocument(MapContentSourceToTextXSLFile(contentSource));

    var htmlData = xApplyXSLT(xmlDoc, xslHTMLDoc);
    var textData;

    if (_isFirefox) 
    {
        textData = xApplyXSLT(xmlDoc, xslTextDoc);
        textData = BuildRows(textData);

        // The output of an XSL needs to be a XML doc
        // Now remove the minimal markup that we used to make the raw text an XML
        textData = CleanUpTextData(textData);

		// remove markup from HTML content, since Firefox ignores disable-output-escaping
        var oXmlFromHtml = xLoadXMLData(htmlData);
        var htmlContentNodes = oXmlFromHtml.getElementsByClassName("htmlContent");

        for (var i = 0; i < htmlContentNodes.length; i++) {
        	var textNode = htmlContentNodes[i].childNodes[0];
        	if (null != textNode) {
        		htmlContentNodes[i].childNodes[0].nodeValue = textNode
        			.nodeValue
					.replace(/\<br ?\/\>/gi, "\n")              // replace <br/> with newline
        			.replace(/\<li.*>/gi, "\n * ")              // replace <li> with * (content) newline
        			.replace(/\<style[^\<]*\<\/style\>/, "")    // strip style blocks
        			.replace(/&nbsp;/gi, "")                    // strip spaces
        			.replace(/\<[^\>]*>/gi, "");                // strip all other tags
        	}
        }

        htmlData = xXMLDocumentToString(oXmlFromHtml);
    }
    
    xCopy(htmlData, textData);
}

