/*************************************************************************
 *
 * ADOBE CONFIDENTIAL
 * ___________________
 *
 *  Copyright 2015 Adobe Systems Incorporated
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 **************************************************************************/

/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, maxerr: 50, continue: true */
/*global dw, AssetInfo, DWfile */

//Bootstrap assets

var xmlLocation = "/Shared/LiveEdit/Extensions/ResponsiveLayout/assets/resource/";
var xmlFile_1 = "bootstrap.xml";

var bootstrapRoot = "Shared/LiveEdit/ResponsiveAssets/bootstrap/";
var bundlePath = "bundle/";
var BootstrapJsFile = "bootstrap.js";
var cssVersion;
var BootstrapAltJsFile = "bootstrap-3.3.5.js";
var BootstrapJsPath = bootstrapRoot + bundlePath + "js/" + BootstrapJsFile;
var BootstrapCssFile = "bootstrap.css";
var BootstrapAltCssFile = "bootstrap-3.3.5.css";
var BootstrapCssPath = bootstrapRoot + bundlePath + "css/" + BootstrapCssFile;
var BootstrapJqueryFile = "jquery-1.11.3.min.js";
var jQueryVersion = "1.11.3";
var supportedBootstrapJqueryFiles = ["jquery-1.11.3.min.js", "jquery-1.11.2.min.js"];
var supportedJqueryVersions = ["1.11.2", "1.11.3"];
var BootstrapJqueryPath = bootstrapRoot + bundlePath + "js/" + BootstrapJqueryFile;

var GlyphFontFile1 = "glyphicons-halflings-regular.eot";
var GlyphFontPath1 = bootstrapRoot + bundlePath + "fonts/" + GlyphFontFile1;
var GlyphFontFile2 = "glyphicons-halflings-regular.svg";
var GlyphFontPath2 = bootstrapRoot + bundlePath + "fonts/" + GlyphFontFile2;
var GlyphFontFile3 = "glyphicons-halflings-regular.ttf";
var GlyphFontPath3 = bootstrapRoot + bundlePath + "fonts/" + GlyphFontFile3;
var GlyphFontFile4 = "glyphicons-halflings-regular.woff";
var GlyphFontPath4 = bootstrapRoot + bundlePath + "fonts/" + GlyphFontFile4;
var GlyphFontFile5 = "glyphicons-halflings-regular.woff2";
var GlyphFontPath5 = bootstrapRoot + bundlePath + "fonts/" + GlyphFontFile5;

var BootstrapImageFile1 = "MediaObj_Placeholder.png";
var BootstrapImagePath1 = bootstrapRoot + BootstrapImageFile1;
var BootstrapImageFile2 = "Thumbnail_Placeholder.png";
var BootstrapImagePath2 = bootstrapRoot + BootstrapImageFile2;
var BootstrapImageFile3 = "Carousel_Placeholder.png";
var BootstrapImagePath3 = bootstrapRoot + BootstrapImageFile3;
var BootstrapImageFile4 = "ImgResponsive_Placeholder.png";
var BootstrapImagePath4 = bootstrapRoot + BootstrapImageFile4;

//Headlights strings

var RESPONSIVE_HEADLIGHTS = {
    RWD_Category: "RWD",
    RWD_SubCategory: "RWD_Bootstrap",
    RWD_PageConverted: "Bootstrap_PageConverted_ComponentInserted"
};

//functions

function UpdateFileNamesWithAppropriateVersion() {
    "use strict";
    
    if (cssVersion === undefined) {
        var cssFilePath = dw.getUserConfigurationPath() + BootstrapCssPath;
        var str = DWfile.read(cssFilePath);
        if (str) {
            /* comment in Bootstrap.css is of the form Bootstrap v3.3.5 */
            var reg = str.match(/Bootstrap v\d+\.\d+\.\d+/i);
            if (reg.length > 0) {
                cssVersion = reg[0].substr(11);
                BootstrapAltCssFile = "bootstrap-" + cssVersion + ".css";
                BootstrapAltJsFile = "bootstrap-" + cssVersion + ".js";
            }
        }
    }
}

function getBootstrapCss(useAltBootstrap) {
    "use strict";
    var CssAsset = [],
        assetObject = {};
    if (useAltBootstrap) {
        UpdateFileNamesWithAppropriateVersion();
    }
    assetObject.fullPath = BootstrapCssPath;
    assetObject.file = "css/" + (useAltBootstrap ? BootstrapAltCssFile : BootstrapCssFile);
    assetObject.type = "link";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    CssAsset.push(assetObject);

    return (CssAsset);
}

function getBootstrapJsScript(useAltBootstrap) {
    "use strict";
    var JsAsset = [],
        assetObject = {};
    if (useAltBootstrap) {
        UpdateFileNamesWithAppropriateVersion();
    }
    assetObject.fullPath = BootstrapJsPath;
    assetObject.file = "js/" + (useAltBootstrap ? BootstrapAltJsFile : BootstrapJsFile);
    assetObject.type = "javascript";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    JsAsset.push(assetObject);

    return (JsAsset);
}

function getBootstrapJqueryScript() {
    "use strict";
    var JsAsset = [],
        assetObject = {};
    assetObject.fullPath = BootstrapJqueryPath;
    assetObject.file = "js/" + BootstrapJqueryFile;
    assetObject.type = "javascript";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    JsAsset.push(assetObject);

    return (JsAsset);
}

function getBootstrapGlyphFonts() {
    "use strict";
    var FontAsset = [],
        assetObject = {};
    assetObject.fullPath = GlyphFontPath1;
    assetObject.file = "fonts/" + GlyphFontFile1;
    assetObject.type = "";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    FontAsset.push(assetObject);

    assetObject = {};
    assetObject.fullPath = GlyphFontPath2;
    assetObject.file = "fonts/" + GlyphFontFile2;
    assetObject.type = "";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    FontAsset.push(assetObject);

    assetObject = {};
    assetObject.fullPath = GlyphFontPath3;
    assetObject.file = "fonts/" + GlyphFontFile3;
    assetObject.type = "";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    FontAsset.push(assetObject);

    assetObject = {};
    assetObject.fullPath = GlyphFontPath4;
    assetObject.file = "fonts/" + GlyphFontFile4;
    assetObject.type = "";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    FontAsset.push(assetObject);

    assetObject = {};
    assetObject.fullPath = GlyphFontPath5;
    assetObject.file = "fonts/" + GlyphFontFile5;
    assetObject.type = "";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    FontAsset.push(assetObject);

    return (FontAsset);
}

function getBootstrapMediaObjImages() {
    "use strict";
    var ImageAsset = [],
        assetObject = {};
    assetObject.fullPath = BootstrapImagePath1;
    assetObject.file = "images/" + BootstrapImageFile1;
    assetObject.type = "image";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    ImageAsset.push(assetObject);

    return (ImageAsset);
}

function getBootstrapThumbnailImages() {
    "use strict";
    var ImageAsset = [],
        assetObject = {};
    assetObject.fullPath = BootstrapImagePath2;
    assetObject.file = "images/" + BootstrapImageFile2;
    assetObject.type = "image";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    ImageAsset.push(assetObject);

    return (ImageAsset);
}

function getBootstrapCarouselImages() {
    "use strict";
    var ImageAsset = [],
        assetObject = {};
    assetObject.fullPath = BootstrapImagePath3;
    assetObject.file = "images/" + BootstrapImageFile3;
    assetObject.type = "image";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    ImageAsset.push(assetObject);

    return (ImageAsset);
}

function getBootstrapResponsiveImages() {
    "use strict";
    var ImageAsset = [],
        assetObject = {};
    assetObject.fullPath = BootstrapImagePath4;
    assetObject.file = "images/" + BootstrapImageFile4;
    assetObject.type = "image";
    assetObject.useDefaultFolder = false;
    assetObject.documentRelative = false;
    ImageAsset.push(assetObject);

    return (ImageAsset);
}

function populateGlyphFontAssets(assetList) {
    "use strict";
    if (!window.doInsert) {
        return;
    }

    var dom = dw.getDocumentDOM(),
        fontsReq = true,
        links = dom.getElementsByTagName('link'),
        fileName,
        assetInfo,
        fontAssets,
        str,
        i;

    if (dom.isResponsiveFeatureDocument()) {
        if (links) {
            for (i = 0; i < links.length; i += 1) {
                fileName = links[i].href;
                if ((fileName) && (fileName.indexOf(".css") === fileName.length - 4)) {
                    str = fileName.toLowerCase();
                    if ((str.indexOf("bootstrap") > -1) && (str.indexOf("cdn") > -1) && (str.indexOf("http") === 0)) {
                        fontsReq = false;
                        break;
                    }
                }
            }
        }
    }

    if (fontsReq) {
        fontAssets = getBootstrapGlyphFonts();
        //import the font files required for Glyphicons to render
        for (i = 0; i < fontAssets.length; i += 1) {
            assetInfo = new AssetInfo(fontAssets[i].fullPath, fontAssets[i].file, fontAssets[i].type, fontAssets[i].useDefaultFolder, fontAssets[i].documentRelative);
            assetList.push(assetInfo);
        }
    }

    return true;
}

function populateCssAssets(assetList, replaceExistingAssetsInfo) {
    "use strict";

    if (!window.doInsert) {
        return;
    }

    var dom = dw.getDocumentDOM();

    if (!dom) {
        window.doInsert = false;
        return;
    }
    var i = 0,
        links = dom.getElementsByTagName('link'),
        useAltBootstrapName = false,
		replaceExistingCSS = false,
        scripts = dom.getElementsByTagName('script'),
        scriptSrc,
        fileName;
    
    if (links) {
        for (i = 0; i < links.length; i += 1) {
            fileName = links[i].href;
            if ((fileName) && (fileName.indexOf(".css") === fileName.length - 4)) {
                if (fileName.toLowerCase().indexOf("bootstrap") > -1) {
                    replaceExistingCSS = true;
                    if (fileName.toLowerCase().indexOf("cdn") === -1) {
                        useAltBootstrapName = true;
                    }
                    break;
                }
            }
        }
    }

    if (dom && (dom.getDesignViewMode() === "live" || dom.getView() === "code")) {
        if (replaceExistingCSS) {
            dw.popupCommand("InsertBootstrapCSSFile.htm");
            if (!dom.getInsertBootstrapCSS()) {
                window.doInsert = false;
                return;
            } else {
                replaceExistingAssetsInfo.replaceCss = true;
            }
        }
    }

    replaceExistingAssetsInfo.useAltBootstrapName = useAltBootstrapName;
    var assets = getBootstrapCss(useAltBootstrapName),
        assetInfo;

    //import the bootstrap css file.
    for (i = 0; i < assets.length; i += 1) {
        assetInfo = new AssetInfo(assets[i].fullPath, assets[i].file, assets[i].type, assets[i].useDefaultFolder, assets[i].documentRelative);
        assetList.push(assetInfo);
        replaceExistingAssetsInfo.addLinks = true;
    }
    
    if (replaceExistingAssetsInfo.replaceCss) {
        if (scripts) {
            for (i = 0; i < scripts.length; i += 1) {
                scriptSrc = scripts[i].src;
                if ((scriptSrc) && (scriptSrc.indexOf(".js") === scriptSrc.length - 3)) {
                    if (scriptSrc.toLowerCase().indexOf("bootstrap") > -1) {
                        var jsAssets = getBootstrapJsScript(replaceExistingAssetsInfo.useAltBootstrapName);
                        //import the bootstrap js file. 
                        //WatsonBug# 3972960 
                        for (i = 0; i < jsAssets.length; i += 1) {
                            assetInfo = new AssetInfo(jsAssets[i].fullPath, jsAssets[i].file, jsAssets[i].type, jsAssets[i].useDefaultFolder, jsAssets[i].documentRelative);
                            assetList.push(assetInfo);
                        }
                        break;
                    }
                }
            }
        }
    }
    
    populateGlyphFontAssets(assetList);
    
    replaceExistingAssetsInfo.addMetaInfo = true;
    
    
     /*  check if jQuery reference is already present in doc in the Head, in this case css link should be added above it
    */
    if (scripts) {
        for (i = 0; i < scripts.length; i += 1) {
            scriptSrc = scripts[i].src;
            if ((scriptSrc) && (scriptSrc.indexOf(".js") === scriptSrc.length - 3)) {
                if (scriptSrc.toLowerCase().indexOf("jquery") > -1) {
                    if (dom.getElementsByTagName('head')[0].innerHTML.indexOf(scripts[i].outerHTML) > -1) {
                        replaceExistingAssetsInfo.jQueryPresent = true;
                        break;
                    }
                }
            }
        }
    }
    
    dw.logEvent(RESPONSIVE_HEADLIGHTS.RWD_Category, RESPONSIVE_HEADLIGHTS.RWD_SubCategory, RESPONSIVE_HEADLIGHTS.RWD_PageConverted);

    return true;
}

function populateScriptAssets(assetList, replaceExistingAssetsInfo) {
    "use strict";

    if (!window.doInsert) {
        return;
    }

    var dom = dw.getDocumentDOM(),
        jsReq = true,
        noRequiredJQuery = true,
        i,
        jqAssets,
        jsAssets,
        assetInfo,
        scripts = dom.getElementsByTagName('script'),
        noJQFound = true;

    function populateJqueryInfo() {
        jqAssets = getBootstrapJqueryScript();
        //import the jquery file.
        for (i = 0; i < jqAssets.length; i += 1) {
            assetInfo = new AssetInfo(jqAssets[i].fullPath, jqAssets[i].file, jqAssets[i].type, jqAssets[i].useDefaultFolder, jqAssets[i].documentRelative);
            assetList.push(assetInfo);
            replaceExistingAssetsInfo.addLinks = true;
        }
    }

    if (scripts) {
        for (i = 0; i < scripts.length; i += 1) {
            var scriptSrc = scripts[i].src;
            if ((scriptSrc) && (scriptSrc.indexOf(".js") === scriptSrc.length - 3)) {
                if (scriptSrc.toLowerCase().indexOf("bootstrap") > -1) {
                    jsReq = false;
                } else if (scriptSrc.toLowerCase().indexOf("jquery") > -1) {
                    // our supported version of jquery might already be already present
					var lowerScriptSrc = scriptSrc.toLowerCase();

					supportedBootstrapJqueryFiles.forEach(function (supportedBootstrapJQueryFile) {
						if (lowerScriptSrc.indexOf(supportedBootstrapJQueryFile) > -1) {
							noRequiredJQuery = false;
						}
					});

					if (noRequiredJQuery) {
						// it might be a CDN link
						if (lowerScriptSrc.indexOf("http") === 0) {
							supportedJqueryVersions.forEach(function (supportedJQueryVersion) {
								if (lowerScriptSrc.indexOf(supportedJQueryVersion) > -1) {
									noRequiredJQuery = false;
								}
							});
						}
					}

                    noJQFound = false;
                }
            }
        }
    }

    if (noRequiredJQuery) {
        if (noJQFound) {
            // no jquery found
            populateJqueryInfo();
        } else {
            // a jquery file is available
            //The dialog box will be not displayed if the user is in design view as "Switch to live view" dialog will appear and this will be pointless to show before that. 
            if (dom.getShouldShowJQueryInsertDialog() && (dom.getDesignViewMode() === "live" || dom.getView() === "code")) {
                dw.popupCommand("InsertBootstrapJQueryFile.htm");
                if (dom.getShouldInsertBootstrapJQuery()) {
                    populateJqueryInfo();
                    replaceExistingAssetsInfo.replaceJQuery = true;
                }
            }
        }
    }
    if (jsReq) {
        var useAlternateName = false;
        jsAssets = getBootstrapJsScript(useAlternateName);
        //import the bootstrap js file.
        for (i = 0; i < jsAssets.length; i += 1) {
            assetInfo = new AssetInfo(jsAssets[i].fullPath, jsAssets[i].file, jsAssets[i].type, jsAssets[i].useDefaultFolder, jsAssets[i].documentRelative);
            assetList.push(assetInfo);
            replaceExistingAssetsInfo.addLinks = true;
        }
    }
    
    if ((!jsReq) && noJQFound) {
        //bootstrap JS existed but we added jQuery
        //Then jQuery needs to be added before bootstrap.js
        replaceExistingAssetsInfo.moveJQueryAboveJs = true;
    }
}