/**
 * JS FILE: init.js
 * @author haudum
 * @copyright Lovely Systems AG
 *
 */

var domain = window.location.hostname.match(/(.*)\.(\w+\.\w+)/);
if (domain) document.domain = domain[2];

/****************************************
 * Events
 ****************************************/
var events = {};
events.AjaxEvent = {
    LOAD : "load",
    COMPLETE : "complete",
    SUCCESS : "success",
    FAIL : "fail",
    READY : "ready",
    HISTORY : "history"
};
events.BatchEvent = {
    INIT : "init",
    LOAD : "load",
    PARSE : "parse",
    COMPLETE : "complete"
};
events.UserEvent = {
    ACTION : "user_action",
    READY : "ready",
    LOGIN : "login",
    LOGOUT : "logout"
};
events.CaptchaEvent = {
    INIT : "init",
    LOAD : "load",
    CREATE : "create",
    COMPLETE : "complete",
    DESTROY : "destroy",
    RELOAD : "reload"
};
events.OverlayEvent = {
    INIT : "init",
    LOAD : "load",
    COMPLETE : "open",
    CLOSE : "close",
    CHANGE : "change"
};
events.TabEvent = {
    SWITCH : "switch"
};
events.FormEvent = {
    BEFORE_SUBMIT : "beforeSubmit",
    SUBMIT : "submit",
    RESPONSE : "response",
    SUCCESS : "success",
    FAIL : "fail",
    FORMDATA : "formdata"
};
events.UploadEvent = {
    SELECT : "select",
    PROGRESS : "progress",
    COMPLETE : "complete",
    ERROR : "error",
    DEFAULT : "default"
};
events.RPCEvent = {
    RESPONSE : "response",
    ERROR : "error",
    SUCCESS : "success",
    FAIL : "fail"
};

/****************************************
 * Browser Sniffing
 ****************************************/
var isIE6 = ($.browser.msie && Math.floor($.browser.version) == 6);
var isIE7 = ($.browser.msie && Math.floor($.browser.version) == 7);
var isSafari = ($.browser.safari);
var isFirefox = ($.browser.mozilla);
var isIE = (isIE6 || isIE7);

/****************************************
 * Base Globals
 ****************************************/
var GLOBALS = {
    HOSTNAME : function(){
        return window.location.protocol + "//" + window.location.host;
    }(),
    URL : function(){
        return window.location.href;
    }()
};


/****************************************
 * Firebug Console Workaround
 ****************************************/
(function setConsole(){
    if (!window.console || !console.firebug) {
        var names = ["log","debug",
                     "info","warn",
                     "error","assert",
                     "dir","dirxml",
                     "group","groupEnd",
                     "time","timeEnd",
                     "count","trace",
                     "profile","profileEnd"];
        window.console = {};
        for (var i = 0; i < names.length; ++i) {
            window.console[names[i]] = function(){};
        }
    };
}());



/****************************************
 * Inheritance, Subclassing
 ****************************************/
function inheritClass(func, parent){
    var sConstructor = parent.toString();
    var aMatch = sConstructor.match( /\s*function (.*)\(/ );
    if (aMatch != null) func.prototype[aMatch[1]] = parent;
    for (var m in parent.prototype) {
        if (!func.prototype[m]) {
            func.prototype[m] = parent.prototype[m];
        }
    }
};
function makeDispatchable(obj){
    obj._dispatcher = new ls.EventDispatcher();
    obj.addEventListener = function(event,callback,weight) {
        obj._dispatcher.addEventListener(event,callback,weight);
    };
    obj.addEventOnce = function(event,callback,weight){
        obj._dispatcher.addEventOnce(event,callback,weight);
    };
    obj.removeEventListener = function(event) {
        obj._dispatcher.removeEventListener(event);
    };
    obj.dispatchEvent = function(event){
        obj._dispatcher.dispatchEvent(event);
    };
};
var callableType = function(constructor) {
    return function() {
        var callableInstance = function() {
            var args = [];
            for (var i=0; i<arguments.length;i++) {
                args[i] = arguments[i];
            }
            args.unshift($(this));
            return callableInstance.__call__.apply(callableInstance, args);
        }
        constructor.apply(callableInstance, arguments);
        return callableInstance;
    }
};

function isArray(value) {
    return value &&
        typeof value === "object" &&
        typeof value.length === "number" &&
        typeof value.splice === "function" &&
        !(value.propertyIsEnumerable("length"));
};

$.prototype.getNSParams = function(ns){
    var params = {};
    this.each(function(){
        for (var i=0; i<this.attributes.length; i++) {
            var attr = this.attributes[i];
            var name = "";
            if (!ns) {
                name = attr.name;
            } else if (attr.name.indexOf(ns+":") == 0) {
                name = attr.name.split(ns+":")[1];
                params[name] = attr.value;
            }
        }
    });
    return params;
};

String.prototype.trim = function(chars) {
    var res = this.toString().replace(/^\s+|\s+$/g,"");
    if (chars) {
        if (typeof chars == "string") {
            var re = new RegExp(chars,"g");
            res = res.replace(re,"");
        } else if (isArray(chars)) {
            var regStr = "";
            for (var i=0; i<chars.length; i++) {
                regStr += chars[i];
                if (i < chars.length-1) regStr += "|";
            }
            regStr = ls.LovelyUtils.compileString("[${args}]",{"args":regStr});
            var re = new RegExp(regStr,"g");
            res = res.replace(re,"");
        } else if (typeof chars == "number") {
            var max = parseInt(chars,10);
            if (max <= res.length) max = res.length;
            res = res.substr(0,max);
        }
    }
    return res;
};

String.prototype.isQueryString = function() {
    var str = this.toString();
    var pairs = str.split("&");
    for (var i=0; i<pairs.length; i++) {
        var p = pairs[i].split("=");
        if (p.length != 2) {
            return false;
        }
    }
    return true;
};

/****************************************
 * Flash Movie Selector
 ****************************************/
function getFlashMovie(movieName) {
    var movie = document[movieName];
    if (!movie) movie = window[movieName];
    return movie;
};



/****************************************
 * Cookie Stuff
 ****************************************/
function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_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 false;
};
function setCookie(c_name,value,expiredays,path){
    if (!path) path="/";
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    var c = c_name+ "=" +value;
    if (expiredays != null) c+=";expires="+exdate.toGMTString();
    c+=";path="+path;
    document.cookie=c;
};

/****************************************
 * Hover Stuff
 ****************************************/
function showHover(title,id,event){
    var node = $(event.target);
    var id = (id) ? 'bubble_'+id : null;
    var TEMPLATE = '<div class="hoverBubbles" id="${id}"><p>${title}</p></div>';
    var title = (title) ? title : null;
    if(!id || !title){
        console.log('Error in bubbles');
        return;
    }
    var insert = TEMPLATE.replace(/\${id}/,id);
    insert = insert.replace(/\${title}/,title);

    $('body').append(insert);
    var bubble = $('#'+id);
    var top = 0;
    var left = 0;
    if (event.pageY){
        top = event.pageY;
        left = event.pageX;
    }
    else{
        top = event.clientY + document.documentElement.scrollTop;
        left = event.clientX + document.documentElement.scrollLeft;
    }
    bubble.css({"top":top+15,"left":left-25});
    node.bind("mousemove", function(event){
        if (event.pageY){
          top = event.pageY;
          left = event.pageX;
        }
        else{
          top = event.clientY + document.documentElement.scrollTop;
          left = event.clientX + document.documentElement.scrollLeft;
        }
        bubble.css({"top":top+15,"left":left-25});
    });
};

function destroyHover(){
    $('.hoverBubbles').each(function(){
        $(this).remove();
    });
};



/****************************************
 * Simple JSON Parser
 * @deprecrated
 ****************************************/
function readJson(str){
    try {
        var res;
        eval("res="+str);
        return res;
    } catch(e){
        console.warn("ERROR: Json read error: \n"+str);
        return false;
    }
    return false;
};


/****************************************
 * get version of js file
 ****************************************/
function getVersion(file) {
    if (!file || typeof file !== "string") return;
    var scripts = $("script");
    for (var i=0; i<scripts.length; i++) {
        var url = $(scripts[i]).attr("src");
        if (url) {
            var res = url.match(/([\w.]+)\?v=(.*)/);
            if (res && res[1] == file) {
                return res[2];
            }
        }
    }
};

