<?xml version="1.0" encoding="UTF-8" ?> 
<!-- 	
	NETKILLER - Global IT Innovator http://www.netkiller.com
	Copyright (C) 2011  NETKILLER America Inc.
	Latest version of this program;
	http://code.google.com/p/netkiller-googleapps-simple-workflow-gadget

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see http://www.gnu.org/licenses

	NETKILLER - Global IT Innovator http://www.netkiller.com
	Copyright (C) 2011  NETKILLER America Inc.
	Latest version of this program;
	http://code.google.com/p/netkiller-googleapps-simple-workflow-gadget
 -->
<Module>
  <ModulePrefs title="N-Approval Gadget using Google Docs."
     scrolling="true" 
     height="450" 
     author="Netkiller" 
     author_email="admin@netkiller.com">
    <Require feature="opensocial-0.8" />
    <Require feature="locked-domain"/>
    <OAuth>
      <Service name="google">
        <Access url="https://www.google.com/accounts/OAuthGetAccessToken" method="GET" /> 
        <Request url="https://www.google.com/accounts/OAuthGetRequestToken?scope=https://docs.google.com/feeds/" method="GET" /> 
        <Authorization url="https://www.google.com/accounts/OAuthAuthorizeToken?oauth_callback=http://oauth.gmodules.com/gadgets/oauthcallback" /> 
      </Service>
    </OAuth>
  </ModulePrefs>
  <UserPref name="num_entries" display_name="Number of Entries" default_value="100" required="true"/>
  <UserPref name="docs_manager" display_name="Docs Manager's Username" default_value="" required="true"/>
  <Content type="html">
  <![CDATA[ 
  <!-- shindig oauth popup handling code -->
  <script type="text/javascript" src="http://gadget-doc-examples.googlecode.com/svn/trunk/opensocial-gadgets/popup.js"></script>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
  <script type="text/javascript" src="http://nk-gadget.appspot.com/js/json_sans_eval.js"></script>
  <link rel='stylesheet' type='text/css' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css'/>
  <link type="text/css" rel="stylesheet" href="http://nk-gadget.appspot.com/stylesheets/main.css">
  
  <div id="temp" style="display: none"></div>
  <div id="main" style="display: none">
    <div class="docsListHeader">
    	<div class="docsLink">제목</div>
    	<div class="docsPerm">권한</div>
    	<div class="docsLastModified">최종 수정일</div>
    	<div class="headerRight">
    		<a href="#" id="linkReload">새로고침</a>&nbsp;
    		<a href="https://docs.google.com/Doc?docid=0AZQQqEHZz9C9ZGczdng5OGZfMjAzMWZiN2Z4OWRj&hl=en&authkey=CLLRoTc" target="nk_help">도움말</a>
		</div>
    </div>
    <div id="accordion">
    	<h3><a href="#">나의 작성중인 결재 문서함<span id="hDraft"></span></a></h3>
	  	<div class="clearBoth fixHeight" id="draft"></div>
	  	
	  	<h3><a href="#">나의 상신중인 문서함<span id="hSubmitted"></span></a></h3>
	  	<div class="clearBoth fixHeight" id="submitted"></div>
	  	
	  	<h3><a href="#">내가 결재할 문서함<span id="hToBeApprovedByMe"></span></a></h3>
	  	<div class="clearBoth fixHeight" id="toBeApprovedByMe"></div>
	  	
	  	<h3><a href="#">결재가 승인된 문서함<span id="hApproved"></span></a></h3>
	  	<div class="clearBoth fixHeight" id="approved"></div>
	  	
	  	<h3><a href="#">결재가 반려된 문서함<span id="hRejected"></span></a></h3>
	  	<div class="clearBoth fixHeight" id="rejected"></div>
	  	
	  	<h3><a href="#">내가 반려한 문서함<span id="hRejectedByMe"></span></a></h3>
	  	<div class="clearBoth fixHeight" id="rejectedByMe"></div>
	</div>
  </div>

  <div id="approval" style="display: none">
    <img src="http://gadget-doc-examples.googlecode.com/svn/trunk/images/new.gif">
    <a href="#" id="personalize">Personalize this gadget</a>
  </div>

  <div id="waiting" style="display: none">
    Please click
    <a href="#" id="approvaldone">I've approved access</a>
    once you've approved access to your data.
  </div>
  
  <div class="poweredBy">
  	NETKILLER America Inc. GNU A-GPL License <a href="http://code.google.com/p/netkiller-googleapps-simple-workflow-gadget/" target="prj_home">here</a>
  </div>
  <script type="text/javascript">
    //count docs
    var draftCnt = 0;
    var toBeApprovedByMeCnt = 0;
    var rejectedByMeCnt = 0;
    var submittedCnt = 0;
    var approvedCnt = 0;
    var rejectedCnt = 0;
    
	// Get Userprefs
	var prefs = new gadgets.Prefs();
	var entriesNum = prefs.getInt("num_entries");
	var docsManager = prefs.getString("docs_manager");
	var folder = "N-Approval";
    // Display UI depending on OAuth access state of the gadget (see <divs> above).
    // If user hasn't approved access to data, provide a "Personalize this gadget" link
    // that contains the oauthApprovalUrl returned from makeRequest.
    //
    // If the user has opened the popup window but hasn't yet approved access, display
    // text prompting the user to confirm that s/he approved access to data.  The user
    // may not ever need to click this link, if the gadget is able to automatically
    // detect when the user has approved access, but showing the link gives users
    // an option to fetch their data even if the automatic detection fails.
    //
    // When the user confirms access, the fetchData() function is invoked again to
    // obtain and display the user's data.
    function showOneSection(toshow) {
      var sections = [ 'main', 'approval', 'waiting' ];
      for (var i=0; i < sections.length; ++i) {
        var s = sections[i];
        var el = document.getElementById(s);
        if (s == toshow) {
          el.style.display = "block";
        } else {
          el.style.display = "none";
        }
      }
    }
    
    // Process returned JSON feed to display data.
    function showResults(jsondata) {
      var feed = jsondata.feed;
      var entries = feed.entry || [];
      var currentUser = feed.author[0].email.$t;
      var aclFeed;
      var acldata = '{"feed":{"currentUser":"'+currentUser+'", "entry":[';
	
      for (var i=0; i<entries.length; ++i) {
        var entry = entries[i];
        var title = entry.title.$t;
        var resourceId = entry.gd$resourceId.$t;
        var feedLinks = entry.gd$feedLink || [];
        var lastModifiedDate = (entry.updated.$t).substring(0,10);
        var lastModifiedBy = entry.gd$lastModifiedBy.name.$t;
        var links = entry.link || [];
        var alternateLink;
        
        for (var j=0; j<links.length; ++j) {
          var link = links[j];
          if (link.rel == "alternate" && link.type == "text/html") {
            alternateLink = link.href;
            break; 
          }
        }
        
        for (var k=0; k<feedLinks.length; ++k) {
          var feedLink = feedLinks[k];
          if ((feedLink.rel).indexOf("accessControlList")) {
            acldata += '{"resourceId":"'+resourceId+'", "link":"'+feedLink.href+'"}';
            break;
          }
        }
        
		var htmlSrc = "<div id='"+resourceId+"'>";
        htmlSrc += "<div class='docsLink' id='link-"+resourceId+"'><a href='" + alternateLink + "' target='nk_approval'>" + title + "</a></div>";
        htmlSrc += "<div class='docsPerm' id='perm-"+resourceId+"'></div>";
        htmlSrc += "<div class='docsLastModified' title='"+lastModifiedBy+"'>"+lastModifiedDate+"</div>";
        htmlSrc += "<div class='clearboth'></div>";
        htmlSrc += "</div>";
        $(htmlSrc).appendTo("#temp");
      }
      acldata += "]}}";
      acldata = jsonParse(acldata);
      fetchAclData(acldata.feed);
    }

    // Invoke makeRequest() to fetch data from the service provider endpoint.
    // Depending on the results of makeRequest, decide which version of the UI
    // to ask showOneSection() to display. If user has approved access to his
    // or her data, display data.
    // If the user hasn't approved access yet, response.oauthApprovalUrl contains a
    // URL that includes a Google-supplied request token. This is presented in the 
    // gadget as a link that the user clicks to begin the approval process.     
    function fetchData() {
      var params = {};
      var url = "https://docs.google.com/feeds/documents/private/full/-/"+folder+"?alt=json";
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
      params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
      params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "google";
      params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
      params[gadgets.io.RequestParameters.NUM_ENTRIES] = new Number(entriesNum);  
	  
	  gadgets.io.makeRequest(url, function (response) { 
        if (response.oauthApprovalUrl) {
          // Create the popup handler. The onOpen function is called when the user
          // opens the popup window. The onClose function is called when the popup
          // window is closed.
          var popup = shindig.oauth.popup({
            destination: response.oauthApprovalUrl,
            windowOptions: null,
            onOpen: function() { showOneSection('waiting'); },
            onClose: function() { fetchData(); }
          });
          
          // Use the popup handler to attach onclick handlers to UI elements.  The
          // createOpenerOnClick() function returns an onclick handler to open the
          // popup window.  The createApprovedOnClick function returns an onclick 
          // handler that will close the popup window and attempt to fetch the user's
          // data again.
          var personalize = document.getElementById('personalize');
          personalize.onclick = popup.createOpenerOnClick();
          var approvaldone = document.getElementById('approvaldone');
          approvaldone.onclick = popup.createApprovedOnClick();
          showOneSection('approval');
        } else if (response.data) {
          showResults(response.data);
          showOneSection('main');
          $("#accordion").accordion({
          	active: false, 
		    collapsible: true  
          });
        } else {
          var main = document.getElementById('main');
          var err = document.createTextNode('OAuth error: ' +
            response.oauthError + ': ' + response.oauthErrorText);
          main.appendChild(err);
          showOneSection('main');
        }
      }, params);
    }
    
    function fetchAclData(aclFeed) {
      var params = {};
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
      params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
      params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
      params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "google";
      params[gadgets.io.RequestParameters.NUM_ENTRIES] = new Number(entriesNum);
      
      var currentUser = aclFeed.currentUser;
      var entries = aclFeed.entry || [];
      for (var i=0; i<entries.length; ++i) {
        var aclFeedUrl = entries[i].link + "?alt=json";
        gadgets.io.makeRequest(aclFeedUrl, function (response) {
          if (response.data) {	
            showAclResult(response.data, currentUser);
          } else {
            var main = document.getElementById('main');
            var err = document.createTextNode('OAuth error: ' +
              response.oauthError + ': ' + response.oauthErrorText);
            main.appendChild(err);  
            showOneSection('main');
          }
        }, params);
	  }
    }
    
    function showAclResult(jsondata, currentUser) {
      var feed = jsondata.feed;
      var entries = feed.entry || [];
      var resourceId = unescape((feed.id.$t).split("full/")[1] || "");
      var writers = [];
      var readers = [];
      var writerCnt = 0
      var readerCnt = 0;
      var owner = "";
      var isOwner = false;
      var isReader = false;
      var isWriter = false;
      var perm = "";

      for (var i=0; i<entries.length; ++i) {
        var entry = entries[i];
        var role = entry.gAcl$role.value;
        var scope = entry.gAcl$scope.value;
        
        if (role == "owner") {
          owner = scope;
          if (currentUser == scope) {
            isOwner = true;
            perm = role;
            
          }
        } else if (role == "writer") {
          writers[writerCnt++] = scope;
          if (currentUser == scope && !isWriter) {
            isWriter = true;
            perm = role;
          }
        } else if (role == "reader") {
          readers[readerCnt++] = scope;
          if (currentUser == scope && !isReader) {
            isReader == true;
            perm = role;
          }
        }
      }
      
      if (isOwner && readerCnt <= 0 && writerCnt <= 0) {
        state = "draft";
        draftCnt++;
      } else if (!isOwner && readerCnt <= 0 && writerCnt <= 0) {
        if (docsManager == owner) {
          state = "approved";
          approvedCnt++;
        } else {
          state = "submitted";
          submittedCnt++;
        }
        perm = "reader";
      } else if (isOwner && readerCnt <= 0 && writerCnt > 0) {
        state = "rejected";
        rejectedCnt++;
      } else if (isOwner && readerCnt > 0 && writerCnt <= 0) {
        state = "toBeApprovedByMe";
        toBeApprovedByMeCnt++;
      } else if (isWriter) {
        state = "rejectedByMe";
        rejectedByMeCnt++;
      }

      var divCategory = document.getElementById(state);
      var divDoc = document.getElementById(resourceId);
      var divPerm = document.getElementById("perm-"+resourceId);
      divPerm.innerHTML = perm;
      
      $("#hDraft").html("["+draftCnt+"]");
      $("#hToBeApprovedByMe").html("["+toBeApprovedByMeCnt+"]");
      $("#hRejectedByMe").html("["+rejectedByMeCnt+"]");
      $("#hSubmitted").html("["+submittedCnt+"]");
      $("#hApproved").html("["+approvedCnt+"]");
      $("#hRejected").html("["+rejectedCnt+"]");
      
      $(divDoc).appendTo(divCategory);
    }
    
    $("#linkReload").click(function() {
      draftCnt = 0;
      toBeApprovedByMeCnt = 0;
      rejectedByMeCnt = 0;
      submittedCnt = 0;
      approvedCnt = 0;
      rejectedCnt = 0;
    
      $("#draft").html("");
  	  $("#toBeApprovedByMe").html("");
  	  $("#rejectedByMe").html("");
  	  $("#submitted").html("");
  	  $("#approved").html("");
  	  $("#rejected").html("");
  	  
      fetchData();
    });
    
    // Call fetchData() when gadget loads.
    gadgets.util.registerOnLoadHandler(fetchData);
  </script>
  ]]> 
  </Content>
</Module>
