

if (!window.MLC) {
    
    window.MLC = {};
    MLC.id = "mlc";
    if (!MLC.protocol) { MLC.protocol = (("https:" == document.location.protocol) ? "https://" : "http://"); }
    if (!MLC.apiUrl) { MLC.apiUrl = MLC.protocol + 'laurageller.com/api'; }

    if (!MLC.key) { MLC.key = 'c7f2a9dc72a6c900d76065c97d3c4876'; }
    if (!MLC.gaCode){MLC.gaCode = 'UA-7939941-15'};
    
    MLC.AppSettings = {};
    MLC.Utilities = {};
    MLC.ApiClient = {};
    MLC.Temp = {};
    MLC.Cart = {};
    MLC.Products = {}
    MLC.Context = {};
    MLC.Context.doSave;
    MLC.Profile = {};
    MLC.Events = {};
    MLC.Tracking = {};
    MLC.Commerce = {};
    MLC.Document = {};
    
    
    
    MLC.Utilities.handleLoading = function(XHRobj) {
        if (XHRobj.readyState == 4) {        
            eval(XHRobj.responseText);        
        }
    }
    MLC.Utilities.handleError = function(errObj) {
    /*
        alert("Error: " + errObj.number
		+ "\nType: " + errObj.name
		+ "\nDescription: " + errObj.description
		+ "\nSource Object Id: " + errObj.srcElement.instanceId
	    );
	    */
    }
    
    if (!MLC.Utilities.xhrproxy)
    {
        MLC.Utilities.xhrproxy ={};
    }
    
    
    
    MLC.Profile.load = function(callback)
    { 
        var m = ""; 
        m += "key=" + MLC.key;
        if (!MLC.Context.suid)
        {
            alert("MLC.Context.suid is missing");
            return;
        }    
        m += "&suid=" + MLC.Context.suid; 
        MLC.Temp.loadProfileCallback = callback;
        var tid = MLC.Utilities.DynJSInject("loadProfile", MLC.apiUrl + "/profiles/current", m, "MLC.ApiClient.loadProfileHandler");
        MLC.Temp[tid] = callback;
    }
    
    MLC.ApiClient.loadProfileHandler = function (data)
    {
        if (!data.profile)
            return;
        var s;    
        for (s in data.profile)    
        {
            MLC.Profile[s] = data.profile[s];        
        }
        MLC.Events.onLoadProfile();
        
        if (MLC.Temp[data.tid])
        {	
            var old = document.getElementById(data.tid);
            if (old != null) {
                 old.parentNode.removeChild(old);
                 delete old;
            }        
            MLC.Temp[data.tid](data);
            delete MLC.Temp[data.tid];
        }
    }
    
    MLC.Profile.save = function(callback, log)
    {  
        MLC.ApiClient.saveProfile(callback, log);
    }
    
    
    
    MLC.Profile.addRole = function(role, callback, log)
    {
        MLC.Profile.addRolesPrivate = role;              
        MLC.ApiClient.saveProfile(callback, log);
    }
    
    MLC.Profile.addRoles = function(roles, callback, log)
    {   
        MLC.Profile.addRole(roles.join(","), callback, log);
    }
    
    MLC.Profile.removeRole = function(role, callback, log)
    {
        MLC.Profile.removeRolesPrivate = role;
        MLC.ApiClient.saveProfile(callback, log);
    }
    
    MLC.Profile.removeRoles = function(roles, callback, log)
    {
        MLC.Profile.removeRole(roles.join(","), callback, log);
    }
    
    
    
    MLC.Profile.isInRole = function(role)
    { 
        if (!MLC.Profile.roles)
            return false;
        var rs = MLC.Profile.roles.join(",");
        return (rs.indexOf(role)>-1);
    }
    
    MLC.Profile.SendPassword = function(email, callback)
    {    
        var m = ""; 
        m += "key=" + MLC.key;
        m += "&suid=" + MLC.Context.suid; 
        m += "&email=" + email;
        m += "&emailTemplate=send-password";
        MLC.Temp.sendPasswordCallback = callback;
        //var sec = MLC.apiUrl.replace("http", "https");
        var sec = MLC.apiUrl;
        MLC.Utilities.DynJSInject("send-password", sec + "/profiles/current/send-password.js", m, "MLC.ApiClient.sendPasswordHandler");
    }
    MLC.ApiClient.sendPasswordHandler = function (data)
    {
        if ( MLC.Temp.sendPasswordCallback)
        {
             MLC.Temp.sendPasswordCallback(data);
             delete  MLC.Temp.sendPasswordCallback;
        }
    }
    
    MLC.ApiClient.saveProfile = function(callback, log)
    {  
        if (callback)
        {
            MLC.Temp.saveProfileCallback = callback;
        }
        var m = ""; 
        m += "key=" + MLC.key;
        if (!MLC.Context.suid)
        {
            alert("MLC.Context.suid is missing");
            return;
        }    
        m += "&suid=" + MLC.Context.suid; 
        for (var s in MLC.Profile)
        {
            if ( MLC.Utilities.typeOf(MLC.Profile[s]) != 'function' && MLC.Utilities.typeOf(MLC.Profile[s])!= "array")
            {
                var v = MLC.Utilities.profileNameToUrl[s];
                if (v)
                    m += "&"+v+"=" + MLC.Profile[s];
            }
            else if (MLC.Utilities.typeOf(MLC.Profile[s])== "array")
            {
                if (s == "Roles")
                {
                    //do role stuff, dont save but addRoles and removeRoles
                }
                
            }
        }
        if (MLC.Profile.addRolesPrivate)
        {
            MLC.Profile.addRolesPrivate = null;
            delete MLC.Profile.addRolesPrivate
        }
        
        if (MLC.Profile.removeRolesPrivate)
        {
            MLC.Profile.removeRolesPrivate = null;
            delete MLC.Profile.removeRolesPrivate
        }
        
        if (m.toLowerCase().indexOf("fbuid")>-1 || m.toLowerCase().indexOf("email")>-1)        
        {
            if (log)
            {
                MLC.Tracking.trackEvent("Profile", "Save");
            }
            MLC.Utilities.DynJSInject("saveProfile", MLC.apiUrl + "/profiles/current", m, "MLC.ApiClient.saveProfileHandler");
        }
        else
        {
            alert("MLC.ApiClient.saveProfile: fbuid or email is missing from user profile.")
        }
        
        
    }
    
    MLC.ApiClient.saveProfileHandler = function (data)
    {
        if (data.isNewUser && data.profile.uuid) {
                //new user autmatically logged in
                MLC.ApiClient.loginHandler(data.profile);
        }
        //if the user exist in studio and fbuid returned MLC.ApiClient.LoginWithFB();        
        if (data.profile && data.profile.uuid  && data.profile.fbuid && !MLC.Context.uuid)
        {
            MLC.Profile.fbuid =  data.profile.fbuid;
            MLC.Profile.uuid = data.profile.uuid;
            if (data.roles)
                 MLC.Profile.roles = data.roles;
            MLC.ApiClient.LoginWithFB();
        }        
        else
        {
         if (data.roles)
                 MLC.Profile.roles = data.roles;
        }
        
        
        
        //save profile to cookie
        if (MLC.Profile.roles)
            MLC.Utilities.updateCookie("mlc", "roles="+MLC.Profile.roles.join(","), 1000*60*20);
         
            
        if (MLC.Temp.saveProfileCallback)
        {
            MLC.Temp.saveProfileCallback(data);
            delete MLC.Temp.saveProfileCallback;
        }
    }
    
    
    MLC.ApiClient.FBUserInfoInitHandler = function (u, ex)
    {
        //'name', 'pic_square', 'profile_url', 'first_name', 'last_name', 'locale'
        if (!u || !u[0])
        {
            //alert("MLC.ApiClient.FBUserInfoInitHandler: Error no user data from FB")
            //return;
        }
        else
        {
            var purl = u[0].profile_url;      
            var al = purl.substring(purl.lastIndexOf("/")+1)
            var eq = al.indexOf("=");
            if (eq>-1)
            {
                al = al.substring(eq+1);
            }
            MLC.Profile.Alias = MLC.Profile.alias =  al;
            MLC.Profile.FirstName = MLC.Profile.firstName = u[0].first_name;
            MLC.Profile.LastName = MLC.Profile.lastName = u[0].last_name;
            MLC.Profile.Nick= MLC.Profile.nick = u[0].name;
            var l0 = u[0].locale;        
            MLC.Context.lang = l0.replace("_", "-");
        }       
        MLC.Utilities.includeInitFBConnected();
    }
    
    
    /*/
        MLC ApiClient
    /*/
    
    
    
    
    
    MLC.ApiClient.createSession = function(lang)
    {
        // do detection
        var detection = MLC.Utilities.detect();
        var s;
        for (s in detection)
        {
            if (typeof (detection[s])== 'function')
                continue;
            MLC.Context[s] = detection[s];
        }
       
        var m = "";
        m += "key=" + MLC.key;
        if (MLC.Context.lang)
            lang = MLC.Context.lang;
        if (lang)
            m += "&lang="+lang;
            
        if(MLC.Context.navigatorLanguage && MLC.Context.navigatorLanguage!=undefined)
            m += "&navigatorLanguage=" +MLC.Context.navigatorLanguage;
        
        if (MLC.Context.colorDepth && MLC.Context.colorDepth!=undefined)
        m += "&colorDepth="+MLC.Context.colorDepth;
        
        if (MLC.Context.screenWidth && MLC.Context.screenWidth!=undefined)
        m += "&screenWidth="+MLC.Context.screenWidth;
        
        if (MLC.Context.screenHeight && MLC.Context.screenHeight!= undefined)
        m += "&screenHeight="+MLC.Context.screenHeight;
        
        if (MLC.Context.flashVersion && MLC.Context.flashVersion!=undefined)
        m += "&flashVersion="+MLC.Context.flashVersion;
        
        if (MLC.Context.timeZoneOffset && MLC.Context.timeZoneOffset!=undefined)
        m += "&timeZoneOffset=" + MLC.Context.timeZoneOffset;
        
        if (MLC.Context.country && MLC.Context.country!=undefined)
        m += "&country="+MLC.Context.country;
        
        if (MLC.Context.state && MLC.Context.state!=undefined)
        m += "&state="+MLC.Context.state;
        
        if (MLC.Context.city && MLC.Context.city!=undefined)
        m += "&city="+MLC.Context.city;
        
        if (MLC.Context.latitude && MLC.Context.latitude!=undefined)
        m += "&latitude="+MLC.Context.latitude;
        
        if (MLC.Context.longitude && MLC.Context.longitude!=undefined)
        m += "&longitude="+MLC.Context.longitude
        
        if (MLC.Profile.fbuid)
            m+= "&fbuid="+MLC.Profile.fbuid;
        
        MLC.Utilities.DynJSInject("createSession", MLC.apiUrl + "/create-session.js", m, "MLC.ApiClient.createSessionHandler");
    }
    
    MLC.ApiClient.newSession = function(callback)
    {
        lang = "en";
        var m = "";
        m += "key=" + MLC.key;
        if (MLC.Context.lang)
            lang = MLC.Context.lang;        
        m += "&lang="+lang;
        var tid = MLC.Utilities.DynJSInject(null, MLC.apiUrl + "/create-session.js", m, "MLC.ApiClient.genericJSONHandler");
        MLC.Temp[tid] = callback;
    }
    
    MLC.ApiClient.createSessionHandler = function (data)
    {
         var c = "";
         
         MLC.Context.suid = data.suid;
         MLC.Context.lang = data.lang;
         c += "&suid=" + data.suid;
         c += "&lang=" + data.lang;
         
         MLC.Utilities.setCookie("mlc", c, 1000*60*20);        
         
         if (data.uuid)
         {
            MLC.Events.onConnected ();
            MLC.Utilities.renderMLC ();
         }
         else
         {
            if (MLC.Profile.fbuid)
            {
                //after save raise Init and signup                
                MLC.ApiClient.saveProfile();
            }
            else
            {
                
            }
            MLC.Events.onNotConnected();
         }   
             
         MLC.Context.isReady = true;
         MLC.Events.onReady();               
    }
    
    MLC.ApiClient.logout = function(uuid)
    {
        var c = MLC.Utilities.getCookie("mlc");
        if (c.indexOf("uuid")==-1 && !uuid)
            return;
        
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;
        MLC.Utilities.DynJSInject("logout", MLC.apiUrl + "/logout.js", m, "MLC.ApiClient.logoutHandler");
    }
    
    MLC.ApiClient.logoutHandler = function (data)
    {   
        //alert("MLC.ApiClient.logoutHandler: data.success "+data.success)
        if (data.success)
        {
            var c = "";
            //delete cookie
            MLC.Utilities.setCookie("mlc", c, -1000*60*60*24);  
            MLC.Profile = {};
            MLC.Context.fbuid = null;
            delete MLC.Context.fbuid;
            
            MLC.Context.uuid = null;
            delete MLC.Context.uuid;
           
           MLC.Events.onNotConnected();
        } 
        else
        {
            alert("MLC.ApiClient.logoutHandler: Logout failed")
        }
    }
    
    MLC.ApiClient.login = function(un, pw, callback) {
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;
        m += "&un="+un;
        m += "&pw="+pw;
        MLC.Temp.loginCallback = callback;
        //var sec = MLC.apiUrl.replace("http", "https");        
        var sec = MLC.apiUrl;
        MLC.Utilities.DynJSInject("login", sec + "/login.js", m, "MLC.ApiClient.loginProxyHandler");
    }   
    MLC.ApiClient.loginProxyHandler = function (data)
    {
        if (data.success)
        {
            var c = "";
            c += "&mlcLogin=true";
            MLC.Utilities.updateCookie("mlc", c, 1000*60*20); 
        }
        MLC.ApiClient.loginHandler(data);
    }
    MLC.ApiClient.loginHandler = function (data)
    {  
        if (data.success)
        {   
            var c = "";
                     
            MLC.Context.uuid = data.uuid;
            
            c += "&uuid=" + data.uuid;
            
            if (data.fbuid && data.fbuid == MLC.Profile.fbuid)
            {
                c += "&fbuid=" + data.fbuid;
            }
            
            if (data.nick)
            {
                MLC.Context.nick = data.nick;
                c += "&nick=" + data.nick;
            }
            
            if (data.email)
            {
                MLC.Profile.email = data.email;
                c += "&email=" + data.email;
            }
            
            if (data.roles)
            {
                MLC.Context.roles = data.roles;
                c += "&roles=" + data.roles.join(",");
                 MLC.Profile.roles = data.roles;             
            }    
            
            if (data.lang)
            {
                MLC.Context.lang = data.lang;
                c += "&lang=" + data.lang;    
            }         
            
            MLC.Utilities.updateCookie("mlc", c, 1000*60*20);             
            MLC.Utilities.renderMLC();          
            MLC.Events.onConnected ();
        }
        else
        {
            //alert("MLC.ApiClient.loginHandler: Login failed")
        }
        if (MLC.Temp.loginCallback)
        {
            MLC.Temp.loginCallback(data);
            delete MLC.Temp.loginCallback;
        }
    }
    
    MLC.ApiClient.LoginWithFB = function()
    {
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;                       
        m += "&fbuid="+MLC.Profile.fbuid;
        m += "&lang="+MLC.Context.lang;
        MLC.Utilities.DynJSInject("login", MLC.apiUrl + "/login.js", m, "MLC.ApiClient.loginHandler");
    }
    
    
    MLC.Cart.SaveCartItem = function( cartUid, productUId, sku, quantity, callback)
    {
        //validate cartUid        
        var cu = "new";
        if (!MLC.Cart.cartUids)MLC.Cart.cartUids=[];        
        for (var i=0;i< MLC.Cart.cartUids.length;i++)
        {
            if (cartUid == MLC.Cart.cartUids[i])
            {
                cu = cartUid;
                break;
            }
        }
        
        
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;
        m += "&quantity="+quantity;
        var cartUrl =  MLC.apiUrl + "/carts/"+cu+"/"+productUId+"/"+sku+".js";
        MLC.Temp.saveCartCallback = callback;
        MLC.Utilities.DynJSInject("save-cart",cartUrl, m, "MLC.Cart.saveCartItemHandler");
    }
    
    MLC.Cart.saveCartItemHandler  = function (data)
    {
        var o = {};
        var a = [];
        for (var i=0; i < MLC.Cart.cartUids ;i++)
        {
            o[MLC.Cart.cartUids[i]] = true;
        }
        if (!o[data.cartUid])
            MLC.Cart.cartUids.push(data.cartUid);
            
        var c = "&cartUids="+ MLC.Cart.cartUids.join(",");
        var alive = 1000 * 60 *60 * 24 * 30;
        MLC.Utilities.setCookie(MLC.key+"-cart", c, alive);         
        MLC.Temp.saveCartCallback(data);
    }
    
    
    MLC.Cart.GetCart = function (cartUid, callback)
    {
        var cu; 
        if (!MLC.Cart.cartUids)MLC.Cart.cartUids=[];        
        for (var i=0;i< MLC.Cart.cartUids.length;i++)
        {
            if (cartUid == MLC.Cart.cartUids[i])
            {
                cu = cartUid;
                break;
            }
        }
        if (!cu)
        {
            callback(null);
            return;
        }
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;
        var cartUrl =  MLC.apiUrl + "/carts/"+cu+".js";
        MLC.Temp.getCartCallback = callback;
        MLC.Utilities.DynJSInject("get-cart",cartUrl, m, "MLC.Cart.getCartHandler");
    }
    
    MLC.Cart.getCartHandler = function (data)
    {   
        var c;
        if (data.cart)
        {
            var n = 0;
            for (i=0; i < data.cart.items.length;i++)
            {
                n+=data.cart.items[i].quantity;
            }
            c = "&itemNum="+ n;
            MLC.Cart.cart = data.cart;
        }
        else
        c = "";
        var alive = 1000 * 60 *60 * 24 * 30;
        MLC.Utilities.updateCookie(MLC.key+"-cart", c, alive); 
        
        MLC.Temp.getCartCallback(data);
    }
    
    
    MLC.Products.GetProducts = function (cat, start, max,callback)
    {
        var m = "";
        m += "key=" + MLC.key;
        m += "&suid=" + MLC.Context.suid;
        m += "&start=" + start;
        m += "&max=" + max;	                   
        m += "&tid=" + new Date().getTime();
        MLC.Temp.getProductsCallback = callback;
        MLC.Utilities.xhrproxy.onreadystatechange = MLC.Products.productsHandler;
        if (cat)
        {
            MLC.Utilities.xhrproxy.open("GET", MLC.apiUrl + "/products/categories/" + $('span:first', node).attr("alias") + ".js");	                           
        }
        else
        {
            MLC.Utilities.xhrproxy.open("GET", MLC.apiUrl + "/products.js");
        }
         MLC.Utilities.xhrproxy.send(m);
    }
    
    MLC.Products.productsHandler = function ()
    {
        if (MLC.Utilities.xhrproxy.readyState == 4) {
            var data = eval("(" + MLC.Utilities.xhrproxy.responseText + ")");
            MLC.Temp.getProductsCallback(data)
        }
    }
    
    
    
    MLC.Products.GetProduct = function (alias, callback)
    {
        var m = "";
        m += "key=" + MLC.key;           
        m += "&suid=" + MLC.Context.suid;         
        m += "&tid=" + new Date().getTime();
        MLC.Temp.getProductCallback = callback;
        MLC.Utilities.xhrproxy.onreadystatechange = MLC.Products.productHandler;
        MLC.Utilities.xhrproxy.open("GET", MLC.apiUrl + "/products/" + alias + ".js");
        MLC.Utilities.xhrproxy.send(m);
    }
    
    MLC.Products.productHandler = function ()
    {
        if (MLC.Utilities.xhrproxy.readyState == 4) {
            var data = eval("(" + MLC.Utilities.xhrproxy.responseText + ")");
            MLC.Temp.getProductCallback(data)
        }
    }
    
    MLC.Tracking.pageTracker
    MLC.Tracking.customPageVars = [];
    MLC.Tracking.customEventVars = [];
    MLC.Tracking.addCustomPageVars = function(o)
    {
        MLC.Tracking.customPageVars.push(o);  
    }
    
    MLC.Tracking.addCustomEventVars = function(o)
    {
        MLC.Tracking.customEventVars.push(o);  
    }
    
    MLC.Tracking.trackEvent = function (category, action, label, value)
    {   
        if (!category) return;
        if (!action) return;
        label = label?label:"";
        value = value?value:undefined;
        
        for (i=0;i< MLC.Tracking.customEventVars.length;i++)
        {
            var o = MLC.Tracking.customEventVars[i];
            MLC.Tracking.pageTracker._setCustomVar(o.slot, o.name, o.value, o.scope);
        }
        
        MLC.Tracking.pageTracker._trackEvent(category, action, label, value);
    }
    
     
    MLC.Commerce.Purchase = function(value, callback)
    {
         value += "&key=" + MLC.key;
         value += "&suid=" + MLC.Context.suid; 
                 
         var purl = MLC.apiUrl + "/purchase.js";
         
         MLC.Temp.purchaseCallback = callback;        
         //var sec = purl.replace("http", "https");
         var sec = purl;
         MLC.Utilities.DynJSInject("purchase", sec, value, "MLC.Commerce.purchaseHandler");
    }
    MLC.Commerce.purchaseHandler = function (data)
    {   
        //ordernumber status==success
        if (data.status && data.status=="Success" && MLC.Cart.cart && MLC.Tracking.pageTracker) {
                  try {
                      var cart = MLC.Cart.cart;
                      
                      MLC.Tracking.pageTracker._addTrans(
                           data.orderNumber,                              
                           'Laura Geller',                                
                            subtotal,                                     
                            tax,                                          
                            shipping,                                     
                            (MLC.Profile.city?MLC.Profile.city:""),       
                            (MLC.Profile.state?MLC.Profile.state:""),     
                            (MLC.Profile.country?MLC.Profile.country:"")  
                        );
                      for (var i =0; i < cart.items.length; i++) 
                      {    
                            MLC.Tracking.pageTracker._addItem(
                               data.orderNumber,           
                               cart.items[i].sku,          
                               cart.items[i].product,      
                               (cart.items[i].variation ? cart.items[i].variation : ""),   
                               cart.items[i].price, 
                               cart.items[i].quantity
                            );
                      }
                  
                      MLC.Tracking.pageTracker._trackTrans();
                  }
                  catch (e) { }
          }
        
        MLC.Cart.cart = null;
        MLC.Temp.purchaseCallback(data);        
    }
    
    MLC.Commerce.PurchaseStatus = function(transUid, cartUid, callback, debug)
    {
        var value = "";
         value += "&key=" + MLC.key;
         value += "&suid=" + MLC.Context.suid;
         value += "&transUid=" + transUid;
         value += "&cartUid=" + cartUid;
         
         if (debug)
         {
            value += "&status="+ debug;
         }
         
        var purl = MLC.apiUrl + "/purchase-status.js";
        //var sec = purl.replace("http", "https"); 
        var sec = purl;
        MLC.Temp.purchaseStatusCallback = callback;
        
        MLC.Utilities.DynJSInject("purchase", sec, value, "MLC.Commerce.purchaseStatusHandler");
    }
    
    
    MLC.Commerce.purchaseStatusHandler = function (data)
    {   
        MLC.Temp.purchaseStatusCallback(data);        
    }
    
    
    MLC.Document.save = function(doc, callback)
    {
        if (!doc)return;
        MLC.ApiClient.saveDocument(doc, callback);
        
    }
    
    MLC.Document.load = function( uid, callback, interactive)
    {
        MLC.ApiClient.getDocument(uid, callback, interactive);
    }
    
    MLC.Document.list = function( start, max , callback , q, sortBy, sortOrder, minAvailability, maxAvailability)
    {
        
        MLC.ApiClient.getDocumentList(start, max ,  callback, q, sortBy, sortOrder, minAvailability, maxAvailability );
    }
    
    
    MLC.ApiClient.saveDocument = function(doc, callback)
    {
        if (!doc)alert("Error: Document is missing!");
        
        
        
        MLC.Temp.saveDocumentCallback = callback;
        
        
        
        var m = "";
	    m += "key=" + MLC.key;
	    m += "&suid=" + MLC.Context.suid;
	    // m += "&callback=saveDocumentHandler";
	    m += "&tid=" + new Date().getTime();
	    var json = new MLC.Utilities.JSON();
	    var jso = json.decode(doc);	    
	    m += "&data=" + escape(jso);
	    
	    //POST either Flash or AJAX
	    if (MLC.Utilities.xhrproxy)
	    {
	        MLC.Utilities.xhrproxy.onreadystatechange = MLC.ApiClient.saveDocumentFLHandler;
	        if (!doc.uid) {
	            MLC.Utilities.xhrproxy.open("POST", MLC.apiUrl + "/docs/new.js");
	        }
	        else {
	            MLC.Utilities.xhrproxy.open("POST", MLC.apiUrl + "/docs/" + doc.uid + ".js");
	        }
	        MLC.Utilities.xhrproxy.send(m);
	    }
    }
    
    
    MLC.ApiClient.saveDocumentFLHandler = function ()
    {
        if (MLC.Utilities.xhrproxy.readyState == 4) {
	        var data = eval("(" + MLC.Utilities.xhrproxy.responseText + ")");
	        if (!data.success && data.incidentId)
	        {
	            alert("Sorry but an error has occurred\n\n" +
                      "The error have been logged and will be analysed.\n\n"+
                      "Incident #:"+ data.incidentId)
	        }
	        if (MLC.Temp.saveDocumentCallback)
	        {
	            MLC.Temp.saveDocumentCallback(data);
	            delete MLC.Temp.saveDocumentCallback;
	        }
	    }
    }
    
    
    MLC.ApiClient.getDocument = function(uid, callback, interactive)
    {
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;
        if (interactive) m += "&interactive=true";
        //MLC.Temp.getDocumentCallback = callback;
        var tid = MLC.Utilities.DynJSInject(null ,MLC.apiUrl+"/docs/"+uid+".js", m, "MLC.ApiClient.genericJSONHandler");
        MLC.Temp[tid] = callback;
        
    }
    
    MLC.ApiClient.getDocumentList = function ( start, max , callback, q, sortBy, sortOrder, minAvailability, maxAvailability)
    {
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;
        if (start)
            m += "&start="+start; 
        if (max)
            m += "&max="+max;     
        if (q)
        {
            m+= "&q=" + q;
            }
        else if(sortBy && sortOrder){
            m+= "&sortBy=" + sortBy;
            m+= "&sortOrder=" + sortOrder;
        }
        else if ((minAvailability != null && minAvailability != undefined) && (maxAvailability != null && maxAvailability != undefined))
        {
            m += "&minAvailability="+minAvailability;
            m += "&maxAvailability="+maxAvailability;
        }
            
        
       // MLC.Temp.getDocumentListCallback = callback;
        var tid = MLC.Utilities.DynJSInject(null,MLC.apiUrl+"/docs.js", m, "MLC.ApiClient.genericJSONHandler");
        MLC.Temp[tid] = callback;
    }
    
    MLC.Document.interact = function (uid, callback, assignPoints, rank)
    {
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;
        if (assignPoints)
        {
        m += "&assignPoints="+assignPoints;
        }
        if (rank)
        {
        m += "&rank="+rank;
        }
        var tid = MLC.Utilities.DynJSInject(null ,MLC.apiUrl+"/docs/"+uid+"/interact.js", m,"MLC.ApiClient.genericJSONHandler");
        MLC.Temp[tid] = callback;
    }
    
    MLC.Document.Category  = {};
    MLC.Document.Category.list = function (callback)
    {
        var m = "";
        m += "key="+MLC.key;
        m += "&suid="+MLC.Context.suid;        
        var tid = MLC.Utilities.DynJSInject(null ,MLC.apiUrl+"/docs/categories.js", m,"MLC.ApiClient.genericJSONHandler");
        MLC.Temp[tid] = callback;
    }
    
    MLC.ApiClient.genericJSONHandler = function ( data)
    {
        if (!data.success && data.incidentId)
	        {
	            alert("Sorry but an error has occurred\n\n" +
                      "The error have been logged and will be analysed.\n\n"+
                      "Incident #:"+ data.incidentId);
                      
	        }
	        
        if (MLC.Temp[data.tid])
        {
            var old = document.getElementById(data.tid);
            if (old != null) {
                 old.parentNode.removeChild(old);
                 delete old;
            }  
            MLC.Temp[data.tid](data);
            delete MLC.Temp[data.tid];
        }
    }
    
    
    
    /*/
        MLC Context
    /*/
    MLC.Context.isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;     
    MLC.Context.isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
    MLC.Context.isWebkit = (navigator.appVersion.toLowerCase().indexOf("webkit") != -1) ? true : false;
    MLC.Context.doExpires = true;    
    MLC.Context.lang;
    MLC.Context.isReady = false;
    MLC.Context.isConnected;
    MLC.Context.isFBConnected;
    
    
    MLC.Context.RegPage = function(p_name, p_url)
    {
        var alive = 1000 * 60 *60 * 24 * 30;
        MLC.Utilities.setCookie(p_name, "value="+escape(p_url), alive);
    }
    MLC.Context.GetRegPage = function (p_name)
    {
        var c = MLC.Utilities.getCookie(p_name);
        var a = c.split("=");
        if (a[1] && a[1].length > 5)
            return unescape(a[1]);
        else
            return null;
    }
    
    
    /*/
        MLC Utilities
    /*/
       
		MLC.Utilities.Valdation = {};
		MLC.Utilities.Valdation.PaymentCardType = {};
		MLC.Utilities.Valdation.PaymentCardType.Visa = "Visa";
		MLC.Utilities.Valdation.PaymentCardType.MasterCard = "MasterCard";
		MLC.Utilities.Valdation.PaymentCardType.Amex = "Amex";
		MLC.Utilities.Valdation.PaymentCardType.Discover = "Discover";
		MLC.Utilities.Valdation.PaymentCardType.Maestro = "Maestro";
		MLC.Utilities.Valdation.PaymentCardType.Solo = "Solo";
		
	 
		
		MLC.Utilities.renderMLC = function()
    {
        var tags = document.getElementsByTagName("*");
		
	    var n = tags.length;	
	    var i;
		var toRender = {};
	    for (i = 0; i < n; i++)
	    {	
		    var t = tags[i];
			if (!t || !t.tagName) continue;
		    var s = t.nodeName.toLowerCase();			
			//alert(s);
			var node;
			if (!MLC.Context.isIE && s.indexOf("mlc")>-1) node = s.split(":")[1];	 
			else node = s;
			if (node.indexOf("nick")>-1)
			{
				toRender["nick"] = true;				
			}
			if (node.indexOf("login")>-1)
			{
				toRender["login"] = true;
			}
			if (s.indexOf("open-studio-button")>-1)
			{
				toRender["open-studio-button"] = true;
			}
	    }
		var k;
		for (k in toRender)
		{
			MLC.Utilities.include(k+"-script", MLC.apiUrl + "/plugins/"+k+"/plugin.js", null);				
		}
    }
		
		MLC.Utilities.Valdation.validateCardNumber = function(cardType, cardNumber)
		{
			if (!cardNumber || cardNumber.length==0)
		    {
		        return false;
		    }
			else
		    { 
		        var chars = cardNumber;		
		        cardNumber = "";
		        for  (var i=0; i< chars.length; i++)
		        {
					var c = chars.charAt(i);
		            if (c.match(/[0-9]/g))
		            {
		                cardNumber += c;
		            }
		        }
		        if (cardNumber.length < 11 || cardNumber.length > 25)
		        {
		            return false;
		        }
		    }
			var pattern;
		    switch (cardType)
		    {
		        case MLC.Utilities.Valdation.PaymentCardType.Visa:
		            pattern = "^4[0-9]{12}(?:[0-9]{3})?$";
		            break;
		        case MLC.Utilities.Valdation.PaymentCardType.MasterCard:
		            pattern = "^5[1-5][0-9]{14}$";
		            break;
		        case MLC.Utilities.Valdation.PaymentCardType.Amex:
		            pattern = "^3[47][0-9]{13}$";
		            break;
		        case MLC.Utilities.Valdation.PaymentCardType.Discover:
		            pattern = "^6(?:011|5[0-9]{2})[0-9]{12}$";
		            break;
		        default:
		            return true;
		    }
			return cardNumber.match(new RegExp(pattern, "g"));
		}
			
		MLC.Utilities.Valdation.validateSecurityCode = function(securityCode, cardType)
       {
           if (!securityCode || securityCode.length==0)
           {
               return false;
           }
           else
           {
               var chars = securityCode;		
		        securityCode = "";
		        for  (var i=0; i < chars.length; i++)
		        {
					var c = chars.charAt(i);
		            if (c.match(/[0-9]/g))
		            {
		                securityCode += c;
		            }
		        }
               if (cardType == MLC.Utilities.Valdation.PaymentCardType.Visa ||
			    cardType == MLC.Utilities.Valdation.PaymentCardType.MasterCard ||
				cardType == MLC.Utilities.Valdation.PaymentCardType.Discover ||
				cardType == MLC.Utilities.Valdation.PaymentCardType.Maestro || 
				cardType == MLC.Utilities.Valdation.PaymentCardType.Solo)
               {
                   if (securityCode.length == 3)
                   {
                       return true;
                   }
                   else
                   {
                       return false;
                   }
               }
               else if (cardType == MLC.Utilities.Valdation.PaymentCardType.Amex)
               {
                   if (securityCode.length == 4)
                   {
                       return true;
                   }
                   else
                   {
                       return false;
                   }
               }
               else
               {
                   return false;
               }
           }
       }
		MLC.Utilities.Valdation.validateEmail= function(email)
       {
           if (!email || email.length==0)
           {
               return false;
           }
           else
           {
		   	    while(email.charAt(0)==" ")
				{
					email = email.substring(1);					
				}
				while(email.charAt(email.length-1)==" ")
				{
					email = email.substring(0, email.length-1);
				}
               email = email.toLowerCase();
               var pattern = "^(([\\w-]+\\.)+[\\w-]+|([a-z]{1}|[\\w-]{2,}))@"
                               + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                               + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                               + "([a-z]+[\\w-]+\\.)+[a-z]{2,4})$";

               return email.match(new RegExp(pattern, "g"));
           }
       }
       
       
    MLC.Utilities.profileNameToUrl = {"email":"email","emailTemplate":"emailTemplate","fbuid":"fbuid","addRolesPrivate":"addRoles","removeRolesPrivate":"removeRoles","un":"un","alias":"alias","nick":"nick","prefix":"prefix","firstName":"firstName","lastName":"lastName","suffix":"suffix","gender":"gender","dob":"dob","astroSign":"astroSign","agent":"agent","agentCode":"agentCode","mStandard":"mStandard","mAccuracy":"mAccuracy","eyeColor":"eyeColor","eyeDescr":"eyeDescr","ethnicity":"ethnicity","hairColor":"hairColor","hairDescr":"hairDescr","hairLength":"hairLength","skinColor":"skinColor","skinDescr":"skinDescr","naturalDescr":"naturalDescr","tattooDescr":"tattooDescr","piercingDescr":"piercingDescr","height":"height","weight":"weight","bustGirth":"bustGirth","bicepsGirth":"bicepsGirth","state":"state","city":"city","sublocation":"sublocation","street1":"street1","street2":"street2","postalCode":"postalCode", "phone":"phone"};
    
    
    MLC.Utilities.ajaxObject = function (url, callbackFunction) {
    var that = this;
    this.updating = false;
    this.abort = function() {
        if (that.updating) {
            that.updating = false;
            that.AJAX.abort();
            that.AJAX = null;
        }
    }
    this.update = function(passData, postMethod) {
        if (that.updating) { return false; }
        that.AJAX = null;
        if (window.XMLHttpRequest) {
            that.AJAX = new XMLHttpRequest();
        } else {
            that.AJAX = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (that.AJAX == null) {
            return false;
        } else {
            that.AJAX.onreadystatechange = function() {
                if (that.AJAX.readyState == 4  ) 
                {   
                    that.updating = false;  
                    var o = that.AJAX;
                    that.callback(that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML);
                    that.AJAX = null;
                }
                
            }
            that.updating = new Date();
            if (/post/i.test(postMethod)) {
                var uri = urlCall + '?' + that.updating.getTime();
                that.AJAX.open("POST", uri, true);
                that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                that.AJAX.send(passData);
            } else {
                var uri = urlCall + '?' + passData + '&timestamp=' + (that.updating.getTime());
                that.AJAX.open("GET", uri, true);
                // that.AJAX.setRequestHeader( "Content-type", "text/javascript" );
                that.AJAX.send(null);
            }
            return true;
        }
    }
    var urlCall = url;
    this.callback = callbackFunction || function() { };
}
   
   MLC.Utilities.typeOf = function(v) 
   {
      if (typeof(v) == "object") {
        if (v === null) return "null";
        if (v.constructor == (new Array).constructor) return "array";
        if (v.constructor == (new Date).constructor) return "date";
        if (v.constructor == (new RegExp).constructor) return "regex";
        return "object";
      }
      return typeof(v);
    }

    MLC.Utilities.parseJSON = function(filter) {

        // Parsing happens in three stages. In the first stage, we run the text against
        // a regular expression which looks for non-JSON characters. We are especially
        // concerned with '()' and 'new' because they can cause invocation, and '='
        // because it can cause mutation. But just to be safe, we will reject all
        // unexpected characters.

        try {
            if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
        test(this)) {

                // In the second stage we use the eval function to compile the text into a
                // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                // in JavaScript: it can begin a block or an object literal. We wrap the text
                // in parens to eliminate the ambiguity.

                var j = eval('(' + this + ')');

                // In the optional third stage, we recursively walk the new structure, passing
                // each name/value pair to a filter function for possible transformation.

                if (typeof filter === 'function') {

                    function walk(k, v) {
                        if (v && typeof v === 'object') {
                            for (var i in v) {
                                if (v.hasOwnProperty(i)) {
                                    v[i] = walk(i, v[i]);
                                }
                            }
                        }
                        return filter(k, v);
                    }

                    j = walk('', j);
                }
                return j;
            }
        } catch (e) {

            // Fall through if the regexp test fails.

        }
        throw new SyntaxError("parseJSON");
    };
    
    MLC.Utilities.trim = function (value)
    {
        if (typeof value != "string") return null;
        while (value.charAt(0) == " ") {
            value = value.substring(1);
        }
        while (value.charAt(value.length - 1) == " ") {
            value = value.substring(0, value.length - 1);
        } 
        return value;
    }
    
    
    MLC.Utilities.setCookie = function(c_name, value, alive) {
        
        var exdate = new Date();        
        var st = exdate.getTime();       
        exdate.setTime (st + alive);        
        document.cookie = c_name + "=" + escape(value) + ((!MLC.Context.doExpires) ? "" : ";expires=" + exdate.toGMTString())+"; path=/";
     }
     
     MLC.Utilities.updateCookie = function(c_name, update, alive) 
     {        
       
        var i;
        var s;
     
        var value = MLC.Utilities.getCookie(c_name);
        var ps = value.split("&");
        var o = {};
        for (i in ps)
        {
            var ta = ps[i].split("=");
            if (!ta || ta.length <2)
                continue;
                
            var p = ta[0];
            var v = ta[1];
            o[p] = v;
        }
        
        
        if (update && update!="")
        {
            ps = update.split("&");       
            for (i in ps)
            {
                ta = ps[i].split("=");
                if (!ta || ta.length <2)
                continue;
                p = ta[0];
                v = ta[1];
                o[p] = v;
            }
        }
        value = "";
        for (s in o)
        {
            if (o[s] == "" || o[s]== null || o[s]==undefined )
            {
                continue;
            }
            value += "&"+s+"="+o[s];
        }
       
        var exdate = new Date();
        exdate.setTime (exdate.getTime() + alive);
        document.cookie = c_name + "=" + escape(value) + ((!MLC.Context.doExpires) ? "" : ";expires=" + exdate.toGMTString());
     }
    
     MLC.Utilities.getCookie = function (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 "";
    }
    
    MLC.Utilities.includeInit = function ()
    {
        MLC.init("en", 0);    
    }
    
    MLC.Utilities.includeInitFBConnected = function (fb_uid)
    {
        MLC.init("en", 2, fb_uid);    
    }
    
    MLC.Utilities.includeInitFBNotConnected = function ()
    {
        MLC.init("en", 1);    
    }
    
    /* jsHandler.js */
    MLC.Utilities.include = function (id, filename, callback, target)
    {
        var old = document.getElementById(id);
        if (old != null) {
          old.parentNode.removeChild(old);
          delete old;
        }
       	 if (!target || target == undefined) target = "body";

        var body = document.getElementsByTagName(target).item(0);
        var script = document.createElement('script');
        script.id = id;
        script.src = filename;
        script.type = 'text/javascript';
        if (MLC.Context.isIE)
        {   
            script.onreadystatechange  = function () 
            {
                if (script.readyState == "loaded" || script.readyState == "complete") 
                {
                if (callback) eval(callback+"()")
                }
            }
        }
        else
        {        
            script.onload = eval(callback);
        }
        body.insertBefore(script, body.childNodes.item(0));  
    }
    
    MLC.Utilities.DynJSInject = function(id, url, data, callback, target)
    {  
       if (id)
       { 
           var old = document.getElementById(id);
           if (old != null) {
             old.parentNode.removeChild(old);
             delete old;
           }	   
       }
       var tid ;
       tid = new Date().getTime() + Math.floor( Math.random()*100000 );       
       while(MLC.Temp[tid])
       {
            tid = new Date().getTime() + Math.floor( Math.random()*100000 );  
       }
       
	   if (!target || target == undefined) target = "body";
       var body = document.getElementsByTagName(target).item(0);
       var script = document.createElement('script');
       script.id = id? id : tid;
       script.type = 'text/javascript';
       var src = url +"?";
       if (data && data != undefined)
            src += data;
       if (callback && callback != undefined)
            src += "&callback="+callback;
            
       src +="&tid=" + tid;                 
       script.src = src; 
       body.insertBefore(script, body.childNodes.item(0)); 
       return tid;
    }
    
    MLC.Utilities.addGATrackingCode = function()
    {
        if(!MLC.gaCode || MLC.gaCode == "")
            return;
        
        
       var target = "body";
       var body = document.getElementsByTagName(target).item(0);
       var script = document.createElement('script');
       script.id = "ga_tracking";
       script.type = 'text/javascript';
       var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
       
       if (MLC.Context.isIE)
        {   
            script.onreadystatechange  = function () 
            {
                if (script.readyState == "loaded" || script.readyState == "complete") 
                {
                    MLC.Events.onGaTrackingLoaded();
                }
            }
        }
        else
        {        
            script.onload = MLC.Events.onGaTrackingLoaded;
        }
        
       var src = gaJsHost + "google-analytics.com/ga.js";                        
       
       script.src = src; 
       body.insertBefore(script, body.childNodes.item(0));
    }
    
    
    MLC.Utilities.GetQueryParam = function ( name )
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1];
    }
    
    
    MLC.Utilities.JSON = function()
    {
	    var json = {};
	    json.encode = function (s)
	    {	
		    return ((s)?eval("("+s+")"):null);
	    };
    	
	    json.decode = function (o)
	    {
		    function r(arr)
		    {
			    var parts = [];
		        var is_list = MLC.Utilities.typeOf(arr) == "array";//(Object.prototype.toString.apply(arr) === '[object Array]');

		        for(var key in arr) {
		    	    var value = arr[key];
		            if(typeof value == "object") 
		            { 	//Custom handling for arrays
		                if(is_list) 
		            		    parts.push( r(value) ); /* :RECURSION: */
		                else 
		            		    parts.push('"' + key + '":' + r(value)); /* :RECURSION: */
		            } else 
		            {
		                var str = "";
		                if(!is_list) 
		            		    str = '"' + key + '":';
		                //Custom handling for multiple data types
		                if(typeof value == "number") 
		            		    str += value; //Numbers
		                else if(value === false) 
		            		    str += 'false'; //The booleans
		                else if(value === true) 
		            		    str += 'true';
		                else 
		            		    str += '"' + value + '"'; //All other things
		                // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
		                parts.push(str);
		            }
		        }
		        var rjson = parts.join(",");		    
		        if(is_list) 
		    	    return '[' + rjson + ']';//Return numerical JSON
		        return '{' + rjson + '}';//Return associative JSON
		    }
		    return r(o);
	    };
	    return json;
    }
     MLC.Utilities.getEmptyProductVariation = function()
    {
     var o ={										    
										   'sku':'', 
										   'warehouseSku':'', 
										   'manufacturerSku':'', 
										   'ean13':'', 
										   'upcA':'', 
										   'asin':'', 
										   'stockQuantity':1, 
										   'stockQuantityAlert':1,  
										   'images':[], 
										   'translations':{'en':{'name':'', 'descr':''}}
										   }
     
     return o;
    }
    MLC.Utilities.getEmptyProduct = function()
    {
        var o = {	 
								 'categories':[],
								 'template':'api/products/templates/template.js',
								 'translations':{'en':{'lang':'',														
												'alias':'',
												'title':'',
												'details':'',
												'descr':'',
												'instructions':'',
												'data':'',
												'notes':'',
												'shippingMessage':'',
												'inStockMessage':'In Stock',
												'outOfStockMessage':'Out of Stock'
												}
												},								
								'pricing':[{"currency":'USD' ,
										"price": 0, 
										"validFrom":"", 
										"validTo":""} ],									 
								
								'taxFree': false,
								'shippingPolicy':'none'/*shippable, free, none*/,
								'minOrderQuantity':1,
								'maxOrderQuantity':1,
								'shippingWidth':1,
								'shippingHeight':1,
								'shippingLength':1,
								'shippingWeight':1,
								'width':1,
								'height':1,
								'length':1,
								'weight':1,
								'config':'',
								'netWeight':1, 
								'manufacturerUid':'',
								'manufacturerLabel':'',
								'variations':[
										   {										    
										   'sku':'', 
										   'warehouseSku':'', 
										   'manufacturerSku':'', 
										   'ean13':'', 
										   'upcA':'', 
										   'asin':'', 
										   'stockQuantity':1, 
										   'stockQuantityAlert':1,  
										   'images':[], 
										   'translations':{'en':{'name':'', 'descr':''}}
										   } ]																
								 };
        
        return o;
    }
        
        
    MLC.Utilities.detectPlugin =  function(mname, desc, ext) {
	    var ndx=0;	if (navigator.mimeTypes && mname != '' ? (navigator.mimeTypes[mname] && navigator.mimeTypes[mname].enabledPlugin != false) : true) {
		    if (navigator.plugins) {
			    cnt = navigator.plugins.length;
			    if (mname != "" && navigator.mimeTypes[mname] == null)
				    {return 0;}
			    if (cnt > 0) {
				    for (ndx = 0; ndx < cnt; ndx++) {
					    if ((navigator.plugins[ndx].description.indexOf(desc) != -1) || (navigator.plugins[ndx].name.indexOf(desc) != -1))
						    {return 1;}
				    }
			    }
		    }
	    }
	    return 0;
    }
     
    MLC.Utilities.detectFlash = function () {
	    for (i = 10; i > 2; i--) {if (MLC.Utilities.detectPlugin('application/x-shockwave-flash','Flash '+i,'swf') == 1) return i;}
	    return MLC.Utilities.detectPlugin('application/x-shockwave-flash','Flash','swf') == 1 ? 2 : 0;
    }
     
    
    MLC.Utilities.detect = function () 
    {
        var result = {};
        if (screen.colorDepth && screen.colorDepth !=undefined)
	      result.colorDepth = screen.colorDepth;
	    
	    if (screen.width && screen.width !=undefined)
	        result.screenWidth = screen.width;
	    
	    if ( screen.height && screen.height!=undefined)
            result.screenHeight = screen.height;
	    
	    if (navigator.language && navigator.language!=undefined)
            result.navigatorLanguage = navigator.language;
	    
	    var fv = MLC.Utilities.detectFlash();
	    if (fv && fv!=undefined)
           result.flashVersion = MLC.Utilities.detectFlash();
           
	    var d = new Date();
        result.timeZoneOffset = d.getTimezoneOffset();
	    
	    if (window.google.loader.ClientLocation) {
		    var cl = window.google.loader.ClientLocation;		    
		    if (cl.address.country_code != undefined)
		    result.country = cl.address.country_code;
		    if (cl.address.city!=undefined)
		    result.city = cl.address.city;
		    if (cl.address.region!=undefined)
		    result.state = cl.address.region;
		    if (cl.latitude!=undefined)
		    result.latitude = cl.latitude;
		    if (cl.longitude!=undefined)
		    result.longitude = cl.longitude;
	    }
	   
	    
	    result.toString = function ()
	    {
	        var r = "";
	        for (var s in this)
	        {
	            if (s != "toString" && this[s]!= undefined)
	            {
	                r += "&"+s+"="+this[s];   
	            }	        
	        }
	        return r;
	    }
	    
	    return result;
    }
    
    
     /*/
        Events;
     /*/
        MLC.Events.onReadyCollection = [];
        MLC.Events.onConnectedCollection = [];
        MLC.Events.onNotConnectedCollection = [];
        MLC.Events.onLoadProfileCollection = [];
        MLC.Events.onGaTrackingLoadedCollection = [];
        
        MLC.Events.onReady = function()
        {
            var i;
            for (i = 0;i < MLC.Events.onReadyCollection.length; i++)
            {
                var f = MLC.Events.onReadyCollection[i];
                f();
            }            
        }
        
        MLC.Events.onConnected = function()
        {
            MLC.Context.isConnected = true;
            var i;
            for (i = 0;i < MLC.Events.onConnectedCollection.length; i++)
            {
                var f = MLC.Events.onConnectedCollection[i];
                f();
            }
            
            //Do after Connected Stuff
            MLC.Utilities.addGATrackingCode();
        }
        
        MLC.Events.onNotConnected = function()
        {
            MLC.Context.isConnected = false;
            var i;
            for (i = 0;i < MLC.Events.onNotConnectedCollection.length; i++)
            {
                var f = MLC.Events.onNotConnectedCollection[i];
                f();
            }
            
            //Do after NOT Connected Stuff
            MLC.Utilities.addGATrackingCode();
        }
        
        MLC.Events.onLoadProfile = function()
        {
            var i;
            for (i = 0;i < MLC.Events.onLoadProfileCollection.length; i++)
            {
                var f = MLC.Events.onLoadProfileCollection[i];
                f();
            }
        }
        
        MLC.Events.onGaTrackingLoaded = function()
        {
            var i;
            for (i = 0;i < MLC.Events.onGaTrackingLoadedCollection.length; i++)
            {
                var f = MLC.Events.onGaTrackingLoadedCollection[i];
                f();
            }
            
            try{
                MLC.Tracking.pageTracker = _gat._getTracker(MLC.gaCode);                
                //add custom variables to page tracker
                for (i=0;i< MLC.Tracking.customPageVars.length;i++)
                {
                    var o = MLC.Tracking.customPageVars[i];
                    MLC.Tracking.pageTracker._setCustomVar(o.slot, o.name, o.value, 3);
                }
                //                
                MLC.Tracking.pageTracker._trackPageview();
            } catch(err) {}
        }
    
    /*/
        Entry point methods;
    /*/
    
    MLC.addOnReadyCallback  = function(f)
    {
        MLC.Events.onReadyCollection.push(f);
    }
    
    MLC.addOnConnectedCallback  = function(f)
    {
        MLC.Events.onConnectedCollection.push(f);
    }
    
    MLC.addOnNotConnectedCallback  = function(f)
    {
        MLC.Events.onNotConnectedCollection.push(f);
    }
    
    MLC.Profile.addOnLoadCallback = function (f)
    {
        MLC.Events.onLoadProfileCollection.push(f);
    }
    
    MLC.Profile.addOnGaTrackingLoadedCallback = function (f)
    {
        MLC.Events.onGaTrackingLoadedCollection.push(f);
    }
    
    MLC.init = function(lang, fbStatus) 
    {
        var i;
        // fbStatus = 0 = no fb
        //            1 = has fb but not connected
        //            2 = connected        
        var cn = "mlc";
        var c = MLC.Utilities.getCookie(cn);
        var ca = c.split("&");
        
        for (i=0; i < ca.length;i++)
        {
            if (ca[i].indexOf("=") == -1)
                continue;
                
            var va = ca[i].split("=");
            MLC.Context[va[0]] = va[1];
            
            if (va[0] == "nick")            
            {
                MLC.Profile.nick = va[1];
            }
            if (va[0] == "roles")            
            {
                MLC.Profile.roles = va[1].split(",");
            }
            if (va[0] == "email")            
            {
                MLC.Profile.email = va[1];
            } 
        }//
        
        //retrieve cartUid
        
        var crtn = MLC.key+"-cart";
        var crt = MLC.Utilities.getCookie(crtn);
        var crts = crt.split("&");
        if (!MLC.Cart.cartUids)MLC.Cart.cartUids = [];
        for (i=0; i < crts.length;i++)
        {
            if (crts[i].indexOf("=") == -1)
                continue;                
            var va = crts[i].split("=");
            if (va[0] == "cartUids")
            {
                var cartUids  = va[1].split(",")
                MLC.Cart.cartUids = cartUids;
            }
        }
        
        //
        if (c == null || c == undefined || c == "") 
        {
            //MLC.ApiClient.saveProfile();
            MLC.ApiClient.createSession(lang);             
        }
        else 
        {  
            var c = MLC.Utilities.getCookie("mlc");
            if (MLC.Profile.fbuid && MLC.Profile.fbuid != MLC.Context["fbuid"])
                c+= "&fbuid="+MLC.Profile.fbuid;            
            MLC.Utilities.updateCookie("mlc", "", 1000*60*20);
            
            var detection = MLC.Utilities.detect();
            var s;
            for (s in detection)
            {
                if (typeof (detection[s])== 'function')
                    continue;
                MLC.Context[s] = detection[s];
            }
            
            
            if (c.toLowerCase().indexOf("uuid")>-1)
            {
                 MLC.Utilities.renderMLC();
                 MLC.Events.onConnected ();
            }
            else
            {
                if (fbStatus == 2)
                {
                    if (MLC.Context.doSave)
                    {
                        MLC.Context.doSave = false;
                        MLC.ApiClient.saveProfile();
                    }
                    else
                    {
                        MLC.ApiClient.LoginWithFB();
                    }
                }
                else
                {
                    MLC.Events.onNotConnected();
                }
             }   
             
              MLC.Context.isReady = true;
              MLC.Events.onReady();           
        }
       
    }
    
    
    
    
    //load gjsapi
    //load jquery
    
    MLC.Utilities.googleLoaded = function()
    {        
        if (!window.jQuery)
        {   
            //MLC.Utilities.jQueryLoaded
            //window.google.load("jquery", "1.3");            
           // window.google.setOnLoadCallback( MLC.Utilities.jQueryLoaded);
           MLC.Utilities.include("jqueryjs", MLC.protocol + "ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js", "MLC.Utilities.jQueryInit", "head")
        }
        else
        {
            MLC.Utilities.jQueryLoaded();
        }
    }
    MLC.Utilities.jQueryInit = function()
    {
        if(jQuery.isReady) 
        {
            MLC.Utilities.jQueryLoaded();
        }
        else
        {
            //$(document).ready( MLC.Utilities.jQueryLoaded );
            MLC.Utilities.jQueryLoaded ();
        }
    }
    
    MLC.Utilities.jQueryLoaded = function ()
    {   
        //load flXHR
        MLC.Utilities.include("jqueryjs", MLC.apiUrl+"/controls/com/flxhr/flXHR.js", "MLC.Utilities.flXHRLoaded", "head");
    }
    
    MLC.Utilities.flXHRLoaded = function ()
    {
         MLC.Utilities.xhrproxy = new flensed.flXHR({ autoUpdatePlayer: true, instanceId: "xhrproxy-1", xmlResponseText: false, onerror: MLC.Utilities.handleError, onreadystatechange: MLC.Utilities.handleLoading, loadPolicyURL: MLC.apiUrl+"/../crossdomain.xml" });        
        
        //initialize MLC.
        //with  facebook
        if (MLC.AppSettings.FBApiKey)
        {
            MLC.Utilities.include("fbjsapi", MLC.protocol + "static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US", "MLC.Utilities.includeFBInit");
        }
        else
        {
            //without facebook
            MLC.Utilities.includeInit();
        }
    }
    MLC.Utilities.include("gjsapi", MLC.protocol + "www.google.com/jsapi?key=ABQIAAAAkxeYDY0QrDGhDEFQ18Z5sBSlmO7_MREsfma48udr_A6C-9oW4xQTFnOwKDcDMmicbF7IHU0m0jKXPA", "MLC.Utilities.googleLoaded");
    
    
}

