﻿

$(document).ready(function() {
    CheckPrint();
    AddRadEditorCommands();
    ApplyStyleNewWindowLink();
    var url = window.location.pathname;

    if (url.substring(url.length - 13, url.length).toLowerCase() == "allitems.aspx") {
        $('#left-content').hide();
    }
    $('h1').each(function() {
        if ($(this).html() == "&nbsp;" || $(this).html() == null) {
            $(this).css('display', 'none');
        }
    });
    UpdateLookupSelects();
    $('.update-lookup-button').click(function() {
        UpdateLookupSelects();
    });
    $('select.multilookup-select').dblclick(function() {
        UpdateLookupSelects();
    });
    $('ul.sitemap-list ul.closed').hide();


});
function getNumberOfSearchResults() {
// what a crappy way to get the number of search results.
    var n = 0;
    var regex = /<clickInfoXml>(.*)clickInfoXml>/g;
    $('script').each(function() {
        var html = jQuery.trim($(this).html());
        var match = html.match(regex);
        if (match != null) {
            if (window.DOMParser) {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(match[0], "text/xml");
            }
            else // Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(match[0]);
            }
            var iXML = xmlDoc.getElementsByTagName("clickInfoXml")[0].childNodes[0].text;
            if (window.DOMParser) {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(iXML, "text/xml");
            }
            else // Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(iXML);
            }

            n = xmlDoc.getElementsByTagName("i")[0].getAttribute("n");
            return;

        }

    });
    
    return n;
}


function UpdateLookupSelects() {
    if (typeof (relatedLookupValues) != "undefined" && typeof (sourceControlId) != "undefined" && typeof (resultControlId) != "undefined") {
        $('#' + sourceControlId + ' option').each(function() {
            $(this).text(relatedLookupValues[$(this).attr('value')]);
        });
        $('#' + resultControlId + ' option').each(function() {
            $(this).text(relatedLookupValues[$(this).attr('value')]);
        });

    }
}
// Begin Sitestat code CMC v.1.0.1 
function sitestat(u) {
    var d = document, l = d.location; ns_pixelUrl = u + "&ns__t=" + (new 
Date().getTime()); u = ns_pixelUrl + "&ns_c=" + ((d.characterSet) ? d.characterSet : d.defaultCharset)
+ "&ns_ti=" + escape(d.title) + "&ns_jspageurl=" + escape(l && l.href ? l.href : d.URL) + "&ns_referrer=" +
escape(d.referrer); (d.images) ? new Image().src = u : d.write('<' + 'p><img src="' + u + '" height="1" width="1" alt="*"><' + '/p>');
}

function ns_onclick(i, b, c, h, j) {
    var e = ""; if (typeof ns_pixelUrl == "string") { e = ns_pixelUrl.substring(0, ns_pixelUrl.indexOf("?") + 1) } e += c; e += "&ns_type=" + h + "&ns_action=view"; e += "&ns__t=" + (new Date()).getTime(); if (!b) { b = i.href } var d = document.referrer; if (d.lastIndexOf("/") == d.length - 1) { d = d.substring(d.lastIndexOf("/"), 0) } if (d.length > 0) { e += "&amp;ns_referrer=" + escape(d) } j = j || ""; var f = (i && i.target && i.target != "") ? (i.target.substring(0, 1) == "_") ? i.target.substring(1) : i.target : "self"; var g = new Image(); if (f && b) { if (window[f]) { window.ns_softclick_timer = function(k, a) { return function() { if (window.ns_softclick_timeout) { window.clearTimeout(window.ns_softclick_timeout) } g.onload = g.onerror = function() { return }; window[((window[k]) ? k : "self")].location.href = a } } (f, b); ns_softclick_timeout = window.setTimeout("ns_softclick_timer()", 5000); g.onload = g.onerror = window.ns_softclick_timer } else { window.open(b, f, j) } } g.src = e; return false
}

function GetSiteStatCounter(resourcePath) {
    if (resourcePath == null) {
        return;
    }
    var result = resourcePath.toString();
    if (result.substr(0, 1) == "/") {
        result = result.substr(1, result.length - 1);
    }
    // although vs2008 intellisense does not like this, this is the way to replace all forward slashes by a dot
    result = result.replace(/\//g, ".").replace(/ /g, "_").toLocaleLowerCase();  
    
    
    return result;
    
}




function setMap(mapId, inputAddress) {
    var geoCode = {
        address: inputAddress
    };
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode(
    geoCode,
        function(results, status) {
            if (results.length >= 1) {
                var location = results[0].geometry.location;
                var mapOptions =
                {
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    center: location,
                    zoom: 15
                };


                var map = new google.maps.Map(document.getElementById(mapId), mapOptions);
                var marker = new google.maps.Marker({
                    position: location,
                    map: map
                });
            }
        }
    );

}


function OpenInNewWindow(url) {
    // Change "_blank" to something like "newWindow" to load all links in the same new window
    var newWindow = window.open(url);
    newWindow.focus();
    return false;
}

function ApplyStyleNewWindowLink() {
    $.expr[':'].newwindowstyle = function(obj) {
        //return obj.target == "_blank";// && !obj.hasClass('cms-admin-link');
        var cssClass = obj.getAttribute('class');
        if (cssClass == null) {
            cssClass = "";
        }
        return (obj.target == "_blank" || obj.rel == "external") && cssClass.indexOf("cms-admin-link") < 0; // && !obj.hasClass('cms-admin-link');
    };
    $('a:newwindowstyle').after("<img src='/Style Library/Images/RDW/new_win.gif' alt='' class='image-new-window'/>");

    $('a[rel*=external]').click(function() { return OpenInNewWindow(this.href) }); ;

}
function AddRadEditorCommands() {
    if (typeof (RadEditorCommandList) == "undefined") {
        // radeditor is not loaded.
        return;
    }
    // Really. If the "ApplyClass" tool is not enabled, the "ApplyClass" in the Image Manager is not rendered according to the <classes>-definition, but ALL
    // classes are shown. Therefore -> enabling ApplyClass-tool and hiding. 
    $('ul.reToolbar li span.ApplyClass').parent().parent().css('display', 'none');
    RadEditorCommandList["Abbr"] = function(commandName, editor, oTool) {

        if (!RadE_HasRules) {
            RTE2_InstantiateStaticSafeHtmlRules();
            RadE_HasRules = true;
        }
        var docEditor = editor.Document;
        var params = editor._dialogParameters;
        var configObj = new AssetPickerConfig("");
        configObj.ClientID = editor.Id;
        configObj.DefaultAssetLocation = "";
        configObj.CurrentWebBaseUrl = params["CurrentWebBaseUrl"];
        configObj.AllowExternalUrls = params["AllowExternalUrls"];
        var bInserting = false;
        var elemToReplace = null;
        var fragmentId = null;
        var elemViewToEdit = FormJSRTE_GetNearestContainingParentElementOfTypes(editor.get_contentWindow().frameElement.id, editor.getSelectedElement(), new Array("SPAN"));
        if ((elemViewToEdit != null) && (elemViewToEdit.id == g_strRTE2ReusableFragmentCommonToken)) {
            fragmentId = elemViewToEdit.getAttribute("fragmentid");
        }

        var dialogInput = new Object();
        dialogInput.fragmentId = fragmentId;
        var callback = function(dialogOutput) {

            var abbrString = '<abbr title="' + dialogOutput.meaning + '">' + dialogOutput.abbr + '</abbr>';
            editor.pasteHtml(abbrString);
            editor.setFocus();
        };

        var dialogUrl = params["CurrentWebBaseUrl"] + "/_layouts/RDWNL/RadEditor/Abbr.aspx";
        commonShowModalDialog(dialogUrl, "dialogHeight:200px; dialogWidth:350px; center:yes; resizable:yes; scroll:no; status:no;", callback, dialogInput);
    }

    RadEditorCommandList["Lang"] = function(commandName, editor, oTool) {

        if (!RadE_HasRules) {
            RTE2_InstantiateStaticSafeHtmlRules();
            RadE_HasRules = true;
        }
        var docEditor = editor.Document;
        var params = editor._dialogParameters;
        var configObj = new AssetPickerConfig("");
        configObj.ClientID = editor.Id;
        configObj.DefaultAssetLocation = "";
        configObj.CurrentWebBaseUrl = params["CurrentWebBaseUrl"];
        configObj.AllowExternalUrls = params["AllowExternalUrls"];
        var bInserting = false;
        var elemToReplace = null;
        var fragmentId = null;
        var elemViewToEdit = FormJSRTE_GetNearestContainingParentElementOfTypes(editor.get_contentWindow().frameElement.id, editor.getSelectedElement(), new Array("SPAN"));
        if ((elemViewToEdit != null) && (elemViewToEdit.id == g_strRTE2ReusableFragmentCommonToken)) {
            fragmentId = elemViewToEdit.getAttribute("fragmentid");
        }

        var dialogInput = new Object();
        dialogInput.fragmentId = fragmentId;
        var callback = function(dialogOutput) {
            var langString = '<span lang="' + dialogOutput.strlang + '">' + dialogOutput.str + '</span>';
            editor.pasteHtml(langString);
            editor.setFocus();
        };

        var dialogUrl = params["CurrentWebBaseUrl"] + "/_layouts/RDWNL/RadEditor/Lang.html";
        commonShowModalDialog(dialogUrl, "dialogHeight:200px; dialogWidth:350px; center:yes; resizable:yes; scroll:no; status:no;", callback, dialogInput);
    }
    RadEditorCommandList["H2"] = function(commandName, editor, args) {
        editor.pasteHtml('<h2> ' + editor.getSelectionHtml() + ' </h2>');

    }
    RadEditorCommandList["MOSSLinkManager"] = function(commandName, editor, args) {
        var params = editor._dialogParameters;
        var docEditor = editor.get_document();
        var configObj = new AssetPickerConfig("");
        configObj.ClientID = editor.get_id();
        configObj.DefaultAssetLocation = "";
        configObj.DefaultAssetImageLocation = "";
        configObj.CurrentWebBaseUrl = params["CurrentWebBaseUrl"];
        configObj.AllowExternalUrls = params["AllowExternalUrls"];
        var bInserting = false;
        var elemToReplace = null;
        var linkAsset = new LinkAsset("");
        var innerLinkHTML = null;
        linkAsset.ManageLinkDisplayText = false;
        var elemLink = FormJSRTE_GetNearestContainingParentElementOfTypes(editor.get_contentWindow().frameElement.id, editor.getSelectedElement(), new Array("A"));
        if (!elemLink) {
            bInserting = true;
            elemLink = docEditor.createElement("A");

            if (elemLink == null) return;
            var editorSelection = editor.getSelection();
            if (editorSelection.isControl()) {
                elemToReplace = editor.getSelectedElement();
            }
            else {
                innerLinkHTML = editorSelection.getHtml();
            }
        }
        else {
            innerLinkHTML = elemLink.innerHTML;
        }
        configObj.ReturnCallback = function(newAssetUrl, newAssetText, currentConfig, dialogReturnedData) {
            if (dialogReturnedData) {
                var sizeText = "";
                var download = false;
                if (dialogReturnedData.IconUrl && dialogReturnedData.IconUrl != "") {
                    // calculate size
                    var size = Math.round(filesize(newAssetUrl) / 1000);
                    sizeText = "&nbsp;(" + size + " kB)";
                    download = true;

                }
                var linkText = "";
                if ($telerik.isIE)
                    linkText = elemLink.innerText;
                else
                    linkText = elemLink.textContent;
                if (innerLinkHTML && innerLinkHTML != "") {
                    elemLink.innerHTML = innerLinkHTML;
                }
                else if (linkText == "") {
                    if (linkAsset.AssetText && linkAsset.AssetText != "") {
                        linkText = linkAsset.AssetText;
                    }
                    else {
                        linkText = linkAsset.AssetUrl;
                    }
                    elemLink.innerHTML += linkText;
                }
                if (elemToReplace != null) {
                    var parentEl = elemToReplace.parentNode;
                    elemLink.innerHTML = "";
                    parentEl.insertBefore(elemLink, elemToReplace);
                    elemLink.appendChild(elemToReplace);
                    linkAsset.FixupIconsAndEmptyAnchors(elemLink);
                    elemLink.appendChild(sizeText);
                    return;
                }

                else if (bInserting) {
                    var selection = docEditor.selection;
                    if (selection != null) {
                        var textRange = selection.createRange();
                        if (textRange != null) {
                            var text = textRange.text;
                            if (text && text != "" && !text.match(/^\s+$/)) {
                                textRange.execCommand("Unlink");
                                elemLink.innerHTML = textRange.htmlText;
                                linkAsset.FixupIconsAndEmptyAnchors(elemLink);
                            }
                            var tempDiv = docEditor.createElement("DIV");
                            tempDiv.appendChild(elemLink);
                            var innerHTML = tempDiv.innerHTML;
                            if (download == true) {
                                var counter = GetSiteStatCounter(newAssetUrl);        
                                // not possible to set onclick event using attribute-model                        
                                innerHTML = innerHTML.replace("href", "onclick=\"ns_onclick(this, '" + counter + "', 'pdf'); return false;\" href");
                            }
                            textRange.pasteHTML(innerHTML);
                            if (download == true) {
                                textRange.pasteHTML(sizeText);
                            }
                            tempDiv = null;
                        }
                    }
                    else {
                        //if we cannot get the selection, use the editor paste function instead

                        var tempDiv = docEditor.createElement("DIV");
                        tempDiv.appendChild(elemLink);
                        var innerHTML = tempDiv.innerHTML;
                        if (download == true) {
                            var counter = GetSiteStatCounter(newAssetUrl);
                            // not possible to set onclick event using attribute-model                        
                            innerHTML = innerHTML.replace("href", "onclick=\"ns_onclick(this, '" + counter + "', 'pdf'); return false;\" href");
                        }
                        textRange.pasteHTML(innerHTML, commandName);
                        if (download == true) {
                            textRange.pasteHTML(sizeText, commandName);
                        }                        
                        tempDiv = null;
                    }
                }
                else {
                    linkAsset.FixupIconsAndEmptyAnchors(elemLink);
                }
            }
        }
        linkAsset.LaunchModalDialogOnElement(configObj, elemLink, true, !bInserting);
    }
};

function OnClientPasteHtml(sender, args) {
    var commandName = args.get_commandName();
    var value = args.get_value();

    if (commandName == "ImageManager") {
        //See if an img has an alt tag set 
        var div = document.createElement("DIV");

        //Do not use div.innerHTML as in IE this would cause the image's src or the link's href to be converted to absolute path.
        //This is a severe IE quirk.
        Telerik.Web.UI.Editor.Utils.setElementInnerHtml(div, value);

        //Now check if there is alt attribute 
        var img = div.firstChild;
        if (!img.alt) {
            var alt = prompt("No alt tag specified. Please specify an alt attribute for the image", "");
            img.setAttribute("alt", alt);

            //Set new content to be pasted into the editor 
            args.set_value(div.innerHTML);
        }
    }
}

function filesize(url) {
    /* prepend root url*/
    if (url.indexOf("http") < 0) {
        url = location.protocol + '//' + location.host + url;
    }
    var webUrl;
    
    $().SPServices({
        operation: "WebUrlFromPageUrl",
        async: false,
        pageURL: url,
        completefunc: function(xData, Status) {
            $(xData.responseXML).find("WebUrlFromPageUrlResult").each(function() {
                webUrl = $(this).text();
                return;
            })
        }
    });
    /* weburl now is url of the web where listitem with url exists*/
    var listTitle;
    var listPath = url.replace(webUrl, "");
    listPath = listPath.substring(0, listPath.indexOf("/", 1));

    $().SPServices({
        operation: "GetListCollection",
        async: false,
        webURL: webUrl,
        completefunc: function(xData, Status) {
            $(xData.responseXML).find("List").each(function() {
                var defaultViewUrl = $(this).attr("DefaultViewUrl");
                var listCollList = defaultViewUrl.substring(0, defaultViewUrl.indexOf("/", 1));
                if (listPath.indexOf(listCollList) >= 0) {
                    listTitle = $(this).attr("Title");
                    return false;
                }
            });
        }
    });
    /* listtitle is e.g. "Documenten van siteverzameling */
    var fileName = "";
    var queryOptions = "";
    var fullFilePath = url.replace(webUrl, "").replace(listPath, "");
    if (fullFilePath.indexOf("/") == 0) {
        fullFilePath = fullFilePath.substring(1);
    }
    var splitIndex = fullFilePath.lastIndexOf("/");
    if (splitIndex > 0) {
        fileName = fullFilePath.substring(splitIndex + 1);
        var folderName = fullFilePath.substring(0, splitIndex);
        queryOptions = "<QueryOptions><Folder>" + folderName + "</Folder></QueryOptions>";
    }
    else {
        fileName = fullFilePath;
    }
    fileName = decodeFileName(fileName);
    var size;
    var options = 
    {
        operation: "GetListItems",
        webURL: "/",
        async: false,
        listName: listTitle,
        CAMLViewFields: "<ViewFields><FieldRef Name='FileSizeDisplay' /></ViewFields>",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>" + fileName + "</Value></Eq></Where></Query>",
        /*        CAMLQueryOptions : queryOptions,*/
        completefunc: function(xData, Status) {
            $(xData.responseXML).find("[nodeName='z:row']").each(function() {
                size = $(this).attr("ows_FileSizeDisplay");
            })
        }
    };
    if (queryOptions != "") {
        options.CAMLQueryOptions = queryOptions;
    }
    $().SPServices(options);
    return size;
}
function decodeFileName(val)
{    
    var len = val.length;
    var backlen = len;
    var i = 0;

    var newStr = "";
    var frag = "";
    var encval = "";
    var original = val;

    
    while (backlen > 0) {
        lastpercent = val.lastIndexOf("%");
        if (lastpercent != -1) // we found a % char. Need to handle
        {
            // everything *after* the %
            frag = val.substring(lastpercent + 1, val.length);
            // re-assign val to everything *before* the %
            val = val.substring(0, lastpercent);
            if (frag.length >= 2) // end contains unencoded
            {
                //  alert ("frag is greater than or equal to 2");
                encval = frag.substring(0, 2);
                newStr = frag.substring(2, frag.length) + newStr;
                //convert the char here. for now it just doesn't add it.
                if ("01234567890abcdefABCDEF".indexOf(encval.substring(0, 1)) != -1 &&
                       "01234567890abcdefABCDEF".indexOf(encval.substring(1, 2)) != -1) {
                    encval = String.fromCharCode(parseInt(encval, 16)); // hex to base 10
                    newStr = encval + newStr; // prepend the char in
                }
                // if so, convert. Else, ignore it.
            }
            // adjust length of the string to be examined
            backlen = lastpercent;
            // alert ("backlen at the end of the found % if is: " + backlen);
        }
        else { newStr = val + newStr; backlen = 0; } // if there is no %, just leave the value as-is
    } // end while
    
    return newStr;
}

function pausecomp(millis) {
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while (curDate - date < millis);
}
function CheckPrint() {
    // if ?print=yes is in query-string, load all media="print" for media="screen" too and run print-window
    if (getUrlVars()["print"] == "yes") {
        $("link").each(function() {
            var media = $(this).attr('media');
            if (media == "print") {
                $(this).attr('media', "");
            }
        });
        window.print();
    }

}
function topheaderHover(id, baseSrc, tabHover) {
    if (document.getElementById(id) )
    document.getElementById(id).src = baseSrc + 'sel_' + tabHover + '.gif';
}
function toggleElement(id) {
    if ($(id).is(":visible")) {
        $(id).hide();
    }
    else {
        $(id).show();
    }

}

/* Override ProcessImn in init.js: http://support.microsoft.com/kb/931509*/
/* Just do nothing */
function ProcessImn() {
    return;
    
}

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

