﻿// initializer

if (typeof IZEN === 'undefined') {
    IZEN = {};
}
if (typeof IZEN.util === 'undefined') {
    IZEN.util = {};
}
if (typeof IZEN.fb === 'undefined') {
    IZEN.fb = {};
}


// dom tools
IZEN.util.dom = function() {
    return {
        walkTheDOM: function(node, func) {
            func(node);
            node = node.firstChild;
            while (node) {
                this.walkTheDOM(node, func);
                node = node.nextSibling;
            }
        }
    };

} ();


// ajax utility
IZEN.util.Ajax = function() {
    var thisObj = this;
    getTransport = function() {
        if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
        else if (window.XMLHttpRequest) return new XMLHttpRequest();
        else return false;
    }

    var sto = null;
    var timeOut = 10000;
    var transport = getTransport();
    this.responseType = IZEN.util.Ajax.RAW;
    this.method = "post";

    this.ondone = function(data) {
        //alert(data.currentrating);
    }
    this.onerror = function() {
        //alert('error');
    }

    onComplete = function(data) {
        var d;
        switch (thisObj.responseType) {
            case IZEN.util.Ajax.RAW:
                d = data.responseText;
                break;
            case IZEN.util.Ajax.JSON:
                try {
                    d = IZEN.util.JSON.parse(data.responseText);
                } catch (e) {
                    thisObj.onerror();
                    return;
                }
                break;
        }

        thisObj.ondone(d);
    }

    onStateChange = function() {
        if (transport.readyState == 4 && transport.status == 200) {
            if (sto != null) clearTimeout(sto);
            if (onComplete) {
                setTimeout(function() { onComplete(transport); }, 10);
            }
            //if (this.update)
            //setTimeout(function() { this.update.innerHTML = this.transport.responseText; } .bind(this), 10);
            transport.onreadystatechange = function() { };
        } else if (transport.readyState == 4) {
            if (sto != null) clearTimeout(sto);
            if (thisObj.onerror) {
                setTimeout(function() { thisObj.onerror(); }, 10);

            }
        }

    }

    this.post = function(url, params) {
        transport.open(this.method, url, true);
        transport.onreadystatechange = onStateChange;
        if (this.method == 'post') {
            transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            if (transport.overrideMimeType) transport.setRequestHeader('Connection', 'close');
        }

        sto = setTimeout(function() { if (transport.readyState != 4) { if (transport.abort) { transport.abort(); thisObj.onerror(); } } }, timeOut);

        if ((params != null) && (typeof params == 'object'))
            transport.send(IZEN.util.JSON.toQueryString(params));
        else {
            transport.send('');
        }


    }

    this.abort = function() {
        if (transport.abort)
            transport.abort();
    }

}

IZEN.util.Ajax.RAW = 0;
IZEN.util.Ajax.JSON = 1;


// json

if (typeof Dialog === 'undefined') {

    IZEN.util.JSON = function() {

        function f(n) {
            return n < 10 ? '0' + n : n;
        }

        if (typeof Date.prototype.toJSON !== 'function') {

            Date.prototype.toJSON = function(key) {

                return this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z';
            };

            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 = {
            '\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) {
            var i,
            k,
            v,
            length,
            mind = gap,
            partial,
            value = holder[key];

            if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }

            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }

            switch (typeof value) {
                case 'string':
                    return quote(value);

                case 'number':
                    return isFinite(value) ? String(value) : 'null';

                case 'boolean':
                case 'null':
                    return String(value);
                case 'object':
                    if (!value) {
                        return 'null';
                    }
                    gap += indent;
                    partial = [];

                    if (Object.prototype.toString.apply(value) === '[object Array]') {

                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }

                        v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }

                    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 {

                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = str(k, value);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    }

                    v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
            }
        }

        return {
            stringify: function(value, replacer, space) {

                var i;
                gap = '';
                indent = '';

                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }

                } else if (typeof space === 'string') {
                    indent = space;
                }

                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                    throw new Error('stringify');
                }

                return str('', { '': value });
            },

            parse: function(text, reviver) {

                var j;

                function walk(holder, key) {

                    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;
                }

                throw new SyntaxError('parse');
            },

            toQueryString: function(b) {
                var ret = "";

                for (var k in b) {
                    switch (typeof b[k]) {
                        case 'string':
                            if (ret.length > 0) ret += '&';
                            ret += k + "=" + escape(b[k]);
                            break;

                        case 'number':
                            if (ret.length > 0) ret += '&';
                            ret += k + "=" + isFinite(b[k]) ? String(b[k]) : 'null';
                            break;

                        case 'boolean':
                        case 'null':
                            if (ret.length > 0) ret += '&';
                            ret += k + "=" + String(b[k]);
                            break;
                        case 'object':
                            if (b[k] instanceof Array) {
                                for (var l in b[k]) {
                                    switch (typeof b[k][l]) {
                                        case 'string':
                                            if (ret.length > 0) ret += '&';
                                            ret += k + "[" + l + "]=" + escape(b[k][l]);
                                            break;

                                        case 'number':
                                            if (ret.length > 0) ret += '&';
                                            ret += k + "[" + l + "]=" + isFinite(b[k]) ? String(b[k]) : 'null';
                                            break;

                                        case 'boolean':
                                        case 'null':
                                            if (ret.length > 0) ret += '&';
                                            ret += k + "[" + l + "]=" + String(b[k]);
                                            break;
                                    }
                                }
                            }
                            break;
                    }
                }

                return ret;
            }

        }
    } ();
}


IZEN.util.event = function() {
    return {
        SimpleEvent: function() {

            var listeners = [];
            var count = 0;

            this.fireEvent = function(args) {
                //for (var f in listeners) {
                for (var i = 0; i < count; i++) {
                    var fe = listeners[i];
                    if (fe != null) fe(args);
                }
            }

            this.attachListener = function(f) {
                listeners[count] = f;
                count++;
            }

            this.detachListener = function(f) {
                for (var i = 0; i < count; i++) {
                    if (listeners[i] == f) {
                        listeners.splice(i, 1);
                        count--;
                        break;
                    }
                }
            }
        }
    };
} ();


// facebook unification code
IZEN.fb.messagebox = function(title, text, oktext, canceltext) {
    if (typeof Dialog !== 'undefined') {
        if (canceltext) {
            var dialog = new Dialog().showChoice(title, text, button_confirm = oktext, button_cancel = canceltext);
            return dialog;
        } else {
            var dialog = new Dialog().showMessage(title, text, button_confirm = oktext);
            return dialog;
        }
    } else {
        var container = document.createElement("div");
        var content = document.createElement("div");
        content.style.padding = "10px";
        content.innerHTML = text;

        container.appendChild(content);

        var dialog = new FB.UI.PopupDialog(title, container);

        var footer = document.createElement("div");
        footer.style.textAlign = 'right';
        footer.style.background = '#f0f0f0';
        footer.style.borderTop = 'solid 1px #c0c0c0';
        footer.style.padding = "10px";

        container.appendChild(footer);

        var okay = document.createElement("input");
        okay.className = 'inputbutton';
        okay.type = 'button';
        okay.value = oktext || 'Okay';

        if (canceltext) {
            var cancel = document.createElement("input");
            cancel.className = 'inputbutton inputaux';
            cancel.style.marginLeft = "10px";
            cancel.type = 'button';
            cancel.value = canceltext;
            cancel.onclick = function() { if (dialog.oncancel) dialog.oncancel(); dialog.close() };
        }

        okay.onkeydown = function(e) {
            var keynum;
            if (window.event) // IE
            {
                keynum = e.keyCode;
            }
            else if (e.which) // Netscape/Firefox/Opera
            {
                keynum = e.which;
            }
            if (keynum == 27) {
                dialog.close();
            }
        };
        okay.onclick = function() { if (dialog.onconfirm) dialog.onconfirm(); dialog.close() };

        footer.appendChild(okay);

        if (canceltext) {
            footer.appendChild(cancel);
        }


        dialog.hide = function() { dialog.close(); };
        dialog.setStyle = function(stylename, style) {
            var e = dialog.get_domElement();
            e.style[stylename] = style;
        }

        dialog.set_placement(FB.UI.PopupPlacement.topCenter);
        dialog.show();

        okay.focus();

        return dialog;
    }
}


IZEN.fb.ajax = function() {

    var AjaxCounter = 0;
    var AjaxInvidualCounter = [];
    var AjaxCounterSilent = 0;


    return {
        RAW: typeof Ajax != 'undefined' ? Ajax.RAW : IZEN.util.Ajax.RAW,
        JSON: typeof Ajax != 'undefined' ? Ajax.JSON : IZEN.util.Ajax.JSON,
        FBML: typeof Ajax != 'undefined' ? Ajax.FBML : IZEN.util.Ajax.RAW,

        isAjaxing: function() {
            return (AjaxCounter + AjaxCounterSilent) > 0
        },

        //doAjaxSilent: function(url, params, callback, errorcallback, type) {
        //IZEN.fb.Ajax.doAjax(url, params, callback, errorcallback, type, null);
        //},


        doAjax: function(p) {


            var url, params, callback, errorcallback, type, e_progress;
            if (p) {
                url = p.url;
                params = p.params;
                callback = p.callback;
                errorcallback = p.errorcallback;
                type = p.type;
                e_progress = p.e_progress;
            }



            var silent = false;
            if (!e_progress) silent = true;

            // get progress element and increment counter
            var pbar = e_progress;
            if (!silent) {
                AjaxCounter++;
                //if (!AjaxInvidualCounter[pbar]) AjaxInvidualCounter[pbar] = 0;
                //AjaxInvidualCounter[pbar]++;
                if (!pbar.ajaxcounter) pbar.ajaxcounter = 0;
                pbar.ajaxcounter++;
            }
            else AjaxCounterSilent++;

            if (pbar && !silent) {
                if (pbar.setStyle) {
                    pbar.setStyle("display", "");
                } else {
                    pbar.style.display = "";
                }
            }

            var ajax;

            if (typeof Ajax !== 'undefined')
                ajax = new Ajax();
            else
                ajax = new IZEN.util.Ajax();


            ajax.responseType = (typeof type === 'undefined' ? this.JSON : type);
            ajax.onerror = function() {

                //alert(AjaxInvidualCounter[pbar] + pbar.id);

                if (!silent) {
                    AjaxCounter--;
                    //AjaxInvidualCounter[pbar]--;
                    pbar.ajaxcounter--
                }
                else AjaxCounterSilent--;

                if (AjaxCounter < 0) AjaxCounter = 0;

                if (pbar && !silent) {
                    //if (AjaxInvidualCounter[pbar] == 0) {
                    if (pbar.ajaxcounter == 0) {
                        if (pbar.setStyle) {
                            pbar.setStyle("display", "none");
                        } else {
                            pbar.style.display = "none";
                        }
                    }
                }

                if (errorcallback)
                    errorcallback();
            }

            ajax.ondone = function(data) {

                if (!silent) {
                    AjaxCounter--;
                    //AjaxInvidualCounter[pbar]--;
                    pbar.ajaxcounter--;
                }
                else AjaxCounterSilent--;

                if (AjaxCounter < 0) AjaxCounter = 0;
                if (pbar && !silent) {
                    // if counter is 0, no more asynch call running
                    //if (AjaxInvidualCounter[pbar] == 0) {
                    if (pbar.ajaxcounter == 0) {
                        if (pbar.setStyle) {
                            pbar.setStyle("display", "none");
                        } else {
                            pbar.style.display = "none";
                        }
                    }
                }
                if (callback) callback(data);
            }

            ajax.requireLogin = true;
            ajax.post(url, params);

        }

    }

} ();

IZEN.fb.AdRotator = function(name, adframe, timeout, cachetimeout, retrytimeout) {
    /*
    Example layout
    <div id="adtop" style="width:646px;height:60px;overflow:hidden;">
    <div id="adtop_0" style="position:absolute;">
    <fb:iframe src="<%=AppHelper.HttpAppHostUrl + AppHelper.AdsUrl("646x60.aspx") %>" style='border: 0px;' width='646' height='60' scrolling='no' frameborder='0' />
    </div>
    <div id="adtop_1" style="visibility:hidden;position:absolute;" >
    </div>
    </div>
    */

    var adcount = 0;
    var ename = name;
    var ad = null;
    var fetched = false;
    var tout = 30000;
    var ctout = 0;  // cache next ad immediately
    var rtout = 100;    // retry timeout
    var adf = adframe;
    var thisObj = this;

    var to_tout = null;
    var to_ctout = null;
    var to_retry = null;

    if (timeout != null) tout = timeout;
    if (cachetimeout != null) ctout = cachetimeout;
    if (retrytimeout != null) rtout = retrytimeout;

    this.fetchad = function() {
        fetched = true;
        var e = document.getElementById(ename + "_" + (adcount + 1) % 2);
        //var frame = e.getFirstChild();
        //if (frame != null) {
        //var src = frame.getSrc();
        //var newsrc = src.replace(/#.*/, "");
        //newsrc += "#" + new Date().getDay() + new Date().getHours() + new Date().getMinutes() + new Date().getSeconds();
        //frame.setSrc(newsrc);
        //}
        //else {
        if (e.setInnerFBML) {
            e.setInnerFBML(adf);
        } else {
            e.innerHTML = adf;
        }
        //}
    }

    this.refresh = function() {
        // if not yet cache, cache ads now
        if (!fetched) {
            if (to_ctout != null) clearTimeout(to_ctout);
            to_ctout = setTimeout(thisObj.fetchad, 0);
        }

        // force a refresh
        if (to_tout != null) clearTimeout(to_tout);
        to_tout = setTimeout(thisObj.showad, 10);

    }

    this.showad = function() {
        if (!fetched) {
            to_retry = setTimeout(thisObj.showad, rtout);
            return;   // if nothing new fetched, return
        }

        var prevcount = adcount;

        adcount = ((adcount + 1) % 2);

        fetched = false;
        to_ctout = setTimeout(thisObj.fetchad, ctout);  // start fetching after 15 seconds


        var e = document.getElementById(ename + "_" + adcount);
        var preve = document.getElementById(ename + "_" + prevcount);

        if (e.setStyle) {
            e.setStyle("visibility", "");
            preve.setStyle("visibility", "hidden");
        } else {
            e.style.visibility = "";
            preve.style.visibility = "hidden";
        }


        prevcount = adcount;

        to_tout = setTimeout(thisObj.showad, tout); // set 30 second interval of changing ad
    }

    to_tout = setTimeout(thisObj.showad, tout); // set 30 second interval of changing ad
    to_ctout = setTimeout(thisObj.fetchad, ctout);  // start fetching after 15 seconds
}


IZEN.fb.requireLogin = function(func) {
    if (FB_RequireFeatures) {
        FB_RequireFeatures(["XFBML"], function() {
            if (FB.Connect.get_status().result == 1) {
                func();
            } else {
                FB.Connect.requireSession(function() {
                    FB.Connect.get_status().waitUntilReady(function() {
                        func();
                    });
                });

                /*            
                var dialog = IZEN.fb.messagebox("Login Required", "You need to login to perform the selected function!", "Login", "Cancel");
                dialog.onconfirm = function() {
                FB.Connect.requireSession(function() {
                FB.Connect.get_status().waitUntilReady(function() {
                func();
                });

                    }, true);
                }
                */
            }
        });
    } else {
        func();
    }


}
