/*
 * Cellblock general-purpose management console, a component of
 * the Gloto Platform.  See www.gloto.com for more information,
 * terms, and licensing.
 *
 * Copyright (C) 2005-2008, Gloto Corp.
 * http://www.cellblock.com/terms.htm
 */

function Upload( resources )
{
  var upload = this;	
  	this.attributes = {};
	this.displayName = true;
	this.errorAlert = true;
	this.responsePage;	
	this.receiptEnabled = false;
	this.receiptSubject = "";
	this.receiptMessage = "";
	this.requiredColor = "";
	this.requiredErrorColor = "";
	this.requiredErrorMessage = "";
	this.blockerErrorMessage = "";
	var SUPRESS_FAIL = true;
  
	this.blockUpload = function( error )
	{
		 util.hide("uploadResponse");
		 document.uploadForm.setAttribute("action", "");
		 upload.initForm(SUPRESS_FAIL);
		 status( error );
		 if( upload.errorAlert == true ){
		 	alert( error );
		 }
		 enableUpload();
	};
	
  function clearConsole()
  {
    util.getElement("consoleBody").innerHTML = "";
  }
  
	function disableUpload(){
		util.getElement("submit").disabled = true;
	}
	
	function enableUpload()
	{
		util.getElement("submit").disabled = false;
	}
	
  	function embedPlayer(data)
  	{
    	util.getElement("cellblockPlayer").innerHTML = data.embedCode;
  	}  
  
  function initPlayer()
  {
    upload.api.getCellblockInfo(config.getId(), embedPlayer);
  }

  this.init = function( resource )
  {
		if( resource != null ){
			if( resource.displayName != null ){
				upload.displayName = resource.displayName;
			}
			if( resource.errorAlert != null ){
				upload.errorAlert = resource.errorAlert;
			}
		}
		
    api.getCellblockInfo(config.getId(), setInfo);
  };

  this.initForm = function(foo)
  {
    document.uploadForm.setAttribute("action", config.getContext() + "/api/rest");
    util.getElement("apiKey").setAttribute("value", config.getApiKey());  
    util.getElement("id").setAttribute("value", config.getId());
		var url = window.location.href;
		var responsePageUrl = upload.responsePage || unescape(url.substring(0, (url.lastIndexOf("/")) + 1)) + "uploadResponse.html";
		util.getElement("responsePage").setAttribute("value", responsePageUrl);
    
    // SET UPLOAD CALLBACK
    setUploadCallback(foo);
  };

  function println(text)
  {
    var console = util.getElement("consoleBody");
    console.appendChild(document.createTextNode(text));
    console.appendChild(document.createElement("br"));
  }
  
	this.processAttributes = function()
	{
		// Grab etc. fields and add them to the attributes list
		for( var i = 0; i < document.uploadForm.length; i++ ){
			var input = document.uploadForm[i];
			if( input.getAttribute("attribute") != null ){
				upload.setAttribute( input.getAttribute("name"), input.value );
			}
		}
		upload.setAttributeList();
	};
	
	this.processBlockers = function(){
		for( var i = 0; i < document.uploadForm.length; i++ ){
			var input = document.uploadForm[i];
			if( input.getAttribute("blocker") != null){
				if( input.getAttribute("type").toLowerCase() == "checkbox" && !input.checked ){
					upload.blockUpload( upload.blockerErrorMessage );
					return false;
				}
			}
		}
		
		return true;
	};
	
	this.processRequired = function()
	{
		var fail = 0;
		for( var i = 0; i < document.uploadForm.length; i++ ){
			var input = document.uploadForm[i];
			if( input.getAttribute("required") != null ){
				if( input.value == "" ){
					input.style.backgroundColor = upload.requiredErrorColor;
					input.onfocus = function(){
						this.style.backgroundColor = upload.requiredColor;
					};
					++fail;
				}
			}
		}
	
		if( fail ){
			upload.blockUpload( upload.requiredErrorMessage );
			return false;
		}
		
		return true;
	};
	
  this.processUpload = function()
  {
		disableUpload();
		status("Uploading file ...");
		upload.processAttributes();
		if( upload.processRequired() ){
		upload.processBlockers();
		}
  };

	this.setAttribute = function(key, value)
	{
		upload.attributes[key] = value;
	};

	this.setAttributeList = function()
	{
		var attributeString = "";
		for( var key in upload.attributes ){
			attributeString += key + "=" + upload.attributes[key] + ";";
		}
		util.getElement("attributeList").setAttribute("value", attributeString);
	};

	this.setBlockerErrorMessage = function( message )
	{
		upload.blockerErrorMessage = message;
	};

  function setInfo(data)
  {
		if( util.valid( data ) ){
			if( upload.displayName == true ){
    		util.getElement("cellblockName").innerHTML = data.name;
			}
			
			var receipt = data.senderAcknowledgementInfo;
			if( receipt != null ){
				upload.receiptEnabled = receipt.enabled;
				upload.receiptSubject = receipt.subject;
				upload.receiptMessage = receipt.body;
			}
			
		}else{
			util.error( data );
		}
  }
  
	this.setRequiredColor = function( color )
	{
		upload.requiredColor = color;
	};

	this.setRequiredErrorColor = function( color )
	{
		upload.requiredErrorColor = color;
	};
	
	this.setRequiredErrorMessage = function( message )
	{
		upload.requiredErrorMessage = message;
	};
	
	this.setResponsePage = function( src )
	{
		upload.responsePage = src;
		util.getElement("responsePage").setAttribute("value", src );
	};

  function setUploadCallback(foo)
  {
    upload.uploadCallback = function(){
			uploadComplete(foo);
		};
  }

	function showName( bool ){
		upload.showName = bool;
	}

  function status(text)
  {
    var consoleBody = util.getElement("consoleBody");
		if( consoleBody != null )
		{
			consoleBody.innerHTML = text;
  	}
	}

  this.uploadCallback = function(){  };
  
  function uploadComplete(foo)
  {
		if( foo == null || !foo ){
			util.show("uploadResponse");
			document.uploadForm.reset();
			if( upload.receiptEnabled ){
				status( upload.receiptMessage );
			}else{
				status("Upload Complete");
			}
		}
		// Need to re-init form AFTER reset for IE - Reset clears dynamically appended values
		upload.initForm();
		enableUpload();
  }
}
