/* ---[ SETUP NAMESPACE ]--- */
if(typeof(mdp) != 'object'){
	var mdp = {};
}
/**
 * mdpUploader
 *
 * @author Jeremiah LaBresh
 * @requirements SWFObject, MooTools1.11
 * @classDescription Will allow you to create an upload button utilizing flash.
 *
 * @param referenceObject:String ***REQUIRED***
 * 				Name of the instance of the mdpUploader so call backs can be called appropriately
 *
 * @param flashNameValue:String
 * 				Name of the flash object so that if more than one uploader is on the page there is no conflict
 **/

function removeHashFromID (thisID){
    return thisID.replace("#", "");
}

function mdpUploader(referenceObject, flashNameValue, buttonDivID, formHandlerURL, formHandlerDomain, fileTypes, maxFileSize, maxFileCount){

	/* ---[ CLASS VARIABLES ]--- */
	/* public */
	/* none */

	/* private */
	var _refObject;	/* Name of the reference object (i.e. var refObj = new mdpUploader()...) */
	var _flashName;	/* if you need more than one mdpUploader ona  page, then set this to a unique name for each */
	var _divID;		/* divID is the value of the Div ID attribute that flash gets added to */
	var _flashRef;	/* reference to flash object. This gets set after the flash file is written to the page. */
	var _listeners;	/* this is set by an object that is passed to this.eventListeners */
	var _buttonID;	/* the ID of the main upload button used for disabling and enabling */
	var _fileCount = 0;
	var _formHandlerURL, _formHandlerDomain, _fileTypes, _maxFileSize, _maxFileCount;
    var _self = this;
    var _divRef;

    /* ---[ CONSTRUCTOR ]--- */
	function init(){
	  /* initialization code */
		_refObject = referenceObject;
		_flashName = flashNameValue == undefined || flashNameValue == "" ? "mdpFileUpload" : flashNameValue;
		_divID = "#dv" + _flashName;
		_buttonID = "#"+buttonDivID;
		_formHandlerURL = formHandlerURL;
		_formHandlerDomain = formHandlerDomain;
		_fileTypes = fileTypes;
		_maxFileSize = maxFileSize;
		_maxFileCount = maxFileCount;

		/* if the divID does not exists, add it to the body */
		if( !$( _divID ) ){
			$("<div>").attr({'id': removeHashFromID(_divID)}).appendTo($('body:first')).css('display','hidden');

		}

		var errorMessage = "";

		/* check for major errors */
		if(_refObject == undefined || _refObject == "") errorMessage += "There is an error, you need to define the 'referenceObject'\n";
		if(_flashName == undefined || _flashName == "") errorMessage += "There is an error, you need to define the 'flashNameValue'\n";
		if(_divID == undefined || _divID == "dv") errorMessage += "There is an error with 'divID', you need to define 'flashNameValue'\n";

        if( $(buttonDivID) ){
            $( buttonDivID ).css('opacity',0.5);
        }

        if(errorMessage.length > 0) {
			alert("mdpUploader Error (" + _refObject + ") == \n" + errorMessage);
		} else {
			addFlashDiv();
        }

	}

    function addFlashDiv(){

		/* if the divID does not exists, add it to the body */
		if($(_divID)){
			$("<div>").attr({'id': removeHashFromID(_divID)}).appendTo($('body:first')).css('display','hidden');
		}
        /* createFlash - build our flash object on the page */

        createFlash( _buttonID);

        _flashRef = thisMovie( _flashName );

    }

    /* ---[ PUBLIC METHODS ]--- */
	this.setEventListeners = function(o){
        _listeners = o;
	};


    var cntr = 0;
	this.flashIsReady = function( s ){
        if( s ) s = s+"";
        if( typeof( _flashRef.flashIsReady ) == "undefined" ){

            if( cntr < 6) {
                /*$( _divID ).remove();*/
                _self.create();
            }
            cntr++;
        } else {
            _flashRef.flashIsReady( "true" );
            $( buttonDivID ).css('opacity', 1 );
        }

    };

    this.jsReady = function(){
        return true;};

	this.create = function(){
        addFlashDiv();
	};

	this.returnFileCount = function(i){
		 _fileCount = i;
	};

	this.returnDivID = function(){
		return _divID;
	};

	/* ---[ PRIVATE METHODS ]--- */

	function createFlash( bdid ){
        var flDiv = $(bdid);
		var curDimensions = {height:flDiv.height(),width:flDiv.width(), top:flDiv.css("top"), left: flDiv.css("left")};
        var absPosition = flDiv.offset();
		var flDivChild = $(_divID);
		var randNum = Math.random() * 999999999999;
		var ppnav_h = new SWFObject("/web/flash/mdp/app/mdpupload/mdpUploader.swf?" +randNum , _flashName, curDimensions.width, curDimensions.height, "9", "#FFFFFF");

        ppnav_h.addParam("wmode", 'transparent');
		ppnav_h.addParam("scale", "noscale");
		ppnav_h.addParam("allowScriptAccess", "always");
		ppnav_h.addVariable("refObject", _refObject);
		ppnav_h.addVariable("w", curDimensions.width);
		ppnav_h.addVariable("h", curDimensions.height);
		ppnav_h.addVariable("formHandlerURL", _formHandlerURL);
		ppnav_h.addVariable("formHandlerDomain", _formHandlerDomain);
		ppnav_h.addVariable("fileTypes", _fileTypes);
		ppnav_h.addVariable("maxFileSize", _maxFileSize);
		ppnav_h.addVariable("maxFileCount", _maxFileCount);

        ppnav_h.write( removeHashFromID(_divID));
		curDimensions = {height:flDiv.height(),width:flDiv.width()};

        flDivChild.css({
            "position": "absolute",
            "z-index" : "1335",
            "width" :  curDimensions.width + "px",
            "height" : curDimensions.height + "px",
            "top" : (absPosition.top)+"px",
            "left" : (absPosition.left+3) +"px"
        });
	}

	function thisMovie(movieName) {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName];
		} else {
			return document[movieName];
		}
	}

	/* ---[ EVENT LISTENERS ]--- */
	this.onListComplete = function(o){

		/* --- onListComplete --- */
		/* modify the object if needed before it is sent to the call back */
        if ( _listeners.onListComplete)  _listeners.onListComplete(o);
	};

	this.onFileComplete = function(o){
		/* --- onFileComplete --- */

        if ( _listeners.onFileComplete)  _listeners.onFileComplete(o);
	};

	this.onFileUploadComplete = function(o){
		/* --- onFileUploadComplete --- */
		if ( _listeners.onFileUploadComplete)  _listeners.onFileUploadComplete(o);
	};

	this.onTooManyFiles = function(o){
		/* --- onTooManyFiles --- */
		if ( _listeners.onTooManyFiles)  _listeners.onTooManyFiles(o);
	};

	this.onTooLargeFile = function(o){
		/* --- onTooLargeFile --- */
		if ( _listeners.onTooLargeFile)  _listeners.onTooLargeFile(o);
	};

	this.onFileSelected = function(o){
		/* --- onFileSelected --- */
		if ( _listeners.onFileSelected)  _listeners.onFileSelected(o);
	};

	this.onFileProgressEvent = function(o){
		/* --- onFileProgressEvent --- */
			if ( _listeners.onFileProgressEvent)  _listeners.onFileProgressEvent(o);

	};

	this.onBrowseCancelledEvent = function(o){
		/* --- onBrowseCancelledEvent --- */
		if ( _listeners.onBrowseCancelledEvent)  _listeners.onBrowseCancelledEvent(o);
	};

	this.errorEvent = function(o){
        /* --- errorEvent --- */
		if ( _listeners.errorEvent) {
			 _listeners.errorEvent(o);
		} else {
			alert("Error: " + (o.name ? o.name : "") + ":\n" + o.message);
		}
	};

	/* ---[ RUN ]--- */
	init();
}


/**
 * mdpThumbnailHandler
 *
 * @author Jeremiah LaBresh
 * @requirements SWFObject, MooTools1.11
 * @classDescription This will allow you add a thumbnail creator to a form. Works with share my, may need some adjustments to work in any environment
 *
 * @param mdpThumbnailInstance:String ***REQUIRED***
 * 				Name of the instance of the mdpThumbnailHandler so call backs can be called appropriately
 *
 * @param parentDivID:String
 * 				The id of the parent div of the form
 *
 * @param fullImagePath:String
 * 				Full path of the image. Preferably same domain as flash.
 **/

	function mdpThumbnailHandler(mdpThumbnailInstance, parentDivID, fullImagePath, createOnImagesLoad, mdpFormHandler, justThumb){
		/* no private vars */
		var self = "";
		var parent = "";
		var fullImage = "";
		var flashName = "";
		var flashRef = "";
		var fullImageField = "";
		var createOnLoad = "";
        var flashDiv = "";
        var dataForm;
        var currentSlide;
        var formHandler;
        var justThumbnail;
        function init(){
            justThumbnail = !justThumb ? false : justThumb ;
            self = mdpThumbnailInstance;
			parent = parentDivID;
			fullImage = fullImagePath;
			flashDiv = parent + "thumbnail";
			createOnLoad = createOnImagesLoad;
			flashName = "flashThumbnail_"+parent;
            dataForm = $("div[id=" + parent + "dataform]");
            currentSlide = dataForm;
            formHandler = mdpFormHandler;
            /*thumbnailObject
			alert("self:" + self + "\n" + "parent:" + parent + "\n" + "fullImage:" + fullImage + "\n" + "flashDiv:" + flashDiv + "\n");
			*/
			fullImageField = $("#" + parent).find("input[name$=fullImagePath]").first();
			fullImageField.val(fullImage.replace(getDomain(),""));

		    var randNum = Math.random() * 999999999999;
			var thb = new SWFObject("/web/flash/mdp/app/createthumbnail/CreateThumbnail.swf?randNum=" + randNum, flashName, "310", "150", "9", "#FFFFFF");
			thb.addParam("wmode", 'transparent');
			thb.addParam("scale", "noscale");
			thb.addParam("allowScriptAccess", "always");
			thb.addVariable("f", fullImage);
			thb.addVariable("s", "/dyn/dyn/servlet/ShareMyGalleryImageUploadServlet.dyn");
			thb.addVariable("r", "550x550x_large,380x380x_slideshow");
			thb.addVariable("c", createOnLoad);
			thb.addVariable("j", self);
			thb.addVariable("jt", justThumbnail);
			thb.write(removeHashFromID(flashDiv));

            flashRef = thisMovie(flashName);

		}

		function thisMovie(movieName) {
			if ($.browser.msie) {
				return window[movieName];
			} else {
				return document[movieName];
			}
		}

		function getDomain(){

			if(!mdp.pageVars) {mdp.pageVars = {};}
			if(!mdp.pageVars.currentLocation) {mdp.pageVars.currentLocation = document.location + "";}
			if(!mdp.pageVars.domainName) {mdp.pageVars.domainName = mdp.pageVars.currentLocation.substring(0,mdp.pageVars.currentLocation.indexOf("/",mdp.pageVars.currentLocation.indexOf("//")+2));} /* we assume that the domain is http://DOMAINNAME.com/something */
			return mdp.pageVars.domainName;
		}


		this.flashIsReady = function(s){

            flashRef.flashIsReady("true");
		};

		this.jsReady = function(){ return true;};

		this.onImageCreated = function(o){
         /*   var d ="";
            for (var i in o) {d += "o[" + i + "] == " + o[i] + "<br />";}
            if($("#tempMessageCenter")){
                $("#tempMessageCenter")[0].innerHTML += "inside - onImageCreated:<br />" + d + "<hr /><br />";
            }*/

            var newJSON = o.file;
            var jsonObject = $.parseJSON( newJSON );

            if(jsonObject.statusMessage == "OK"){

                if(jsonObject.result && o.type){
                    var elem;
                    switch(o.type){
                    case "_thumb":
                        elem = $("#" + parent).find("input[name$=thumbImagePath]").first();
                        break;
                    case "_large":
                        elem = $("#" + parent).find("input[name$=largeImagePath]").first();
                        break;
                    case "_slideshow":
                        elem = $("#" + parent).find("input[name$=slideImagePath]").first();
                        break;
                    case "_orig":
                        elem = $("#" + parent).find("input[name$=origImagePath]").first();
                        break;
                    }
                    if(elem) {
                        elem.val(jsonObject.result);

                        if($("#tempMessageCenter").length > 0){
                            $("#tempMessageCenter")[0].innerHTML += "inside - onImageCreated - value set for :" + elem.name + ":<br />" + elem.val() + "<hr /><br />";
                        }
                    }
                } else {
                    /*
                    alert("we recieved no thumbnail data");
                     */
                }
            } else {
                alert( "error creating thumbnails: " + jsonObject.statusMessage );
            }

		};

		this.errorEvent = function(o){
			/* --- errorEvent --- */
            var d ="";
            for (var i in o) {d += "o[" + i + "] == " + o[i] + "<br />";}
            if($("#tempMessageCenter").length > 0){
                $("#tempMessageCenter")[0].innerHTML += "inside - errorEvent:<br />" + d + "<hr /><br />";
            }
		};

		this.thumbnailSaved = function(o){
			/* --- thumbnailSaved --- */
            var d ="";
            for (var i in o) {d += "o[" + i + "] == " + o[i] + "<br />";}
            if($("#tempMessageCenter").length > 0){
                $("#tempMessageCenter")[0].innerHTML += "inside - thumbnailSaved:<br />" + d + "<hr /><br />";
            }

            $(flashDiv).css("width",105 + "px");
            currentSlide.animate({opacity:1});
            /*
            currentSlide.slideIn();
            */

            mdp[formHandler].hideShowHelpBoxes(parent, false);
            if($("#"+mdp.moveToStep2Function.id)) {$("#"+mdp.moveToStep2Function.id).css('opacity',1);}

		};

		this.thumbnailModified = function(o){
			/* --- thumbnailModified --- */
            var d ="";
            for (var i in o) {d += "o[" + i + "] == " + o[i] + "<br />";}
            if($("#tempMessageCenter").length > 0){
                $("#tempMessageCenter")[0].innerHTML += "inside - thumbnailModified:<br />" + d + "<hr /><br />";
            }

            mdp[formHandler].hideShowHelpBoxes(parent, true);
			var elem = $(parent).find("input[name$=thumbImagePath]").first();
                elem.val("");

            currentSlide.animate({opacity:0});

            flashDiv = typeof(flashDiv) == "string" ? $("#" + flashDiv) : $(flashDiv);
            flashDiv.css("position","absolute");
            flashDiv.css("z-index",1330);
            flashDiv.css("width",310 + "px");
            flashDiv.css("height",150 + "px");
            $("#"+mdp.moveToStep2Function.id).css('opacity',0);
        };

		this.messageEvent = function(o){
			/* --- messageEvent --- */
            var d ="";
            for (var i in o) {d += "o[" + i + "] == " + o[i] + "<br />";}
            if($("#tempMessageCenter")){
                $("#tempMessageCenter").innerHTML += "inside - messageEvent:<br />" + d + "<hr /><br />";
            }


		};

		init();

	}



	/**
	 * uploadFormHandler
	 *
	 * @author Jeremiah LaBresh
	 * @requirements MooTools1.11, mdpThumbnailHandler, mdpUploader
	 * @classDescription This will help in the communication between the uploader and the form
	 *
	 * @param form:String ***REQUIRED***
	 * 				ID of the form the uploader and thumbnails are attached to.
	 *
	 * @param statusArray:String
	 * 				object of IDs to display status
	 *
	 * @param mdpUploaderInstance:String
	 * 				Reference to the mdpUplaoder object
	 **/
	function uploadFormHandler(form, statusArray, mdpUploaderInstance,numForms,mdpFormHandlerReference,step2, mess){

        /* VARIABLES */

		var formID; /* formID we are handling */
		var statusArea; /* object of IDs to display status */
		var currentMessage; /* var to store the orgional message */
		var mdpUpload; /* var to store the orgional message */
		var formOptions; /* var to store some options */
		var totalForms ;
		var usedForms ;
		var selfish;
		var messages;

		this.formIDs = new Array();
		this.thumbnailObject = {};

        /* CONSTRUCTOR */

		function init(){
			formID = form;
			statusArea = statusArray;
			currentMessage = new Array();
			mdpUpload = mdpUploaderInstance;
			thumbnailObject = {};
			totalForms = (numForms == undefined ? 6 : numForms);
			usedForms = 0;
			selfish = mdpFormHandlerReference;
            messages = mess;

            addExitEvent();

			$("#"+mdp.moveToStep2Function.id).css('opacity',0);
		}

        function exitHandler( e ){
		 e.returnValue = "If you leave, your Album will not be saved.";
        }

        function addExitEvent(){
            $(window).bind('beforeunload', exitHandler );
        }

        function removeExitEvent(){
            $(window).unbind('beforeunload', exitHandler );
        }

        /* GETTERS/SETTERS */

		this.getMdpUploadDivId = function(){
			return "" + mdpUpload.returnDivID();
		};

		this.setOrigionalStatus = function(){
			for(var i=0; i<statusArea.length; i++) {
				if ($(statusArea[i])) {
					$(statusArea[i]).innerHTML = "";
					/*$(statusArea[i]).innerHTML = currentMessage[statusArea[i]];*/
				}
			}
		};

		this.setStatus = function(txt){
			for(var i=0; i<statusArea.length; i++) {
				if ($(statusArea[i])) {
					currentMessage[statusArea[i]] = $(statusArea[i]).innerHTML;
					$(statusArea[i]).innerHTML = "";
					/*$(statusArea[i]).innerHTML = txt;*/
				}
			}
		};

        this.getUsedFormCount = function(){
			return usedForms;
		};

		this.availableForms = function(){
			return totalForms - getUsedFormCount();
		};

        /* PUBLIC */

        this.addThumbnail = function(id,imgPath,mdpUploadFormReference,createOnload, justThumb){
            if(createOnload == undefined) {createOnload = "true";}
			if(justThumb == undefined) {justThumb = "false";}

	                                                        /*function mdpThumbnailHandler(mdpThumbnailInstance, parentDivID, fullImagePath, createOnImagesLoad, mdpFormHandler, justThumb){*/
            mdp[mdpUploadFormReference]["thumbnailObject"][id] = new mdpThumbnailHandler( "mdp." + mdpUploadFormReference + ".thumbnailObject." + id, id, imgPath, createOnload, mdpUploadFormReference, justThumb );

		};

        /* begin dialog */
        this.dialog = function(msg,type,opt){
			verify(msg,type,opt);
		};

		this.dialogEnd = function(){
			unBlockWindow();
		};

		function unBlockWindow(){
			Window.unblock();
		}
        /* end dialog */

        /* begin free forms */
        this.getFreeUploadForm = function(){
            var uploadForm = $(".uploadForm");

           hideShowHelpBoxes( "step1", false, true );

            for(var t=0; t<uploadForm.length; t++){
				if ($("#" + uploadForm[t].id).hasClass('invisible')) {
					$("#" + uploadForm[t].id).removeClass("invisible");
					this.formIDs = t;
					$("#" + uploadForm[t].id).find('input').each(function(i,e){
						$(e).toggleClass("required");
						$(e).toggleClass("invisible");
						$("." + $(e).attr("name").replace(/[^a-zA-Z 0-9]+/g,'')).each(function(i,e){
                            $(e).val("");
                            if($(e).hasClass("invisible")) $(e).toggleClass('invisible');
						});
                        $(e).change( function(){;validateTextField($(this));} );

                        $(e).keyup(function(){;validateTextField($(this));} );
                    });

					$("#" + uploadForm[t].id).find('textarea').each(function(i,e){
						$(e).toggleClass("required");
                        $(e).val("");
						$(e).toggleClass("invisible");
						$("." + $(e).attr("name").replace(/[^a-zA-Z 0-9]+/g,'')).each(function(i,e){
							if($(e).hasClass("invisible")) $(e).toggleClass('invisible');
						});
                        $(e).change(function(){validateTextArea($(this));} );

                        $(e).keyup(function(){validateTextArea($(this));} );
					});

					$("#"+uploadForm[t].id).find('button[id$=remove]').first().click(function(e){

						verify("Are you sure you want to remove this photo?","delete",{id:uploadForm[t].id + ""});

					});
                    /*
					$(uploadForm[t].id).getElement('button[id$=remove]').focus(function(e){
						var getID = this.id;
						checkFocus(getID);
					});
                    */
                    $("#step1").find("div[id^=uploadForm]").each(function(i,e){
                        if((!$(e).hasClass("invisible")) && ($(e).hasClass("uploadForm"))) {
                            if($(e).id) hideShowHelpBoxes($(e).id, false);
                        }
                    });
                    return $("#" + uploadForm[t].id);
				}
			}

            $("#step1").find("div[id^=uploadForm]").each(function(i,e){
                if((!$(e).hasClass("invisible")) && ($(e).hasClass("uploadForm"))) {
                    if($(e).id) hideShowHelpBoxes($(e).id, false);
                }
            });
			return false;
		};

		this.getLoadedUploadForm = function(mdpUploadFormReference,messageDivID,messages){
			var uploadForm = $("div.uploadForm");
			for(var t=0; t<uploadForm.length; t++){
				var currentFormID ="#" + uploadForm[t].id;
                if($(currentFormID)) {
                    if ($(currentFormID).hasClass('loaded')) {
                        $(currentFormID).removeClass("loaded");
                        this.formIDs = t;

                        $(currentFormID).find('input').each(function(i,e){
                            e = $(e);
                            e.toggleClass("required");
                            e.toggleClass("invisible");
                            $("." + e.attr("name").replace(/[^a-zA-Z 0-9]+/g,'')).each(function(i,e){
                                e = $(e);
                                if(e.hasClass("invisible")) e.toggleClass('invisible');
                            });
                        });

                        $(currentFormID).find('textarea').each(function(i,e){
                            e = $(e);
                            e.toggleClass("required");
                            e.toggleClass("invisible");
                            $("." + e.attr("name").replace(/[^a-zA-Z 0-9]+/g,'')).each(function(i,e){
                                e = $(e);
                                if(e.hasClass("invisible")) e.toggleClass('invisible');
                            });

                        });

                        $(currentFormID).find('button[id$=remove]').first().click(function(e){

                            e = $(e);

                            e.unbind("focus");
                            var getID = $(e.id);
                            getID = getID.replace("button","uploadForm");
                            getID = getID.replace("remove","");

                            verify("Are you sure you want to remove this photo?","delete",{id:getID});

                        });

                       /* $(currentFormID).getElement('button[id$=remove]').focus(function(e){
                            var getID = this.id;
                            checkFocus(getID);
                        });*/

                        var thumbFull = $(currentFormID).find("input[name$=fullImagePath]").first().val();
                        mdp[mdpUploadFormReference].addThumbnail(removeHashFromID(currentFormID),thumbFull,mdpUploadFormReference,"false","true");

                   }
                }
            }

            mdp[mdpUploadFormReference].updateCountMessage(messageDivID);

            $("#step1").find("div[id^=uploadForm]").each(function(i,e){

                e = $(e);
                if((!e.hasClass("invisible")) && (e.hasClass("uploadForm"))) {
                    if(e.attr("id")) hideShowHelpBoxes(e.attr('id'), false);
                }
            });

		};
        /* end free forms */

        /* begin delete image */
		function verify(msg,type,opt){

			var div = $("<div>").html(msg + "<br /><br />");
			if(!type) type ="";
			switch(type){
				case "delete":
					/* to use delete pass in {id:DIV_ID} to set that div to empty */
					$("<button>").attr({'class':'M4'}).click(function(){ if(opt.id){removeForm(opt.id);}}).html('Yes, Remove').appendTo(div);
					$("<button>").attr({'class':'M4'}).click(function(){ Window.unblock();}).html('No, Cancel').appendTo(div);
					break;
				case "processing":
					break;
				default:
					$("<button>").click(function(){ Window.unblock();}).html('Close Window').appendTo(div);
					break;
			}

			Window.block(div,'#000');
		}

		function removeForm(idStr){
			idStr = "#"+ idStr;
            if (!$(idStr).hasClass('invisible')) {
                /* remove help boxes */
                hideShowHelpBoxes("step1",false,true);

                /* set class to invisible so we cant see it */
				$(idStr).addClass("invisible");
				/* set forms value to "" and toggle required */
				$(idStr).find('input').each(function(i,e){
                    e = $(e);
					e.toggleClass("required");
					e.val("");
					$("." + e.attr("name").replace(/[^a-zA-Z 0-9]+/g,'')).each(function(i,e){
                        e = $(e);
						if(e.hasClass("invisible")) e.toggleClass('invisible');
					});
				});

                /* set forms value to "" and toggle required */
				$(idStr).find('textarea').each(function(i,e){
                        e = $(e);
					e.toggleClass("required");
					e.val("");
					$("." + e.attr("name").replace(/[^a-zA-Z 0-9]+/g,'')).each(function(i,e){
                        e = $(e);
						if(e.hasClass("invisible")) e.toggleClass('invisible');
					});
				});

				/* clear out thumbnail */
				$(idStr).find("div[id$=thumbnail]").first().html("&nbsp;");

				/* set image values to ""   */
				$(idStr).find("input[name$=photoId]").val("");
				$(idStr).find("input[name$=thumbImagePath]").val("");
				$(idStr).find("input[name$=fullImagePath]").val("");
				$(idStr).find("input[name$=largeImagePath]").val("");
				$(idStr).find("input[name$=slideImagePath]").val("");
				updateCountMessage("statusMessageTop");

                /* move help boxes */

                $("#step1").find("div[id^=uploadForm]").each(function(i,e){
                        e = $(e);
                    if((!e.hasClass("invisible")) && (e.hasClass("uploadForm"))) {
                        if(e.id) hideShowHelpBoxes(e.id, false);
                    }
                });

                unBlockWindow();
			}

		}
        /* end delete image */

        /* begin form focus */
		function checkFocus(eleID){

			/*
			 * I don't really like writing form specific code, but this will only work for the upload form
			 */
			if(eleID){
				var count = eleID.replace("button","").replace("remove","");
				var nextForm = $("#uploadForm" + ((count * 1) + 1));
				if(nextForm){
					if(nextForm.hasClass("invisible")){
						/*
						 * Go to submit button?
						 */
						$("#moveToStep2").focus();
					} else {
						var nextField = $("input[id^=title]",nextForm.id);
						if(nextField[0]){
                            nextField[0].focus();
						}

					}
				}
			}
		}
        /* end form focus */

        /* begin messaging */
		function updateCountMessage(divID){
            var returnDiv = $(mdp.mdpUploader.returnDivID());

            if (returnDiv.length > 0){
                var left = returnDiv.css("left").substr(0,returnDiv.css("left").length-2);
            }
            $("#" + divID).html("You may choose up to " + mdp.mdpUploadFormHandler.checkUsedFormCount() + " photos for your album.");

            if(mdp.mdpUploadFormHandler.checkUsedFormCount() == 0){
                if(!$(mdp.mdpUploader.returnDivID()).attr("templeft")){
                    $(mdp.mdpUploader.returnDivID()).attr("templeft",(left));
                }
                $(mdp.mdpUploader.returnDivID()).css("left",(left-10000) + "px");
            } else {
                if($(mdp.mdpUploader.returnDivID()).attr("templeft")){
                    $(mdp.mdpUploader.returnDivID()).css("left",($(mdp.mdpUploader.returnDivID()).attr("templeft")) + "px");
                }
            }

        }

		this.updateCountMessage = function(divID){
			updateCountMessage(divID);
		};

		this.checkUsedFormCount = function(){

            var availableForms = 0;
			var uploadForm = $("div.uploadForm");

			for(var t=0; t<uploadForm.length; t++){
                var thisFormID = "#" + uploadForm[t].id;
                if($(thisFormID)){
                    if ($(thisFormID).hasClass('invisible')) {
                        availableForms++;
                    }
                }
            }

			/* move to step 2 */
			if(availableForms == 6){
				$("#"+mdp.moveToStep2Function.id).css('opacity',0.0);
                if($("#nextMessage")) $("#nextMessage").innerHTML = "";
            } else {
				$("#"+mdp.moveToStep2Function.id).click(function(ev){mdp.moveToStep2Function.click(ev)}).css('opacity',1);
			}

			return availableForms;
		};
        /* end messaging */

        function validateTextField( e ){
            /**
             * pass in a text field
             */

            if(typeof(e.preventDefault) == "function"){
                e = $(this);
            }

               e = $(e);

            if( e.val() != null ){
                var val = ( e.val().replace(/^\W+/,'')).replace(/\W+$/, '' );
                if( val == "" ){
                    e.removeClass( "validation-passed" );
                    e.addClass( "validation-failed" );
                } else if( val != "" ){
                    if( e.hasClass( "phone" ) ){
                        var regex = /^(\d{3})-(\d{3})-(\d{4})$/;
                        if ( !regex.test( e.val() ) ) {
                            e.removeClass( "validation-passed" );
                            e.addClass( "validation-failed" );
                        } else {
                            e.removeClass( "validation-failed" );
                            e.addClass( "validation-passed" );
                        }
                    } else {
                        e.removeClass( "validation-failed" );
                        e.addClass( "validation-passed" );
                    }
                }
            } else {
                /* do nothing */
            }


        }

        function validateTextArea( e ){
            /**
             * pass in a textarea
             */
            if(typeof(e.preventDefault) == "function"){
                e = $(this);
            } else {
                e = $(e);
            }


            if( e.val() != null ){

                var val = (e.val().replace(/^\W+/,'')).replace(/\W+$/,'');
                if(val == ""){
                    e.removeClass("validation-passed");
                    e.addClass("validation-failed");
                } else if(val != ""){
                    if(val.length <= 1500){
                        e.removeClass("validation-failed");
                        e.addClass("validation-passed");
                    } else {
                        e.removeClass("validation-passed");
                        e.addClass("validation-failed");
                    }
                }
            } else {
                /* do nothing */
            }


        }

        function getHelpIcon(e){

            var next = $(e).next();
          while(!$.isEmptyObject(next) && !next.hasClass("helpIcon")){

                next = next.next();
            }

            return next;
        }

        function validateCheckbox( e ){
            /**
             * pass in a checkbox
             */
            var helpIcon = getHelpIcon(e);
            helpIcon = $(helpIcon);
            e = $(e);
            if(e.attr('checked')){
                e.removeClass("validation-failed");
                e.addClass("validation-passed");
                if(helpIcon != null && helpIcon.hasClass("validation-failed")){
                    helpIcon.removeClass("validation-failed");
                    helpIcon.addClass("validation-passed");
                }
            } else{
                e.removeClass("validation-passed");
                e.addClass("validation-failed");
                if(helpIcon != null && helpIcon.hasClass("validation-passed")){
                    helpIcon.removeClass("validation-passed");
                    helpIcon.addClass("validation-failed");
                }
            }

        }

        function validateCombobox( e ){
            /**
             * pass in a combo/select box
             */
            e = $(e);
            var val = ( e.val().replace(/^\W+/,'')).replace(/\W+$/, '' );
            if( val == "" ){
                e.removeClass( "validation-passed" );
                e.addClass( "validation-failed" );
            } else if(val != ""){
                e.removeClass( "validation-failed" );
                e.addClass( "validation-passed" );
            }

        }

        /* begin validation */

        this.validateUploadForms = function( returnObject ){
            /* validates step 1 */
            var passed = true;
            var returnObj = returnObject ? returnObject : false;
            var errorObj = {};

            $("#step1").find("div[id^=uploadForm]").each(function(i,e){
                e = $(e);
                if((!e.hasClass("invisible")) && (e.hasClass("uploadForm"))) {
                    /* set forms value to "" and toggle required */
                    e.find('input[type=text]').each( function(i, el ){
                        el = $(el);
                        validateTextField(el);
                        if( el.hasClass( "validation-failed" ) ) {
                            passed = false;
                            errorObj[ el.attr("name") ] = el.val();
                        }

                    });

                    /* set forms value to "" and toggle required */
                    e.find('textarea').each(function(i,el){
                        el = $(el);
                        validateTextArea( el );
                        if( el.hasClass( "validation-failed" ) ) {
                            passed = false;
                            errorObj[ el.attr("name") ] = el.val();
                        }
                    });
                }
            });

            if(!passed){
                if(returnObj){
                    return errorObj;
                } else {
                    removeExitEvent();
                    return passed;
                }
            } else {
                return passed;
            }
        };

        this.validateContestForms = function( returnObject, continueObject, onChangeEvent ){
            /* validates step 2 */
            var passed = true;
            var returnObj = returnObject ? returnObject : false;
            var errorObj = {};
            var continueObj = continueObject ? continueObject : null;

            $("#step2").find("div[class=uploadCategoryGroup]").each(function(i,e){
                    /* set forms value to "" and toggle required */
                    $(e).find('input[type=text]').each(function(i,el){
                        el = $(el);
                        if(el.hasClass("required")){

                            validateTextField( el );
                            if( el.hasClass( "validation-failed" ) ) {
                                passed = false;
                                errorObj[ el.attr("name") ] = el.val();
                            }

                        }
                    });

                    $(e).find('input[type=checkbox]').each(function(i,el){
                        el = $(el);
                        if(el.hasClass("required")){

                            validateCheckbox( el );

                            if( el.hasClass( "validation-failed" ) ){
                                passed = false;
                                errorObj[el.attr("name") ] = el.val();
                            }
                        }
                    });

                    $(e).find('select').each(function(i,el){
                        el = $(el);
                        if(el.hasClass("required")){
                            validateCombobox( el );

                            if( el.hasClass( "validation-failed" ) ){
                                passed = false;
                                errorObj[el.attr("name") ] = el.val();
                            }
                        }
                    });

            });

            if(!passed){
                if(returnObj){
                    /* return a error object */
                    return errorObj;
                } else {
                    /* return a error boolean */
                    return passed;
                }
            } else {
                if( continueObj ){
                    return continueObj;
                } else {
                    removeExitEvent();
                    return passed;
                }
            }
        };

        this.checkIfContest = function( updateEvent ) {

			/*
			 * this is based on the following structure
			 * div[id=categorySelect]
			 *
			 * */
            mdp.mdpUploadFormHandler.hideShowHelpBoxes ("contestDiv", false, true);
			var categorySelect = $("#categorySelect");
			var selectedCategory = "sc" + categorySelect.val();
			var contestCheckbox = $('#contestCheckbox');
            if(contestCheckbox != null) {contestCheckbox.attr("checked", false); }
			var show = false;

			var contestDiv = $('#contestDiv');
            if(mdp.sharemyCatObj[selectedCategory]) {
				if (mdp.sharemyCatObj[selectedCategory].photoContestFlag) {
					$('#rulesLink').attr("href",mdp.sharemyCatObj[selectedCategory].contestRulesURL);

                    contestCheckbox.addClass("required");
                    contestCheckbox.removeClass("validation-passed");
                    contestCheckbox.removeClass("invisible");

                    show = true;

					if (mdp.sharemyCatObj[selectedCategory].phoneRequiredFlag) {
						$('#phoneRequiredDiv').css("display",'block');
                        $('#contestPhone').addClass("required").removeClass("validation-passed").removeClass("invisible");
                        $('#phoneRequiredTxt').css("display",'block');

                    } else {
                        $('#phoneRequiredDiv').addClass("required").css("display",'none');
                        $('#contestPhone').removeClass("required").addClass("invisible");
						$('#phoneRequiredTxt').css("display",'none');

                    }

					if (mdp.sharemyCatObj[selectedCategory].contestCheckboxText != "") {
						$('#contestExtraBoxText').html(mdp.sharemyCatObj[selectedCategory].contestCheckboxText);
						$('#contestExtraBoxDiv').css("display",'block');
                        $('#contestExtraBox').addClass("required").removeClass("invisible").removeClass("validation-passed").attr("checked",false);


					} else {
						$('#contestExtraBoxDiv').css("display",'none');
                        $('#contestExtraBox').removeClass("required").addClass("invisible").attr("checked",false);
					}

                    if (mdp.sharemyCatObj[selectedCategory].optinText != "" && mdp.sharemyCatObj[selectedCategory].optinText != 'null') {
                        $('#optinTextDiv').text(mdp.sharemyCatObj[selectedCategory].optinText);
                        $('#optinBoxDiv').css("display", 'block');
                        $('#optinBox').removeClass("validation-passed").removeClass("invisible").attr("checked", false);
                    } else {
                        $('#optinBoxDiv').css("display", 'none');
                        $('#optinBox').addClass("invisible").attr("checked", false);
                    }
                     if (mdp.sharemyCatObj[selectedCategory].optinText2 != "" && mdp.sharemyCatObj[selectedCategory].optinText2 != 'null') {
                        $('#optinTextDiv2').text(mdp.sharemyCatObj[selectedCategory].optinText2);
                        $('#optinBoxDiv2').css("display", 'block');
                        $('#optinBox2').removeClass("validation-passed").removeClass("invisible").attr("checked", false);
                    } else {
                        $('#optinBoxDiv2').css("display", 'none');
                        $('#optinBox2').addClass("invisible").attr("checked", false);
                    }
				} else {
                    contestCheckbox.removeClass("required");
					show = false;
				}
			} else {
                contestCheckbox.addClass("invisible");
                contestCheckbox.removeClass("required");
				show = false;
			}
            mdp.mdpUploadFormHandler.hideShowHelpBoxes ("contestDiv", false);

            if(show){
				$("#"+contestDiv.attr('id')).css("display",'block');
                return true;
			} else {
				$("#"+contestDiv.attr('id')).css("display",'none');
                return false;
            }
		};

        this.hideShowHelpBoxes = function(optionalID, hide, remove){hideShowHelpBoxes(optionalID, hide, remove);};

        function hideShowHelpBoxes (optionalID, hide, remove){
            var parentDivID, removeBox, hideBoxes, ele, cnt;
            if(remove){
                removeBox = true;
            } else {
                removeBox = false;
            }

            if(hide){
                hideBoxes = hide == true ? true : false;
            } else {
                hideBoxes = false;
            }

            if(!$("#" + optionalID)) {
                parentDivID = "#" + formID;/* from constructor */
            } else {
                if($("#"+optionalID).length > 0){
                    parentDivID = "#"+optionalID;
                } else {
                    parentDivID = "#"+formID;/* from constructor */
                }
            }

            /* set forms value to "" and toggle required */
            $(parentDivID).find('input[type=text]').each(function(i,e){

                ele = createHelpBoxes(e);
                ele = $(ele);
                if(ele){
                    if(removeBox){
                        ele.remove();
                    } else {
                        if(hideBoxes){
                            ele.removeClass('invisible');
                        } else {
                            ele.removeClass('invisible');
                        }
                    }
                }
            });

            /* set forms value to "" and toggle required */
            $(parentDivID).find('textarea').each(function(i,e){
                ele = createHelpBoxes(e);
                ele = $(ele);
                if(ele){
                    if(removeBox){
                        ele.remove();
                    } else {
                        if(hideBoxes){
                            ele.addClass('invisible');
                        } else {
                            ele.removeClass('invisible');
                        }
                    }
                }
            });
        }

        function createHelpBoxes(el,msg){
            if(!msg) {
                msg = {};
                msg.message = "";
            }

            /*if(el.css("visibility") != "hidden" && el.css("display") != "none"){*/
                /*
                 * IE6 reports these as 'inherit' if the parent is hidden, FF2+ reports these as expected
                 */

                var className = $(el).attr("name").replace(/[^a-zA-Z 0-9]+/g,'');
                var elementExists = false;
                var checkForElement = $("div[class^="+ className + "]", "body");
                if(checkForElement.length < 1){
                   var boxSize = {x:20 , y:20};
                   var offsetX = 20;
                   var offsetY = 0;
                   if($.browser.msie != undefined) {
                       switch($(el).nodeName){
                        case "TEXTAREA" :
                            offsetX = 40;
                            break;
                        case "INPUT" :
                            offsetX = 20;
                            break;
                       }
                   }
                 /* el = $(el);*/
                   $(el).css( 'padding-right', boxSize.x + 'px' );

                   var cls = $( "." + className );
                   $(el).addClass( className );

                    if(msg.message == "") {
                        if( messages.help ){
                            var classes = el.className;
                            var classArray = classes.split(" ");
                            for(var i=0; i<classArray.length; i++){
                                var currentClass = classArray[i];
                                for(var s in messages.help){
                                    if(messages.help[s].cls){
                                        if(messages.help[s].cls == currentClass){
                                            msg.message = messages.help[s].message ? messages.help[s].message : "";
                                        }
                                    }
                                }
                            }
                        } else {
                            msg.message = "";
                        }
                    }


                    /**/

                    var elOffset = $(el).offset();
                   var ele = $("<div>").attr({'class':className + ' helpmessage ',
                                              'title':msg.message}).bind({
                                                    mouseover:function(e){
                                                    var toolTip = $("div.tool-tip:first","body");
                                                    if(toolTip.length == 0){
                                                        toolTip = $("<div>").attr({'class':'tool-tip '}).appendTo(document.body);
                                                    }

                                                    var toolDiv = toolTip.find("div").first();
                                                    if(toolDiv.length == 0){
                                                        toolDiv = $("<div>").appendTo(toolTip);
                                                        toolDiv = toolTip.find("div").first();
                                                    }

                                                    var toolTitle = toolDiv.find(".tool-title").first();
                                                    if(toolTitle.length == 0){
                                                        toolTitle = $("<div>").attr({'class':'tool-title '}).appendTo(toolDiv);
                                                        toolTitle = toolDiv.find(".tool-title").first();
                                                    }
                                                    toolTitle.text("");

                                                    var toolText = toolDiv.find(".tool-text").first();
                                                    if(toolText.length == 0){
                                                        toolText = $("<div>").attr({'class':'tool-text '}).appendTo(toolDiv);
                                                        toolText = toolDiv.find(".tool-text").first();
                                                    }

                                                    toolText.text(this.title);
                                                    this.title = "";

                                                    var thisCoords = $(this).offset();
                                                    toolTip.css({	position: 'absolute',
                                                                        top: (thisCoords.top - ($.browser.msie ? 15 : 0)) + 'px',
                                                                        left: (thisCoords.left + 20) + 'px',
                                                                        visibility: 'visible'});

                                                },mouseout:function(e){
                                                    var toolTip = $("div.tool-tip:first","body");
                                                    toolTip.css({	position: 'absolute',
                                                                            top: -10000 + 'px',
                                                                            left: -10000 + 'px',
                                                                            visibility: 'hidden'});
                                                    var toolDiv = toolTip.find("div").first();
                                                    var toolTitle = toolDiv.find(".tool-title").first();
                                                    toolTitle.text("");
                                                    var toolText = toolDiv.find(".tool-text").first();
                                                    this.title = toolText.text();
                                                    toolText.text("");
                                                }}
                                        ).css({
                                                    position:'absolute',
                                                    top: (elOffset.top - offsetY) + 'px' ,
                                                    left: (elOffset.left + $(el).width())  + 'px',
                                                    width: '20px',
                                                    height:'20px'}
                                ).appendTo(document.body);
                    return ele;
                } else {

                    return checkForElement[0];
                }

            /*}*/

        }
        /* end form validation */

        /* deprecating */
		this.setUsedFormCount = function(i){
			mdpUpload.setPossibleUpload(i);
			usedForms = i;
		};
        /* deprecating */



        init();
	}

/* EOF */
