﻿Shadowbox.init({
    skipSetup: true,
    players: ["img", "swf", "wmp", "iframe", "html"],
    language: "da"
});

String.prototype.substrUntil = function(delimeter) {
    var index = this.indexOf(delimeter);
    return index > 0 ? this.substr(0, index) : this;
}

String.prototype.startsWith = function(str) {
    return this.indexOf(str) == 0;
}

var WebInfo = {

    loadTransformedFeed: function(containerId, feedUrl, xslUrl) {
        $.ajax({
            type: "POST",
            url: "/_layouts/WebInfo/ClientRssService.asmx/GetFeedMarkup",
            data: "{'feedUrl':'" + feedUrl + "','xslUrl':'" + xslUrl + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus, xmlHttpRequest) {
                $("#" + containerId).html(data.d);
            },
            error: function(xmlHttpRequest, textStatus, errorThrown) {
                alert("E: " + textStatus);
            }
        });
    },


    queryParameters: null,

    getQueryParameter: function(name) {
        if (!this.queryParameters) {
            this.queryParameters = {};
            var search = window.location.search.substrUntil('#');
            search = search && search.startsWith('?') ? search.substr(1) : search;
            parameters = search.toLowerCase().split('&');
            for (index in parameters) {
                var parameter = parameters[index];
                var atoms = parameter.split('=');
                this.queryParameters[atoms[0]] = atoms[1];
            }
        }
        return this.queryParameters[name];
    },

    openPrint: function() {
        window.open(window.location.href.substrUntil('#') + (window.location.search ? '&' : '?') + 'print=&language=' + WebInfo.currentLanguage);
    },

    setTableLayout: function($table) {
        $table.each(
            function() {
                $(this).find('tbody > tr:nth-child(even)').addClass('odd');
                $(this).find('tbody > tr:nth-child(odd)').addClass('even');
                $(this).find('tbody > tr:first-child').addClass('firstrow').removeClass('even');
            }
        );
    },

    resizeIFrames: function() {
        $('iframe')
			.filter(
				function() {
				    return !this.height;
				}
			)
			.load(
				function() {
				    $(this).height(this.contentWindow.document.body.scrollHeight + 25);
				}
			);
    },

    wrapLyteBoxes: function() {
        $('img[src*=/_w/]').each(
			function() {
			    var s = this.src.replace("/_w/", "/");
			    var i = s.lastIndexOf("_");

			    var pre = s.substring(0, i);
			    var post = s.substring(i + 1);
			    post = post.substring(0, post.lastIndexOf("."));

			    s = pre + "." + post;

			    if (!this.border) {
			        this.border = 0;
			    }

			    $(this).wrap("<a href='" + s + "' rel='shadowbox[Billeder]'></a>");
			}
		);
        Shadowbox.setup();
    },

    injectWebPartFooters: function() {
        $('.bottomParts tr .ms-WPHeader').each(
			function() {
			    $(this)
					.closest("table")		//Locate header table
					.parent()				//Navigate one up, otherwise next 'closest' will find self
					.closest("table")		//Locate WebPart bounding table
					.find("tr:first")		//Find first tr
					.parent()				//Get parent of tr to ensure we have the tbody and not table if one is present
					.append(
						"<tr>" +
						"	<td>" +
						"	  <table border='0' cellpadding='0' cellspacing='0' width='100%'>" +
						"		<tr class='wi-WPFooter'>" +
						"		  <td style='width:100%;'>" +
						"			<div>" +
						"				<span>&nbsp;</span>" +
						"			</div>" +
						"		  </td>" +
						"		</tr>" +
						"	  </table>" +
						"	</td>" +
						"</tr>"
					);
			}
		);
    },

    forcePrintStyles: function() {
        $('link')
			.filter(
				function() {
				    return this.href && this.href.toLowerCase().indexOf("/_layouts/webinfo/css/dlrprint.css") > -1;
				}
			)
			.each(
				function() {
				    this.media = "all";
				}
			);
    },

    scaleTextTags: function(tagname) {
        var collection = document.getElementsByTagName(tagname);
        for (i = 0; i < collection.length; i++) {
            var pt = false;
            var s;
            if (collection[i].style.fontSize) {
                if (collection[i].style.fontSize.indexOf("px") != -1) {
                    s = parseInt(collection[i].style.fontSize.replace("px", ""));
                }
                else if (collection[i].style.fontSize.indexOf("pt") != -1) {
                    s = parseInt(collection[i].style.fontSize.replace("pt", ""));
                    pt = true;
                }
                s = s + 3;
                if (pt)
                    collection[i].style.fontSize = s + "pt";
                else
                    collection[i].style.fontSize = s + "px";
            }
            //            else if (collection[i].currentStyle['fontSize']) {
            //                if (collection[i].currentStyle['fontSize'].indexOf("px") != -1) {
            //                    s = parseInt(collection[i].currentStyle['fontSize'].replace("px", ""));
            //                }
            //                else if (collection[i].currentStyle['fontSize'].indexOf("pt") != -1) {
            //                    s = parseInt(collection[i].currentStyle['fontSize'].replace("pt", ""));
            //                    pt = true;
            //                }
            //            }

        }
    },

    upsizeText: function() {
        //        WebInfo.scaleTextTags('p');
        //        WebInfo.scaleTextTags('div');
        //        WebInfo.scaleTextTags('span');
        //        WebInfo.scaleTextTags('a');
        //        WebInfo.scaleTextTags('h1');
        //        WebInfo.scaleTextTags('h2');
        //        WebInfo.scaleTextTags('h3');
        //        WebInfo.scaleTextTags('h4');
        //        WebInfo.scaleTextTags('h5');
        if (document.body.style.zoom != 0)
            document.body.style.zoom *= 1.2;
        else
            document.body.style.zoom = 1.2;

        var collection = document.getElementsByTagName('img');
        for (i = 0; i < collection.length; i++) {
            collection[i].style.zoom = 0.83333;
        }
    },

    initLoginFrame: function() {
        var frame = document.getElementById('loginframe');
        if (frame) {
            var v = document.getElementById('loginframeContent').firstChild.nodeValue;
            var doc = frame.contentDocument ? frame.contentDocument : frame.contentWindow.document;
            doc.open();
            doc.write('<html><head>');
            if (v.indexOf('text/css') == -1) { // If no css added in constructors copy from parent
                for (i = 0; i < document.styleSheets.length; i++) {
                    var href = document.styleSheets[i].href;
                    if (href) {
                        doc.write("<link rel='stylesheet' type='text/css' href='" + href + "' /> ");
                    }
                }
            }
            doc.write(v);
            doc.close();
        }
    },

    toggleEditorPart: function(id) {
        var minus = "/_layouts/images/TPMin2.gif";
        var plus = "/_layouts/images/TPMax2.gif";
        var container = $('#' + id + "_Container");
        var icon = $('#' + id + "_Icon");
        if (container.is(":visible")) {
            container.hide();
            icon.attr("src", plus);
        }
        else {
            container.show();
            icon.attr("src", minus);
        }
    },

    currentLanguage: "da",

    translate: function(language, callback) {
        var from = WebInfo.currentLanguage;
        WebInfo.currentLanguage = language;
        Microsoft.Translator.translate(document.body, from, language, callback);
    },

    init: function() {
        //Translate if requested
        var language = WebInfo.getQueryParameter("language");
        if (language && WebInfo.currentLanguage != language) {
            //Defer remaining initialization until after translation is done
            WebInfo.translate(language, WebInfo.init);
            return;
        }

        var isPrint = WebInfo.getQueryParameter("print") != undefined;

        //Resize all iframes on page
        WebInfo.resizeIFrames();
        //Wrap all images with /_w/ in src url with lightbox
        WebInfo.wrapLyteBoxes();

        if (isPrint) {
            //Force print styling if print query parameter is defined
            WebInfo.forcePrintStyles();
            WebInfo.upsizeText();
            window.print();
        }
        else {
            //Init login frame
            WebInfo.initLoginFrame();
            //Inject footer rows in all webpart tables
            WebInfo.injectWebPartFooters();
        }

        //Style tables
        WebInfo.setTableLayout($('.pageContent table.WebInfoTable'));
    }

};