﻿if ("undefined" == typeof ac) {
    ac = {};
}

window.$my = {}

/* ---- ac.browser ---- */
/*
usage :

ac.browser.major
*/

ac.browser = (function() {
    var agent = navigator.userAgent.toLowerCase();
    var version = navigator.appVersion;

    return {
        nav: navigator,
        agent: agent,
        version: version,
        netscape: (agent.indexOf('mozilla') >= 0) && (agent.indexOf('compatible') < 0),
        explorer: explorer = agent.indexOf('msie') > 0,
        major: parseInt(version, 10),
        minor: parseFloat(version)
    };
})();

ac.Connection = (function() {
    var isReady = false;
    var readyList = [];
    return {
        setReady: function() {
            isReady = true;

            if (readyList) {
                jQuery.each(readyList, function() {
                    this.call(document, jQuery);
                });
            }
        },
        ready: function(fn) {
            if (!isReady) {
                readyList.push(fn);
            }
            else {
                fn.call(document, jQuery);
            }
            return this;
        }
    };
})();

/* ---- ac.url ---- */
/*
usage :

var url = ac.url("http://www.allocine.fr/?foo=bar");
url.params["foo2"] = "bar2";
url.hash = "top";
delete url.params["foo"];
url.build(); // => "http://www.allocine.fr/?foo2=bar2#top"
*/

ac.url = function(fullUrl) {

    var ar = fullUrl.split("?");
    this.stem = ar[0];

    if (ar.length > 1) {
        var query = ar[1];
        var arQuery = query.split("#");

        if (arQuery.length > 1) {
            this.hash = arQuery[1];
        }
        else {
            this.hash = "";
        }

        this.params = (function(s) {
            var params = {};
            if (!s) {
                return params;
            }
            var ps = s.split("&");
            for (var i in ps) {
                var p = ps[i];
                var pos = p.indexOf('=');
                if (pos > 0) {
                    params[p.substring(0, pos)] = p.substr(pos + 1);
                }
                
            }
            return params;
        })(arQuery[0]);
    }
    else {
        this.params = [];
        this.hash = "";
    }
};

ac.url.format = function(pattern, params) {
    var result = ac.formatPattern(pattern, params);
    result = result.replace(/\([^)]+\)/, "");
    return result;
};

ac.formatPattern = function(pattern, params) {
    var result = pattern;
    for (var name in params) {
        result = result.replace("(" + name + ")", encodeURIComponent(params[name]));
    }
    return result;
};

ac.url.prototype.build = function() {
    var search = "";
    for (var p in this.params) {
        search += (search ? "&" : "") + p + "=" + (this.params[p] || "");
    }
    return this.stem + (search ? ("?" + search) : "") + (this.hash ? "#" + this.hash : "");
};

/* ---- ac.cookie ---- */
/*
usage :
ac.cookie(name) : gets "name" cookie value
ac.cookie(name, value, options) : sets "name" cookie value
ac.cookie(name, null) : deletes "name" cookie value
options object ->
{
date:     (Date) absolute date
days:     (number) days offset
hours:    (number) hours offset
minutes:  (number) minutes offset
midnight: (bool) set the computed date to midnight
}
*/

ac.cookie = (function() {

    var domain = (function() {
        var acDomains = ["allofamille"];
        // var acDomains = ["screenrush", "allocine", "ac-net.net"];
        var result = window.location.hostname;
        var index = -1;
        for (var i = 0; i < acDomains.length; i++) {
            index = Math.max(index, result.indexOf(acDomains[i]));
        }
        if ((-1 == index) && jQuery.browser.netscape && 4 == jQuery.browser.major) {
            return "";
        }
        else {
            return "." + result.substr(index);
        }
    })();

    var setCookie = function(name, value, expiration) {
        document.cookie = name + "=" + escape(value) + "; expires=" + expiration.toGMTString() + (("; domain=" + domain) || "") + "; path=/";
    };

    var getCookie = function(name) {
        var cookies = document.cookie;
        var prefix = name + "=";
        var begin = cookies.indexOf("; " + prefix);
        if (begin == -1) {
            begin = cookies.indexOf(prefix);
            if (begin != 0)
                return null;
        }
        else {
            begin += 2;
        }
        var end = cookies.indexOf(";", begin);
        if (end == -1) {
            end = cookies.length;
        }
        return unescape(cookies.substring(begin + prefix.length, end));
    };

    return function(name, value, options) {

        if (('undefined' == typeof value) && ('undefined' == typeof options))
            return getCookie(name);
        else if (null == value) {
            var expiration = new Date();
            expiration.setTime(expiration.getTime() - 1);
            setCookie(name, "", expiration);
        }
        else {
            options = options || {};

            var expiration = options.date ? options.date : new Date();

            var offset = 0;
            if ("number" == typeof options.days)
                offset += options.days * 24 * 60 * 60 * 1000;
            if ("number" == typeof options.hours)
                offset += options.hours * 60 * 60 * 1000;
            if ("number" == typeof options.minutes)
                offset += options.minutes * 60 * 1000;
            if (offset)
                expiration.setTime(expiration.getTime() + offset);
            if (options.midnight)
                expiration.setHours(0, 0, 0, 0);

            setCookie(name, value, expiration);
        }
    }
})();

/* ---- ac.StringBuilder ---- */
/*
usage :

var sb = new ac.StringBuilder();
alert(sb.append("to").append("to").toString());
sb.setSeparator('|');
alert(sb.clear().append("to").append("to").toString());
*/

ac.StringBuilder = function() {
    this.strings = [];
    this.separator = '';
};
ac.StringBuilder.prototype.setSeparator = function(separator) {
    if (separator) {
        this.separator = separator;
    }
    return this;
};
ac.StringBuilder.prototype.append = function(value) {
    if (value) {
        this.strings.push(value);
    }
    return this;
};
ac.StringBuilder.prototype.clear = function() {
    delete this.strings;
    this.strings = [];
    return this;
}
ac.StringBuilder.prototype.toString = function() {
    return this.strings.join(this.separator);
}

/* ---- ac.log ---- */
/*
wraps console.log on supporting browsers
usage :

ac.log(sas_manager);
*/
ac.makeAlias = function(object, name) {
    var fn = object ? object[name] : null;
    if (typeof fn == 'undefined') return function() { }
    return function() {
        return fn.apply(object, arguments)
    }
}

ac.trace = {
    write: function() { },
    warn: function() { }
};

/* ---- $.formatTemplate ---- */
/*
usage :
$.formatTemplate("hello, [%name%]", {name:"David"});
*/
jQuery.extend(
    {
        formatTemplate: function(input, values) {
            return input.replace(/\[%([^%]+)\%]/ig, function(m, name) {
                return (!values || (values[name] === undefined)) ? "" : values[name];
            });
        }
    }
);

/* ---- $().loadTemplate ---- */
/*
usage :
$("#target").loadTemplate("/templates/test.html", {name:"David"}, function(){$("#target").remove();});
*/
jQuery.fn.extend(
    {
        loadTemplate: function(url, values, error) {
            var self = this;
            jQuery.ajax(
                {
                    url: url,
                    success: function(responseData) {
                        self.html(jQuery.formatTemplate(responseData, values));
                    },
                    error: error
                }
            );
        }
    }
);

/* hide and disable player */
function manageOverlayPlayer(toStop) {
    if ($("#V6_player").size() > 0) {
        if (toStop) {
            $("#V6_player").each(function() { try { this.sendToActionScript("pause"); } catch (err) { } });
            $("#V6_player").css("visibility", "hidden");
        }
        else {
            $("#V6_player").css("visibility", "visible");
        }
    }
}

function createOption(value, text, selected) {
    var option = document.createElement("option");
    option.value = value;
    option.text = text;
    option.selected = selected;
    return option;
}

//ac.global = {};

