/** 
 * Javascript components of Dreamgirl 4
 * 
 * Depends on prototype.js and scriptaculous.js
 *
 * What's dreamgirl? www.meetdreamgirl.com
 *
 * Not available for reuse or redistribution without permission.
 *
 * (c) Papercut Media 2005-2007
 *
 */

var version= 4.0;

var xmllock;
var submitlock = false;
var myid;

var iF;
var dg_editing = false
var bodyoffset;
var snapback_x;
var snapback_y;

/* Runs asynchronous call to processor */
function dgCallToProcessor(url) {
        if (xmllock) {
                window.alert("Please wait for current action to finish");
        } else {
        	xmllock = true;
			new Ajax.Request(url,{
				method : 'GET',
				onSuccess: function(transport) {
				    // unlock the xml action lock
				    xmllock = false;
				    // TODO: just reload affected section of document
				    feedbackCompleted();
				},
				onFailure: function(transport) {
    					displayInlineFeedback("There was a problem with your request: "+transport.status);					
				}
			});
	}
}

/**
 * Destroys all previously loaded edit forms on page (called by close action)
 */
function clearFrames() {
		$$('.dgInlineForm').each(function(editframe) {
			//	Effect.Fade(editframe.getAttribute('id'));
                myparent = editframe.parentNode.getAttribute('id');
				
	                $(myparent+'Button').up(2).removeClassName('dgActiveElement');
                editframe.hide();
		} );
        // clear the global submit lock so another action can take place
        submitlock = false;
}


/**
 * Reveals inline edit form for dreamgirl
 *
 * @param id DOM id of parent element of iframe (the element you're clicking from)
 * @param url url of edit form
 * @highlight boolean if we want to change the highlight class of parent element
 */
 
function dgRevealForm(id,url,highlight) {
	 	myid = id+'Frm';
        // if running on an existing frame, toggle it off
        if ($(myid)) {
			clearFrames();
		
//	        $(myid).show();
//
				Effect.Fade(myid);
//				$(myid).hide();
	//			$(myid) = null;
				jumpTo(snapback_x,snapback_y,20);
                $(id+'Button').setAttribute('class','dgButtonLink');
                
                if (highlight) {                
	                $(id+'Button').up(2).removeClassName('dgActiveElement');
                } 
				$(myid).remove();
        } else {
                clearFrames();       
                bodyheight = document.body.scrollHeight;
                bodywidth = document.body.scrollWidth;
                if (submitlock) {
                        alert("Dreamgirl is currently working. Please wait until she is ready");
                } else {
	                $(id+'Button').setAttribute('class','dgInlineButtonActivated');
	                if (highlight) {
		                $(id+'Button').up(2).addClassName('dgActiveElement');
	                }
					
					iF = Builder.node('iframe',{
						className: 'dgInlineForm',
						scrolling: 'no',
						frameborder: 'no',
						border: 0,
						id: myid,
						src: url
					});
	                $(id).appendChild(iF);
				//	var drag = new Draggable(id);

                }
        }
}


/* User-side feedback */
function displayInlineFeedback(message) {
	if ($('dgProgressDiv')) {
    	$("dgProgressDiv").remove();
	   	$('wrap').hide();
 	}
	document.body.appendChild(Builder.node('div',{id: 'dgInlineFeedback'}));         
}


function feedbackCompleted() {
    displayInlineFeedback("Success"); 
	window.location.reload(false);
}

function resizeFrame(documentEl) {
	   if (myid) {
       $(myid).style.height = (documentEl.body.scrollHeight) + "px";
       $(myid).style.width = (documentEl.body.scrollWidth) + "px";
	}
}

function resizeFrameTo(height,width) {
        if (myid) {
			$(myid).style.height = height+"px";
			$(myid).style.width = width+"px";
        }
}

		
function revealMe(documentEl) { 
    resizeFrame(documentEl);
    if ($(myid)) {
        $(myid).show();
//Effect.Appear(myid,{duration: 0.5});
        if (documentEl.forms.length) {
                Form.focusFirstElement(documentEl.forms[0]);
        }
       
        if ($(myid).offsetTop) {
                snapback_x = document.body.scrollLeft;
                snapback_y = document.body.scrollTop;
				
                var xPos = findPosX($(myid));
                if (xPos < 0) {
                    $(myid).style.marginLeft = "0px";
                }
                jumpTo(xPos,findPosY($(myid)),20);
        }
       }


}


function initEditForm() {
  //      initFileUploads();
		$$(".closeAction").each(function(formAction) {	
			Event.observe(formAction,"click",function(e) {
				Event.stop(e);
				destroyMe();
			});
		});
		$$(".submitbutton").each(function(formAction) {	
			Event.observe(formAction,"click",function(e) {
				Event.stop(e);
				processMe();
			});
		});		
        preloadImages();
		if (window.edToolbar) {
			$$("textarea").each(function(element) {
				edToolbar(element.id,'extended');
			});
		}
        window.parent.revealMe(document); 
}


/**
	Resizes textarea on user interaction
*/
function resizeText(element,enlarge) {
        element = $(element);
        if (element) {
                element.style.height = (element.offsetHeight + enlarge)+"px";
        }
        window.parent.resizeFrame(document);
}

        
function jumpTo(x,y,ms) {

        me_y = document.body.scrollTop;
		window.scrollTo(x,y);
/*
        var timer = 0;
        
        if (y > me_y) {
           diff = (y - me_y);
           increment = Math.round(diff / ms);
 
           for (i = me_y; i <= y; i = (i + increment)) {
                setTimeout("window.scrollTo(" + x + "," + i + ")",1);
                timer ++;
           }
        } else if (y < me_y) {
            diff = (me_y - y);
            increment = Math.round(diff / ms);
           for (i = me_y; i >= y; i = (i - increment)) {
               setTimeout("window.scrollTo(" + x + "," + i + ")",1);
                timer ++;
           }                           
        } else {
                window.scrollTo(x,y);
        } */
}


function destroyMe() {
        window.parent.clearFrames();
}

function processMe() {
        collapseToProgress();
		window.parent.submitlock = true;
        document.forms[0].submit();
}


function collapseToProgress() {
     $('main').hide();  
     progress = document.body.appendChild(Builder.node('div',{id: 'dgProgressDiv'}));
}    


var preloaded = false;
function preloadImages() {
        if (!preloaded) {
                images = new Array();
                images[0] = "choose-hit.gif";
                images[1] = "choose-over.gif";
                images[2] = "close-click.gif";
                images[3] = "close-over.gif";
                images[4] = "save-click.gif";
                images[5] = "save-over.gif";
                images[6] = "success.png";
                images[7] = "success.gif";
                images[8] = "dreaming.gif";
                imageObj = document.createElement('img');
                images.each(function(e) {
                        imageObj.src = "http://work.papercutmedia.com/rtr/dreamgirl/images/" + e;
                });
                preloaded = true;
         }
}


function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}

/** 
	Functionality is attached to Dreamgirl elements via classnames set PHP-side. 
	We loop through elements with these classes and attach appropriate listeners.
	
	If no Javascript is present, actions will be performed by direct links.
*/


function initDG() {
	attachListeners();
	dg_editing = true;
}

function attachListeners() {
	$$(".dgCallToProcessor").each(function(inLineAction) {
				if (inLineAction.hasClassName('confirmAction')) {
					Event.observe(inLineAction,'click',function(e) {
						Event.stop(e);
						if (confirm("Are you sure you wish to delete this?")) {
							dgCallToProcessor(inLineAction.href);
						}
					});
				} else {
					Event.observe(inLineAction,'click',function(e) {
						Event.stop(e);
						dgCallToProcessor(inLineAction.href);
					});			
				}
	});
	$$(".dgRevealForm").each(function(formAction) {	
		Event.observe(formAction,"click",function(e) {
			Event.stop(e);
			dgRevealForm(formAction.up('span',0).id,formAction.href,true);
		});
	});
}

