var AppInfo = {
    url: 'http://qkrwnsgml.appspot.com/',
    title: 'Send Coffee',
    link: 'http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=133447',
    logo: 'http://qkrwnsgml.appspot.com/img/icedcoffee_64.jpg',
    page: 'home',
    init: function () {
        var prefs = gadgets.views.getParams();

        AppInfo.page = prefs['page'] !== undefined ? prefs['page'] : 'home';

        Event.observe($('homeTab'), 'click', function (event) {
            var canvas_view = new gadgets.views.View('canvas');
            gadgets.views.requestNavigateTo(canvas_view, {
                'page': 'home'
            });
        });
        Event.observe($('sentTab'), 'click', function (event) {
            var canvas_view = new gadgets.views.View('canvas');
            gadgets.views.requestNavigateTo(canvas_view, {
                'page': 'sent'
            });
        });
        Event.observe($('receivedTab'), 'click', function (event) {
            var canvas_view = new gadgets.views.View('canvas');
            gadgets.views.requestNavigateTo(canvas_view, {
                'page': 'received'
            });
        });
        
        OpenSocial.init(UserInfo.req);
//        StatusBar.init();   //  Status Bar Gage
        switch (AppInfo.page) {
            case 'home':
                $('canvas_main').show();
                $('sent').hide();
                $('received').hide();

                $('homeTab').addClassName('selected');
                $('sentTab').removeClassName('selected');
                $('receivedTab').removeClassName('selected');
                break;
            case 'sent':
                $('sent').show();
                $('canvas_main').hide();
                $('received').hide();
                
                $('sentTab').addClassName('selected');
                $('homeTab').removeClassName('selected');
                $('receivedTab').removeClassName('selected');
                break;
            case 'received':
                $('received').show();
                $('canvas_main').hide();
                $('sent').hide();                

                $('sentTab').removeClassName('selected');
                $('homeTab').removeClassName('selected');
                $('receivedTab').addClassName('selected');
                break;
        }
    }
};
/**
 * Class name : OpenSocial
 *
 * Instances :
 *  - os : opensocial container
 *  - os_token : myspace opensocial token
 *  - dataReqObj : object of data request
 * Methods :
 *  - init() : initialization function for opensocial
 *  - ajax() : ajax function using opensocial io gadget
 */
var OpenSocial = {
    /* Instances */
    os: null,
    os_token: null,
    dataReqObj: null,
    /* Methods */
    init : function (callback) {
        this.os = opensocial.Container.get();
        this.os_token = MyOpenSpace.MySpaceContainer.OSToken;

        this.dataReqObj = this.os.newDataRequest();
        
        
        if (typeof (callback) === 'function') {
            callback();
        }
    },
    /**
    *	method name : ajax()
    *
    *	url : target url of ajax request
    *	data : post data of ajax request
    *	callback: callback function of ajax request
    */
    ajax : function (url, data, callback) {
        if (typeof(callback) === 'function') {
            var params = {};
    
            params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
            params[gadgets.io.RequestParameters.POST_DATA]= gadgets.io.encodeValues(data);
            params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
            
            gadgets.io.makeRequest(url, callback, params);
        }
        else {
            try {   // for firefox javscript console
                console.log('callback parameter makes error.');
            }
            catch (e) {
            }
        }
    }
};

/**
 * Class name : UserInfo
 *
 * Instances :
 *  - uid : uid of viewer
 *  - name : display name of viewer
 *  - thumb : thumbnail image of viewer
 *  - profile_link : profile link of viewer
 *
 * Methods :
 *  - req() : retrieve user information
 *  - reqCallback() : callback function for userReq()
 *  - update() : update user information to database
 */
var UserInfo = {
    /* instances */
    uid : null,
    name : null,
    thumb : null,
    profile_link : null,
    key: null,	// for google app engine datastore
    /* methods */
    req : function () { //  내 정보 추가.
        var viewerReq = OpenSocial.os.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER);
        
        OpenSocial.dataReqObj.add(viewerReq, 'userInfo');
        OpenSocial.dataReqObj.send(UserInfo.reqCallback);
    },
    reqCallback : function (res) {
        if (res.hadError()) {
            var data = res.get('userInfo');
            
            try {
                    console.log(data.getErrorCode() + '\n' + data.getErrorMessage());	
            }
            catch(e) {
                    
            }
        }
        else {
            var viewer = res.get('userInfo').getData();

            UserInfo.uid = viewer.getId();
            UserInfo.name = viewer.getDisplayName();
            UserInfo.thumb = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
            UserInfo.profile_link = viewer.getField(opensocial.Person.Field.PROFILE_URL);

            UserInfo.update();
        }
    },
    update : function () {
        var data = {
            uid: this.uid,
            name: this.name,
            thumb: this.thumb,
            profile_link: this.profile_link
        };
        
        var url = AppInfo.url + 'member/add';
        
        OpenSocial.ajax(url, data, function (res) {
            if (res.data['error'] === 0) {
                UserInfo.key = res.data['data']['user_key'];	// for google app engine datastore

                if (AppInfo.page === 'home') {
                    FriendsInfo.init('app', FriendsSelector.viewFriendsList);

                    StatusBar.init();
                }
                else if (AppInfo.page === 'sent') {
                    Sent.init();
                }
                else if (AppInfo.page === 'received') {
                    Received.init();
                }
            }
        });
    }
};

/**
 * Class name : FriendsInfo
 *
 * Instances :
 *  - list : list of viewer's friends
 *  - obj : json obj of viewer's friends
 *  - callback : callback function for friends request
 *  - first : start number of friends request; default = 0
 */
var FriendsInfo = {
    /* instances */
    data: [],
    callback: undefined,
    first: 1,
    max: 100,
    /* methods */
    init : function (mode, callback) {
        FriendsInfo.first = 1;
        FriendsInfo.max = 100;

        if (typeof (callback) === 'function') {
            FriendsInfo.callback = callback;
        }
            
        FriendsInfo.data = [];
        
        $('friendsList').innerHTML = "<img style='position:absolute; top:0px; left:100px;' src='http://qkrwnsgml.appspot.com/img/loading.gif' />";       
        FriendsInfo.req();
    },
    req : function () {
        var params = {};
        params[opensocial.DataRequest.PeopleRequestFields.FIRST] = FriendsInfo.first;
        params[opensocial.DataRequest.PeopleRequestFields.MAX] = FriendsInfo.max;
        params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = opensocial.DataRequest.SortOrder.NAME;  // 알파벳순 정렬
        params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.ALL;        
        
        var friendsIdSpec = opensocial.newIdSpec({'userId' : 'VIEWER', 'groupId' : 'FRIENDS'}); // IdSpec 생성
        
        var viewerFriendsReq = OpenSocial.os.newFetchPeopleRequest(friendsIdSpec, params);  // owner의 친구들에 대한 정보를 opensocial.Person(0.7)으로 반환.
        OpenSocial.dataReqObj.add(viewerFriendsReq, 'friendsReq');
        
        OpenSocial.dataReqObj.send(FriendsInfo.reqCallback);
    },
    reqCallback : function (res) {
        if (res.hadError()) {
            FriendsInfo.max -= 1;
            FriendsInfo.req();
        }
        else {
            var obj = res.get('friendsReq').getData();
            
            obj.each(function (friend) {
                FriendsInfo.data.push({
                    'uid': friend.getId(),
                    'name': friend.getDisplayName(),
                    'thumb': friend.getField(opensocial.Person.Field.THUMBNAIL_URL),
                    'profile_link': friend.getField(opensocial.Person.Field.PROFILE_URL),
                    'has_app': friend.getField(opensocial.Person.Field.HAS_APP)
                });
            });
            
            if (obj.getTotalSize() < FriendsInfo.max) {
                if (typeof (FriendsInfo.callback) === 'function') {
                    FriendsInfo.callback();
                }
            }
            else {
                FriendsInfo.first += FriendsInfo.max;
                FriendsInfo.req();
            }
        }
    }
};

var Feed = {
    selectedFriends: null,
    idx: 0,
    callback: null,
    sender_key: null,       // History
    receiver_uid: null,     // History
    gift_key: null,         // History
    key: null,              // History
    init : function (callback) {
        Feed.selectedFriends = [];
        var selected = $('friendsList').getElementsByClassName('selected');
        
        for (var idx = 0; idx < selected.length; ++idx) {
            var uid = selected[idx].id.split('_')[1];
            Feed.selectedFriends.push({
                uid: uid,
                name: selected[idx].getElementsByClassName('name')[0].innerHTML,
                hasapp: $('hasapp_' + uid).value
            });
        }
        
        Feed.idx = 0;
        
        if (typeof (callback) === 'function') {
            Feed.callback = callback;
        }
        
        if (Feed.selectedFriends.size() > 0) {
            Feed.send();
        }
    },
    send : function () {
        if (typeof (Feed.callback) === 'function') {
            Feed.callback(Feed.selectedFriends[Feed.idx].uid);
        }
        if (Feed.selectedFriends[Feed.idx].hasapp === 'true') {
            //console.log(UserInfo.key);
            //console.log(StatusBar.selected.identify());
            
            var strTemplate =   '<img src=\"http://qkrwnsgml.appspot.com/img/coffee/#{gift_img}.jpg\" alt=\"#{title}\" style=\"width:96px;height:96px;\" />' +
                                '<p>' +
                                '   #{sender} sent a #{gift_name} to you! ' +
                                '   <a href=\"#{link}\">Click here to drink it.</a>' +
                                '</p>';

            var template = new Template(strTemplate);

            var data = {
                gift_key: StatusBar.selected.identify()
            };
        
            var url = AppInfo.url + 'gift/select';
              
            // Gift Table에서 click한 아이템 선택.
            OpenSocial.ajax(url, data, function (res) {
                var msg = opensocial.newMessage(template.evaluate({
                    sender: UserInfo.name,
                    gift_img: res.data['data'][0]['gift'],
                    gift_name: res.data['data'][0]['gift'].replace(/_/g, " "),
                    title: AppInfo.title,
                    link: AppInfo.link
                }));
            
                msg.setField(opensocial.Message.Field.TITLE, "Send Coffee");
                msg.setField(opensocial.Message.Field.TYPE, opensocial.Message.Type.PUBLIC_MESSAGE);

                OpenSocial.os.requestSendMessage(Feed.selectedFriends[Feed.idx].uid, msg, Feed.sendCallback);
            });
        }
        else {
            var strTemplate =   'Hi #{receiver}. #{sender} has sent you iced coffee! ' + 
                                'Click "Add" below to drink it!';

            var template = new Template(strTemplate);
            
            var msg = opensocial.newMessage(template.evaluate({
                receiver: Feed.selectedFriends[Feed.idx].name,
                sender: UserInfo.name,
                title: AppInfo.title
            }));
            
            msg.setField(opensocial.Message.Field.TITLE, "Send Coffee");

            OpenSocial.os.requestShareApp(Feed.selectedFriends[Feed.idx].uid, msg, Feed.sendCallback);
            
        }
    },
    sendCallback : function (res) {
        if (res === MyOpenSpace.PostTo.Result.ERROR) {
            //console.log('callback gave error');
            Feed.repeat();
        }
        else if (res.data_ === 0) {
            //console.log('user cancelled PostTo');
            Feed.repeat();
        }
        else if (res.data_ === 1) {
            //console.log('WE ARE MEETING WITH GREAT SUCCESS!!!');
            Feed.update();      // History Table에 넣는다.
        }
        else {
            //console.log('Unrecognized response: ' + res);
            Feed.repeat();
        }
    },
    repeat : function () {
        ++Feed.idx;
        try {
            console.log(Feed.idx);
        }
        catch (e) {
                
        }
        if (Feed.idx < Feed.selectedFriends.size()) {
            Feed.send();
        }
        else {
            window.parent.location = AppInfo.link;
        }
    },
    update : function () {      
        var data = {
            sender_key: UserInfo.key,
            receiver_uid: Feed.selectedFriends[Feed.idx].uid,
            gift_key: StatusBar.selected.identify()
        };
        
        var url = AppInfo.url + 'history/update';
              
        // History Table에 추가한다.
        OpenSocial.ajax(url, data, function (res) {
            
            // e-mail 입력받은 경우만 추가된다.
            if ( $('email').value.length > 0 ) {    
                var url = AppInfo.url + 'member/email';
                
                var data = {
                    sender_key: UserInfo.key,
                    email: $('email').value
                }
                // e-mail Member Table에 추가.
                OpenSocial.ajax(url, data, function (res) {
                });
            }
            Feed.repeat();
        });
    }
};

var FriendsSelector = {
    list: null,
    size: 0,
    selected_num: 0,
    handleInputBox: 'init',
    clear: function () {
        for (var idx = 0; idx < FriendsSelector.size; ++idx) {
            FriendsSelector.list[idx].className = '';
        }
    },
    seeAll: function () {
        for (var idx = 0; idx < FriendsSelector.size; ++idx) {
            FriendsSelector.list[idx].parentNode.style.display = '';
        }
    },
    selectAll: function () {
        $('searchUsersField').value = 'Start Typing a Friend\'s Name';
        FriendsSelector.handleInputBox = 'init';
        
        for (var idx = 0; idx < FriendsSelector.size; ++idx) {
            var friend = FriendsSelector.list[idx];

            friend.parentNode.style.display = '';
            
            if (!friend.hasClassName('selected')) {
                friend.toggleClassName('selected');
            }

            FriendsSelector.selected_num = FriendsSelector.size;
        }
    },
    viewFriendsList: function () {
        if (FriendsInfo.data.size() > 0) {
            $('friendsList').update('');
                    
            var strTemplate =   '<li>' +
                                '   <a id=\"challengeUser_#{uid}\">' +
                                '	<span class="name">#{name}</span>' +
                                '	<span class="thumb">' +
                                '		<img src=\"#{thumb}\" />' +
                                '	</span>' +
                                '       <img class=\"msgType\" src=\"#{msg_img}\" alt=\"#{msg_type}\" />' +
                                '   </a>' +
                                '   <input type=\"hidden\" name=\"hasapp[]\" id=\"hasapp_#{uid}\" value=\"#{has_app}\" />' +
                                '</li>';

            var friendsTemplate = new Template(strTemplate);

            FriendsInfo.data.each(
                function (friend) {
                    $('friendsList').insert(
                        friendsTemplate.evaluate({
                            'uid': friend['uid'],
                            'thumb': friend['thumb'],
                            'name': friend['name'],
                            'msg_img': AppInfo.url + (friend['has_app'] ? 'img/comment_icon.gif' : 'img/invite_icon.gif'),
                            'msg_type': friend['has_app'] ? 'added' : 'have not added',
                            'has_app': friend['has_app']
                        })
                    );
                }
            );
            
            FriendsSelector.init();
        }
    },
    init: function () {
        FriendsSelector.list = $('friendsList').getElementsByTagName('a');
        FriendsSelector.size = FriendsSelector.list.length;
        FriendsSelector.selected_num = 0;
        FriendsSelector.handleInputBox = 'init';
        
        $('searchUsersField').value = 'Start Typing a Friend\'s Name';
        
        for (var idx = 0; idx < FriendsSelector.size; ++idx) {
            Event.observe(FriendsSelector.list[idx], 'click', function (event) {
                Event.findElement(event, 'a').toggleClassName('selected');
            });
        }

        $('selectAllBtn').observe('click', function () {
            FriendsSelector.selectAll();
        });
        
        // clear selections
        $('clearBtn').observe('click', function () {
            for (var idx = 0; idx < FriendsSelector.size; ++idx) {
                var friend = FriendsSelector.list[idx];
                
                if (!friend.parentNode.style.display !== 'none' && friend.hasClassName('selected')) {
                    friend.toggleClassName('selected');
                }

                --FriendsSelector.selected_num;
            }
        });
    
        // search users by keyword
        $('searchUsersField').observe('focus', function () {
            if (FriendsSelector.handleInputBox === 'init') {
                $('searchUsersField').value = '';
                FriendsSelector.handleInputBox = 'set';

                new Form.Element.Observer('searchUsersField', 0.2, function (element, value) {
                    
                    if (value !== '' && FriendsSelector.handleInputBox !== 'init') {
                        for (var idx = 0; idx < FriendsSelector.size; ++idx) {
                            var lower_value = value.toLowerCase();
                            var nameSpan = FriendsSelector.list[idx].getElementsByClassName('name')[0];
                            var lower_name = nameSpan.innerHTML.toLowerCase();
                            
                            if (lower_name.include(lower_value)) {
                                FriendsSelector.list[idx].parentNode.style.display = '';
                            }
                            else {
                                FriendsSelector.list[idx].parentNode.style.display = 'none';
                            }
                        }
                    }
                    else {
                        FriendsSelector.seeAll();
                    }
                });
            }
        });
        
        $('searchUsersField').observe('blur', function () {
            var inputBox = $('searchUsersField');

            if (inputBox.value.blank()) {
                inputBox.value = 'Start Typing a Friend\'s Name';
                FriendsSelector.handleInputBox = 'init';
            }
        });
        
        $('seeAllBtn').observe('click', function () {
            $('searchUsersField').value = 'Start Typing a Friend\'s Name';
            FriendsSelector.handleInputBox = 'init';

            FriendsSelector.seeAll();
        });
        
        $('sendBtn').observe('click', function () {
            Feed.init();
        });
    }
};

/*
    Status Bar의 게이지 채우기 & Item List 받아오기 & ItemSelect
*/
var StatusBar = {
    userCnt: null,  //  유저가 보낼 수 있는 아이템 수
    fullBar: null,  //  전체 bar 크기  
    sendCnt: null,  //  사용자가 보낸 item 수
    maxxCnt: null,  //  전체 item 수
    initCnt: null,  //  기본적으로 보여줄 (item 갯수 * 5)
    lockCnt: null,  //  다음 아이템의 lock해제를 위한 갯수
    nowItems: null, //  현재 보낼 수 있는 아이템 수
    image: null,        //Gift List
    name: null,         //Gift List
    key: null,          //Gift List
    items: [],          //Gift List
	selected: null,		//Item Select    
    init: function (){
        StatusBar.userCnt;   
        StatusBar.fullBar = -600; 
//        StatusBar.sendCnt = 62;      //DB  
//        StatusBar.maxxCnt = 27;      //DB   
        StatusBar.initCnt = 15;       // 기본설정 3개
        StatusBar.lockCnt = 5;        // 기본설정 5개
        
        var data = {
            sender_key: UserInfo.key
        };
           
        var url = AppInfo.url + 'history/dbget';


        OpenSocial.ajax(url, data, function (res) {
            // 보낸 item 갯수 받아온다.            
            for ( var idx = 0; idx < res.data['data'].length; ++idx) {
                StatusBar.sendCnt += res.data['data'][idx]['amount'];
            }
            
            var data = {
                image: this.image,
                name: this.name,
                key: this.key
            };
            
            function items () {
                var coffeeUrl = null;
                var coffeeName = null;
                var item_key = null;
            }
            StatusBar.items = new Array();
            
            var url = AppInfo.url + 'gift/list';
    
            // Gift Table의 정보 받아 온다.
            OpenSocial.ajax(url, data, function (res) {
                for( var idx = 0; idx < res.data['data'].length; ++idx ) {
                    StatusBar.items[idx] = new items();
                    StatusBar.items[idx].coffeeUrl = res.data['data'][idx]['image'];
                    StatusBar.items[idx].coffeeName = res.data['data'][idx]['name'];
                    StatusBar.items[idx].item_key = res.data['data'][idx]['gift_key'];
                }
                StatusBar.maxxCnt = res.data['data'].length; 
                //console.log(res.data['data'].length);


                // unlock 계산식
                StatusBar.nowItems = Math.floor( (StatusBar.sendCnt + StatusBar.initCnt) / StatusBar.lockCnt );    // (sendCnt(Max:120) + basicCnt) / lockCnt;
                
                if (StatusBar.nowItems > StatusBar.maxxCnt) {StatusBar.userCnt = StatusBar.maxxCnt;}
                else {StatusBar.userCnt = StatusBar.nowItems}
                
                // bar의 게이지 크기 계산.
                var barPosition = Math.round(( (StatusBar.maxxCnt - StatusBar.userCnt)/StatusBar.maxxCnt ) * StatusBar.fullBar);
                // statusBar CSS
                $('statusBar').style.background = 'url(http://qkrwnsgml.appspot.com/img/status_bar.jpg) no-repeat ' + barPosition + 'px 0';
                $('user_item').innerHTML = StatusBar.userCnt;
                $('max_item').innerHTML = StatusBar.maxxCnt;
        
                var moreSend = StatusBar.sendCnt%StatusBar.lockCnt;	// 다음 item unlock 위해 보내야 할 count
        
                var limitCnt = (StatusBar.maxxCnt - (StatusBar.initCnt/StatusBar.lockCnt)) * StatusBar.lockCnt;	// lock 전부 풀기 위해 보내야 할 send Count
                
                if ( limitCnt > StatusBar.sendCnt ) { // 다음 lock을 위해 item을 몇 개 더 보내야 하는지 알려준다.
                    switch (moreSend) {
                        case 0 :
                            $('moreSend').innerHTML = "5 cups of coffee"
                            break;
                        case 1 :
                            $('moreSend').innerHTML = "4 cups of coffee"
                            break;
                        case 2 :
                            $('moreSend').innerHTML = "3 cups of coffee"
                            break;
                        case 3 :
                            $('moreSend').innerHTML = "2 cups of coffee"
                            break;
                        case 4 :
                            $('moreSend').innerHTML = "a cup of coffee"
                            break;
                    }
                }
                else {  // 모든 lock을 풀었을 때
                    $('downStatusBar').innerHTML = 	'You can send all gift!!';
                    $('downStatusBar').style.fontWeight = 'bolder';
                }            

                // template of coffee(HTML Tag)     
                var coffeeTemplate = new Template('<a id="#{item_key}"><img src="#{coffeeUrl}" /><div class="breakline"></div><span class="name">#{coffeeName}</span><br /></a>');            
                //  item Lock 해제.
                for( idx = 0; idx < StatusBar.nowItems; ++idx) {
                    if(idx == StatusBar.maxxCnt){ //  전체 갯수보다 send item count가 많으면 반복문 탈출
                        break;
                    }
                    $('coffee').insert( //  core of 'for'
                        coffeeTemplate.evaluate({
                            'coffeeUrl': StatusBar.items[idx].coffeeUrl,
                            'coffeeName': StatusBar.items[idx].coffeeName.replace(/_/g, " "),
                            'item_key': StatusBar.items[idx].item_key
                        })
                    );
                }
                StatusBar.selected = null;	//	인스턴스 초기화
                
                //	변수 items에 itemList의 child중 <a>태그 참조
                var drinks = $('coffee').getElementsByTagName('a');	
                
                //	아이템 선택(선택된 상품은 테두리로 표시한다.)
                for(var idx = 0; idx < drinks.length; idx++){
                    //	click 되어진 <a>태그
                    Event.observe(drinks[idx], 'click', function(event){
                        //	selected변수가 click 이벤트가 일어난 <a>태그 참조 
                        var selected = Event.findElement(event, 'a');
                        
                        // 아이템을 처음 선택한 경우
                        if(StatusBar.selected === null){
                            StatusBar.selected = selected;	//	클릭된 <a>태그 StatusBar의 selected 인스턴스가 참조
                            StatusBar.selected.toggleClassName('selected');	//	클릭한 <a>태그에 Class="selected" 넣는다.
                        }
                        // 이미 선택된 아이템 이외의 또 다른 아이템 선택한 경우
                        // Character.selected 기존에 선택된 것, selected는 지금 선택한 것
                        else if(StatusBar.selected !== selected){
                            StatusBar.selected.toggleClassName('selected');	//	기존에 선택 된 <a>태그에 ClassName 뺀다.
                            StatusBar.selected = selected;					//	StatusBar의 selected 인스턴스가 이번에 선택한 <a>태그 참조
                            StatusBar.selected.toggleClassName('selected');	//	이번에 선택한 <a>태그에 ClassName 넣는다.
                        }
                        // 선택한 아이템 다시 선택하는 경우
                        else{
                            StatusBar.selected.toggleClassName('selected');	//	기존에 선택된 <a>태그에 ClassName 뺀다.
                            StatusBar.selected = null;						//	StatusBar의 selected 인스턴스에 null값을 넣는다.
                        }
                    });
                }                
            });
        });
        
/*        // coffee array, DB에서 받아올 것.
        var coffeeImg = ['Green_Tea_Frappuccino','Caramel_Frappuccino','Cinnamon_Dolce','Double_Chip_Frappuccino','Coffee_Frappuccino','Iced_Americano_With_White_Mocha','Iced_Carmel_Macchiato_Upside_Down','Iced_Carmel_Macchiato','Iced_coffee','Latte','Iced_caffe_latte','Mocha_Frappuccino','Passion_fruit_tea_lemonade','Pure_Espresso','Starbucks_Double_Shot_On_Ice','Strawberry_And_Cream_Frappuccino','Vanilla_Bean_Frappuccino','Iced_caffe_americano','DoubleShot','Iced_caramel_macchiato','Chocolate_cream_chip_frappuccino','Mango_tea_frappuccino','White_chocolate_mocha_frappuccino','Espresso_frappuccino','Tazo_iced_tea','Iced_tazo_chai_tea_latte','Iced_caffe_mocha']
        var coffeeName = ['Green Tea Frappuccino','Caramel Frappuccino','Cinnamon Dolce','Double Chip Frappuccino','Coffee Frappuccino','Iced Americano With White Mocha','Iced Carmel Macchiato Upside Down','Iced Carmel Macchiato','Iced coffee','Latte','Iced caffe latte','Mocha Frappuccino','Passion fruit tea lemonade','Pure Espresso','Starbucks Double Shot On Ice','Strawberry And Cream Frappuccino','Vanilla Bean Frappuccino','Iced caffe americano','DoubleShot','Iced caramel macchiato','Chocolate cream chip frappuccino','Mango tea frappuccino','White chocolate mocha frappuccino','Espresso frappuccino','Tazo iced tea','Iced tazo chai tea latte','Iced caffe mocha']
*/ 
    }
}

/*
    Sent History
*/
var Sent = {
    sender: null,
    receiver: null,
    gift_name: null,
    gift_image: null,
    time: null,
    init: function () {
        var data = {
            sender_key: UserInfo.key
        };
        
        var url = AppInfo.url + 'history/sent_list';
        
        //템플릿
        var strTemplate =   '<div class="feed_story">' +
                                '   <div class="feed_icon">' +
                                '   	<img src="#{gift_image}" />' +
                                '	</div>' +
                                '	<div class="feed_body">' +
                                '	    <div class="feed_headline"></div>' +
                                '       <div class="feed_title">' +
                                '           #{sender} sent #{gift_name} to #{receiver} at #{time}' +
                                '       </div>' +
                                '   </div>' +
                                '</div>';

        var sentTemplate = new Template(strTemplate);
        
        OpenSocial.ajax(url, data, function (res) {
            for( var idx = 0; idx < res.data['data'].length; ++idx ) {
                //값 받는다
                Sent.sender = res.data['data'][idx]['sender']['name'];
                Sent.receiver = res.data['data'][idx]['receiver']['name'];
                Sent.gift_name = res.data['data'][idx]['gift']['name'].replace(/_/g," ");
                Sent.gift_image = res.data['data'][idx]['gift']['image'];
                Sent.time = res.data['data'][idx]['time'];
                
                //템플릿 실행.
                $('sent').insert(
                    sentTemplate.evaluate({
                        'sender': Sent.sender,
                        'receiver': Sent.receiver,
                        'gift_name': Sent.gift_name,
                        'gift_image': Sent.gift_image,
                        'time': Sent.time.substr(0,19)
                    })
                );
            }
        });
    }
}

/*
    Received History
*/
var Received = {
    sender: null,
    receiver: null,
    gift_name: null,
    gift_image: null,
    init: function () {
        var data = {
            receiver_key: UserInfo.key
        };
        
        var url = AppInfo.url + 'history/received_list';
        
        //템플릿
        var strTemplate =   '<div class="feed_story">' +
                                '   <div class="feed_icon">' +
                                '   	<img src="#{gift_image}" />' +
                                '	</div>' +
                                '	<div class="feed_body">' +
                                '	    <div class="feed_headline"></div>' +
                                '       <div class="feed_title">' +
                                '           #{sender} sent #{gift_name} to #{receiver} at #{time}' +
                                '       </div>' +
                                '   </div>' +
                                '</div>';

        var receivedTemplate = new Template(strTemplate);
        
        OpenSocial.ajax(url, data, function (res) {
            for( var idx = 0; idx < res.data['data'].length; ++idx ) {
                //값 받는다
                Received.sender = res.data['data'][idx]['sender']['name'];
                Received.receiver = res.data['data'][idx]['receiver']['name'];
                Received.gift_name = res.data['data'][idx]['gift']['name'].replace(/_/g," ");
                Received.gift_image = res.data['data'][idx]['gift']['image'];
                Received.time = res.data['data'][idx]['time'];
                
                //템플릿 실행.
                $('received').insert(
                    receivedTemplate.evaluate({
                        'sender': Received.sender,
                        'receiver': Received.receiver,
                        'gift_name': Received.gift_name,
                        'gift_image': Received.gift_image,
                        'time': Received.time.substr(0,19)
                    })
                );
            }
        });
    }
}
