﻿/// Picker
// ----------------------------------------------------------------------------
if(!gigya)var gigya = {};

/// Variables.
gigya.FriendsSelector = {};
gigya.FriendsSelector.dialogFrame = null;
gigya.FriendsSelector.inited = false;
gigya.FriendsSelector.parentRef = null;
gigya.FriendsSelector.frameRef = null;
gigya.FriendsSelector.friendsCollection = null;
gigya.FriendsSelector.selectedFriends = null;
gigya.FriendsSelector.hasCss = false;
gigya.FriendsSelector.callback = null;
gigya.FriendsSelector.conf = {}
gigya.FriendsSelector.defualtConf = {
    caption: "Friends Selector",
    width: 400,
    height: null,
    css: '/wildfire/js/gigya.FriendsSelector.css',
    offset:null,        /// { 'left': 0, 'top':0 }
    containerWindow: window,
    relativeTo: null
}


/// Divs.
gigya.FriendsSelector.Divs = {};
gigya.FriendsSelector.Divs.Holder = null;
gigya.FriendsSelector.Divs.Friends = null;
gigya.FriendsSelector.Divs.PickerLimitMsg = null;
gigya.FriendsSelector.Divs.FilterByName = null;
gigya.FriendsSelector.ShowType = null;

/// Enum for the Filtering options.
gigya.FriendsSelector.FilterBy = {
    ALL: "all",
    SELECTED: "selected",
    UNSELECTED: "unselected"
}



/// Urls.
gigya.FriendsSelector.Urls = {}
gigya.FriendsSelector.Urls.Canvas = 'http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=113070&appvers=dev';
gigya.FriendsSelector.Urls.AppInstall = '';

/// Templates.
gigya.FriendsSelector.SelectedTabTemplate = new Template('Selected ( <b>#{Count}</b> )');
gigya.FriendsSelector.MaxSelectionMessageTemplate = new Template('You may only select #{Count} friend(s).');
gigya.FriendsSelector.FilterByNameTemplate = new Template('Start Typing a Friend\'s Name');
gigya.FriendsSelector.FriendTemplate = new Template('<li class="friend" id="friend_#{UID}" ><a onclick="gigya.FriendsSelector.selectFriend(parseInt(this.parentNode.id.split(\'_\')[1]));return false;" href="#" ><span class="friend_image" ><img src="#{photoURL}" /><span></span></span><strong class="friend_name">#{Name}</strong></a></li>');
gigya.FriendsSelector.UI = new Template(''+
'	<div id="top">'+
'    <div class="top_left">'+
'           <h2>#{caption}</h2>'+
'           <h3><span class="fsDescription">#{description}</span></h3>'+
'       </div>'+
'       <div class="top_right">'+
'	        <div id="search">'+
'	            <span class="search_text">Find Friends: </span><input type="text" id="filterbyname" />'+
'	        </div>'+
'	    </div>'+
'	    <div class="clear"></div>'+
'	</div>'+
'	<div class="clear"></div>'+
'	<div class="wrapper">'+
'	<div id="tabs">'+
'	    <a onclick="gigya.FriendsSelector.Tabs.show(gigya.FriendsSelector.FilterBy.ALL);return false;" href="#" class="seltab tab_all" >View all</a>'+
'	    <a onclick="gigya.FriendsSelector.Tabs.show(gigya.FriendsSelector.FilterBy.SELECTED);return false;" href="#"  class="tab_selected" id="tab_selected">Selected(0)</a>'+
'	    <a onclick="gigya.FriendsSelector.Tabs.show(gigya.FriendsSelector.FilterBy.UNSELECTED);return false;" href="#" class="tab_unselected" >Unselected</a>'+
'	    <div class="clear"></div>'+
'	</div>'+
'	<div class="clear"></div>'+
'	<ul id="friends" class="friends"></ul>'+
'   <div class="clear"></div>'+
'   <input type="button" value="OK" style="width:80px" onclick="gigya.FriendsSelector.ok();" />'+
'   <input type="button" value="Cancel" style="width:80px"  onclick="gigya.FriendsSelector.cancel();" />' +
'   <div class="bottom clear"></div>'+
'	</div>'
);


gigya.FriendsSelector.initialize = function() 
{
    
    var body = $(document.body);
    
    /// Inject Css.
    if(!this.hasCss){
        this.AddCss(this.conf.css);
        this.hasCss = true;    
    }
    
    ///Add UI
    this.Divs.Holder = new Element("div"); 
    this.Divs.Holder.addClassName('fsholder');
    this.Divs.Holder.update(this.UI.evaluate(this.conf));
    this.Divs.Holder.setStyle({"display":"none"});
    $(document.body).appendChild(this.Divs.Holder);
    
    setTimeout(function(){
        //this.getParentCenter(this.Divs.Holder);
        
        this.Divs.Holder.setStyle({"display":"block"});
    }.bind(this),300);
    
	
	///Friends
	this.Divs.Friends = this.Divs.Holder.select("#friends")[0];

    ///Add PickerLimit Messege Div.
    this.Divs.PickerLimitMsg = new Element("div",{id: "PickerLimitMsg"});
    this.Divs.PickerLimitMsg.setStyle({display:"none"});
    $(document.body).appendChild(this.Divs.PickerLimitMsg);
    
	/// initialize Picker Limit/Picker Limit Message Dom objects.
	this.Divs.PickerLimitMsg.update(this.MaxSelectionMessageTemplate.evaluate({Count: gigya.FriendsSelector.conf.maxSelection}));

	
	/// initialize Filter By Name Dom object.
	this.Divs.FilterByName = this.Divs.Holder.select("#filterbyname")[0];
	this.Divs.FilterByName.value = this.FilterByNameTemplate.evaluate({})
	this.Divs.FilterByName.observe("focus", function(){this.value='';});
    this.Divs.FilterByName.observe("blur", function(){if(this.value=='')this.value=gigya.FriendsSelector.FilterByNameTemplate.evaluate({});});
	this.Divs.FilterByName.observe("keyup", function(){gigya.FriendsSelector.insertFriends(this.value);return true;});
	
	///Default show type.
	this.ShowType = this.FilterBy.All;

}

gigya.FriendsSelector.injectDialogFrame = function(conf)
{
    var containerDoc;
    if (conf.containerWindow)
        containerDoc = conf.containerWindow.document
    else
        containerDoc = window.document;

    var ifr = containerDoc.createElement('iframe');
    ifr.id = 'ifrSelector';
    ifr.style.position = "absolute";
    ifr.style.display = "none";
    ifr.style.left = 0;
    ifr.style.top = 0;
    if (Prototype.Browser.IE)
    {
        ifr.style.width = 455;
        ifr.style.height = 355;
    } else
    {
        ifr.style.width = "465px";
        ifr.style.height = "360px";
    }
    ifr.frameBorder = 0;
    ifr.scrolling = "no";

    containerDoc.body.appendChild(ifr);

    var sb = [
				'<html id="html">',
				'<head>',
				'<scr', 'ipt src="http://cdn.gigya.com/wildfire/JS/prototype.js"></scr', 'ipt>',
				'<scr', 'ipt src="http://cdn.gigya.com/wildfire/JS/gigya.friendsSelector.js"></scr', 'ipt>',
				'</head>',
				'<body style="margin:0px;padding:0px;background-color:Transparent;" id="body" >',
				'</body></html>'
			];
    var html = sb.join('');

    this.dialogFrame = ifr;
    var doc = this.getDialogFrameDocument();
    doc.open();
    doc.write(html);
    doc.close();
    try
    {
        if (this.dialogFrame.contentWindow && this.dialogFrame.contentWindow.gigya
                && this.dialogFrame.contentWindow.gigya.FriendsSelector)
            this.frameRef = this.dialogFrame.contentWindow.gigya.FriendsSelector;
    }
    catch (e) { }
    return this.dialogFrame;
}
gigya.FriendsSelector.centerDialogFrame = function()
{
    this.dialogFrame.style.display = 'block';
    /// if there is an offset under config
    if (this.conf.offset)
    {
        this.dialogFrame.style.left = (this.conf.offset.left) + 'px';
        this.dialogFrame.style.top = (this.conf.offset.top) + 'px';
    }
    /// else if there is a relativeTo under config.
    else if (this.conf.relativeTo)
    {
        this.dialogFrame.style.left = 0;
        this.dialogFrame.style.top = 0;

        var offset = this.getScrollOffset(this.conf.relativeTo);
        var dOffset = this.getOffset(this.conf.relativeTo);
        var left = (Math.round(this.conf.relativeTo.clientWidth - this.dialogFrame.clientWidth) / 2);
        var top = (offset.top); //(Math.round(this.conf.relativeTo.clientHeight - this.dialogFrame.clientHeight) / 2);

        if ((top + this.dialogFrame.clientHeight) > this.conf.relativeTo.clientHeight)
            top -= ((top + this.dialogFrame.clientHeight) - this.conf.relativeTo.clientHeight);
        //top = (offset.top - top);

        if (top < 0) top = 0;

        this.dialogFrame.style.left = (offset.left) + left;
        this.dialogFrame.style.top = top;


    }
    ///else center screen.
    else
    {
        var offset = this.getOffset(window);
        var winSize = this.getWindowSize(window);
        this.dialogFrame.style.left = offset.left + Math.round((winSize.width - this.dialogFrame.clientWidth) / 2) + 'px';
        this.dialogFrame.style.top = offset.top + Math.round((winSize.height - this.dialogFrame.clientHeight) / 2) + 'px';
    }

}
gigya.FriendsSelector.getOffset = function(elm)
{
    
    var offset = {left:0,top:0};
    ///If itsss a window.
    if(!elm.tagName)
    {
        offset = {
            left: elm.document.body.offsetLeft,
            top: elm.document.body.offsetTop
        };
    }
    ///Else its an element.
    else 
    {
        
        offset = {
            left: elm.offsetLeft ,
            top: elm.offsetTop
        };
    }
    
    offset.left = parseInt(offset.left.toString().replace('px',''));
    offset.top = parseInt(offset.top.toString().replace('px',''));
    
    if(isNaN(offset.top))
        offset.top = 0;
        
    if(isNaN(offset.left))
        offset.left = 0;
        
    return offset;
}

gigya.FriendsSelector.getScrollOffset = function(elm)
{
    
    var offset = {left:0,top:0};
    ///If itsss a window.
    if(!elm.tagName)
    {
        offset = {
            left: elm.document.body.scrollLeft,
            top: elm.document.body.scrollTop
        };
    }
    ///Else its an element.
    else 
    {
        offset = {
            left: $(elm).scrollLeft ,
            top: $(elm).scrollTop
        };
    }
    
    offset.left = parseInt(offset.left.toString().replace('px',''));
    offset.top = parseInt(offset.top.toString().replace('px',''));
    
    if(isNaN(offset.top))
        offset.top = 0;
        
    if(isNaN(offset.left))
        offset.left = 0;
        
    return offset;
}

gigya.FriendsSelector.getWindowSize = function(win)
{
    var winW;
    var winH;
    if (win.innerWidth)
    {
        winW = win.innerWidth;
        winH = win.innerHeight;
    } else
    {

        if(win.document)
        {
                winW = win.document.body.offsetWidth;
                winH = win.document.body.offsetHeight;
        }
        else
        {
            winW = win.documentElement.offsetWidth;
            winH = win.documentElement.offsetHeight;
        }

    }
    return { 'width': winW, 'height': winH };
}
    
    
gigya.FriendsSelector.zIndex = 1000;
gigya.FriendsSelector.getParentCenter = function(elm, parent)
{
    elm = $(elm);
    
    if (parent)
    {
        parent = $(parent);
        parent.insert({ top: elm });
    }
    else
        parent = document.viewport;

    var parentElm = elm.up();
    var parentDim = parent.getDimensions();
    var parentOffset = parentElm.cumulativeScrollOffset();

    var elmDim = elm.getDimensions();
    var elmOffset = elm.cumulativeScrollOffset();
    var docOffset = document.viewport.getScrollOffsets();
    
    
    var left = elmOffset.left + docOffset.left + parentOffset.left + ((parentDim.width - elmDim.width)/2);
    var top =  elmOffset.top + parentOffset.top +  docOffset.top + ((parentDim.height - elmDim.height)/2);

//    var left = 0;
//    var top = 0;

    ///TODO: should be the solution, currently there has an error on IE7.
    //elm.clonePosition(parent,{offsetTop:top,offsetLeft:left,setWidth:false,setHeight:false});
    elm.setStyle({ position: "absolute" });
    elm.setStyle({ zIndex: ++gigya.FriendsSelector.zIndex });
    elm.setStyle({ top: top + "px" });
    elm.setStyle({ left: left + "px" });
}

gigya.FriendsSelector.init = function(conf)
{
    this.inited = true;
    if (this.dialogFrame == null)
        this.injectDialogFrame(conf);
}

/// Friends Selector Show
gigya.FriendsSelector.show = function(conf, friends, callback)
{
    if (!this.inited) throw ("gigya.FriendsSelector.init must be called before show");

    if (typeof this.dialogFrame.contentWindow.gigya == 'undefined') // dialog window not ready yet
    {
        setTimeout(function() { gigya.FriendsSelector.show(conf, friends, callback); }, 100);
        return;
    }

    this.conf = this.createConfiguration(conf);

    ///Center now.
    this.centerDialogFrame();

    ///Call the show that inside the iframe.
    if (!this.frameRef)
        this.frameRef = this.dialogFrame.contentWindow.gigya.FriendsSelector;

    this.frameRef.showDialogFrame(conf, friends, callback);

}

gigya.FriendsSelector.showDialogFrame = function(conf, friends, callback)
{
    this.parentRef = window.parent.gigya.FriendsSelector;
    this.dispose();

    this.conf = this.createConfiguration(conf);
    this.friendsCollection = friends;
    this.selectedFriends = new Hash();

    this.friendsCollection.getById = function(id)
    {
        User = null;
        this.each(function(gsUser)
        {
            if (User == null && gsUser.SNUID == id)
                User = gsUser;
        });
        return User;
    }

    this.callback = callback;
    this.initialize();

    this.insertFriends(null);
}

gigya.FriendsSelector.hide = function(){
    this.dialogFrame.style.display = 'none';
}


gigya.FriendsSelector.getDialogFrameDocument = function()
{
    if(this.dialogFrame.contentDocument)         
        doc = this.dialogFrame.contentDocument;  
    else if(this.dialogFrame.contentWindow)  
        doc = this.dialogFrame.contentWindow.document;  
       
    return doc;  
}

gigya.FriendsSelector.createConfiguration = function(conf)
{
    for(var i in this.defualtConf)
    {
        if(!conf[i])
            conf[i] = this.defualtConf[i];
    }
    
    return conf;
}

gigya.FriendsSelector.insertFriends = function(filter) {

    this.Divs.Friends.setStyle({ display: "block" });
    this.Divs.Friends.update('');
    
    if (this.friendsCollection) {
        this.friendsCollection.each(function(Gs_User) {
                ///If we have a user and ( no filter than show the user or if there is a filter than check if match).
                if (Gs_User && (!filter || Gs_User.name.toLowerCase().startsWith(filter.toLowerCase()))) {
                    
                    ///make sure there will be an icon for the user.
                    var defaultImage = "http://wildfire.gigya.com/wildfire/i/friendsSelector/ploni.gif";
                    if(typeof(Gs_User.photoURL) != 'string' ||  !Gs_User.photoURL || Gs_User.photoURL=="" )
                        Gs_User.photoURL = defaultImage;
                    
                    ///create a friend template.
                    var html = this.FriendTemplate.evaluate({
                        UID: Gs_User.SNUID,
                        Name: Gs_User.name,
                        photoURL: Gs_User.photoURL
                    });
                    
                    
                    ///Insert the new friend.
                    var liFriend = ((new Element("div")).update(html)).down();

                    if (this.selectedFriends.get(Gs_User.SNUID))
                        liFriend.addClassName('friend_selected');

                    /// Show.
                    var show = false;
                    switch (this.ShowType) {
                        case this.FilterBy.SELECTED:
                            show = this.selectedFriends.get(Gs_User.SNUID) != undefined;
                            break;

                        case this.FilterBy.UNSELECTED:
                            show = this.selectedFriends.get(Gs_User.SNUID) == undefined;
                            break;

                        case this.FilterBy.ALL:
                        default:
                            show = true;
                            break;
                    }

                    /// add friend.
                    if (show)
                        this.Divs.Friends.insert({ bottom: liFriend });
                }
        } .bind(this));
    }
}


gigya.FriendsSelector.selectFriend = function(id)
{
    var elm = $("friend_"+id);
    var flag = false;

    /// collection storage is above the limit , announce collection is full.
    if(!this.selectedFriends.get(id) && this.selectedFriends.keys().length>=this.conf.maxSelection)
    {
        if(window.PickerLimitMsgInterval)
            clearInterval(window.PickerLimitMsgInterval);
    
        this.progress(true,this.Divs.PickerLimitMsg,this.Divs.Friends);
            
        window.PickerLimitMsgInterval = setTimeout(function(){
            this.progress(false,this.Divs.PickerLimitMsg);
        }.bind(this),2500);
    }
    
    /// User Is Not Exists in the collection then add.
    else if(!this.selectedFriends.get(id))
    {
        this.selectedFriends.set(id,this.friendsCollection.getById(id))
        elm.addClassName("friend_selected");
        flag = true;
        
        if(this.ShowType == this.FilterBy.UNSELECTED)
        {
            this.insertFriends();
        }
    }
    
    /// Is Exists in the collection then remove.
    else if(this.selectedFriends.get(id))
    {
        flag = true;
        
        /// if we are on selected showtype(tab) then fadeout the user.
        if(this.ShowType == this.FilterBy.SELECTED)
        {
            this.fadeOut(elm);
            setTimeout( function()
            {
                elm.removeClassName("friend_selected");
                this.selectedFriends.unset(id);
                $("tab_selected").update(this.SelectedTabTemplate.evaluate({ Count: gigya.FriendsSelector.selectedFriends.keys().length }));
            }.bind(this),300);

        }
        else
        {
            elm.removeClassName("friend_selected");
            this.selectedFriends.unset(id);
        }
       
    }

    
    ///update "selected" tab.
    if(flag)
        $("tab_selected").update(this.SelectedTabTemplate.evaluate({ Count: this.selectedFriends.keys().length }));
        
    ///blur selection (fix for the dashed border) for IE.
    if(Prototype.Browser.IE && this.ShowType != this.FilterBy.UNSELECTED)
        elm.blur();
}


gigya.FriendsSelector.Tabs = {}
gigya.FriendsSelector.Tabs.show = function(tab)
{
    ///Normalize tabs.
    var tabs = $("tabs");
    tabs.select("a").each( function(curTab){
        curTab.removeClassName('seltab');
    });
    this.Divs.FilterByName.value = this.FilterByNameTemplate.evaluate({});
    
    ///Change ShowType.
    var curTabClassName;
    switch(tab)
    {
        case this.FilterBy.SELECTED:
            this.ShowType = this.FilterBy.SELECTED;
            curTabClassName = ".tab_selected";
            break;
            
        case this.FilterBy.UNSELECTED:
            this.ShowType = this.FilterBy.UNSELECTED;
            curTabClassName = ".tab_unselected";
            break; 
        case this.FilterBy.ALL:
        default:
            this.ShowType = this.FilterBy.ALL;
            curTabClassName = ".tab_all";
            break;
             
    }
    
    ///Change Class For selected tab.
    var curTab = tabs.select(curTabClassName)[0];
    curTab.addClassName('seltab');
    
    ///blur selection (fix for the dashed border) for IE.
    if(Prototype.Browser.IE)
        curTab.blur();
    
    /// Re build the friends UI.
    this.insertFriends();
}.bind(gigya.FriendsSelector);



gigya.FriendsSelector.AddCss = function(css)
{

    var header = document.getElementsByTagName("head")[0];         
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    cssNode.href = css;
    cssNode.media = 'screen';
    header.appendChild(cssNode);
}


///Show/Hide progress.
gigya.FriendsSelector.inProgress = false;
gigya.FriendsSelector.progress = function(on,elm,parent)
{
    if(!elm)
        return;
        
    if (on)
    {
        this.inProgress = true;
        elm.style.display = "none";
		this.getParentCenter(elm,parent);
        this.fadeIn(elm);
    } else 
    {
        this.inProgress = false;
        this.fadeOut(elm);
    }
}

///FadeIn Element.
gigya.FriendsSelector.fadeIn = function(elm)
{
    try {
	    Effect.Appear(elm,{duration:0.3})
    } catch (e)
    {
	    elm.show();
    }
}

///FadeOut Element.
gigya.FriendsSelector.fadeOut = function(elm)
{
    try{
	    Effect.Fade(elm,{duration:0.3})
    } catch (e)
    {
	    elm.hide();
    }
	
}

///Return with selected friends.
gigya.FriendsSelector.ok = function(){
    var selFriends = new Array();
    
    this.selectedFriends.each(function(iter){
        selFriends.push(iter.value);
    });
    
    this.callback(selFriends,false);
    this.dispose();
    this.parentRef.hide();
}

///Cancel.
gigya.FriendsSelector.cancel = function(){
    this.callback(null,true);
    this.dispose();
    this.parentRef.hide();
}

///Dispose Component.
gigya.FriendsSelector.dispose = function(){
    try{
	    
        this.selectedFriends = null;
        this.Divs.Holder.remove();
        this.Divs.Holder = null;
    }
    catch(e){}
}
