﻿//protoype voor pixelrequest
function PixelRequest(siteID) {
    this.siteID = siteID;
    this.UA = "";    
    this.timeStamp = new Date();
    this.orderID = "";
    this.orderPartner = "";
    this.orderValue = "";
    this.orderTax = "";
    this.PixelRequestItemList = new Array();
    this.CookieItemList = new Array();

    }

//protoype voor pixelrequestitem
function PixelRequestItem() {
    this.name = "";
    this.category = "";
    this.price = 0;
}

//globale variable om iframe content in weg te schrijven
var iframeHtml;

//functies
function PlacePixels(pixelRequest) {
    //cookie info toevoegen aan pixelRequest
    pixelRequest.CookieItemList = eval(GetCookie("cookieInfo"));

    //Dynamic Script Tag Hack opbouwen
    DynamicScriptTagHack(JSON.stringify(pixelRequest), "WritePixel")
}

//callbackfunctie
function WritePixel(jsonResponse) {

    //Fix om de JsonResponse van .NET met de verkeerde 'datums' om te zetten naar goede Json 'datums'
    var jsonReponseText = JSON.stringify(jsonResponse);
    var pixelResponse = JSON.parse(jsonReponseText, MicrosoftJSONSerializationFix);

    var pixelList = pixelResponse.PixelList;
    var cookieItemList = pixelResponse.CookieItemList;

    //schrijven van pixel naar Iframe
    var iframeHTMl = GetIframeContent(pixelList);
    SetIFrame(iframeHTMl);

    //cookie wegschrijven    
    SetCookie("cookieInfo", JSON.stringify(cookieItemList));

    //Dynamic Script Tag Hack weghalen na gebruik
    RemoveScript();
}


//functie om Dynamic script tag uit te voeren
function DynamicScriptTagHack(jsonString, callback) {
    var request = "http://www.wtjes.nl/GetPixels.aspx?json=" + JSON.stringify(pixelRequest) + "&cb=WritePixel";
    //var request = "GetPixels.aspx?json=" + JSON.stringify(pixelRequest) + "&cb=WritePixel";
    var head = document.getElementsByTagName("body").item(0);
    var script = document.createElement("script");
    script.setAttribute("id", "GetPixelScript");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", request);
    head.appendChild(script);
}

//functie om iframecontent te generen
function GetIframeContent(pixelList) {
    //var iframeHTMl = "<html><head><title>Pixels</title><head><body>";
    testfunction = "<SCR" + "IPT type=text/javascript>\r\n" +
                       "    document.write = function (text) {\r\n" +
                       "        eval(document.writeln(text));\r\n" +
                       "    }\r\n" +
                       "</SCR" + "IPT>\r\n";
    var iframecontent = "";
    for (var i = 0; i < pixelList.length; i++) {
        var pixel = pixelList[i];
        iframecontent += "\t\t<!-- " + pixel.Id + "-->\r\n";
        iframecontent += "\t\t" + pixel.Html + "\r\n";
    }
    //return iframeHTMl + "</body></html>";
    return iframecontent;
}

//functie om script in iframe weg te schrijven
function SetIFrame(scriptData) {
    iframeHtml = scriptData;

    var iframe = document.createElement("iframe");
    iframe.setAttribute("border", 1);
    iframe.setAttribute("width", 300);
    iframe.setAttribute("height", 400);
    var body = document.body;
    body.appendChild(iframe);
   

    if (BrowserDetect.browser == "Explorer")
    //nodig omdat ie asynchroon de javascript gaat uitvoeren en dus zaken aanroept die nog niet bestaan
        iframe.src = "javascript:parent.iframeHtml;";
    else {
        var doc = iframe.contentDocument;
        doc.open();
        doc.write(scriptData);
        doc.close();
    }

    // create orphan element set HTML to
    //var orphNode = document.getElementById("placeholder");
    //orphNode.innerHTML = iframeHtml;

    // get the script nodes, add them into an arrary, and remove them from orphan node
    //var scriptNodes = orphNode.getElementsByTagName('script');
    //var scripts = [];
    //while (scriptNodes.length) {
        // push into script array
        //var node = scriptNodes[0];
        //scripts.push(node.text);

        // then remove it
        //node.parentNode.removeChild(node);
    //}

    // add html to place holder element (note: we are adding the html before we execute the scripts)
    //document.getElementById(id).innerHTML = orphNode.innerHTML;

//    // execute stored scripts
//    var head = document.getElementsByTagName('head')[0];
//    while (scripts.length) {
//        var scriptNode = document.createElement('script');
//        scriptNode.type = 'text/javascript';
//        scriptNode.src = scripts
//        scriptNode.text = scripts.shift(); // add the code to the script node
//        head.appendChild(scriptNode); // add it to the page
//        head.removeChild(scriptNode); // then remove it
//    }   


//    document.getElementById("placeholder").innerHTML = scriptData;

//    var re = /<script\b[\s\S]*?>([\s\S]*?)<\//ig;
//    var match;
//    while (match = re.exec(scriptData)) {
//        eval(match[1]);
//    }

    
    
    //var scripts = div.getElementsByTagName("script");
    //for (i = 0; i < scripts.length; i++) {
//        var script = document.createElement("script");
//        script.scr = scripts[i].src;
//        script.innerText = scripts[i].innerText;
//        head.appendChild(script);
    //};
    


}



//functie om Dynamic Script Tag Hack weghalen
function RemoveScript() {
    var old = document.getElementById('GetPixelScript');
    if (old != null) {
        old.parentNode.removeChild(old);
        delete old;
    }
}

function SetCookie(name,value)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+1);
    document.cookie=name+ "=" +escape(value) + ";expires="+exdate.toGMTString();
}

function GetCookie(name) {
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}


//JSON implementatie van json.org
if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

        // Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to
        // obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                return String(value);


            case 'object':


                if (!value) {
                    return 'null';
                }


                gap += indent;
                partial = [];

                // Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    // Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    // If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

            var i;
            gap = '';
            indent = '';

            // If the space parameter is a number, make an indent string containing that
            // many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

                // If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

            // If there is a replacer, it must be a function or an array.
            // Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

            // Make a fake root object containing our value under the key of ''.
            // Return the result of stringifying the value.

            return str('', { '': value });
        };
    }


    // If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

            // The parse method takes a text and an optional reviver function, and returns
            // a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

                // The walk method is used to recursively walk the resulting structure so
                // that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }


            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {


                j = eval('(' + text + ')');


                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            // If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
} ());

//Einde JSON implementatie van json.org

//fix om /Date\xxxxxxxxxxx/ naar een javascript date om te zetten
function MicrosoftJSONSerializationFix(key, value) {
    if (typeof value === 'string') {
        var isDate = /Date\(([-+]?\d+[-+]?\d+)\)/.exec(value);
        if (isDate) {
            value = new Date(eval(isDate[1]));
        }
    }
    return value;
}

//browserdetect 
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.userAgent,
		    subString: "iPhone",
		    identity: "iPhone/iPod"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};
BrowserDetect.init();

