/*
 * Cellblock general-purpose management console, a component of
 * the Gloto Platform.  See www.gloto.com for more information,
 * terms, and licensing.
 *
 * Copyright (C) 2005-2010, Gloto Corp.
 * http://www.cellblock.com/terms.htm
 */

function Util() {
	var util = this;
	var t; // For smoothscroll timeout
	var lightboxOpen = false;

	this.noClick = function(){
		return "javascript:void(0);";
		//return "#";
	};

	this.initTitleBar = function( target, hideLogout ) {

		var titleBar = util.clear(target);

		if( !hideLogout ){
			var logout = util.createElement({
				type:"div",
				id:"logoutDiv",
				parentNode: titleBar
			});

			util.createElement({
				type: "div",
				id: "titleBarUser",
				parentNode: logout
			});

			util.createElement({
				type: "a",
				href: util.noClick(),
				text: "Help",
				onclick: function(){
					util.launchHelp('whitelabel');
				},
				parentNode: logout
			});

			util.createElement({
				type: "a",
				href: util.noClick(),
				text: "Logout",
				onclick: function(){
					session.logout();
				},
				parentNode: logout
			});
		}

		var branding = util.createElement({
			type: "div",
			id: "titleBarBranding",
			parentNode: titleBar
		});

		util.createElement({
			text: " Social Media Platform",
			parentNode: branding
		});

		var span = util.createElement({
			text: " : ",
			parentNode: branding

		});

		util.createElement( {
			type :"span",
			text :config.getRealm(),
			className :"pointer",
			onclick : function() {
				util.goUrl('dashboard.html', true);
			},
			parentNode : span
		});

		util.createElement({
			type: "div",
			id: "titleBarNav",
			parentNode: logout
		});

		util.console.createConsole("console");
	};

	this.goUrl = function(url, clean) {
		window.location = url + util.getUrlParameters(clean);
	};

	this.getUrlParameter = function(name) {
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.href);
		if (results === null)
			return null;
		else
			return results[1];
	};

	this.getUrlParameters = function(clean) {
		var parameters = "?realm=" + config.getRealm();
		parameters += "&context=" + config.getContextDisplay(true);

		if ( !clean ) {
			parameters += "&cb=" + config.getId();
		}

		return parameters;
	};

	this.getElement = function(id, reset) {
    var element;
		if (typeof (id) == "string") {
			element = document.getElementById(id);
		} else {
			element = id;
		}
    if( element && reset )
      util.clear( element );
    return element;
	};

	this.removeElement = function(element) {
		element.parentNode.removeChild(element);
	};

	this.valid = function(data, error) {
		if (data !== null && data.status == "ok") {
			return true;
		}

		return false;
	};

	this.capitalize = function(str) {
		str = str.toLowerCase();
		var firLet = str.substr(0, 1);
		var rest = str.substr(1, str.length - 1);
		return firLet.toUpperCase() + rest;
	};

	this.error = function(error) {
		var name = error.errorName;
		var words = name.split("_");
		for ( var i = 0; i < words.length; i++) {
			words[i] = util.capitalize(words[i]);
		}
		var message = "Error: " + words.join(" ") + "\n" + error.errorMsg;
		if (util.console != null && util.console.installed()) {
			util.console.errorln(message);
		} else {
			alert(message);
		}
	};

	this.include = function(filename) {
		document.write('<script type="text/javascript" src="' + filename + '"></scr' + 'ipt>');
	};

	this.isPrivateAttribute = function(key) {
		/*for( var attribute in _privateAttributes ){
			if(key.toLowerCase() == attribute.toLowerCase()){
				return true;
			}
		}*/

		return false;
	};

	this.hide = function(element) {
		if (typeof (element) == "string") {
			element = util.getElement(element);
		}

		if (element == null) {
			return;
		}

		element.style.display = "none";
	};

	this.show = function(element) {
		if (typeof (element) == "string") {
			element = util.getElement(element);
		}

		if (element == null) {
			return;
		}

		element.style.display = "block";
	};

	this.toggleVisibility = function(element) {
		if (typeof (element) == "string") {
			element = util.getElement(element);
		}

		if (element == null) {
			return;
		}

		var display = element.style.display;
		if (display !== null && display.toLowerCase() == "none") {
			util.show(element);
		} else {
			util.hide(element);
		}
	};

	this.constructAttributeMap = function(data) {
		var attributes = {};
		for ( var i in data.attributes) {
			var attribute = data.attributes[i];
			attributes[attribute.name] = attribute.value;
		}

		return attributes;
	};

	var setIf = function(element, map, key) {
		if (map[key] != null) {
			element.setAttribute(key, map[key]);
		}
	};

	this.createElement = function(props) {
		var type = props.type || "span";
		var element = document.createElement(type);

		if (props.text != null) {
			element.innerHTML = props.text;
			//element.appendChild( document.createTextNode( props.text ) );
		}

		setIf(element, props, 'id');
		setIf(element, props, 'name');
		setIf(element, props, 'value');
		setIf(element, props, 'href');
		setIf(element, props, 'src');
		setIf(element, props, 'style');
		setIf(element, props, 'disabled');
		setIf(element, props, 'target');
		setIf(element, props, 'title');
		setIf(element, props, 'size');
		setIf(element, props, 'multiple');
		setIf(element, props, 'rows');
		setIf(element, props, 'cols');
		setIf(element, props, 'wrap');
		setIf(element, props, 'width');
		setIf(element, props, 'height');
		setIf(element, props, 'align');
		setIf(element, props, 'valign');
		setIf(element, props, 'cellpadding');
		setIf(element, props, 'cellspacing');
		setIf(element, props, 'border');

		if (props.className != null) {
			element.setAttribute("class", props.className);
			element.setAttribute("className", props.className);
		}

		if (props.onclick != null) {
			element.onclick = props.onclick;
		}

		if (props.onmouseover != null) {
			element.onmouseover = props.onmouseover;
		}

		if (props.onmouseout != null) {
			element.onmouseout = props.onmouseout;
		}

		if (props.onchange != null) {
			element.onchange = props.onchange;
		}

		if (props.onfocus != null) {
			element.onfocus = props.onfocus;
		}

		if (props.onblur != null) {
			element.onblur = props.onblur;
		}

		if (props.childNode != null) {
			element.appendChild(props.childNode);
		}

		if (props.parentNode != null) {
			util.getElement(props.parentNode).appendChild(element);
		}

		return element;
	};

	this.createForm = function(props) {
		var element = document.createElement("form");

		setIf(element, props, 'method');
		setIf(element, props, 'action');
		setIf(element, props, 'target');
		setIf(element, props, 'onsubmit');

    return setCommonProps( element, props );
	};

	this.createInput = function(props) {
		if( props.button ){
			var element = document.createElement("button");
			if (props.value != null) {
				element.innerHTML = props.value;
			}
		}else{
			var element = document.createElement("input");
			setIf(element, props, 'value');
			setIf(element, props, 'disabled');
		}
		setIf(element, props, 'size');
    return setCommonProps( element, props );
  };

  this.createSelect = function(props){
    var selected = props.selected || "";
    var element = document.createElement("select");
    for( key in props.options )
    {
      var option = document.createElement("option");
      if( key.toLowerCase() == selected.toLowerCase() )
        option.setAttribute( "selected", true );
      option.value = key;
      option.innerHTML = props.options[key];
      element.appendChild( option );
    }
    setIf(element, props, 'disabled');
    return setCommonProps( element, props );
  };

  var setCommonProps = function( element, props ){
		setIf(element, props, 'id');
		setIf(element, props, 'name');
		setIf(element, props, 'type');
		setIf(element, props, 'value');
		setIf(element, props, 'title');

		if (props.className != null) {
			element.setAttribute("class", props.className);
			element.setAttribute("className", props.className);
		}

		if (props.onclick != null) {
			element.onclick = props.onclick;
		}

		if (props.childNode != null) {
			element.appendChild(props.childNode);
		}

		if (props.parentNode != null) {
			util.getElement(props.parentNode).appendChild(element);
		}

		return element;
	};

	this.escape = function(string) {
		string = string.replace(/([\'])/gm, '&apos;'); // escape single quote
		return (string != null) ? string.replace(/([=;])/gm, '\\$1') : ""; // escape special characters
	};

	this.kv = function(key, value) {
		return util.escape(key) + "=" + util.escape(value) + ";";
	};

	this.clear = function(element) {
		var node = util.getElement(element);
		if( node != null ){
			while( node.firstChild )
			{
				node.removeChild(node.firstChild);
			}
			return node;
		}else{
			return null;
		}
	};

	this.closure = function(params, func) {
		return function() {
			func(params);
		};
	};

	this.isCellblock = function(context) {
		if (context == "cellblock") {
			return true;
		}
		return false;
	};

	this.isFrame = function(context) {
		if (context == "frame") {
			return true;
		}
		return false;
	};

	this.isUser = function(context) {
		if (context == "user") {
			return true;
		}
		return false;
	};

	this.createPaging = function(target, currentPage, pageCount, label, appendix,
			callback) {
		function createPageNumber(pageNumber) {
			var text = pageNumber;
			var className = "default";
			var onclick = function() {
			};

			if (pageNumber != (currentPage + 1)) {
				className = "pointer";
				onclick = util.closure(pageNumber - 1, callback);
			}

			util.createElement( {
				type :"span",
				className :className,
				text :text,
				onclick :onclick,
				parentNode :target
			});
		}

		function createElipse(target) {
			util.createElement( {
				type :"span",
				text :" ... ",
				parentNode :target
			});
		}

		util.clear(target);

		if (label != null) {
			util.createElement( {
				type :"span",
				text :label,
				style :"font-weight: bold; 	text-transform: capitalize;",
				parentNode :target
			});
		}

		if (pageCount > 1) {
			createPageNumber(1);

			// show start elipse?
			if (currentPage > 3 && pageCount > 7) {
				createElipse(target);
			}

			var delta = 1;
			var count = pageCount - 2;
			if (pageCount > 6) {
				count = 5;
				if (currentPage >= 3) {
					delta = currentPage - 2;
				}
				delta = Math.min(delta, pageCount - count);
				if (pageCount - currentPage <= 3) {
					--delta;
				}

			}
			for ( var i = 0; i < count; ++i) {
				var ii = i + delta;
				createPageNumber(ii + 1);
			}

			// show end elipse?
			if (pageCount - currentPage > 4 && pageCount > 7) {
				createElipse(target);
			}

			createPageNumber(pageCount);
		} else {
			createPageNumber(1);
		}

		if (appendix != null) {
			util.createElement( {
				type :"span",
				className: "appendix",
				text :appendix,
				//style :"font-weight: bold; 	text-transform: capitalize;",
				parentNode :target
			});
		}
	};

	this.initCellblockNavigation = function( target, cbId, spam ) {
		function createNavButton( url, text, parent ){
			var current = ( window.location.href.indexOf( url ) > 0 );
			util.createElement({
				type: (!current) ? "a" : "span",
				className: (current) ? "default" : "pointer",
				href: url + util.getUrlParameters(true) + "&cb=" + cbId,
				text: text,
				parentNode: parent
			});

		}

		function callback( target, data ){
			if( util.valid( data )){
				target = util.clear( target );

				var navigation = util.createElement({
					type: "h3",
					parentNode: target
				});



				util.createElement( {
					type :"span",
					className: (config.get("spamId") == cbId) ? "default spam" : "default",
					text : data.name,
					parentNode : navigation
				});

				var cellblockNav = util.createElement({
					type:"span",
					className: "cellblockNav",
					parentNode: navigation
				});

				createNavButton( "manager.html", "Manage", cellblockNav );
				createNavButton( "upload.html", "Upload", cellblockNav );
				createNavButton( "skinner.html", "Skinner", cellblockNav );

				if( config.isAdmin() ){
					createNavButton("settings.html", "Settings", cellblockNav );
					createNavButton("filters.html", "Filters", cellblockNav );

					/*util.createElement({
						type: "a",
						href: "download.html" + util.getUrlParameters(true) + "&cb=" + cbId,
						text: "Download Content",
						className: "pointer",
						parentNode: navigation
					});*/
				}

				util.createElement({
					type: "a",
					onclick: util.closure( cbId, util.launchPlayer ),
					text: "Launch Player",
					className: "pointer",
					parentNode: cellblockNav
				});
			}else{
				util.error( data );
			}

		}

		function getCellblockInfo( cbId ){
			api.getCellblockInfo(cbId, function( data ){
				callback( target, data );
			});
		}

		if( config.get("spamId") == null ){
			api.call("GetImageFilterInfo",{realmId:config.getRealm()},function(data){
				if( util.valid(data)){
					config.set("spamId", data.corpusCellblockId);
					getCellblockInfo(cbId);
				}else{
					util.error(data);
				}
			});
		}else{
			getCellblockInfo(cbId);
		}



		/*util.createElement({
			type: "a",
			href: "alert.html" + util.getUrlParameters() + "&cb=" + cbId,
			text: "New Content Alert",
			className: "pointer",
			parentNode: navigation
		});*/

	};

	this.initAdminNavigation = function( node ) {
		var navigation = util.clear(node);

		function urlMatch( urls ){
			for( var i = 0; i < urls.length; i++ ){
				if( window.location.href.indexOf( urls[i] ) > 0 ){
					return true;
				}
			}
			return false;
		}

		function mungeLink( url , text, urls ){
			if( urls == null ){
				urls = new Array( url );
			}else{
				urls.push( url );
			}
			var link = util.createElement({
				type: "a",
				href: url + util.getUrlParameters(true),
				text: text,
				className: "pointer",
				parentNode: navigation
			});

			if( urlMatch( urls ) ){
				link.setAttribute( "id", "active" );
			}

//			if( urlMatch( urls ) ){
//				util.createElement({
//					type: "div",
//					id: "active",
//					text: text,
//					parentNode: navigation
//				});
//			}else{
//
//			}

		}

		mungeLink( "dashboard.html", "Dashboard" );
		mungeLink( "commander.html", "Media", new Array( "manager.html", "upload.html", "skinner.html", "settings.html", "filters.html" ) );

		if( config.isAdmin() ){
			mungeLink( "users.html", "Users");
			mungeLink( "designer.html", "Mobile Sites" );
			mungeLink( "spam.html", "Spam Filter" );
			mungeLink( "language.html", "Language Filter" );
			mungeLink( "setup.html", "Advanced" );
		}
	};

	this.showCommander = function() {
		window.location = "commander.html" + util.getUrlParameters(true);
	};

	this.showUsers = function() {
		if (!config.isAdmin()) {
			alert("No Access");
			return;
		}

		window.location = "users.html" + util.getUrlParameters(true);
	};

	this.showConfig = function() {
		if (!config.isAdmin()) {
			alert("No Access");
			return;
		}

		window.location = "config.html" + util.getUrlParameters(true);
	};

	this.showDerg = function() {
		if (!config.isAdmin()) {
			alert("No Access");
			return;
		}

		window.location = "derg.html" + util.getUrlParameters(true);
	};

	this.showMobileEditor = function() {
		if (!config.isAdmin()){
			alert("No Access");
			return;
		}

		window.location = "designer.html" + util.getUrlParameters(true);

	};

	this.showMap = function( node ){
		var map = util.getElement(node);
		if( map != null ){
			map.setAttribute("style", "visibility:visible");
		}
	};

	this.hideMap = function( node ){
		var map = util.getElement(node);
		if( map != null ){
			map.setAttribute("style", "visibility:hidden");
		}
	};

	this.launchPlayer = function( cbId ) {
		var url = "player.html" + util.getUrlParameters(true) + "&cb=" + cbId;
		window.open( url, "_blank", "width=400,height=370,scrollbars=0,status=0,menubar=0,location=0,resizable=0" );
	};

	this.launchHelp = function( type ) {
		var url = url = "help/index.html" + util.getUrlParameters(true) + "&show=" + type;
		window.open( url, "help", "width=620,height=450,scrollbars=1,status=0,menubar=0,location=0,resizable=1" );
	};

	this.createCellblockSelect = function ( name, target, value ) {
		api.getRealmCellblocks( 0, 10, function( data ) {
			if( util.valid( data ) ){
				var cellblockSelect = util.createElement({
					type: "select",
					name: name,
					parentNode: target
				});

				var option = util.createElement({
						type: "option",
						text: "",
						value: "",
						parentNode: cellblockSelect
					});


				var cellblocks = data.cellblocks;
				for( var i = 0; i < cellblocks.length; i++ ){
					var cellblock = cellblocks[i];
					var option = util.createElement({
						type: "option",
						text: cellblock.name,
						value: cellblock.id,
						parentNode: cellblockSelect
					});

					if( value != null && cellblock.id == value ){
						option.setAttribute("selected", "true");
					}
				}
			}else{
				util.error( data );
			}
		});
	};

	this.createSkinSelect = function ( name, target, value ) {
		api.getRealmSkins( function( data ) {
			if( util.valid( data ) ){
				var skinSelect = util.createElement({
					type: "select",
					name: name,
					multiple: true,
					style: "width: 200px;",
					size: 4,
					parentNode: target
				});

				var skins = data.displayModels;
				var skinMap = util.stringToObject( value );
				var skinList = new Array();
				skinList = skinMap[config.getId()];

				for( var i = 0; i < skins.length; i++ ){
					var skin = skins[i];
					var option = util.createElement({
						type: "option",
						text: skin.name,
						value: skin.id,
						parentNode: skinSelect
					});

					if( skinList != null && util.indexOf( skinList, skin.id ) >= 0 ){
						option.setAttribute("selected", "true");
					}
				}
			}else{
				util.error( data );
			}
		});
	};

	this.createSiteSelect = function ( name, target, value ) {
		api.getMyTemplates( function( data ) {
			if( util.valid( data ) ){
				var siteSelect = util.createElement({
					type: "select",
					name: name,
					multiple: true,
					style: "width: 200px;",
					size: 4,
					parentNode: target
				});

				var sites = data.displayModels;
				var siteMap = util.stringToObject( value );
				var siteList = new Array();
				siteList = siteMap[config.getId()];

				for( var i = 0; i < sites.length; i++ ){
					var site = sites[i];
					var option = util.createElement({
						type: "option",
						text: site.name,
						value: site.id,
						parentNode: siteSelect
					});

					if( siteList != null && util.indexOf( siteList, site.id ) >= 0 ){
						option.setAttribute("selected", "true");
					}
				}
			}else{
				util.error( data );
			}
		});
	};

	this.lightbox = function(title, body, width, callback){
		if( util.lightboxOpen() ){
			util.removeLightbox();
		}

		var screenWidth = document.documentElement.clientWidth + document.documentElement.scrollLeft;

		var layer = document.createElement("div");
		layer.style.zIndex = 666;
		layer.id = "layer";
		layer.style.position = "absolute";
		layer.style.top = "0px";
		layer.style.left = "0px";
		layer.style.height = document.documentElement.scrollHeight + "px";
		layer.style.width = screenWidth + "px";
		layer.style.backgroundColor = "black";
		layer.style.opacity = ".6";
		layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
		document.body.appendChild(layer);

		var div = document.createElement("div");
		div.style.zIndex = 667;
		div.id = "lightbox";
		width = (width != null ) ? width : 500;
		div.style.width = width + "px";
		div.style.position = (navigator.userAgent.indexOf("MSIE 6") > -1) ? "absolute" : "fixed";
		div.style.left = (screenWidth / 2) - (width / 2) + "px";
		document.body.appendChild(div);


		var inner = "";

		inner += "<table width='100%' cellpadding='10'>";
		inner += "<tr><td id='lightboxTitle' align='left'></td><td id='lightboxClose' align='right'></td></tr>";
		inner += "<tr><td id='lightboxBody' colspan='2' align='left'></td></tr>";
		inner += "</table>";

		div.innerHTML = inner;

		var a = util.createInput({
			button: true,
			type: "input",
			value: "Close",
			href: "javascript:void(0)",
			parentNode: "lightboxClose"
		});

		a.onclick = function()
		{
			if( callback != null ){
				callback();
			}
			util.removeLightbox();
		};

		util.getElement("lightboxTitle").innerHTML = title;
		var lightboxBody = util.clear("lightboxBody");
		if( typeof body == "string"){
			lightboxBody.innerHTML = body;
		}else{
			lightboxBody.appendChild( body );
		}
		lightboxOpen = true;
	};

	this.removeLightbox = function(){
		document.body.removeChild(document.getElementById("layer"));
		document.body.removeChild(document.getElementById("lightbox"));
		lightboxOpen = false;
	};

	this.lightboxOpen = function(){
		return lightboxOpen;
	};

	this.isCompatibleBrowser = function(){
		var browserName=navigator.appName;
		var browserVer=parseInt(navigator.appVersion,10);
		if ( browserName=="Microsoft Internet Explorer" && browserVer <= 7 ) {
			return false;
		}

		return true;
	};

	this.stringToObject = function( str ){
		var foo = ( str == "" || str == "{}" || str == null ) ? "{}" : eval( '(' + str + ')' );
		return foo;
	};

	this.removeFromArray = function( s, arr ){
		var index = util.indexOf( arr, s );//arr.indexOf(s);
		if (index != -1)
			arr.splice(index, 1);
		return arr;
	};

	this.indexOf = function( arr, element ){
		var length = arr.length;

		for ( var i = 0; i < length; i++) {
			if (arr[i] == element) {
				return i;
			}
		}

		return -1;
	};

	this.noCache = function ( s ){
		if (s.indexOf("?") == -1) {
			return s + "?" + Math.ceil(Math.random() * 1000);
		}

		return s + "&" + Math.ceil(Math.random() * 1000);
	};

	this.roundNumber = function(number, decimals) {
		return Math.round(number*Math.pow(10,decimals))/Math.pow(10,decimals);
	};

	this.scrollToTop = function(){
		function getDocElName(){
		    if(document.compatMode && document.compatMode == "CSS1Compat"){
		        return "documentElement";
		    }
		    else{
		        return "body";
		    }
		}

		var y = document[getDocElName()].scrollTop;
	    if (y!=0){
	        window.scrollBy(0,-50);
	        t=setTimeout('util.scrollToTop()',10);
	    }
	    else clearTimeout(t);
	    return false;
	};

	this.getDateTime = function(){
		var d = new Date();
		var curr_hour = d.getHours();
		if (curr_hour == 0){
		   curr_hour = 12;
		}
		curr_hour = curr_hour + "";
		if( curr_hour.length == 1 ){
			curr_hour = "0" + curr_hour;
		}

		var curr_min = d.getMinutes();
		curr_min = curr_min + "";
		if (curr_min.length == 1){
		   curr_min = "0" + curr_min;
		}

		var curr_sec = d.getSeconds();
		curr_sec = curr_sec + "";
		if (curr_sec.length == 1){
			curr_sec = "0" + curr_sec;
		}

		return curr_hour + ":" + curr_min + ":" + curr_sec;

	};

	this.toBoolean = function( str ){
		return ( str.toLowerCase() == "true" );
	};

	this.createTransactionId = function(){
		var date = new Date();
		return date.getTime();
	};

	this.swfEmbed = function(resources){
		// Globals
		// Major version of Flash required
		var requiredMajorVersion = 9;
		// Minor version of Flash required
		var requiredMinorVersion = 0;
		// Minor version of Flash required
		var requiredRevision = 124;

		var target = util.getElement(resources.target, true);
		var width = resources.width;
		var height = resources.height;
		var id = resources.id;
		var name = resources.name;
		var src = resources.src;

		function output( str ){
			if( target == null ){
				document.write( str );
			}else{
				target.innerHTML = str;
			}
		}

		<!--
		var hasProductInstall = DetectFlashVer(6, 0, 65);

		// Version check based upon the values defined in globals
		var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

		if ( hasProductInstall && !hasRequestedVersion ) {
			// DO NOT MODIFY THE FOLLOWING FOUR LINES
			// Location visited after installation is complete if installation is required
			var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
			var MMredirectURL = window.location;
		    document.title = document.title.slice(0, 47) + " - Flash Player Installation";
		    var MMdoctitle = document.title;

			var str = AC_FL_RunContent(
				"src", "playerProductInstall",
				"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
				"width", width,
				"height", height,
				"align", "middle",
				"id", id,
				"quality", "high",
				"bgcolor", "#ffffff",
				"name", name,
				"allowScriptAccess","sameDomain",
				"type", "application/x-shockwave-flash",
				"pluginspage", "http://www.adobe.com/go/getflashplayer"
			);
			output( str );
		} else if (hasRequestedVersion) {
			// if we've detected an acceptable version
			// embed the Flash Content SWF when all tests are passed
			var str = AC_FL_RunContent(
					"src", "swf/" + src,
					"width", width,
					"height", height,
					"align", "middle",
					"id", id,
					"quality", "high",
					"bgcolor", "#ffffff",
					"name", name,
					"allowScriptAccess","sameDomain",
					"type", "application/x-shockwave-flash",
					"pluginspage", "http://www.adobe.com/go/getflashplayer"
			);
			output( str );
		  } else {  // flash is too old or we can't detect the plugin
		    var alternateContent = 'Alternate HTML content should be placed here. '
		  	+ 'This content requires the Adobe Flash Player. '
		   	+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
		    output( alternateContent );  // insert non-flash content
		  }
		// -->
	}
}

var util = new Util();

function Upload(resources) {
	var upload = this;
	this.resources = resources;
	this.attributes = {};
	this.errorAlert = (upload.resources.errorAlert) ? true : false;
	this.receiptEnabled = false;
	this.receiptSubject = "";
	this.receiptMessage = "";
	this.requiredColor = "";
	this.requiredErrorColor = "";
	this.requiredErrorMessage = "";
	this.blockerErrorMessage = "";
	this.api = new Gloto.Api(upload.resources.apiKey);
	var SUPRESS_FAIL = true;


	this.blockUpload = function(error) {
		util.hide("uploadResponse");
		document.uploadForm.removeAttribute("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;
	}

	this.init = function(resource) {
		if (resource != null) {
			if (resource.errorAlert != null) {
				upload.errorAlert = resource.errorAlert;
			}
		}
	};

	this.initForm = function(foo) {
		document.uploadForm.setAttribute("action", upload.resources.uploadContext + "/api/rest");
		util.getElement("apiKey").setAttribute("value", upload.resources.apiKey);
		util.getElement("id").setAttribute("value", upload.resources.aka);
	};

	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 == "") {
					var mask = input.getAttribute("mask");

					function createOnFocus(input, mask){
						return function(){
							var clickInput = (mask != null) ? util.getElement(mask) : input;
							clickInput.style.backgroundColor = upload.requiredColor;
						};
					}

					input.onfocus = createOnFocus(input, mask);

					input = (mask != null) ? util.getElement(mask) : input;
					input.style.backgroundColor = upload.requiredErrorColor;

					++fail;
				}
			}
		}

		if (fail) {
			upload.blockUpload(upload.requiredErrorMessage);
			return false;
		}

		return true;
	};

	this.processUpload = function() {

		disableUpload();
		status("Uploading file ...");
		upload.processAttributes();
		if (upload.processRequired()) {
			if( upload.processBlockers() ){
				var transactionId = Math.floor(Math.random() * 1000000);
				util.getElement("transactionId").setAttribute("value", transactionId);

				// SET UPLOAD CALLBACK
				setUploadCallback(transactionId);
				return true;
			}else{
				clearUploadCallback();
				return false;
			}
		}else{
			clearUploadCallback();
			return false;
		}
	};

	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)) {
			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;
	};

	function clearUploadCallback(){
		upload.uploadCallback = function(){

		};
	}

	function setUploadCallback(transactionId) {
		upload.uploadCallback = function() {
			uploadComplete(transactionId);
		};
	}

	function showName(bool) {
		upload.showName = bool;
	}

	function status(text) {
		var console = util.getElement("console");
		if (console != null) {
			console.innerHTML = text;
		}
	}

	this.uploadCallback = function() {
	};

	function uploadComplete(transactionId) {
		document.uploadForm.reset();
		if( transactionId ){
				upload.api.call( "GetTransactionResult", {id: transactionId}, function(data) {
					if (util.valid(data)) {
						status("Thank you.  Your file was uploaded successfully.");
						if( upload.resources.callback != null ){
							upload.resources.callback();
						}
					} else {
						util.error(data);
					}
				});
			// Need to re-init form AFTER reset for IE - Reset clears dynamically appended values
			upload.initForm();
			enableUpload();
		}
	}

	this.initFileMask = function( target, mask ){
		var targetElement = util.getElement(target);
		var maskElement = util.getElement(mask);

		targetElement.setAttribute("mask", mask);
		targetElement.onmouseout = function(){
			maskElement.value = targetElement.value;
		};
	};
}
