/*

Zep Library API - Public API available for access to the ZepInvest library of content.

ZepFrog Corp. © Copyright 2012

Public Interfaces...

	There are multiple components to the Library, the public server-side API (e.g. zepcontent.aspx) and client-side convience methods (this file).

	Server-Side APIs...

	Client-Side Convience Methods...
	
		getContentReferences(varJSONPCallback, varOID)
		recordTime(varUser_Id, varOID, varTime_Interval)
		registerUser(varJSONPCallback, varUser_Id, varLevel, varEmail, varFirstName, varLastName)

Usage...

	getContentReferences, (varJSONPCallback, varOID)
		A JSONP request. Answers content references for varOID, returned via varJSONPCallback reponse JSON representation; function returns true/false.

		Server Side API Request: a URL with querystring parameters...

			https://api.zepinvest.com/public/zepcontent.aspx/?callback=<callback>&key=<key>&oid=<oid>

				<callback> : string, JSONP callback function name implemented by caller
				<key> : string, unique identifier as received from server call (...) validating access to requested resource
				<oid> : string, unique object identifier of the content requested as received via content.rss

			Complete example request...

				https://api.zepinvest.com/public/zepcontent.aspx/?callback=getContentReferencesCallback&key=$P$BQLaV9efNpuSbiE1Xm4TbP68YArLSL1&oid=37816

		Server API Response: a valid JSON structure (set of case sensitive double quoted key / value pairs), wrapped with the callback function as discovered in querystring parameter...

			<varJSONPCallback>({“OID”:”<oid>”,“Preview”:”<url_preview_png>”,“SwfFile”:”<url_content_swf>”,“PageImagePattern”:”<url_content_pattern_png>”,“JSONFile”:”<url_content_json>”,”textStatus”:”<textStatus>”});

				<varJSONPCallback> | string, JSONP callback function name as discovered in querystring parameter

			Key(case sensitive) : Value | description...

				“OID”:”<oid>” | string, answer unique object identifier as discovered in querystring parameter
				“Preview”:”<url_preview_png>” | string, url to png resource representing preview
				“SwfFile”:”<url_content_swf>” | string, url to swf resource representing full content
				“PageImagePattern”:”<url_content_png_pattern>” | string, url to png resources representing pattern of content pages with wild card
				“JSONFile”:”<url_content_json>” | string, url to js resource representing content metadata
				”textStatus”:”<textStatus>” | string, status of request e.g. “success”

			Complete example response...

				getContentReferencesCallback(response) where 'response' is...

				({"OID":"U747","Preview":"https://api.zepinvest.com/ContentUpdate/746/38037/747/document_1.png","SwfFile":"https://api.zepinvest.com/ContentUpdate/746/38037/747/document.swf","PageImagePattern":"https://api.zepinvest.com/ContentUpdate/746/38037/747/document_*.png","JSONFile":"https://api.zepinvest.com/ContentUpdate/746/38037/747/document.js","Status":"null"})

		Client API Usage: JavaScript, requires jQuery 1.5.2 or later...

			<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
			<script type="text/javascript" src="./wp-content/scripts/zep_library_api.js"></script>

			<script type="text/javascript">
			var $oid= "35338"; // $oid as resolved from event target element clicked, as provided with the RSS feed

			jQuery(document).ready(function($){
	    		$bResult = ZepLibrary.getContentReferences($oid, 'getContentReferencesCallback'); // answers true/false, response handled with jsonpCallback
	    		alert('ZepLibrary.getContentReferences: ' + $bResult);
				}); // document.ready

			// ZepAPI callback response handling
			function getContentReferencesCallback(response) {
	    		alert('getContentReferencesCallback OID: ' + response.OID + ', Preview: ' + response.Preview + ', SwfFile: ' + response.SwfFile + ', PageImagePattern: ' + response.PageImagePattern + ', JSONFile: ' + response.JSONFile + ', Status: ' + response.textStatus);
				}
			</script>

Alternative Exception Handling (implemented in this file local to function)...

	// AJAX local event 'complete' handling, answer return codes...
	jqxhr.complete(function(return_jqxhr, textStatus) { alert("Complete... textStatus: " + textStatus + ", status: " + return_jqxhr.status  + ", readyState: " + return_jqxhr.readyState); });

	// AJAX global event 'error' handing (not fired for cross-domain / JSONP)
	$(document).ajaxError(function(event, request, settings){ alert("Error requesting page " + settings.url); });

	// AJAX local event 'success' handling
	jqxhr.success(function() { alert("jqxhr.success"); });

*/

var ZepLibrary = (function() {
	var	_key = null; // Initialized with _initKey()
	var ZEP_API_URL = "https://api.zepinvest.com/public/"; // Also defined in zep_functions.php


	// Answers content reference for varOID, returned via varJSONPCallback reponse JSON representation; function returns true/false
	var _getContentReferences = (function(varJSONPCallback, varOID) {
		var	_api = ZEP_API_URL + "zepcontent.aspx";
		
		if (varJSONPCallback != undefined && varOID != undefined && varOID.length) {
			
			// Construct JSONP request
			var jdata = '{"key":"' + _getKey() + '","oid":"' + varOID +'"}'; //alert('jdata: ' + jdata);
			
			jdata = $.parseJSON(jdata); // Answer JavaScript object for remote JSONP; otherwise pass as string for local

		    var jqxhr = $.ajax( _api, {
		        contentType: "application/json; charset=utf-8",        
		        type: "GET",  
		        data: jdata,
		        dataType: "jsonp",
		        jsonpCallback: varJSONPCallback, // Response handled with varJSONPCallback (implemented by caller)
		        success: function (data) {} 
		    });
		
			return true;
		}
		return false;
	}); // _getContentReferences


	var _getKey = (function() {
		// Answer initalized _key or 'false'
		return _key || false;
	}); // _getKey


	var _initKey = (function() {
		$.get("./wp-content/scripts/zep_library_api_key.php", function(key){
			alert('Inside $.get() of _initKey(): ' + key);
			_key = key;
			//return _key;
		});
/*		
			var jqxhr = $.ajax({
				url: './wp-content/scripts/zep_library_api_key.php',
				async: false,
				success: function(key) {
					alert('Inside _getKey(): ' + key);
					return key; // this also returned undefined 
			  }
			});

			// AJAX local event complete handling, answering return codes...
		    jqxhr.complete(function(return_jqxhr, textStatus) { alert("_getKey Complete, textStatus: " + textStatus + " Status: " + return_jqxhr.status); });
*/
		return false; // $.get() fired and immediately returned here... then local success callback function within $.get() triggered
	}); // _initKey


	// Record varTime_Interval for varOID read by varUser_Id, callback not implemented; function returns true/false
	var _recordTime = (function(varUser_Id, varOID, varTime_Interval) {
		var	_api = ZEP_API_URL + "zeptime.aspx";
		
		// varOID representing non-pay assumed exlcuded by caller or core library
		if (varUser_Id != undefined && varOID != undefined && varOID.length && varTime_Interval != undefined) {
			// Construct JSONP request
			var jdata = '{"key":"' + _getKey() + '","wpoid":"' + varUser_Id.toString() + '","issueoid":"' + varOID + '","timespent":"' + varTime_Interval.toString() + '"}'; //alert("jdata: " + jdata);

		    jdata = $.parseJSON(jdata); // Answer JavaScript object for remote JSONP; otherwise pass as string for local
			
		    var jqxhr = $.ajax( _api, {
		        contentType: "application/json; charset=utf-8",        
		        type: "POST",  
		        data: jdata,
		        dataType: "jsonp",
		        jsonpCallback: "JSONPResponse", // Response handled with jsonpCallback (not implemented)
				success: function (data) {}
		    });

		    // AJAX local event 'complete' handling, answer return codes...
		    //jqxhr.complete(function(return_jqxhr, textStatus) { alert("Complete... textStatus: " + textStatus + ", status: " + return_jqxhr.status  + ", readyState: " + return_jqxhr.readyState); });

			return true;
		}
		return false;		
	}); // _recordTime


	// Register varUser_Id, function returns true/false
	var _registerUser = (function(varJSONPCallback, varUser_Id, varLevel, varEmail, varFirstName, varLastName) {
		var	_api = ZEP_API_URL + "zepcreateuser.aspx";
		
		// varLevel will always be (int) -1 thru 4; -1 if not logged in, 0 if logged in as a non-pay subscriber
		if (varUser_Id != undefined) {
			// Construct JSONP request
			var jdata = '{"key":"' + _getKey() + '","wpoid":"' + varUser_Id.toString() + '","level":"' + varLevel.toString() + '","email":"' + varEmail + '","firstname":"' + varFirstName + '","lastname":"' + varLastName + '"}'; alert("jdata: " + jdata);

		    jdata = $.parseJSON(jdata); // Answer JavaScript object for remote JSONP; otherwise pass as string for local
			
		    var jqxhr = $.ajax( _api, {
		        contentType: "application/json; charset=utf-8",        
		        type: "POST",  
		        data: jdata,
		        dataType: "jsonp",
		        jsonpCallback: varJSONPCallback, // Response handled with varJSONPCallback (implemented by caller)
				success: function (data) {}
		    });

		    // AJAX local event 'complete' handling, answer return codes...
		    jqxhr.complete(function(return_jqxhr, textStatus) { alert("Complete... textStatus: " + textStatus + ", status: " + return_jqxhr.status  + ", readyState: " + return_jqxhr.readyState); });

			return true;
		}
		return false;		
	}); // _registerUser


	return {
		getContentReferences : _getContentReferences,
		recordTime : _recordTime,
		registerUser : _registerUser
		
	}
	
})();

