﻿
if (Array.prototype.push == null) {
    Array.prototype.push = function() {
        var n = this.length >>> 0;
        for (var i = 0; i < arguments.length; i++) {
            this[n] = arguments[i];
            n = n + 1 >>> 0;
        }
        this.length = n;
        return n;
    };
}

if (Array.prototype.pop == null) {
    Array.prototype.pop = function() {
        var n = this.length >>> 0, value;
        if (n) {
            value = this[--n];
            delete this[n];
        }
        this.length = n;
        return value;
    };
}

var debugData = '';
/*
window.onerror = function(m, u, l)
{
    if (gigya.SNProxy.getDebugLevel() > 0) debugger;
    //var c = window.onerror.caller || window.onerror.arguments.caller;
    var c = '';
    var i = new Image();
    i.src = 'http://creator.zoho.com/api/test/json/javascript-error/Javascript_Error_Form/add/apikey=3f04084da29bce658c461b8fc7a4771f&Page=' + escape(escape(u)) + '&Line=' + l + '&Message=' + escape(m) + '&Caller=' + escape(('' + c).replace(/[+]/g, '%2b'))
    return true;
};*/

if (typeof gigya == 'undefined') {	gigya= new Object(); }
if (typeof gigya.SNProxy == 'undefined') { 	gigya.SNProxy = new Object(); }

gigya.SNProxy.requests  = {};
gigya.SNProxy.initRequests = {};
gigya.SNProxy.lcp = null;
gigya.SNProxy.MAX_CHUNK_SIZE = 100;
gigya.SNProxy.containerInfo = null;
gigya.SNProxy.requests  = {};
gigya.SNProxy.friendsResult = null;
gigya.SNProxy.friendsByID = null;
gigya.SNProxy.userInfoResult = null;

gigya.SNProxy.friendsSelectorConf = {
	css:"http://cdn.gigya.com/wildfire/js/gigya.FriendsSelector.css",
	maxSelection:10000,
	caption:"Select your friends",
	description:""
}

gigya.SNProxy.init = function(lcid, rid) 
{
    try {
        if (this.getDebugLevel() > 1) debugger;

        if (!this.containerReady) {
            this.initRequests[rid] = lcid;
        } else {
            var result = this.createOKResult(lcid, rid);
            this.sendResult(result);
        }
        if (typeof this.init.impl != "undefined")
            this.init.impl();

    }
    catch (e) {
        this.error(e);
    }
}

gigya.SNProxy.getUserInfo = function(lcid, rid) 
{
    if (this.getDebugLevel() > 1) debugger;
    if (!arguments.callee.impl) return this.handleNoImpl(lcid, rid);
    if (!this.containerInfo.viewerHasApp) return this.handleNoAuth(lcid, rid);

    try {
        if (this.userInfoResult == null)
            this.getUserInfo.impl(lcid, rid);
        else
            this.getUserInfo_callback(this.userInfoResult);
    } catch (e) {
        this.error(e);
    }
}

gigya.SNProxy.getUserInfo_callback = function(result) 
{
    try {
        if (this.getDebugLevel() > 1) debugger;

        this.userInfoResult = result;
        this.sendResult(result)
    } catch (e) { this.error(e); }

}

gigya.SNProxy.sendResult = function(result){
    if (!result.hadError) {
        result.errorCode = $str(null)
	    result.errorMessage= $str(null)
    }
    result.containerInfo = this.containerInfo;
    
    this.lcp.send(result.lcid, "onResult", result);
}

gigya.SNProxy.getFriends = function(lcid, rid)
{
    try
    {
        if (this.getDebugLevel() > 1) debugger;
        if (arguments.callee.impl == null) return this.handleNoImpl(lcid, rid);
        if (!this.containerInfo.viewerHasApp) return this.handleNoAuth(lcid, rid);

        if (this.friendsResult == null)
        {
            this.getFriends.impl(lcid, rid, null);
        }
        else
        {
            var result = Object.clone(this.friendsResult );
            result.lcid = lcid;
            result.rid = rid;
            this.getFriends_callback(result);
        }
    }
    catch (e)
    {
        this.error(e);
    }
}

gigya.SNProxy.getFriends_callback = function(result) {
    try {
        if (this.getDebugLevel() > 1) debugger;

        if (!result.hadError) {
            if (this.friendsResult == null)
                this.cacheFriends(result)

            result.count = result.friends.length;
            // send friends in chuncks of CHUNK_SIZE
            for (result.index = 0; result.index < result.count; result.index += this.MAX_CHUNK_SIZE) {
                result.friends = this.createArray();
                var chunkSize = Math.min(this.MAX_CHUNK_SIZE, result.count - result.index);
                for (var j = 0; j < chunkSize; j++) result.friends.push(this.friendsResult.friends[result.index + j]);
                this.sendResult(result);
            }
        } else {
            this.sendResult(result);
        }
    } catch (e) { this.error(e); }
}

gigya.SNProxy.cacheFriends = function(result)
{
    this.friendsResult = Object.clone(result);
    this.friendsByID = {};
    for (var i = 0; i < result.friends.length; i++)
        this.friendsByID[result.friends[i].gigyaUID] = result.friends[i];
}

gigya.SNProxy.getSNUIDs = function(gigyaIDsStr)
{
    var gids = gigyaIDsStr.split(',');
    var snuids = this.createArray();
    for (var i = 0; i < gids.length; i++)
    {
        if ( !this.isEmpty(this.friendsByID[gids[i]]) )
            snuids.push(this.friendsByID[gids[i]].SNUID);
        else
            snuids.push(gigyaIDsStr);
    }

    return snuids;
}

gigya.SNProxy.sendNotification = function(lcid, rid, rcptStr, subject, body)
{
    try
    {
        if (this.getDebugLevel() > 1) debugger;
        if (!this.containerInfo.viewerHasApp) return this.handleNoAuth(lcid, rid);
        if (!this.sendNotification.impl || !this.getFriends.impl) return this.handleNoImpl(lcid, rid);

        if (this.containerInfo.surface != "canvas")
        {
            var params =
            {
                mode: "msg",
                subject: escape(subject),
                body: escape(body),
                lcid: lcid,
                rid: rid
            }
            if (!this.isEmpty(rcptStr))
                params.rcpt = rcptStr;
                
            this.gotoCanvas.impl(lcid, rid, params, true);
            return;
        } else
        {
            if (!this.isEmpty(rcptStr))
            {
                this.sendNotification.impl(lcid, rid, rcptStr, subject, body, this.sendNotification_callback);
                return;
            }
        }

        this.getFriendsSelector().init(this.friendsSelectorConf);

        if (this.friendsResult == null)
        {
            this.getFriends.impl(lcid, rid,
				function(result)
				{
				    this.friendsResult = result;
				    this.showFriendsSelector(lcid, rid, subject, body);
				} .bind(this)
			);
        } else
        {
            this.showFriendsSelector(lcid, rid, subject, body);
        }
    } catch (e)
    {
        gigya.SNProxy.error(e);
    }
}

gigya.SNProxy.sendNotification_callback = function(result)
{
    try
    {
        if (gigya.SNProxy.getDebugLevel() > 1) debugger;

        if (this.containerInfo.appParams && this.containerInfo.appParams.mode == "msg" && this.containerInfo.surface == "canvas")
        {
            this.containerInfo.appParams.mode = "";
            this.onContainerReady();
        }
        else
        {
            this.sendResult(result);
        }
    } catch (e) { this.error(e); }
}


gigya.SNProxy.showFriendsSelector = function(lcid, rid, subject, body)
{
    if (gigya.SNProxy.getFriendsSelector() == null) throw ("FriendSelector component is missing");
    gigya.SNProxy.getFriendsSelector().show(
		this.friendsSelectorConf,
		this.friendsResult.friends,
		function(recipients)
		{
		    if (recipients && recipients.length > 0)
		    {
		        var snuids = this.createArray();
		        for (var i = 0; i < recipients.length; i++) snuids.push(recipients[i].SNUID);
		        var rcptStr = snuids.join(',');
		        this.sendNotification.impl(lcid, rid, rcptStr, subject, body, this.sendNotification_callback);
		    }
		    else
		    {
		        var result = this.createOKResult(lcid, rid);
		        result.sendCount = 0;
		        this.sendNotification_callback(result);
		    }
		} .bind(this)
	);
}


gigya.SNProxy.getFriendsSelector = function() {
    if (typeof gigya.FriendsSelector != "undefined")
        return gigya.FriendsSelector; // overriden in some providers like FB who returns it from parent.
    else
        return null;
}

gigya.SNProxy.reportUserAction = function(lcid, rid, action) {
    try {
        if (this.getDebugLevel() > 1) debugger;
        if (arguments.callee.impl == null) return this.handleNoImpl(lcid, rid);
        if (!this.containerInfo.viewerHasApp) return this.handleNoAuth(lcid, rid);

        action = this.prepareObject(action);

        this.reportUserAction.impl(lcid, rid, action);
    } catch (e) {
        this.error(e);
    }
}
gigya.SNProxy.prepareObject = function(obj) {
    for (var key in obj) 
    {
        if (this.isEmpty(obj[key]))
            obj[key] = "";
    }
    return obj;
}
gigya.SNProxy.reportAction_callback = function(result) {
    try {
        if (this.getDebugLevel() > 1) debugger;
        this.sendResult(result);
    } catch (e) {
        this.error(e);
    }
}

gigya.SNProxy.gotoCanvas = function(lcid, rid, params, popup) 
{
    try
    {
        if (this.getDebugLevel() > 1) debugger;
        if (arguments.callee.impl == null) return this.handleNoImpl(lcid, rid);
        if (!this.containerInfo.viewerHasApp) return this.handleNoAuth(lcid, rid);
        
        this.gotoCanvas.impl(lcid, rid, params, popup);

    } catch (e) {
        this.error(e);
    }
}

gigya.SNProxy.onContainerReady = function() {
    try {
        if (this.getDebugLevel() > 1) debugger;

		this.lcp = this.getLCProxy();
		
        this.friendsSelectorConf.containerWindow = this.getMainWindow();
        for (var rid in this.initRequests) {
            var result = this.createOKResult(this.initRequests[rid], rid);
            this.sendResult(result);
        }
        if (this.onContainerReady.impl)
            this.onContainerReady.impl();

        if (gigya.SNProxy.getFriendsSelector() != null)
            // initing friend slector in delay to allow iframes to load be fore injection
            setTimeout("gigya.SNProxy.getFriendsSelector().init(gigya.SNProxy.friendsSelectorConf)", 500);

        this.containerReady = true;
    }
    catch (e) {
        this.error(e);
    }

}

gigya.SNProxy.createArray = function()
{
	try {
		return new parent.Array();
	} catch(e)
	{
		return new Array();
	}
}

gigya.SNProxy.createOKResult = function(lcid, rid)
{
	return { hadError:false, rid:rid, lcid:lcid };
}

gigya.SNProxy.createErrorResult = function(lcid, rid, code, msg)
{
    return {hadError:true, errorCode:code, errorMessage:msg, lcid:lcid, rid:rid};
}

gigya.SNProxy.handleNoImpl = function(lcid, rid) 
{
    var result = this.createErrorResult(lcid, rid, "NOT_IMPLEMENTED", "The method is not implemented for the current network");
    this.sendResult(result);
}

gigya.SNProxy.handleNoAuth = function(lcid, rid) {
    var result = this.createErrorResult(lcid, rid, "NOT_AUTHORIZED", "Uanble to access viewer data");
    this.sendResult(result);
}


gigya.SNProxy.getLCProxy = function()
{
	var id  = "LCProxy";
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[id];
	}else{
		if(document[id].length != undefined){
			return document[id][1];
	}
		return document[id];
	}
}

gigya.SNProxy.error = function(e)
{
    if (gigya.SNProxy.isDebug())
    {
        debugger;
    }
    else {
        try {console.log(e.message)} catch(ex) {}
        throw (e);
    }

    //var callerCode = this.error.caller + "";
    //var location = document.location;

    //window.onerror(e+"", location, -1);
}


gigya.SNProxy.getStackTrace = function()
{
    var callstack = [];
    try
    {
        i.dont.exist += 0; //does not exist - that's the point
    } catch (e)
    {
        if (e.stack)
        {
            //Firefox
            return e.stack;
        }
        else
        {
            var currentFunction = arguments.callee.caller;
            while (currentFunction)
            {
                var fn = currentFunction.toString();
                //If we can't get the function name set to "anonymous"
                var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
                callstack.push(fname);
                currentFunction = currentFunction.caller;
            }
            return callstack.join('\n\n');
        }
    }
}

gigya.SNProxy.getMainDoc = function()
{
    // overriden by FB for example, where main doc is parent
    return document;
}
gigya.SNProxy.getMainWindow = function()
{
    // overriden by FB for example, where main window is parent
    return window;
}

gigya.SNProxy.isDebug = function()
{
    return this.getDebugLevel() > 0;
}

gigya.SNProxy.getDebugLevel = function()
{
    if (this.containerInfo && this.containerInfo.appParams && this.containerInfo.appParams.debug)
        return this.containerInfo.appParams.debug;
    else
        return 0;
}

gigya.SNProxy.addImpl = function(method, methodImpl)
{
    method.impl = methodImpl.bind(gigya.SNProxy);
}

gigya.SNProxy.isEmpty = function(obj)
{
    return typeof obj == 'undefined' || obj == null || obj == 'null' ||  obj == '' || (typeof obj == "object" && obj.EmptyString);
}

gigya.SNProxy.setUserDate = function(u, dateStr) 
{
    var d = null;
    if (dateStr != null) {
        try {
            d = new Date(dateStr);
            if (isNaN(d)) d = null;
        } catch (ex) { }
    }

    if (d != null) {
        u.birthDay = d.getDate();
        u.birthMonth = d.getMonth() + 1;
        u.birthYear = d.getFullYear();
    } else {
        u.birthDay = 0;
        u.birthMonth = 0;
        u.birthYear = 0;
    }
}

$str = function(s)
{
    if (s == null || s=="") return { EmptyString: true };
    else return s+"";
}