﻿// ******* ing. G.J. Mollenhorst ********

// WebMethod
// parameters:  pagePath - location of the webservice
//              fn  - Webservice method name to invoke
//              paramArray - string array with parameters for webmethod
//              succesFn - function to invoke in case of succesfull invocation
//              errorFn - function to invoke in case of error
//              objectForCB - the object the successFn works with, in this case the
//                              html object which is to be filled with content
//function WebMethod(pagePath, fn, paramArray, successFn, errorFn, objectForCB) {
//    this.pagePath = pagePath;
//    this.fn = fn;
//    this.paramArray = paramArray;
//    this.successFn = successFn;
//    this.errorFn = errorFn;
//    this.objectForCB = objectForCB;
//    this.actualCallback = successFn;


//    //Create list of parameters in the form:
//    //{"paramName1":"paramValue1","paramName2":"paramValue2"}
//    var paramList = '';
//    if (paramArray.length > 0) {
//        for (var i = 0; i < paramArray.length; i += 2) {
//            if (paramList.length > 0) paramList += ',';
//            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
//        }
//    }
//    paramList = '{' + paramList + '}';
//    // actualCallback = successFn;
//    // objectForActualCB = objectForCB;

//    this.Call = function() {
//        $.ajax({
//            type: "POST",
//            url: pagePath + "/" + fn,
//            contentType: "application/json; charset=utf-8",
//            data: paramList,
//            dataType: "json",
//            success: this.intermediateCallback,
//            error: errorFn
//        });
//    }

//    this.intermediateCallback = function(result) {
//        // apply css & jscript to page

//        // 3 return only HTML
//        successFn(result.d.ContentHTML, objectForCB);
//        // 1 load CSS
//        if (result.d.ContentCssIncludes != null) {
//            for (var i = 0; i < result.d.ContentCssIncludes.length; i++) {
//                checkloadjscssfile(result.d.ContentCssIncludes[i], "css");
//            }
//        }
//        // 2 load JS
//        if (result.d.ContentJavaScriptIncludes != null) {
//            for (var i = 0; i < result.d.ContentJavaScriptIncludes.length; i++) {
//                checkloadjscssfile(result.d.ContentJavaScriptIncludes[i], "js");
//            }
//        }


//    }
//}

// in case of additionalCallback -> this callback function is in the form of function(result) { .. 
function WebMethod(pagePath, fn, paramArray, successFn, errorFn, objectForCB, additionalCallback) {
    this.pagePath = pagePath;
    this.fn = fn;
    this.paramArray = paramArray;
    this.successFn = successFn;
    this.errorFn = errorFn;
    this.objectForCB = objectForCB;
    this.actualCallback = successFn;
    this.additionalCallback = additionalCallback;

    //Create list of parameters in the form:
    //{"paramName1":"paramValue1","paramName2":"paramValue2"}
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    // actualCallback = successFn;
    // objectForActualCB = objectForCB;

    this.Call = function() {
        $.ajax({
            type: "POST",
            url: pagePath + "/" + fn,
            contentType: "application/json; charset=utf-8",
            data: paramList,
            dataType: "json",
            success: this.intermediateCallback,
            error: errorFn
        });
    }

    this.intermediateCallback = function(result) {
        // apply css & jscript to page
        // 1 load CSS

        if (result.d.ContentCssIncludes != null) {
            for (var i = 0; i < result.d.ContentCssIncludes.length; i++) {
                checkloadjscssfile(result.d.ContentCssIncludes[i], "css");
            }
        }

        // 2 return only HTML
        successFn(result, objectForCB);
        
        // 3 load JS
        if (result.d.ContentJavaScriptIncludes != null) {
            for (var i = 0; i < result.d.ContentJavaScriptIncludes.length; i++) {
                checkloadjscssfile(result.d.ContentJavaScriptIncludes[i], "js");
            }
        }


        if (additionalCallback != undefined) {
            additionalCallback(result);
        }
    }
}

//function intermediateCallback(result) {
//    // apply css & jscript to page
//    // 1 load JS
//    if (result.d.ContentJavaScriptIncludes != null) {
//        for (var i = 0; i < result.d.ContentJavaScriptIncludes.length; i++) {
//            checkloadjscssfile(result.d.ContentJavaScriptIncludes[i], "js");
//        }
//    }
//    // 2 load CSS
//    if (result.d.ContentCssIncludes != null) {
//        for (var i = 0; i < result.d.ContentCssIncludes.length; i++) {
//            checkloadjscssfile(result.d.ContentCssIncludes[i], "css");
//        } 
//    }
//    // 3 return only HTML
//    eval(actualCallback(result.d.ContentHTML, objectForActualCB));
//}


// examples
//PageMethod("TestNoParams", [], AjaxSucceeded, AjaxFailed); //No parameters
//PageMethod("TestWithParams", ["a", "value", "b", 2], AjaxSucceeded, AjaxFailed); //With parameters
//WebMethod("HelloWorld", [], AjaxSucceeded, AjaxFailed);


// --- functions to dynamically add jscript / css
function loadjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

function removejscssfile(filename, filetype) {
    var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none" //determine element type to create nodelist from
    var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none" //determine corresponding attribute to test for
    var allsuspects = document.getElementsByTagName(targetelement)
    for (var i = allsuspects.length; i >= 0; i--) { //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
    }
}

var filesadded = "" //list of files already added

function checkloadjscssfile(filename, filetype) {
    if (filesadded.indexOf("[" + filename + "]") == -1) {
        loadjscssfile(filename, filetype);
        filesadded += "[" + filename + "]" //List of files added in the form "[filename1],[filename2],etc"
    }
    else {
        // already loaded -> remove & add again
        removejscssfile(filename, filetype);
        loadjscssfile(filename, filetype);
    }
}


//checkloadjscssfile("myscript.js", "js") //success
//checkloadjscssfile("myscript.js", "js") //redundant file, so file not added


// ------------------------------------------------------------------------------------------------
// function whichBrs
// Purpose      : getting browser manufacturer
// Parameters   :  
// Returns      : string containing browsername
function whichBrs() {
    var agt = navigator.userAgent.toLowerCase();
    if (agt.indexOf("opera") != -1) return 'Opera';
    if (agt.indexOf("staroffice") != -1) return 'Star Office';
    if (agt.indexOf("webtv") != -1) return 'WebTV';
    if (agt.indexOf("beonex") != -1) return 'Beonex';
    if (agt.indexOf("chimera") != -1) return 'Chimera';
    if (agt.indexOf("netpositive") != -1) return 'NetPositive';
    if (agt.indexOf("phoenix") != -1) return 'Phoenix';
    if (agt.indexOf("firefox") != -1) return 'Firefox';
    if (agt.indexOf("safari") != -1) return 'Safari';
    if (agt.indexOf("skipstone") != -1) return 'SkipStone';
    if (agt.indexOf("msie") != -1) return 'Internet Explorer';
    if (agt.indexOf("netscape") != -1) return 'Netscape';
    if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
    if (agt.indexOf('\/') != -1) {
        if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
            return navigator.userAgent.substr(0, agt.indexOf('\/'));
        }
        else return 'Netscape';
    } else if (agt.indexOf(' ') != -1)
        return navigator.userAgent.substr(0, agt.indexOf(' '));
    else return navigator.userAgent;
}

// --- DEFAULT CALLBACKS
// default behaviour --> filling the object with the result.
function BasicContentSucceeded(result, objectForCB) {

    var resultHTML = result.d.ContentHTML;
    if (whichBrs() == 'Internet Explorer') {
        // dealing with IE bug for jquery.html() function
        if (objectForCB[0] != null) {
            objectForCB[0].innerHTML = resultHTML;
        }
        else
        { objectForCB.innerHTML = resultHTML; }
    }
    else {
        objectForCB.html(resultHTML);
    }
}

function BasicContentFailed(result, objectForCB) {
    objectForCB.html("<h1> foutmelding! wilt u zo vriendelijk zijn deze fout te melden bij de beheerder? Vriendelijk bedankt. </h1>");
}



